PostgreSQL Source Code  git master
pathkeys.c File Reference
Include dependency graph for pathkeys.c:

Go to the source code of this file.

Functions

static bool pathkey_is_redundant (PathKey *new_pathkey, List *pathkeys)
 
static bool matches_boolean_partition_clause (RestrictInfo *rinfo, RelOptInfo *partrel, int partkeycol)
 
static Varfind_var_for_subquery_tle (RelOptInfo *rel, TargetEntry *tle)
 
static bool right_merge_direction (PlannerInfo *root, PathKey *pathkey)
 
PathKeymake_canonical_pathkey (PlannerInfo *root, EquivalenceClass *eclass, Oid opfamily, int strategy, bool nulls_first)
 
Listappend_pathkeys (List *target, List *source)
 
static PathKeymake_pathkey_from_sortinfo (PlannerInfo *root, Expr *expr, Relids nullable_relids, Oid opfamily, Oid opcintype, Oid collation, bool reverse_sort, bool nulls_first, Index sortref, Relids rel, bool create_it)
 
static PathKeymake_pathkey_from_sortop (PlannerInfo *root, Expr *expr, Relids nullable_relids, Oid ordering_op, bool nulls_first, Index sortref, bool create_it)
 
PathKeysComparison compare_pathkeys (List *keys1, List *keys2)
 
bool pathkeys_contained_in (List *keys1, List *keys2)
 
bool pathkeys_count_contained_in (List *keys1, List *keys2, int *n_common)
 
Pathget_cheapest_path_for_pathkeys (List *paths, List *pathkeys, Relids required_outer, CostSelector cost_criterion, bool require_parallel_safe)
 
Pathget_cheapest_fractional_path_for_pathkeys (List *paths, List *pathkeys, Relids required_outer, double fraction)
 
Pathget_cheapest_parallel_safe_total_inner (List *paths)
 
Listbuild_index_pathkeys (PlannerInfo *root, IndexOptInfo *index, ScanDirection scandir)
 
static bool partkey_is_bool_constant_for_query (RelOptInfo *partrel, int partkeycol)
 
Listbuild_partition_pathkeys (PlannerInfo *root, RelOptInfo *partrel, ScanDirection scandir, bool *partialkeys)
 
Listbuild_expression_pathkey (PlannerInfo *root, Expr *expr, Relids nullable_relids, Oid opno, Relids rel, bool create_it)
 
Listconvert_subquery_pathkeys (PlannerInfo *root, RelOptInfo *rel, List *subquery_pathkeys, List *subquery_tlist)
 
Listbuild_join_pathkeys (PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, List *outer_pathkeys)
 
Listmake_pathkeys_for_sortclauses (PlannerInfo *root, List *sortclauses, List *tlist)
 
void initialize_mergeclause_eclasses (PlannerInfo *root, RestrictInfo *restrictinfo)
 
void update_mergeclause_eclasses (PlannerInfo *root, RestrictInfo *restrictinfo)
 
Listfind_mergeclauses_for_outer_pathkeys (PlannerInfo *root, List *pathkeys, List *restrictinfos)
 
Listselect_outer_pathkeys_for_merge (PlannerInfo *root, List *mergeclauses, RelOptInfo *joinrel)
 
Listmake_inner_pathkeys_for_merge (PlannerInfo *root, List *mergeclauses, List *outer_pathkeys)
 
Listtrim_mergeclauses_for_inner_pathkeys (PlannerInfo *root, List *mergeclauses, List *pathkeys)
 
static int pathkeys_useful_for_merging (PlannerInfo *root, RelOptInfo *rel, List *pathkeys)
 
static int pathkeys_useful_for_ordering (PlannerInfo *root, List *pathkeys)
 
Listtruncate_useless_pathkeys (PlannerInfo *root, RelOptInfo *rel, List *pathkeys)
 
bool has_useful_pathkeys (PlannerInfo *root, RelOptInfo *rel)
 

Function Documentation

◆ append_pathkeys()

List* append_pathkeys ( List target,
List source 
)

Definition at line 105 of file pathkeys.c.

106 {
107  ListCell *lc;
108 
109  Assert(target != NIL);
110 
111  foreach(lc, source)
112  {
113  PathKey *pk = lfirst_node(PathKey, lc);
114 
115  if (!pathkey_is_redundant(pk, target))
116  target = lappend(target, pk);
117  }
118  return target;
119 }
Assert(fmt[strlen(fmt) - 1] !='\n')
List * lappend(List *list, void *datum)
Definition: list.c:338
static bool pathkey_is_redundant(PathKey *new_pathkey, List *pathkeys)
Definition: pathkeys.c:157
#define lfirst_node(type, lc)
Definition: pg_list.h:174
#define NIL
Definition: pg_list.h:66
static rewind_source * source
Definition: pg_rewind.c:81

References Assert(), lappend(), lfirst_node, NIL, pathkey_is_redundant(), and source.

Referenced by make_pathkeys_for_groupagg().

◆ build_expression_pathkey()

List* build_expression_pathkey ( PlannerInfo root,
Expr expr,
Relids  nullable_relids,
Oid  opno,
Relids  rel,
bool  create_it 
)

Definition at line 809 of file pathkeys.c.

815 {
816  List *pathkeys;
817  Oid opfamily,
818  opcintype;
819  int16 strategy;
820  PathKey *cpathkey;
821 
822  /* Find the operator in pg_amop --- failure shouldn't happen */
823  if (!get_ordering_op_properties(opno,
824  &opfamily, &opcintype, &strategy))
825  elog(ERROR, "operator %u is not a valid ordering operator",
826  opno);
827 
828  cpathkey = make_pathkey_from_sortinfo(root,
829  expr,
830  nullable_relids,
831  opfamily,
832  opcintype,
833  exprCollation((Node *) expr),
834  (strategy == BTGreaterStrategyNumber),
835  (strategy == BTGreaterStrategyNumber),
836  0,
837  rel,
838  create_it);
839 
840  if (cpathkey)
841  pathkeys = list_make1(cpathkey);
842  else
843  pathkeys = NIL;
844 
845  return pathkeys;
846 }
signed short int16
Definition: c.h:429
#define ERROR
Definition: elog.h:35
bool get_ordering_op_properties(Oid opno, Oid *opfamily, Oid *opcintype, int16 *strategy)
Definition: lsyscache.c:206
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:764
static PathKey * make_pathkey_from_sortinfo(PlannerInfo *root, Expr *expr, Relids nullable_relids, Oid opfamily, Oid opcintype, Oid collation, bool reverse_sort, bool nulls_first, Index sortref, Relids rel, bool create_it)
Definition: pathkeys.c:199
#define list_make1(x1)
Definition: pg_list.h:210
unsigned int Oid
Definition: postgres_ext.h:31
#define BTGreaterStrategyNumber
Definition: stratnum.h:33
Definition: pg_list.h:52
Definition: nodes.h:112

References BTGreaterStrategyNumber, elog(), ERROR, exprCollation(), get_ordering_op_properties(), list_make1, make_pathkey_from_sortinfo(), and NIL.

Referenced by set_function_pathlist().

◆ build_index_pathkeys()

List* build_index_pathkeys ( PlannerInfo root,
IndexOptInfo index,
ScanDirection  scandir 
)

Definition at line 545 of file pathkeys.c.

548 {
549  List *retval = NIL;
550  ListCell *lc;
551  int i;
552 
553  if (index->sortopfamily == NULL)
554  return NIL; /* non-orderable index */
555 
556  i = 0;
557  foreach(lc, index->indextlist)
558  {
559  TargetEntry *indextle = (TargetEntry *) lfirst(lc);
560  Expr *indexkey;
561  bool reverse_sort;
562  bool nulls_first;
563  PathKey *cpathkey;
564 
565  /*
566  * INCLUDE columns are stored in index unordered, so they don't
567  * support ordered index scan.
568  */
569  if (i >= index->nkeycolumns)
570  break;
571 
572  /* We assume we don't need to make a copy of the tlist item */
573  indexkey = indextle->expr;
574 
575  if (ScanDirectionIsBackward(scandir))
576  {
577  reverse_sort = !index->reverse_sort[i];
578  nulls_first = !index->nulls_first[i];
579  }
580  else
581  {
582  reverse_sort = index->reverse_sort[i];
583  nulls_first = index->nulls_first[i];
584  }
585 
586  /*
587  * OK, try to make a canonical pathkey for this sort key. Note we're
588  * underneath any outer joins, so nullable_relids should be NULL.
589  */
590  cpathkey = make_pathkey_from_sortinfo(root,
591  indexkey,
592  NULL,
593  index->sortopfamily[i],
594  index->opcintype[i],
595  index->indexcollations[i],
596  reverse_sort,
597  nulls_first,
598  0,
599  index->rel->relids,
600  false);
601 
602  if (cpathkey)
603  {
604  /*
605  * We found the sort key in an EquivalenceClass, so it's relevant
606  * for this query. Add it to list, unless it's redundant.
607  */
608  if (!pathkey_is_redundant(cpathkey, retval))
609  retval = lappend(retval, cpathkey);
610  }
611  else
612  {
613  /*
614  * Boolean index keys might be redundant even if they do not
615  * appear in an EquivalenceClass, because of our special treatment
616  * of boolean equality conditions --- see the comment for
617  * indexcol_is_bool_constant_for_query(). If that applies, we can
618  * continue to examine lower-order index columns. Otherwise, the
619  * sort key is not an interesting sort order for this query, so we
620  * should stop considering index columns; any lower-order sort
621  * keys won't be useful either.
622  */
624  break;
625  }
626 
627  i++;
628  }
629 
630  return retval;
631 }
bool indexcol_is_bool_constant_for_query(PlannerInfo *root, IndexOptInfo *index, int indexcol)
Definition: indxpath.c:3665
int i
Definition: isn.c:73
#define lfirst(lc)
Definition: pg_list.h:170
#define ScanDirectionIsBackward(direction)
Definition: sdir.h:41
Expr * expr
Definition: primnodes.h:1555
Definition: type.h:95

References TargetEntry::expr, i, indexcol_is_bool_constant_for_query(), lappend(), lfirst, make_pathkey_from_sortinfo(), NIL, pathkey_is_redundant(), and ScanDirectionIsBackward.

Referenced by build_index_paths().

◆ build_join_pathkeys()

List* build_join_pathkeys ( PlannerInfo root,
RelOptInfo joinrel,
JoinType  jointype,
List outer_pathkeys 
)

Definition at line 1109 of file pathkeys.c.

1113 {
1114  if (jointype == JOIN_FULL || jointype == JOIN_RIGHT)
1115  return NIL;
1116 
1117  /*
1118  * This used to be quite a complex bit of code, but now that all pathkey
1119  * sublists start out life canonicalized, we don't have to do a darn thing
1120  * here!
1121  *
1122  * We do, however, need to truncate the pathkeys list, since it may
1123  * contain pathkeys that were useful for forming this joinrel but are
1124  * uninteresting to higher levels.
1125  */
1126  return truncate_useless_pathkeys(root, joinrel, outer_pathkeys);
1127 }
@ JOIN_FULL
Definition: nodes.h:289
@ JOIN_RIGHT
Definition: nodes.h:290
List * truncate_useless_pathkeys(PlannerInfo *root, RelOptInfo *rel, List *pathkeys)
Definition: pathkeys.c:1923

References JOIN_FULL, JOIN_RIGHT, NIL, and truncate_useless_pathkeys().

Referenced by consider_parallel_mergejoin(), consider_parallel_nestloop(), match_unsorted_outer(), and sort_inner_and_outer().

◆ build_partition_pathkeys()

List* build_partition_pathkeys ( PlannerInfo root,
RelOptInfo partrel,
ScanDirection  scandir,
bool partialkeys 
)

Definition at line 726 of file pathkeys.c.

728 {
729  List *retval = NIL;
730  PartitionScheme partscheme = partrel->part_scheme;
731  int i;
732 
733  Assert(partscheme != NULL);
734  Assert(partitions_are_ordered(partrel->boundinfo, partrel->live_parts));
735  /* For now, we can only cope with baserels */
736  Assert(IS_SIMPLE_REL(partrel));
737 
738  for (i = 0; i < partscheme->partnatts; i++)
739  {
740  PathKey *cpathkey;
741  Expr *keyCol = (Expr *) linitial(partrel->partexprs[i]);
742 
743  /*
744  * Try to make a canonical pathkey for this partkey.
745  *
746  * We're considering a baserel scan, so nullable_relids should be
747  * NULL. Also, we assume the PartitionDesc lists any NULL partition
748  * last, so we treat the scan like a NULLS LAST index: we have
749  * nulls_first for backwards scan only.
750  */
751  cpathkey = make_pathkey_from_sortinfo(root,
752  keyCol,
753  NULL,
754  partscheme->partopfamily[i],
755  partscheme->partopcintype[i],
756  partscheme->partcollation[i],
757  ScanDirectionIsBackward(scandir),
758  ScanDirectionIsBackward(scandir),
759  0,
760  partrel->relids,
761  false);
762 
763 
764  if (cpathkey)
765  {
766  /*
767  * We found the sort key in an EquivalenceClass, so it's relevant
768  * for this query. Add it to list, unless it's redundant.
769  */
770  if (!pathkey_is_redundant(cpathkey, retval))
771  retval = lappend(retval, cpathkey);
772  }
773  else
774  {
775  /*
776  * Boolean partition keys might be redundant even if they do not
777  * appear in an EquivalenceClass, because of our special treatment
778  * of boolean equality conditions --- see the comment for
779  * partkey_is_bool_constant_for_query(). If that applies, we can
780  * continue to examine lower-order partition keys. Otherwise, the
781  * sort key is not an interesting sort order for this query, so we
782  * should stop considering partition columns; any lower-order sort
783  * keys won't be useful either.
784  */
785  if (!partkey_is_bool_constant_for_query(partrel, i))
786  {
787  *partialkeys = true;
788  return retval;
789  }
790  }
791  }
792 
793  *partialkeys = false;
794  return retval;
795 }
bool partitions_are_ordered(PartitionBoundInfo boundinfo, Bitmapset *live_parts)
Definition: partbounds.c:2853
static bool partkey_is_bool_constant_for_query(RelOptInfo *partrel, int partkeycol)
Definition: pathkeys.c:651
#define IS_SIMPLE_REL(rel)
Definition: pathnodes.h:783
#define linitial(l)
Definition: pg_list.h:176
Relids relids
Definition: pathnodes.h:815
Bitmapset * live_parts
Definition: pathnodes.h:978

References Assert(), i, IS_SIMPLE_REL, lappend(), linitial, RelOptInfo::live_parts, make_pathkey_from_sortinfo(), NIL, PartitionSchemeData::partcollation, partitions_are_ordered(), partkey_is_bool_constant_for_query(), PartitionSchemeData::partnatts, PartitionSchemeData::partopcintype, PartitionSchemeData::partopfamily, pathkey_is_redundant(), RelOptInfo::relids, and ScanDirectionIsBackward.

Referenced by generate_orderedappend_paths().

◆ compare_pathkeys()

PathKeysComparison compare_pathkeys ( List keys1,
List keys2 
)

Definition at line 307 of file pathkeys.c.

308 {
309  ListCell *key1,
310  *key2;
311 
312  /*
313  * Fall out quickly if we are passed two identical lists. This mostly
314  * catches the case where both are NIL, but that's common enough to
315  * warrant the test.
316  */
317  if (keys1 == keys2)
318  return PATHKEYS_EQUAL;
319 
320  forboth(key1, keys1, key2, keys2)
321  {
322  PathKey *pathkey1 = (PathKey *) lfirst(key1);
323  PathKey *pathkey2 = (PathKey *) lfirst(key2);
324 
325  if (pathkey1 != pathkey2)
326  return PATHKEYS_DIFFERENT; /* no need to keep looking */
327  }
328 
329  /*
330  * If we reached the end of only one list, the other is longer and
331  * therefore not a subset.
332  */
333  if (key1 != NULL)
334  return PATHKEYS_BETTER1; /* key1 is longer */
335  if (key2 != NULL)
336  return PATHKEYS_BETTER2; /* key2 is longer */
337  return PATHKEYS_EQUAL;
338 }
@ PATHKEYS_BETTER2
Definition: paths.h:198
@ PATHKEYS_BETTER1
Definition: paths.h:197
@ PATHKEYS_DIFFERENT
Definition: paths.h:199
@ PATHKEYS_EQUAL
Definition: paths.h:196
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:465

References forboth, lfirst, PATHKEYS_BETTER1, PATHKEYS_BETTER2, PATHKEYS_DIFFERENT, and PATHKEYS_EQUAL.

Referenced by add_partial_path(), add_partial_path_precheck(), add_path(), add_path_precheck(), add_paths_to_append_rel(), make_pathkeys_for_groupagg(), pathkeys_contained_in(), and set_cheapest().

◆ convert_subquery_pathkeys()

List* convert_subquery_pathkeys ( PlannerInfo root,
RelOptInfo rel,
List subquery_pathkeys,
List subquery_tlist 
)

Definition at line 865 of file pathkeys.c.

868 {
869  List *retval = NIL;
870  int retvallen = 0;
871  int outer_query_keys = list_length(root->query_pathkeys);
872  ListCell *i;
873 
874  foreach(i, subquery_pathkeys)
875  {
876  PathKey *sub_pathkey = (PathKey *) lfirst(i);
877  EquivalenceClass *sub_eclass = sub_pathkey->pk_eclass;
878  PathKey *best_pathkey = NULL;
879 
880  if (sub_eclass->ec_has_volatile)
881  {
882  /*
883  * If the sub_pathkey's EquivalenceClass is volatile, then it must
884  * have come from an ORDER BY clause, and we have to match it to
885  * that same targetlist entry.
886  */
887  TargetEntry *tle;
888  Var *outer_var;
889 
890  if (sub_eclass->ec_sortref == 0) /* can't happen */
891  elog(ERROR, "volatile EquivalenceClass has no sortref");
892  tle = get_sortgroupref_tle(sub_eclass->ec_sortref, subquery_tlist);
893  Assert(tle);
894  /* Is TLE actually available to the outer query? */
895  outer_var = find_var_for_subquery_tle(rel, tle);
896  if (outer_var)
897  {
898  /* We can represent this sub_pathkey */
899  EquivalenceMember *sub_member;
900  EquivalenceClass *outer_ec;
901 
902  Assert(list_length(sub_eclass->ec_members) == 1);
903  sub_member = (EquivalenceMember *) linitial(sub_eclass->ec_members);
904 
905  /*
906  * Note: it might look funny to be setting sortref = 0 for a
907  * reference to a volatile sub_eclass. However, the
908  * expression is *not* volatile in the outer query: it's just
909  * a Var referencing whatever the subquery emitted. (IOW, the
910  * outer query isn't going to re-execute the volatile
911  * expression itself.) So this is okay. Likewise, it's
912  * correct to pass nullable_relids = NULL, because we're
913  * underneath any outer joins appearing in the outer query.
914  */
915  outer_ec =
917  (Expr *) outer_var,
918  NULL,
919  sub_eclass->ec_opfamilies,
920  sub_member->em_datatype,
921  sub_eclass->ec_collation,
922  0,
923  rel->relids,
924  false);
925 
926  /*
927  * If we don't find a matching EC, sub-pathkey isn't
928  * interesting to the outer query
929  */
930  if (outer_ec)
931  best_pathkey =
933  outer_ec,
934  sub_pathkey->pk_opfamily,
935  sub_pathkey->pk_strategy,
936  sub_pathkey->pk_nulls_first);
937  }
938  }
939  else
940  {
941  /*
942  * Otherwise, the sub_pathkey's EquivalenceClass could contain
943  * multiple elements (representing knowledge that multiple items
944  * are effectively equal). Each element might match none, one, or
945  * more of the output columns that are visible to the outer query.
946  * This means we may have multiple possible representations of the
947  * sub_pathkey in the context of the outer query. Ideally we
948  * would generate them all and put them all into an EC of the
949  * outer query, thereby propagating equality knowledge up to the
950  * outer query. Right now we cannot do so, because the outer
951  * query's EquivalenceClasses are already frozen when this is
952  * called. Instead we prefer the one that has the highest "score"
953  * (number of EC peers, plus one if it matches the outer
954  * query_pathkeys). This is the most likely to be useful in the
955  * outer query.
956  */
957  int best_score = -1;
958  ListCell *j;
959 
960  foreach(j, sub_eclass->ec_members)
961  {
962  EquivalenceMember *sub_member = (EquivalenceMember *) lfirst(j);
963  Expr *sub_expr = sub_member->em_expr;
964  Oid sub_expr_type = sub_member->em_datatype;
965  Oid sub_expr_coll = sub_eclass->ec_collation;
966  ListCell *k;
967 
968  if (sub_member->em_is_child)
969  continue; /* ignore children here */
970 
971  foreach(k, subquery_tlist)
972  {
973  TargetEntry *tle = (TargetEntry *) lfirst(k);
974  Var *outer_var;
975  Expr *tle_expr;
976  EquivalenceClass *outer_ec;
977  PathKey *outer_pk;
978  int score;
979 
980  /* Is TLE actually available to the outer query? */
981  outer_var = find_var_for_subquery_tle(rel, tle);
982  if (!outer_var)
983  continue;
984 
985  /*
986  * The targetlist entry is considered to match if it
987  * matches after sort-key canonicalization. That is
988  * needed since the sub_expr has been through the same
989  * process.
990  */
991  tle_expr = canonicalize_ec_expression(tle->expr,
992  sub_expr_type,
993  sub_expr_coll);
994  if (!equal(tle_expr, sub_expr))
995  continue;
996 
997  /* See if we have a matching EC for the TLE */
998  outer_ec = get_eclass_for_sort_expr(root,
999  (Expr *) outer_var,
1000  NULL,
1001  sub_eclass->ec_opfamilies,
1002  sub_expr_type,
1003  sub_expr_coll,
1004  0,
1005  rel->relids,
1006  false);
1007 
1008  /*
1009  * If we don't find a matching EC, this sub-pathkey isn't
1010  * interesting to the outer query
1011  */
1012  if (!outer_ec)
1013  continue;
1014 
1015  outer_pk = make_canonical_pathkey(root,
1016  outer_ec,
1017  sub_pathkey->pk_opfamily,
1018  sub_pathkey->pk_strategy,
1019  sub_pathkey->pk_nulls_first);
1020  /* score = # of equivalence peers */
1021  score = list_length(outer_ec->ec_members) - 1;
1022  /* +1 if it matches the proper query_pathkeys item */
1023  if (retvallen < outer_query_keys &&
1024  list_nth(root->query_pathkeys, retvallen) == outer_pk)
1025  score++;
1026  if (score > best_score)
1027  {
1028  best_pathkey = outer_pk;
1029  best_score = score;
1030  }
1031  }
1032  }
1033  }
1034 
1035  /*
1036  * If we couldn't find a representation of this sub_pathkey, we're
1037  * done (we can't use the ones to its right, either).
1038  */
1039  if (!best_pathkey)
1040  break;
1041 
1042  /*
1043  * Eliminate redundant ordering info; could happen if outer query
1044  * equivalences subquery keys...
1045  */
1046  if (!pathkey_is_redundant(best_pathkey, retval))
1047  {
1048  retval = lappend(retval, best_pathkey);
1049  retvallen++;
1050  }
1051  }
1052 
1053  return retval;
1054 }
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:225
EquivalenceClass * get_eclass_for_sort_expr(PlannerInfo *root, Expr *expr, Relids nullable_relids, List *opfamilies, Oid opcintype, Oid collation, Index sortref, Relids rel, bool create_it)
Definition: equivclass.c:621
Expr * canonicalize_ec_expression(Expr *expr, Oid req_type, Oid req_collation)
Definition: equivclass.c:500
int j
Definition: isn.c:74
static Var * find_var_for_subquery_tle(RelOptInfo *rel, TargetEntry *tle)
Definition: pathkeys.c:1066
PathKey * make_canonical_pathkey(PlannerInfo *root, EquivalenceClass *eclass, Oid opfamily, int strategy, bool nulls_first)
Definition: pathkeys.c:54
static int list_length(const List *l)
Definition: pg_list.h:150
static void * list_nth(const List *list, int n)
Definition: pg_list.h:297
List * ec_opfamilies
Definition: pathnodes.h:1284
bool pk_nulls_first
Definition: pathnodes.h:1370
int pk_strategy
Definition: pathnodes.h:1369
EquivalenceClass * pk_eclass
Definition: pathnodes.h:1367
Oid pk_opfamily
Definition: pathnodes.h:1368
List * query_pathkeys
Definition: pathnodes.h:369
Definition: primnodes.h:205
TargetEntry * get_sortgroupref_tle(Index sortref, List *targetList)
Definition: tlist.c:345

References Assert(), canonicalize_ec_expression(), EquivalenceClass::ec_collation, EquivalenceClass::ec_has_volatile, EquivalenceClass::ec_members, EquivalenceClass::ec_opfamilies, EquivalenceClass::ec_sortref, elog(), EquivalenceMember::em_datatype, EquivalenceMember::em_expr, EquivalenceMember::em_is_child, equal(), ERROR, TargetEntry::expr, find_var_for_subquery_tle(), get_eclass_for_sort_expr(), get_sortgroupref_tle(), i, j, lappend(), lfirst, linitial, list_length(), list_nth(), make_canonical_pathkey(), NIL, pathkey_is_redundant(), PathKey::pk_eclass, PathKey::pk_nulls_first, PathKey::pk_opfamily, PathKey::pk_strategy, PlannerInfo::query_pathkeys, and RelOptInfo::relids.

Referenced by set_subquery_pathlist().

◆ find_mergeclauses_for_outer_pathkeys()

List* find_mergeclauses_for_outer_pathkeys ( PlannerInfo root,
List pathkeys,
List restrictinfos 
)

Definition at line 1289 of file pathkeys.c.

1292 {
1293  List *mergeclauses = NIL;
1294  ListCell *i;
1295 
1296  /* make sure we have eclasses cached in the clauses */
1297  foreach(i, restrictinfos)
1298  {
1299  RestrictInfo *rinfo = (RestrictInfo *) lfirst(i);
1300 
1301  update_mergeclause_eclasses(root, rinfo);
1302  }
1303 
1304  foreach(i, pathkeys)
1305  {
1306  PathKey *pathkey = (PathKey *) lfirst(i);
1307  EquivalenceClass *pathkey_ec = pathkey->pk_eclass;
1308  List *matched_restrictinfos = NIL;
1309  ListCell *j;
1310 
1311  /*----------
1312  * A mergejoin clause matches a pathkey if it has the same EC.
1313  * If there are multiple matching clauses, take them all. In plain
1314  * inner-join scenarios we expect only one match, because
1315  * equivalence-class processing will have removed any redundant
1316  * mergeclauses. However, in outer-join scenarios there might be
1317  * multiple matches. An example is
1318  *
1319  * select * from a full join b
1320  * on a.v1 = b.v1 and a.v2 = b.v2 and a.v1 = b.v2;
1321  *
1322  * Given the pathkeys ({a.v1}, {a.v2}) it is okay to return all three
1323  * clauses (in the order a.v1=b.v1, a.v1=b.v2, a.v2=b.v2) and indeed
1324  * we *must* do so or we will be unable to form a valid plan.
1325  *
1326  * We expect that the given pathkeys list is canonical, which means
1327  * no two members have the same EC, so it's not possible for this
1328  * code to enter the same mergeclause into the result list twice.
1329  *
1330  * It's possible that multiple matching clauses might have different
1331  * ECs on the other side, in which case the order we put them into our
1332  * result makes a difference in the pathkeys required for the inner
1333  * input rel. However this routine hasn't got any info about which
1334  * order would be best, so we don't worry about that.
1335  *
1336  * It's also possible that the selected mergejoin clauses produce
1337  * a noncanonical ordering of pathkeys for the inner side, ie, we
1338  * might select clauses that reference b.v1, b.v2, b.v1 in that
1339  * order. This is not harmful in itself, though it suggests that
1340  * the clauses are partially redundant. Since the alternative is
1341  * to omit mergejoin clauses and thereby possibly fail to generate a
1342  * plan altogether, we live with it. make_inner_pathkeys_for_merge()
1343  * has to delete duplicates when it constructs the inner pathkeys
1344  * list, and we also have to deal with such cases specially in
1345  * create_mergejoin_plan().
1346  *----------
1347  */
1348  foreach(j, restrictinfos)
1349  {
1350  RestrictInfo *rinfo = (RestrictInfo *) lfirst(j);
1351  EquivalenceClass *clause_ec;
1352 
1353  clause_ec = rinfo->outer_is_left ?
1354  rinfo->left_ec : rinfo->right_ec;
1355  if (clause_ec == pathkey_ec)
1356  matched_restrictinfos = lappend(matched_restrictinfos, rinfo);
1357  }
1358 
1359  /*
1360  * If we didn't find a mergeclause, we're done --- any additional
1361  * sort-key positions in the pathkeys are useless. (But we can still
1362  * mergejoin if we found at least one mergeclause.)
1363  */
1364  if (matched_restrictinfos == NIL)
1365  break;
1366 
1367  /*
1368  * If we did find usable mergeclause(s) for this sort-key position,
1369  * add them to result list.
1370  */
1371  mergeclauses = list_concat(mergeclauses, matched_restrictinfos);
1372  }
1373 
1374  return mergeclauses;
1375 }
List * list_concat(List *list1, const List *list2)
Definition: list.c:560
void update_mergeclause_eclasses(PlannerInfo *root, RestrictInfo *restrictinfo)
Definition: pathkeys.c:1255

References i, j, lappend(), lfirst, list_concat(), NIL, PathKey::pk_eclass, and update_mergeclause_eclasses().

Referenced by generate_mergejoin_paths(), and sort_inner_and_outer().

◆ find_var_for_subquery_tle()

static Var * find_var_for_subquery_tle ( RelOptInfo rel,
TargetEntry tle 
)
static

Definition at line 1066 of file pathkeys.c.

1067 {
1068  ListCell *lc;
1069 
1070  /* If the TLE is resjunk, it's certainly not visible to the outer query */
1071  if (tle->resjunk)
1072  return NULL;
1073 
1074  /* Search the rel's targetlist to see what it will return */
1075  foreach(lc, rel->reltarget->exprs)
1076  {
1077  Var *var = (Var *) lfirst(lc);
1078 
1079  /* Ignore placeholders */
1080  if (!IsA(var, Var))
1081  continue;
1082  Assert(var->varno == rel->relid);
1083 
1084  /* If we find a Var referencing this TLE, we're good */
1085  if (var->varattno == tle->resno)
1086  return copyObject(var); /* Make a copy for safety */
1087  }
1088  return NULL;
1089 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:162
#define copyObject(obj)
Definition: nodes.h:227
List * exprs
Definition: pathnodes.h:1415
struct PathTarget * reltarget
Definition: pathnodes.h:837
Index relid
Definition: pathnodes.h:862
AttrNumber resno
Definition: primnodes.h:1556
bool resjunk
Definition: primnodes.h:1562
AttrNumber varattno
Definition: primnodes.h:217
int varno
Definition: primnodes.h:212

References Assert(), copyObject, PathTarget::exprs, IsA, lfirst, RelOptInfo::relid, RelOptInfo::reltarget, TargetEntry::resjunk, TargetEntry::resno, Var::varattno, and Var::varno.

Referenced by convert_subquery_pathkeys().

◆ get_cheapest_fractional_path_for_pathkeys()

Path* get_cheapest_fractional_path_for_pathkeys ( List paths,
List pathkeys,
Relids  required_outer,
double  fraction 
)

Definition at line 471 of file pathkeys.c.

475 {
476  Path *matched_path = NULL;
477  ListCell *l;
478 
479  foreach(l, paths)
480  {
481  Path *path = (Path *) lfirst(l);
482 
483  /*
484  * Since cost comparison is a lot cheaper than pathkey comparison, do
485  * that first. (XXX is that still true?)
486  */
487  if (matched_path != NULL &&
488  compare_fractional_path_costs(matched_path, path, fraction) <= 0)
489  continue;
490 
491  if (pathkeys_contained_in(pathkeys, path->pathkeys) &&
492  bms_is_subset(PATH_REQ_OUTER(path), required_outer))
493  matched_path = path;
494  }
495  return matched_path;
496 }
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:316
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:346
int compare_fractional_path_costs(Path *path1, Path *path2, double fraction)
Definition: pathnode.c:117
#define PATH_REQ_OUTER(path)
Definition: pathnodes.h:1544
List * pathkeys
Definition: pathnodes.h:1540

References bms_is_subset(), compare_fractional_path_costs(), lfirst, PATH_REQ_OUTER, Path::pathkeys, and pathkeys_contained_in().

Referenced by build_minmax_path(), and generate_orderedappend_paths().

◆ get_cheapest_parallel_safe_total_inner()

Path* get_cheapest_parallel_safe_total_inner ( List paths)

Definition at line 504 of file pathkeys.c.

505 {
506  ListCell *l;
507 
508  foreach(l, paths)
509  {
510  Path *innerpath = (Path *) lfirst(l);
511 
512  if (innerpath->parallel_safe &&
513  bms_is_empty(PATH_REQ_OUTER(innerpath)))
514  return innerpath;
515  }
516 
517  return NULL;
518 }
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:704
bool parallel_safe
Definition: pathnodes.h:1530

References bms_is_empty(), lfirst, Path::parallel_safe, and PATH_REQ_OUTER.

Referenced by add_paths_to_append_rel(), hash_inner_and_outer(), match_unsorted_outer(), and sort_inner_and_outer().

◆ get_cheapest_path_for_pathkeys()

Path* get_cheapest_path_for_pathkeys ( List paths,
List pathkeys,
Relids  required_outer,
CostSelector  cost_criterion,
bool  require_parallel_safe 
)

Definition at line 426 of file pathkeys.c.

430 {
431  Path *matched_path = NULL;
432  ListCell *l;
433 
434  foreach(l, paths)
435  {
436  Path *path = (Path *) lfirst(l);
437 
438  /*
439  * Since cost comparison is a lot cheaper than pathkey comparison, do
440  * that first. (XXX is that still true?)
441  */
442  if (matched_path != NULL &&
443  compare_path_costs(matched_path, path, cost_criterion) <= 0)
444  continue;
445 
446  if (require_parallel_safe && !path->parallel_safe)
447  continue;
448 
449  if (pathkeys_contained_in(pathkeys, path->pathkeys) &&
450  bms_is_subset(PATH_REQ_OUTER(path), required_outer))
451  matched_path = path;
452  }
453  return matched_path;
454 }
int compare_path_costs(Path *path1, Path *path2, CostSelector criterion)
Definition: pathnode.c:71

References bms_is_subset(), compare_path_costs(), lfirst, Path::parallel_safe, PATH_REQ_OUTER, Path::pathkeys, and pathkeys_contained_in().

Referenced by generate_mergejoin_paths(), generate_orderedappend_paths(), and get_cheapest_parameterized_child_path().

◆ has_useful_pathkeys()

bool has_useful_pathkeys ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 1963 of file pathkeys.c.

1964 {
1965  if (rel->joininfo != NIL || rel->has_eclass_joins)
1966  return true; /* might be able to use pathkeys for merging */
1967  if (root->query_pathkeys != NIL)
1968  return true; /* might be able to use them for ordering */
1969  return false; /* definitely useless */
1970 }
List * joininfo
Definition: pathnodes.h:930
bool has_eclass_joins
Definition: pathnodes.h:932

References RelOptInfo::has_eclass_joins, RelOptInfo::joininfo, NIL, and PlannerInfo::query_pathkeys.

Referenced by build_child_join_rel(), build_index_paths(), and set_append_rel_size().

◆ initialize_mergeclause_eclasses()

void initialize_mergeclause_eclasses ( PlannerInfo root,
RestrictInfo restrictinfo 
)

Definition at line 1206 of file pathkeys.c.

1207 {
1208  Expr *clause = restrictinfo->clause;
1209  Oid lefttype,
1210  righttype;
1211 
1212  /* Should be a mergeclause ... */
1213  Assert(restrictinfo->mergeopfamilies != NIL);
1214  /* ... with links not yet set */
1215  Assert(restrictinfo->left_ec == NULL);
1216  Assert(restrictinfo->right_ec == NULL);
1217 
1218  /* Need the declared input types of the operator */
1219  op_input_types(((OpExpr *) clause)->opno, &lefttype, &righttype);
1220 
1221  /* Find or create a matching EquivalenceClass for each side */
1222  restrictinfo->left_ec =
1224  (Expr *) get_leftop(clause),
1225  restrictinfo->nullable_relids,
1226  restrictinfo->mergeopfamilies,
1227  lefttype,
1228  ((OpExpr *) clause)->inputcollid,
1229  0,
1230  NULL,
1231  true);
1232  restrictinfo->right_ec =
1234  (Expr *) get_rightop(clause),
1235  restrictinfo->nullable_relids,
1236  restrictinfo->mergeopfamilies,
1237  righttype,
1238  ((OpExpr *) clause)->inputcollid,
1239  0,
1240  NULL,
1241  true);
1242 }
void op_input_types(Oid opno, Oid *lefttype, Oid *righttype)
Definition: lsyscache.c:1340
static Node * get_rightop(const void *clause)
Definition: nodeFuncs.h:93
static Node * get_leftop(const void *clause)
Definition: nodeFuncs.h:81
Relids nullable_relids
Definition: pathnodes.h:2456
Expr * clause
Definition: pathnodes.h:2423

References Assert(), RestrictInfo::clause, get_eclass_for_sort_expr(), get_leftop(), get_rightop(), NIL, RestrictInfo::nullable_relids, and op_input_types().

Referenced by distribute_qual_to_rels().

◆ make_canonical_pathkey()

PathKey* make_canonical_pathkey ( PlannerInfo root,
EquivalenceClass eclass,
Oid  opfamily,
int  strategy,
bool  nulls_first 
)

Definition at line 54 of file pathkeys.c.

57 {
58  PathKey *pk;
59  ListCell *lc;
60  MemoryContext oldcontext;
61 
62  /* Can't make canonical pathkeys if the set of ECs might still change */
63  if (!root->ec_merging_done)
64  elog(ERROR, "too soon to build canonical pathkeys");
65 
66  /* The passed eclass might be non-canonical, so chase up to the top */
67  while (eclass->ec_merged)
68  eclass = eclass->ec_merged;
69 
70  foreach(lc, root->canon_pathkeys)
71  {
72  pk = (PathKey *) lfirst(lc);
73  if (eclass == pk->pk_eclass &&
74  opfamily == pk->pk_opfamily &&
75  strategy == pk->pk_strategy &&
76  nulls_first == pk->pk_nulls_first)
77  return pk;
78  }
79 
80  /*
81  * Be sure canonical pathkeys are allocated in the main planning context.
82  * Not an issue in normal planning, but it is for GEQO.
83  */
84  oldcontext = MemoryContextSwitchTo(root->planner_cxt);
85 
86  pk = makeNode(PathKey);
87  pk->pk_eclass = eclass;
88  pk->pk_opfamily = opfamily;
89  pk->pk_strategy = strategy;
90  pk->pk_nulls_first = nulls_first;
91 
92  root->canon_pathkeys = lappend(root->canon_pathkeys, pk);
93 
94  MemoryContextSwitchTo(oldcontext);
95 
96  return pk;
97 }
#define makeNode(_type_)
Definition: nodes.h:159
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:135
static struct cvec * eclass(struct vars *v, chr c, int cases)
Definition: regc_locale.c:504
List * canon_pathkeys
Definition: pathnodes.h:307
bool ec_merging_done
Definition: pathnodes.h:304

References PlannerInfo::canon_pathkeys, PlannerInfo::ec_merging_done, eclass(), elog(), ERROR, lappend(), lfirst, makeNode, MemoryContextSwitchTo(), PathKey::pk_eclass, PathKey::pk_nulls_first, PathKey::pk_opfamily, and PathKey::pk_strategy.

Referenced by convert_subquery_pathkeys(), get_useful_pathkeys_for_relation(), make_inner_pathkeys_for_merge(), make_pathkey_from_sortinfo(), and select_outer_pathkeys_for_merge().

◆ make_inner_pathkeys_for_merge()

List* make_inner_pathkeys_for_merge ( PlannerInfo root,
List mergeclauses,
List outer_pathkeys 
)

Definition at line 1600 of file pathkeys.c.

1603 {
1604  List *pathkeys = NIL;
1605  EquivalenceClass *lastoeclass;
1606  PathKey *opathkey;
1607  ListCell *lc;
1608  ListCell *lop;
1609 
1610  lastoeclass = NULL;
1611  opathkey = NULL;
1612  lop = list_head(outer_pathkeys);
1613 
1614  foreach(lc, mergeclauses)
1615  {
1616  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1617  EquivalenceClass *oeclass;
1618  EquivalenceClass *ieclass;
1619  PathKey *pathkey;
1620 
1621  update_mergeclause_eclasses(root, rinfo);
1622 
1623  if (rinfo->outer_is_left)
1624  {
1625  oeclass = rinfo->left_ec;
1626  ieclass = rinfo->right_ec;
1627  }
1628  else
1629  {
1630  oeclass = rinfo->right_ec;
1631  ieclass = rinfo->left_ec;
1632  }
1633 
1634  /* outer eclass should match current or next pathkeys */
1635  /* we check this carefully for debugging reasons */
1636  if (oeclass != lastoeclass)
1637  {
1638  if (!lop)
1639  elog(ERROR, "too few pathkeys for mergeclauses");
1640  opathkey = (PathKey *) lfirst(lop);
1641  lop = lnext(outer_pathkeys, lop);
1642  lastoeclass = opathkey->pk_eclass;
1643  if (oeclass != lastoeclass)
1644  elog(ERROR, "outer pathkeys do not match mergeclause");
1645  }
1646 
1647  /*
1648  * Often, we'll have same EC on both sides, in which case the outer
1649  * pathkey is also canonical for the inner side, and we can skip a
1650  * useless search.
1651  */
1652  if (ieclass == oeclass)
1653  pathkey = opathkey;
1654  else
1655  pathkey = make_canonical_pathkey(root,
1656  ieclass,
1657  opathkey->pk_opfamily,
1658  opathkey->pk_strategy,
1659  opathkey->pk_nulls_first);
1660 
1661  /*
1662  * Don't generate redundant pathkeys (which can happen if multiple
1663  * mergeclauses refer to the same EC). Because we do this, the output
1664  * pathkey list isn't necessarily ordered like the mergeclauses, which
1665  * complicates life for create_mergejoin_plan(). But if we didn't,
1666  * we'd have a noncanonical sort key list, which would be bad; for one
1667  * reason, it certainly wouldn't match any available sort order for
1668  * the input relation.
1669  */
1670  if (!pathkey_is_redundant(pathkey, pathkeys))
1671  pathkeys = lappend(pathkeys, pathkey);
1672  }
1673 
1674  return pathkeys;
1675 }
static ListCell * list_head(const List *l)
Definition: pg_list.h:126
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:341

References elog(), ERROR, lappend(), lfirst, list_head(), lnext(), make_canonical_pathkey(), NIL, pathkey_is_redundant(), PathKey::pk_eclass, PathKey::pk_nulls_first, PathKey::pk_opfamily, PathKey::pk_strategy, and update_mergeclause_eclasses().

Referenced by generate_mergejoin_paths(), and sort_inner_and_outer().

◆ make_pathkey_from_sortinfo()

static PathKey* make_pathkey_from_sortinfo ( PlannerInfo root,
Expr expr,
Relids  nullable_relids,
Oid  opfamily,
Oid  opcintype,
Oid  collation,
bool  reverse_sort,
bool  nulls_first,
Index  sortref,
Relids  rel,
bool  create_it 
)
static

Definition at line 199 of file pathkeys.c.

210 {
211  int16 strategy;
212  Oid equality_op;
213  List *opfamilies;
215 
216  strategy = reverse_sort ? BTGreaterStrategyNumber : BTLessStrategyNumber;
217 
218  /*
219  * EquivalenceClasses need to contain opfamily lists based on the family
220  * membership of mergejoinable equality operators, which could belong to
221  * more than one opfamily. So we have to look up the opfamily's equality
222  * operator and get its membership.
223  */
224  equality_op = get_opfamily_member(opfamily,
225  opcintype,
226  opcintype,
228  if (!OidIsValid(equality_op)) /* shouldn't happen */
229  elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
230  BTEqualStrategyNumber, opcintype, opcintype, opfamily);
231  opfamilies = get_mergejoin_opfamilies(equality_op);
232  if (!opfamilies) /* certainly should find some */
233  elog(ERROR, "could not find opfamilies for equality operator %u",
234  equality_op);
235 
236  /* Now find or (optionally) create a matching EquivalenceClass */
237  eclass = get_eclass_for_sort_expr(root, expr, nullable_relids,
238  opfamilies, opcintype, collation,
239  sortref, rel, create_it);
240 
241  /* Fail if no EC and !create_it */
242  if (!eclass)
243  return NULL;
244 
245  /* And finally we can find or create a PathKey node */
246  return make_canonical_pathkey(root, eclass, opfamily,
247  strategy, nulls_first);
248 }
#define OidIsValid(objectId)
Definition: c.h:711
List * get_mergejoin_opfamilies(Oid opno)
Definition: lsyscache.c:365
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:165
#define BTLessStrategyNumber
Definition: stratnum.h:29
#define BTEqualStrategyNumber
Definition: stratnum.h:31

References BTEqualStrategyNumber, BTGreaterStrategyNumber, BTLessStrategyNumber, eclass(), elog(), ERROR, get_eclass_for_sort_expr(), get_mergejoin_opfamilies(), get_opfamily_member(), make_canonical_pathkey(), and OidIsValid.

Referenced by build_expression_pathkey(), build_index_pathkeys(), build_partition_pathkeys(), and make_pathkey_from_sortop().

◆ make_pathkey_from_sortop()

static PathKey* make_pathkey_from_sortop ( PlannerInfo root,
Expr expr,
Relids  nullable_relids,
Oid  ordering_op,
bool  nulls_first,
Index  sortref,
bool  create_it 
)
static

Definition at line 258 of file pathkeys.c.

265 {
266  Oid opfamily,
267  opcintype,
268  collation;
269  int16 strategy;
270 
271  /* Find the operator in pg_amop --- failure shouldn't happen */
272  if (!get_ordering_op_properties(ordering_op,
273  &opfamily, &opcintype, &strategy))
274  elog(ERROR, "operator %u is not a valid ordering operator",
275  ordering_op);
276 
277  /* Because SortGroupClause doesn't carry collation, consult the expr */
278  collation = exprCollation((Node *) expr);
279 
280  return make_pathkey_from_sortinfo(root,
281  expr,
282  nullable_relids,
283  opfamily,
284  opcintype,
285  collation,
286  (strategy == BTGreaterStrategyNumber),
287  nulls_first,
288  sortref,
289  NULL,
290  create_it);
291 }

References BTGreaterStrategyNumber, elog(), ERROR, exprCollation(), get_ordering_op_properties(), and make_pathkey_from_sortinfo().

Referenced by make_pathkeys_for_sortclauses().

◆ make_pathkeys_for_sortclauses()

List* make_pathkeys_for_sortclauses ( PlannerInfo root,
List sortclauses,
List tlist 
)

Definition at line 1152 of file pathkeys.c.

1155 {
1156  List *pathkeys = NIL;
1157  ListCell *l;
1158 
1159  foreach(l, sortclauses)
1160  {
1161  SortGroupClause *sortcl = (SortGroupClause *) lfirst(l);
1162  Expr *sortkey;
1163  PathKey *pathkey;
1164 
1165  sortkey = (Expr *) get_sortgroupclause_expr(sortcl, tlist);
1166  Assert(OidIsValid(sortcl->sortop));
1167  pathkey = make_pathkey_from_sortop(root,
1168  sortkey,
1169  root->nullable_baserels,
1170  sortcl->sortop,
1171  sortcl->nulls_first,
1172  sortcl->tleSortGroupRef,
1173  true);
1174 
1175  /* Canonical form eliminates redundant ordering keys */
1176  if (!pathkey_is_redundant(pathkey, pathkeys))
1177  pathkeys = lappend(pathkeys, pathkey);
1178  }
1179  return pathkeys;
1180 }
static PathKey * make_pathkey_from_sortop(PlannerInfo *root, Expr *expr, Relids nullable_relids, Oid ordering_op, bool nulls_first, Index sortref, bool create_it)
Definition: pathkeys.c:258
Relids nullable_baserels
Definition: pathnodes.h:259
Index tleSortGroupRef
Definition: parsenodes.h:1320
Node * get_sortgroupclause_expr(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:379

References Assert(), get_sortgroupclause_expr(), lappend(), lfirst, make_pathkey_from_sortop(), NIL, PlannerInfo::nullable_baserels, SortGroupClause::nulls_first, OidIsValid, pathkey_is_redundant(), SortGroupClause::sortop, and SortGroupClause::tleSortGroupRef.

Referenced by generate_nonunion_paths(), grouping_planner(), make_pathkeys_for_groupagg(), make_pathkeys_for_window(), make_union_unique(), minmax_qp_callback(), and standard_qp_callback().

◆ matches_boolean_partition_clause()

static bool matches_boolean_partition_clause ( RestrictInfo rinfo,
RelOptInfo partrel,
int  partkeycol 
)
static

Definition at line 691 of file pathkeys.c.

693 {
694  Node *clause = (Node *) rinfo->clause;
695  Node *partexpr = (Node *) linitial(partrel->partexprs[partkeycol]);
696 
697  /* Direct match? */
698  if (equal(partexpr, clause))
699  return true;
700  /* NOT clause? */
701  else if (is_notclause(clause))
702  {
703  Node *arg = (Node *) get_notclausearg((Expr *) clause);
704 
705  if (equal(partexpr, arg))
706  return true;
707  }
708 
709  return false;
710 }
static Expr * get_notclausearg(const void *notclause)
Definition: nodeFuncs.h:132
static bool is_notclause(const void *clause)
Definition: nodeFuncs.h:123
void * arg

References arg, RestrictInfo::clause, equal(), get_notclausearg(), is_notclause(), and linitial.

Referenced by partkey_is_bool_constant_for_query().

◆ partkey_is_bool_constant_for_query()

static bool partkey_is_bool_constant_for_query ( RelOptInfo partrel,
int  partkeycol 
)
static

Definition at line 651 of file pathkeys.c.

652 {
653  PartitionScheme partscheme = partrel->part_scheme;
654  ListCell *lc;
655 
656  /*
657  * If the partkey isn't boolean, we can't possibly get a match.
658  *
659  * Partitioning currently can only use built-in AMs, so checking for
660  * built-in boolean opfamilies is good enough.
661  */
662  if (!IsBuiltinBooleanOpfamily(partscheme->partopfamily[partkeycol]))
663  return false;
664 
665  /* Check each restriction clause for the partitioned rel */
666  foreach(lc, partrel->baserestrictinfo)
667  {
668  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
669 
670  /* Ignore pseudoconstant quals, they won't match */
671  if (rinfo->pseudoconstant)
672  continue;
673 
674  /* See if we can match the clause's expression to the partkey column */
675  if (matches_boolean_partition_clause(rinfo, partrel, partkeycol))
676  return true;
677  }
678 
679  return false;
680 }
static bool matches_boolean_partition_clause(RestrictInfo *rinfo, RelOptInfo *partrel, int partkeycol)
Definition: pathkeys.c:691
List * baserestrictinfo
Definition: pathnodes.h:924

References RelOptInfo::baserestrictinfo, lfirst, matches_boolean_partition_clause(), and PartitionSchemeData::partopfamily.

Referenced by build_partition_pathkeys().

◆ pathkey_is_redundant()

static bool pathkey_is_redundant ( PathKey new_pathkey,
List pathkeys 
)
static

Definition at line 157 of file pathkeys.c.

158 {
159  EquivalenceClass *new_ec = new_pathkey->pk_eclass;
160  ListCell *lc;
161 
162  /* Check for EC containing a constant --- unconditionally redundant */
163  if (EC_MUST_BE_REDUNDANT(new_ec))
164  return true;
165 
166  /* If same EC already used in list, then redundant */
167  foreach(lc, pathkeys)
168  {
169  PathKey *old_pathkey = (PathKey *) lfirst(lc);
170 
171  if (new_ec == old_pathkey->pk_eclass)
172  return true;
173  }
174 
175  return false;
176 }
#define EC_MUST_BE_REDUNDANT(eclass)
Definition: pathnodes.h:1305

References EC_MUST_BE_REDUNDANT, lfirst, and PathKey::pk_eclass.

Referenced by append_pathkeys(), build_index_pathkeys(), build_partition_pathkeys(), convert_subquery_pathkeys(), make_inner_pathkeys_for_merge(), make_pathkeys_for_sortclauses(), and select_outer_pathkeys_for_merge().

◆ pathkeys_contained_in()

◆ pathkeys_count_contained_in()

bool pathkeys_count_contained_in ( List keys1,
List keys2,
int *  n_common 
)

Definition at line 365 of file pathkeys.c.

366 {
367  int n = 0;
368  ListCell *key1,
369  *key2;
370 
371  /*
372  * See if we can avoiding looping through both lists. This optimization
373  * gains us several percent in planning time in a worst-case test.
374  */
375  if (keys1 == keys2)
376  {
377  *n_common = list_length(keys1);
378  return true;
379  }
380  else if (keys1 == NIL)
381  {
382  *n_common = 0;
383  return true;
384  }
385  else if (keys2 == NIL)
386  {
387  *n_common = 0;
388  return false;
389  }
390 
391  /*
392  * If both lists are non-empty, iterate through both to find out how many
393  * items are shared.
394  */
395  forboth(key1, keys1, key2, keys2)
396  {
397  PathKey *pathkey1 = (PathKey *) lfirst(key1);
398  PathKey *pathkey2 = (PathKey *) lfirst(key2);
399 
400  if (pathkey1 != pathkey2)
401  {
402  *n_common = n;
403  return false;
404  }
405  n++;
406  }
407 
408  /* If we ended with a null value, then we've processed the whole list. */
409  *n_common = n;
410  return (key1 == NULL);
411 }

References forboth, lfirst, list_length(), and NIL.

Referenced by add_paths_to_grouping_rel(), create_one_window_path(), create_ordered_paths(), create_partial_grouping_paths(), create_window_paths(), gather_grouping_paths(), generate_useful_gather_paths(), and pathkeys_useful_for_ordering().

◆ pathkeys_useful_for_merging()

static int pathkeys_useful_for_merging ( PlannerInfo root,
RelOptInfo rel,
List pathkeys 
)
static

Definition at line 1798 of file pathkeys.c.

1799 {
1800  int useful = 0;
1801  ListCell *i;
1802 
1803  foreach(i, pathkeys)
1804  {
1805  PathKey *pathkey = (PathKey *) lfirst(i);
1806  bool matched = false;
1807  ListCell *j;
1808 
1809  /* If "wrong" direction, not useful for merging */
1810  if (!right_merge_direction(root, pathkey))
1811  break;
1812 
1813  /*
1814  * First look into the EquivalenceClass of the pathkey, to see if
1815  * there are any members not yet joined to the rel. If so, it's
1816  * surely possible to generate a mergejoin clause using them.
1817  */
1818  if (rel->has_eclass_joins &&
1819  eclass_useful_for_merging(root, pathkey->pk_eclass, rel))
1820  matched = true;
1821  else
1822  {
1823  /*
1824  * Otherwise search the rel's joininfo list, which contains
1825  * non-EquivalenceClass-derivable join clauses that might
1826  * nonetheless be mergejoinable.
1827  */
1828  foreach(j, rel->joininfo)
1829  {
1830  RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(j);
1831 
1832  if (restrictinfo->mergeopfamilies == NIL)
1833  continue;
1834  update_mergeclause_eclasses(root, restrictinfo);
1835 
1836  if (pathkey->pk_eclass == restrictinfo->left_ec ||
1837  pathkey->pk_eclass == restrictinfo->right_ec)
1838  {
1839  matched = true;
1840  break;
1841  }
1842  }
1843  }
1844 
1845  /*
1846  * If we didn't find a mergeclause, we're done --- any additional
1847  * sort-key positions in the pathkeys are useless. (But we can still
1848  * mergejoin if we found at least one mergeclause.)
1849  */
1850  if (matched)
1851  useful++;
1852  else
1853  break;
1854  }
1855 
1856  return useful;
1857 }
bool eclass_useful_for_merging(PlannerInfo *root, EquivalenceClass *eclass, RelOptInfo *rel)
Definition: equivclass.c:3074
static bool right_merge_direction(PlannerInfo *root, PathKey *pathkey)
Definition: pathkeys.c:1865

References eclass_useful_for_merging(), RelOptInfo::has_eclass_joins, i, j, RelOptInfo::joininfo, lfirst, NIL, PathKey::pk_eclass, right_merge_direction(), and update_mergeclause_eclasses().

Referenced by truncate_useless_pathkeys().

◆ pathkeys_useful_for_ordering()

static int pathkeys_useful_for_ordering ( PlannerInfo root,
List pathkeys 
)
static

Definition at line 1902 of file pathkeys.c.

1903 {
1904  int n_common_pathkeys;
1905 
1906  if (root->query_pathkeys == NIL)
1907  return 0; /* no special ordering requested */
1908 
1909  if (pathkeys == NIL)
1910  return 0; /* unordered path */
1911 
1912  (void) pathkeys_count_contained_in(root->query_pathkeys, pathkeys,
1913  &n_common_pathkeys);
1914 
1915  return n_common_pathkeys;
1916 }
bool pathkeys_count_contained_in(List *keys1, List *keys2, int *n_common)
Definition: pathkeys.c:365

References NIL, pathkeys_count_contained_in(), and PlannerInfo::query_pathkeys.

Referenced by truncate_useless_pathkeys().

◆ right_merge_direction()

static bool right_merge_direction ( PlannerInfo root,
PathKey pathkey 
)
static

Definition at line 1865 of file pathkeys.c.

1866 {
1867  ListCell *l;
1868 
1869  foreach(l, root->query_pathkeys)
1870  {
1871  PathKey *query_pathkey = (PathKey *) lfirst(l);
1872 
1873  if (pathkey->pk_eclass == query_pathkey->pk_eclass &&
1874  pathkey->pk_opfamily == query_pathkey->pk_opfamily)
1875  {
1876  /*
1877  * Found a matching query sort column. Prefer this pathkey's
1878  * direction iff it matches. Note that we ignore pk_nulls_first,
1879  * which means that a sort might be needed anyway ... but we still
1880  * want to prefer only one of the two possible directions, and we
1881  * might as well use this one.
1882  */
1883  return (pathkey->pk_strategy == query_pathkey->pk_strategy);
1884  }
1885  }
1886 
1887  /* If no matching ORDER BY request, prefer the ASC direction */
1888  return (pathkey->pk_strategy == BTLessStrategyNumber);
1889 }

References BTLessStrategyNumber, lfirst, PathKey::pk_eclass, PathKey::pk_opfamily, PathKey::pk_strategy, and PlannerInfo::query_pathkeys.

Referenced by pathkeys_useful_for_merging().

◆ select_outer_pathkeys_for_merge()

List* select_outer_pathkeys_for_merge ( PlannerInfo root,
List mergeclauses,
RelOptInfo joinrel 
)

Definition at line 1404 of file pathkeys.c.

1407 {
1408  List *pathkeys = NIL;
1409  int nClauses = list_length(mergeclauses);
1410  EquivalenceClass **ecs;
1411  int *scores;
1412  int necs;
1413  ListCell *lc;
1414  int j;
1415 
1416  /* Might have no mergeclauses */
1417  if (nClauses == 0)
1418  return NIL;
1419 
1420  /*
1421  * Make arrays of the ECs used by the mergeclauses (dropping any
1422  * duplicates) and their "popularity" scores.
1423  */
1424  ecs = (EquivalenceClass **) palloc(nClauses * sizeof(EquivalenceClass *));
1425  scores = (int *) palloc(nClauses * sizeof(int));
1426  necs = 0;
1427 
1428  foreach(lc, mergeclauses)
1429  {
1430  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1431  EquivalenceClass *oeclass;
1432  int score;
1433  ListCell *lc2;
1434 
1435  /* get the outer eclass */
1436  update_mergeclause_eclasses(root, rinfo);
1437 
1438  if (rinfo->outer_is_left)
1439  oeclass = rinfo->left_ec;
1440  else
1441  oeclass = rinfo->right_ec;
1442 
1443  /* reject duplicates */
1444  for (j = 0; j < necs; j++)
1445  {
1446  if (ecs[j] == oeclass)
1447  break;
1448  }
1449  if (j < necs)
1450  continue;
1451 
1452  /* compute score */
1453  score = 0;
1454  foreach(lc2, oeclass->ec_members)
1455  {
1457 
1458  /* Potential future join partner? */
1459  if (!em->em_is_const && !em->em_is_child &&
1460  !bms_overlap(em->em_relids, joinrel->relids))
1461  score++;
1462  }
1463 
1464  ecs[necs] = oeclass;
1465  scores[necs] = score;
1466  necs++;
1467  }
1468 
1469  /*
1470  * Find out if we have all the ECs mentioned in query_pathkeys; if so we
1471  * can generate a sort order that's also useful for final output. If we
1472  * only have a prefix of the query_pathkeys, and that prefix is the entire
1473  * join condition, then it's useful to use the prefix as the pathkeys as
1474  * this increases the chances that an incremental sort will be able to be
1475  * used by the upper planner.
1476  */
1477  if (root->query_pathkeys)
1478  {
1479  int matches = 0;
1480 
1481  foreach(lc, root->query_pathkeys)
1482  {
1483  PathKey *query_pathkey = (PathKey *) lfirst(lc);
1484  EquivalenceClass *query_ec = query_pathkey->pk_eclass;
1485 
1486  for (j = 0; j < necs; j++)
1487  {
1488  if (ecs[j] == query_ec)
1489  break; /* found match */
1490  }
1491  if (j >= necs)
1492  break; /* didn't find match */
1493 
1494  matches++;
1495  }
1496  /* if we got to the end of the list, we have them all */
1497  if (lc == NULL)
1498  {
1499  /* copy query_pathkeys as starting point for our output */
1500  pathkeys = list_copy(root->query_pathkeys);
1501  /* mark their ECs as already-emitted */
1502  foreach(lc, root->query_pathkeys)
1503  {
1504  PathKey *query_pathkey = (PathKey *) lfirst(lc);
1505  EquivalenceClass *query_ec = query_pathkey->pk_eclass;
1506 
1507  for (j = 0; j < necs; j++)
1508  {
1509  if (ecs[j] == query_ec)
1510  {
1511  scores[j] = -1;
1512  break;
1513  }
1514  }
1515  }
1516  }
1517 
1518  /*
1519  * If we didn't match to all of the query_pathkeys, but did match to
1520  * all of the join clauses then we'll make use of these as partially
1521  * sorted input is better than nothing for the upper planner as it may
1522  * lead to incremental sorts instead of full sorts.
1523  */
1524  else if (matches == nClauses)
1525  {
1526  pathkeys = list_copy_head(root->query_pathkeys, matches);
1527 
1528  /* we have all of the join pathkeys, so nothing more to do */
1529  pfree(ecs);
1530  pfree(scores);
1531 
1532  return pathkeys;
1533  }
1534  }
1535 
1536  /*
1537  * Add remaining ECs to the list in popularity order, using a default sort
1538  * ordering. (We could use qsort() here, but the list length is usually
1539  * so small it's not worth it.)
1540  */
1541  for (;;)
1542  {
1543  int best_j;
1544  int best_score;
1545  EquivalenceClass *ec;
1546  PathKey *pathkey;
1547 
1548  best_j = 0;
1549  best_score = scores[0];
1550  for (j = 1; j < necs; j++)
1551  {
1552  if (scores[j] > best_score)
1553  {
1554  best_j = j;
1555  best_score = scores[j];
1556  }
1557  }
1558  if (best_score < 0)
1559  break; /* all done */
1560  ec = ecs[best_j];
1561  scores[best_j] = -1;
1562  pathkey = make_canonical_pathkey(root,
1563  ec,
1566  false);
1567  /* can't be redundant because no duplicate ECs */
1568  Assert(!pathkey_is_redundant(pathkey, pathkeys));
1569  pathkeys = lappend(pathkeys, pathkey);
1570  }
1571 
1572  pfree(ecs);
1573  pfree(scores);
1574 
1575  return pathkeys;
1576 }
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:495
List * list_copy_head(const List *oldlist, int len)
Definition: list.c:1592
List * list_copy(const List *oldlist)
Definition: list.c:1572
void pfree(void *pointer)
Definition: mcxt.c:1306
void * palloc(Size size)
Definition: mcxt.c:1199
#define linitial_oid(l)
Definition: pg_list.h:178

References Assert(), bms_overlap(), BTLessStrategyNumber, EquivalenceClass::ec_members, EquivalenceClass::ec_opfamilies, EquivalenceMember::em_is_child, EquivalenceMember::em_is_const, EquivalenceMember::em_relids, j, lappend(), lfirst, linitial_oid, list_copy(), list_copy_head(), list_length(), make_canonical_pathkey(), NIL, palloc(), pathkey_is_redundant(), pfree(), PathKey::pk_eclass, PlannerInfo::query_pathkeys, RelOptInfo::relids, and update_mergeclause_eclasses().

Referenced by sort_inner_and_outer().

◆ trim_mergeclauses_for_inner_pathkeys()

List* trim_mergeclauses_for_inner_pathkeys ( PlannerInfo root,
List mergeclauses,
List pathkeys 
)

Definition at line 1703 of file pathkeys.c.

1706 {
1707  List *new_mergeclauses = NIL;
1708  PathKey *pathkey;
1709  EquivalenceClass *pathkey_ec;
1710  bool matched_pathkey;
1711  ListCell *lip;
1712  ListCell *i;
1713 
1714  /* No pathkeys => no mergeclauses (though we don't expect this case) */
1715  if (pathkeys == NIL)
1716  return NIL;
1717  /* Initialize to consider first pathkey */
1718  lip = list_head(pathkeys);
1719  pathkey = (PathKey *) lfirst(lip);
1720  pathkey_ec = pathkey->pk_eclass;
1721  lip = lnext(pathkeys, lip);
1722  matched_pathkey = false;
1723 
1724  /* Scan mergeclauses to see how many we can use */
1725  foreach(i, mergeclauses)
1726  {
1727  RestrictInfo *rinfo = (RestrictInfo *) lfirst(i);
1728  EquivalenceClass *clause_ec;
1729 
1730  /* Assume we needn't do update_mergeclause_eclasses again here */
1731 
1732  /* Check clause's inner-rel EC against current pathkey */
1733  clause_ec = rinfo->outer_is_left ?
1734  rinfo->right_ec : rinfo->left_ec;
1735 
1736  /* If we don't have a match, attempt to advance to next pathkey */
1737  if (clause_ec != pathkey_ec)
1738  {
1739  /* If we had no clauses matching this inner pathkey, must stop */
1740  if (!matched_pathkey)
1741  break;
1742 
1743  /* Advance to next inner pathkey, if any */
1744  if (lip == NULL)
1745  break;
1746  pathkey = (PathKey *) lfirst(lip);
1747  pathkey_ec = pathkey->pk_eclass;
1748  lip = lnext(pathkeys, lip);
1749  matched_pathkey = false;
1750  }
1751 
1752  /* If mergeclause matches current inner pathkey, we can use it */
1753  if (clause_ec == pathkey_ec)
1754  {
1755  new_mergeclauses = lappend(new_mergeclauses, rinfo);
1756  matched_pathkey = true;
1757  }
1758  else
1759  {
1760  /* Else, no hope of adding any more mergeclauses */
1761  break;
1762  }
1763  }
1764 
1765  return new_mergeclauses;
1766 }

References i, lappend(), lfirst, list_head(), lnext(), NIL, and PathKey::pk_eclass.

Referenced by generate_mergejoin_paths().

◆ truncate_useless_pathkeys()

List* truncate_useless_pathkeys ( PlannerInfo root,
RelOptInfo rel,
List pathkeys 
)

Definition at line 1923 of file pathkeys.c.

1926 {
1927  int nuseful;
1928  int nuseful2;
1929 
1930  nuseful = pathkeys_useful_for_merging(root, rel, pathkeys);
1931  nuseful2 = pathkeys_useful_for_ordering(root, pathkeys);
1932  if (nuseful2 > nuseful)
1933  nuseful = nuseful2;
1934 
1935  /*
1936  * Note: not safe to modify input list destructively, but we can avoid
1937  * copying the list if we're not actually going to change it
1938  */
1939  if (nuseful == 0)
1940  return NIL;
1941  else if (nuseful == list_length(pathkeys))
1942  return pathkeys;
1943  else
1944  return list_copy_head(pathkeys, nuseful);
1945 }
static int pathkeys_useful_for_ordering(PlannerInfo *root, List *pathkeys)
Definition: pathkeys.c:1902
static int pathkeys_useful_for_merging(PlannerInfo *root, RelOptInfo *rel, List *pathkeys)
Definition: pathkeys.c:1798

References list_copy_head(), list_length(), NIL, pathkeys_useful_for_merging(), and pathkeys_useful_for_ordering().

Referenced by build_index_paths(), and build_join_pathkeys().

◆ update_mergeclause_eclasses()

void update_mergeclause_eclasses ( PlannerInfo root,
RestrictInfo restrictinfo 
)

Definition at line 1255 of file pathkeys.c.

1256 {
1257  /* Should be a merge clause ... */
1258  Assert(restrictinfo->mergeopfamilies != NIL);
1259  /* ... with pointers already set */
1260  Assert(restrictinfo->left_ec != NULL);
1261  Assert(restrictinfo->right_ec != NULL);
1262 
1263  /* Chase up to the top as needed */
1264  while (restrictinfo->left_ec->ec_merged)
1265  restrictinfo->left_ec = restrictinfo->left_ec->ec_merged;
1266  while (restrictinfo->right_ec->ec_merged)
1267  restrictinfo->right_ec = restrictinfo->right_ec->ec_merged;
1268 }

References Assert(), and NIL.

Referenced by find_mergeclauses_for_outer_pathkeys(), get_useful_ecs_for_relation(), make_inner_pathkeys_for_merge(), pathkeys_useful_for_merging(), select_mergejoin_clauses(), and select_outer_pathkeys_for_merge().