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, 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, 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, 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)
 
Listmake_pathkeys_for_sortclauses_extended (PlannerInfo *root, List **sortclauses, List *tlist, bool remove_redundant, bool *sortable)
 
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:176
#define NIL
Definition: pg_list.h:68
static rewind_source * source
Definition: pg_rewind.c:87

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

Referenced by adjust_group_pathkeys_for_groupagg().

◆ build_expression_pathkey()

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

Definition at line 799 of file pathkeys.c.

804 {
805  List *pathkeys;
806  Oid opfamily,
807  opcintype;
808  int16 strategy;
809  PathKey *cpathkey;
810 
811  /* Find the operator in pg_amop --- failure shouldn't happen */
812  if (!get_ordering_op_properties(opno,
813  &opfamily, &opcintype, &strategy))
814  elog(ERROR, "operator %u is not a valid ordering operator",
815  opno);
816 
817  cpathkey = make_pathkey_from_sortinfo(root,
818  expr,
819  opfamily,
820  opcintype,
821  exprCollation((Node *) expr),
822  (strategy == BTGreaterStrategyNumber),
823  (strategy == BTGreaterStrategyNumber),
824  0,
825  rel,
826  create_it);
827 
828  if (cpathkey)
829  pathkeys = list_make1(cpathkey);
830  else
831  pathkeys = NIL;
832 
833  return pathkeys;
834 }
signed short int16
Definition: c.h:477
#define ERROR
Definition: elog.h:39
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:780
static PathKey * make_pathkey_from_sortinfo(PlannerInfo *root, Expr *expr, Oid opfamily, Oid opcintype, Oid collation, bool reverse_sort, bool nulls_first, Index sortref, Relids rel, bool create_it)
Definition: pathkeys.c:196
#define list_make1(x1)
Definition: pg_list.h:212
unsigned int Oid
Definition: postgres_ext.h:31
#define BTGreaterStrategyNumber
Definition: stratnum.h:33
Definition: pg_list.h:54
Definition: nodes.h:129

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 539 of file pathkeys.c.

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

1097 {
1098  if (jointype == JOIN_FULL || jointype == JOIN_RIGHT)
1099  return NIL;
1100 
1101  /*
1102  * This used to be quite a complex bit of code, but now that all pathkey
1103  * sublists start out life canonicalized, we don't have to do a darn thing
1104  * here!
1105  *
1106  * We do, however, need to truncate the pathkeys list, since it may
1107  * contain pathkeys that were useful for forming this joinrel but are
1108  * uninteresting to higher levels.
1109  */
1110  return truncate_useless_pathkeys(root, joinrel, outer_pathkeys);
1111 }
@ JOIN_FULL
Definition: nodes.h:306
@ JOIN_RIGHT
Definition: nodes.h:307
List * truncate_useless_pathkeys(PlannerInfo *root, RelOptInfo *rel, List *pathkeys)
Definition: pathkeys.c:1943

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 718 of file pathkeys.c.

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

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 301 of file pathkeys.c.

302 {
303  ListCell *key1,
304  *key2;
305 
306  /*
307  * Fall out quickly if we are passed two identical lists. This mostly
308  * catches the case where both are NIL, but that's common enough to
309  * warrant the test.
310  */
311  if (keys1 == keys2)
312  return PATHKEYS_EQUAL;
313 
314  forboth(key1, keys1, key2, keys2)
315  {
316  PathKey *pathkey1 = (PathKey *) lfirst(key1);
317  PathKey *pathkey2 = (PathKey *) lfirst(key2);
318 
319  if (pathkey1 != pathkey2)
320  return PATHKEYS_DIFFERENT; /* no need to keep looking */
321  }
322 
323  /*
324  * If we reached the end of only one list, the other is longer and
325  * therefore not a subset.
326  */
327  if (key1 != NULL)
328  return PATHKEYS_BETTER1; /* key1 is longer */
329  if (key2 != NULL)
330  return PATHKEYS_BETTER2; /* key2 is longer */
331  return PATHKEYS_EQUAL;
332 }
@ 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:467

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(), adjust_group_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 853 of file pathkeys.c.

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

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

References i, j, lappend(), lfirst, list_concat(), NIL, 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 1050 of file pathkeys.c.

1051 {
1052  ListCell *lc;
1053 
1054  /* If the TLE is resjunk, it's certainly not visible to the outer query */
1055  if (tle->resjunk)
1056  return NULL;
1057 
1058  /* Search the rel's targetlist to see what it will return */
1059  foreach(lc, rel->reltarget->exprs)
1060  {
1061  Var *var = (Var *) lfirst(lc);
1062 
1063  /* Ignore placeholders */
1064  if (!IsA(var, Var))
1065  continue;
1066  Assert(var->varno == rel->relid);
1067 
1068  /* If we find a Var referencing this TLE, we're good */
1069  if (var->varattno == tle->resno)
1070  return copyObject(var); /* Make a copy for safety */
1071  }
1072  return NULL;
1073 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:179
#define copyObject(obj)
Definition: nodes.h:244
List * exprs
Definition: pathnodes.h:1507
struct PathTarget * reltarget
Definition: pathnodes.h:884
Index relid
Definition: pathnodes.h:909
AttrNumber resno
Definition: primnodes.h:1818
AttrNumber varattno
Definition: primnodes.h:238
int varno
Definition: primnodes.h:233

References Assert(), copyObject, PathTarget::exprs, IsA, lfirst, RelOptInfo::relid, RelOptInfo::reltarget, 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 465 of file pathkeys.c.

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

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 498 of file pathkeys.c.

499 {
500  ListCell *l;
501 
502  foreach(l, paths)
503  {
504  Path *innerpath = (Path *) lfirst(l);
505 
506  if (innerpath->parallel_safe &&
507  bms_is_empty(PATH_REQ_OUTER(innerpath)))
508  return innerpath;
509  }
510 
511  return NULL;
512 }
#define bms_is_empty(a)
Definition: bitmapset.h:105
bool parallel_safe
Definition: pathnodes.h:1629

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 420 of file pathkeys.c.

424 {
425  Path *matched_path = NULL;
426  ListCell *l;
427 
428  foreach(l, paths)
429  {
430  Path *path = (Path *) lfirst(l);
431 
432  /*
433  * Since cost comparison is a lot cheaper than pathkey comparison, do
434  * that first. (XXX is that still true?)
435  */
436  if (matched_path != NULL &&
437  compare_path_costs(matched_path, path, cost_criterion) <= 0)
438  continue;
439 
440  if (require_parallel_safe && !path->parallel_safe)
441  continue;
442 
443  if (pathkeys_contained_in(pathkeys, path->pathkeys) &&
444  bms_is_subset(PATH_REQ_OUTER(path), required_outer))
445  matched_path = path;
446  }
447  return matched_path;
448 }
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 1983 of file pathkeys.c.

1984 {
1985  if (rel->joininfo != NIL || rel->has_eclass_joins)
1986  return true; /* might be able to use pathkeys for merging */
1987  if (root->query_pathkeys != NIL)
1988  return true; /* might be able to use them for ordering */
1989  return false; /* definitely useless */
1990 }
List * joininfo
Definition: pathnodes.h:976
bool has_eclass_joins
Definition: pathnodes.h:978

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 1228 of file pathkeys.c.

1229 {
1230  Expr *clause = restrictinfo->clause;
1231  Oid lefttype,
1232  righttype;
1233 
1234  /* Should be a mergeclause ... */
1235  Assert(restrictinfo->mergeopfamilies != NIL);
1236  /* ... with links not yet set */
1237  Assert(restrictinfo->left_ec == NULL);
1238  Assert(restrictinfo->right_ec == NULL);
1239 
1240  /* Need the declared input types of the operator */
1241  op_input_types(((OpExpr *) clause)->opno, &lefttype, &righttype);
1242 
1243  /* Find or create a matching EquivalenceClass for each side */
1244  restrictinfo->left_ec =
1246  (Expr *) get_leftop(clause),
1247  restrictinfo->mergeopfamilies,
1248  lefttype,
1249  ((OpExpr *) clause)->inputcollid,
1250  0,
1251  NULL,
1252  true);
1253  restrictinfo->right_ec =
1255  (Expr *) get_rightop(clause),
1256  restrictinfo->mergeopfamilies,
1257  righttype,
1258  ((OpExpr *) clause)->inputcollid,
1259  0,
1260  NULL,
1261  true);
1262 }
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
Expr * clause
Definition: pathnodes.h:2513

References Assert(), RestrictInfo::clause, get_eclass_for_sort_expr(), get_leftop(), get_rightop(), NIL, 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:176
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:138
static struct cvec * eclass(struct vars *v, chr c, int cases)
Definition: regc_locale.c:504
List * canon_pathkeys
Definition: pathnodes.h:320
bool ec_merging_done
Definition: pathnodes.h:317

References PlannerInfo::canon_pathkeys, PlannerInfo::ec_merging_done, eclass(), elog(), ERROR, lappend(), lfirst, makeNode, MemoryContextSwitchTo(), 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 1620 of file pathkeys.c.

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

References elog(), ERROR, lappend(), lfirst, list_head(), lnext(), make_canonical_pathkey(), NIL, pathkey_is_redundant(), 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,
Oid  opfamily,
Oid  opcintype,
Oid  collation,
bool  reverse_sort,
bool  nulls_first,
Index  sortref,
Relids  rel,
bool  create_it 
)
static

Definition at line 196 of file pathkeys.c.

206 {
207  int16 strategy;
208  Oid equality_op;
209  List *opfamilies;
211 
212  strategy = reverse_sort ? BTGreaterStrategyNumber : BTLessStrategyNumber;
213 
214  /*
215  * EquivalenceClasses need to contain opfamily lists based on the family
216  * membership of mergejoinable equality operators, which could belong to
217  * more than one opfamily. So we have to look up the opfamily's equality
218  * operator and get its membership.
219  */
220  equality_op = get_opfamily_member(opfamily,
221  opcintype,
222  opcintype,
224  if (!OidIsValid(equality_op)) /* shouldn't happen */
225  elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
226  BTEqualStrategyNumber, opcintype, opcintype, opfamily);
227  opfamilies = get_mergejoin_opfamilies(equality_op);
228  if (!opfamilies) /* certainly should find some */
229  elog(ERROR, "could not find opfamilies for equality operator %u",
230  equality_op);
231 
232  /* Now find or (optionally) create a matching EquivalenceClass */
233  eclass = get_eclass_for_sort_expr(root, expr,
234  opfamilies, opcintype, collation,
235  sortref, rel, create_it);
236 
237  /* Fail if no EC and !create_it */
238  if (!eclass)
239  return NULL;
240 
241  /* And finally we can find or create a PathKey node */
242  return make_canonical_pathkey(root, eclass, opfamily,
243  strategy, nulls_first);
244 }
#define OidIsValid(objectId)
Definition: c.h:759
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,
Oid  ordering_op,
bool  nulls_first,
Index  sortref,
bool  create_it 
)
static

Definition at line 254 of file pathkeys.c.

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

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

Referenced by make_pathkeys_for_sortclauses_extended().

◆ make_pathkeys_for_sortclauses()

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

Definition at line 1129 of file pathkeys.c.

1132 {
1133  List *result;
1134  bool sortable;
1135 
1137  &sortclauses,
1138  tlist,
1139  false,
1140  &sortable);
1141  /* It's caller error if not all clauses were sortable */
1142  Assert(sortable);
1143  return result;
1144 }
List * make_pathkeys_for_sortclauses_extended(PlannerInfo *root, List **sortclauses, List *tlist, bool remove_redundant, bool *sortable)
Definition: pathkeys.c:1166

References Assert(), and make_pathkeys_for_sortclauses_extended().

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

◆ make_pathkeys_for_sortclauses_extended()

List* make_pathkeys_for_sortclauses_extended ( PlannerInfo root,
List **  sortclauses,
List tlist,
bool  remove_redundant,
bool sortable 
)

Definition at line 1166 of file pathkeys.c.

1171 {
1172  List *pathkeys = NIL;
1173  ListCell *l;
1174 
1175  *sortable = true;
1176  foreach(l, *sortclauses)
1177  {
1178  SortGroupClause *sortcl = (SortGroupClause *) lfirst(l);
1179  Expr *sortkey;
1180  PathKey *pathkey;
1181 
1182  sortkey = (Expr *) get_sortgroupclause_expr(sortcl, tlist);
1183  if (!OidIsValid(sortcl->sortop))
1184  {
1185  *sortable = false;
1186  continue;
1187  }
1188  pathkey = make_pathkey_from_sortop(root,
1189  sortkey,
1190  sortcl->sortop,
1191  sortcl->nulls_first,
1192  sortcl->tleSortGroupRef,
1193  true);
1194 
1195  /* Canonical form eliminates redundant ordering keys */
1196  if (!pathkey_is_redundant(pathkey, pathkeys))
1197  pathkeys = lappend(pathkeys, pathkey);
1198  else if (remove_redundant)
1199  *sortclauses = foreach_delete_current(*sortclauses, l);
1200  }
1201  return pathkeys;
1202 }
static PathKey * make_pathkey_from_sortop(PlannerInfo *root, Expr *expr, Oid ordering_op, bool nulls_first, Index sortref, bool create_it)
Definition: pathkeys.c:254
#define foreach_delete_current(lst, cell)
Definition: pg_list.h:390
Index tleSortGroupRef
Definition: parsenodes.h:1393
Node * get_sortgroupclause_expr(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:379

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

Referenced by make_pathkeys_for_sortclauses(), and standard_qp_callback().

◆ matches_boolean_partition_clause()

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

Definition at line 683 of file pathkeys.c.

685 {
686  Node *clause = (Node *) rinfo->clause;
687  Node *partexpr = (Node *) linitial(partrel->partexprs[partkeycol]);
688 
689  /* Direct match? */
690  if (equal(partexpr, clause))
691  return true;
692  /* NOT clause? */
693  else if (is_notclause(clause))
694  {
695  Node *arg = (Node *) get_notclausearg((Expr *) clause);
696 
697  if (equal(partexpr, arg))
698  return true;
699  }
700 
701  return false;
702 }
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 643 of file pathkeys.c.

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

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:1394

References EC_MUST_BE_REDUNDANT, and lfirst.

Referenced by append_pathkeys(), build_index_pathkeys(), build_partition_pathkeys(), convert_subquery_pathkeys(), make_inner_pathkeys_for_merge(), make_pathkeys_for_sortclauses_extended(), 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 359 of file pathkeys.c.

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

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

Referenced by add_paths_to_grouping_rel(), create_final_distinct_paths(), create_one_window_path(), create_ordered_paths(), create_partial_distinct_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 1818 of file pathkeys.c.

1819 {
1820  int useful = 0;
1821  ListCell *i;
1822 
1823  foreach(i, pathkeys)
1824  {
1825  PathKey *pathkey = (PathKey *) lfirst(i);
1826  bool matched = false;
1827  ListCell *j;
1828 
1829  /* If "wrong" direction, not useful for merging */
1830  if (!right_merge_direction(root, pathkey))
1831  break;
1832 
1833  /*
1834  * First look into the EquivalenceClass of the pathkey, to see if
1835  * there are any members not yet joined to the rel. If so, it's
1836  * surely possible to generate a mergejoin clause using them.
1837  */
1838  if (rel->has_eclass_joins &&
1839  eclass_useful_for_merging(root, pathkey->pk_eclass, rel))
1840  matched = true;
1841  else
1842  {
1843  /*
1844  * Otherwise search the rel's joininfo list, which contains
1845  * non-EquivalenceClass-derivable join clauses that might
1846  * nonetheless be mergejoinable.
1847  */
1848  foreach(j, rel->joininfo)
1849  {
1850  RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(j);
1851 
1852  if (restrictinfo->mergeopfamilies == NIL)
1853  continue;
1854  update_mergeclause_eclasses(root, restrictinfo);
1855 
1856  if (pathkey->pk_eclass == restrictinfo->left_ec ||
1857  pathkey->pk_eclass == restrictinfo->right_ec)
1858  {
1859  matched = true;
1860  break;
1861  }
1862  }
1863  }
1864 
1865  /*
1866  * If we didn't find a mergeclause, we're done --- any additional
1867  * sort-key positions in the pathkeys are useless. (But we can still
1868  * mergejoin if we found at least one mergeclause.)
1869  */
1870  if (matched)
1871  useful++;
1872  else
1873  break;
1874  }
1875 
1876  return useful;
1877 }
bool eclass_useful_for_merging(PlannerInfo *root, EquivalenceClass *eclass, RelOptInfo *rel)
Definition: equivclass.c:3120
static bool right_merge_direction(PlannerInfo *root, PathKey *pathkey)
Definition: pathkeys.c:1885

References eclass_useful_for_merging(), RelOptInfo::has_eclass_joins, i, j, RelOptInfo::joininfo, lfirst, NIL, 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 1922 of file pathkeys.c.

1923 {
1924  int n_common_pathkeys;
1925 
1926  if (root->query_pathkeys == NIL)
1927  return 0; /* no special ordering requested */
1928 
1929  if (pathkeys == NIL)
1930  return 0; /* unordered path */
1931 
1932  (void) pathkeys_count_contained_in(root->query_pathkeys, pathkeys,
1933  &n_common_pathkeys);
1934 
1935  return n_common_pathkeys;
1936 }
bool pathkeys_count_contained_in(List *keys1, List *keys2, int *n_common)
Definition: pathkeys.c:359

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 1885 of file pathkeys.c.

1886 {
1887  ListCell *l;
1888 
1889  foreach(l, root->query_pathkeys)
1890  {
1891  PathKey *query_pathkey = (PathKey *) lfirst(l);
1892 
1893  if (pathkey->pk_eclass == query_pathkey->pk_eclass &&
1894  pathkey->pk_opfamily == query_pathkey->pk_opfamily)
1895  {
1896  /*
1897  * Found a matching query sort column. Prefer this pathkey's
1898  * direction iff it matches. Note that we ignore pk_nulls_first,
1899  * which means that a sort might be needed anyway ... but we still
1900  * want to prefer only one of the two possible directions, and we
1901  * might as well use this one.
1902  */
1903  return (pathkey->pk_strategy == query_pathkey->pk_strategy);
1904  }
1905  }
1906 
1907  /* If no matching ORDER BY request, prefer the ASC direction */
1908  return (pathkey->pk_strategy == BTLessStrategyNumber);
1909 }

References BTLessStrategyNumber, lfirst, 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 1424 of file pathkeys.c.

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

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(), 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 1723 of file pathkeys.c.

1726 {
1727  List *new_mergeclauses = NIL;
1728  PathKey *pathkey;
1729  EquivalenceClass *pathkey_ec;
1730  bool matched_pathkey;
1731  ListCell *lip;
1732  ListCell *i;
1733 
1734  /* No pathkeys => no mergeclauses (though we don't expect this case) */
1735  if (pathkeys == NIL)
1736  return NIL;
1737  /* Initialize to consider first pathkey */
1738  lip = list_head(pathkeys);
1739  pathkey = (PathKey *) lfirst(lip);
1740  pathkey_ec = pathkey->pk_eclass;
1741  lip = lnext(pathkeys, lip);
1742  matched_pathkey = false;
1743 
1744  /* Scan mergeclauses to see how many we can use */
1745  foreach(i, mergeclauses)
1746  {
1747  RestrictInfo *rinfo = (RestrictInfo *) lfirst(i);
1748  EquivalenceClass *clause_ec;
1749 
1750  /* Assume we needn't do update_mergeclause_eclasses again here */
1751 
1752  /* Check clause's inner-rel EC against current pathkey */
1753  clause_ec = rinfo->outer_is_left ?
1754  rinfo->right_ec : rinfo->left_ec;
1755 
1756  /* If we don't have a match, attempt to advance to next pathkey */
1757  if (clause_ec != pathkey_ec)
1758  {
1759  /* If we had no clauses matching this inner pathkey, must stop */
1760  if (!matched_pathkey)
1761  break;
1762 
1763  /* Advance to next inner pathkey, if any */
1764  if (lip == NULL)
1765  break;
1766  pathkey = (PathKey *) lfirst(lip);
1767  pathkey_ec = pathkey->pk_eclass;
1768  lip = lnext(pathkeys, lip);
1769  matched_pathkey = false;
1770  }
1771 
1772  /* If mergeclause matches current inner pathkey, we can use it */
1773  if (clause_ec == pathkey_ec)
1774  {
1775  new_mergeclauses = lappend(new_mergeclauses, rinfo);
1776  matched_pathkey = true;
1777  }
1778  else
1779  {
1780  /* Else, no hope of adding any more mergeclauses */
1781  break;
1782  }
1783  }
1784 
1785  return new_mergeclauses;
1786 }

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

Referenced by generate_mergejoin_paths().

◆ truncate_useless_pathkeys()

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

Definition at line 1943 of file pathkeys.c.

1946 {
1947  int nuseful;
1948  int nuseful2;
1949 
1950  nuseful = pathkeys_useful_for_merging(root, rel, pathkeys);
1951  nuseful2 = pathkeys_useful_for_ordering(root, pathkeys);
1952  if (nuseful2 > nuseful)
1953  nuseful = nuseful2;
1954 
1955  /*
1956  * Note: not safe to modify input list destructively, but we can avoid
1957  * copying the list if we're not actually going to change it
1958  */
1959  if (nuseful == 0)
1960  return NIL;
1961  else if (nuseful == list_length(pathkeys))
1962  return pathkeys;
1963  else
1964  return list_copy_head(pathkeys, nuseful);
1965 }
static int pathkeys_useful_for_ordering(PlannerInfo *root, List *pathkeys)
Definition: pathkeys.c:1922
static int pathkeys_useful_for_merging(PlannerInfo *root, RelOptInfo *rel, List *pathkeys)
Definition: pathkeys.c:1818

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 1275 of file pathkeys.c.

1276 {
1277  /* Should be a merge clause ... */
1278  Assert(restrictinfo->mergeopfamilies != NIL);
1279  /* ... with pointers already set */
1280  Assert(restrictinfo->left_ec != NULL);
1281  Assert(restrictinfo->right_ec != NULL);
1282 
1283  /* Chase up to the top as needed */
1284  while (restrictinfo->left_ec->ec_merged)
1285  restrictinfo->left_ec = restrictinfo->left_ec->ec_merged;
1286  while (restrictinfo->right_ec->ec_merged)
1287  restrictinfo->right_ec = restrictinfo->right_ec->ec_merged;
1288 }

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().