1 /*-------------------------------------------------------------------------
4 * Utilities for matching and building path keys
6 * See src/backend/optimizer/README for a great deal of information about
7 * the nature and use of path keys.
10 * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
11 * Portions Copyright (c) 1994, Regents of the University of California
14 * $PostgreSQL: pgsql/src/backend/optimizer/path/pathkeys.c,v 1.54 2003/11/29 19:51:50 pgsql Exp $
16 *-------------------------------------------------------------------------
20 #include "nodes/makefuncs.h"
21 #include "optimizer/clauses.h"
22 #include "optimizer/pathnode.h"
23 #include "optimizer/paths.h"
24 #include "optimizer/planmain.h"
25 #include "optimizer/tlist.h"
26 #include "optimizer/var.h"
27 #include "parser/parsetree.h"
28 #include "parser/parse_func.h"
29 #include "utils/lsyscache.h"
30 #include "utils/memutils.h"
33 static PathKeyItem *makePathKeyItem(Node *key, Oid sortop);
34 static List *make_canonical_pathkey(Query *root, PathKeyItem *item);
35 static Var *find_indexkey_var(Query *root, RelOptInfo *rel,
41 * create a PathKeyItem node
44 makePathKeyItem(Node *key, Oid sortop)
46 PathKeyItem *item = makeNode(PathKeyItem);
49 item->sortop = sortop;
55 * The given clause has a mergejoinable operator, so its two sides
56 * can be considered equal after restriction clause application; in
57 * particular, any pathkey mentioning one side (with the correct sortop)
58 * can be expanded to include the other as well. Record the exprs and
59 * associated sortops in the query's equi_key_list for future use.
61 * The query's equi_key_list field points to a list of sublists of PathKeyItem
62 * nodes, where each sublist is a set of two or more exprs+sortops that have
63 * been identified as logically equivalent (and, therefore, we may consider
64 * any two in a set to be equal). As described above, we will subsequently
65 * use direct pointers to one of these sublists to represent any pathkey
66 * that involves an equijoined variable.
69 add_equijoined_keys(Query *root, RestrictInfo *restrictinfo)
71 Expr *clause = restrictinfo->clause;
72 PathKeyItem *item1 = makePathKeyItem(get_leftop(clause),
73 restrictinfo->left_sortop);
74 PathKeyItem *item2 = makePathKeyItem(get_rightop(clause),
75 restrictinfo->right_sortop);
79 /* We might see a clause X=X; don't make a single-element list from it */
80 if (equal(item1, item2))
84 * Our plan is to make a two-element set, then sweep through the
85 * existing equijoin sets looking for matches to item1 or item2. When
86 * we find one, we remove that set from equi_key_list and union it
87 * into our new set. When done, we add the new set to the front of
90 * It may well be that the two items we're given are already known to be
91 * equijoin-equivalent, in which case we don't need to change our data
92 * structure. If we find both of them in the same equivalence set to
93 * start with, we can quit immediately.
95 * This is a standard UNION-FIND problem, for which there exist better
96 * data structures than simple lists. If this code ever proves to be
97 * a bottleneck then it could be sped up --- but for now, simple is
102 /* cannot use foreach here because of possible lremove */
103 cursetlink = root->equi_key_list;
106 List *curset = lfirst(cursetlink);
107 bool item1here = member(item1, curset);
108 bool item2here = member(item2, curset);
110 /* must advance cursetlink before lremove possibly pfree's it */
111 cursetlink = lnext(cursetlink);
113 if (item1here || item2here)
116 * If find both in same equivalence set, no need to do any
119 if (item1here && item2here)
121 /* Better not have seen only one in an earlier set... */
122 Assert(newset == NIL);
126 /* Build the new set only when we know we must */
128 newset = makeList2(item1, item2);
130 /* Found a set to merge into our new set */
131 newset = set_union(newset, curset);
134 * Remove old set from equi_key_list.
136 root->equi_key_list = lremove(curset, root->equi_key_list);
137 freeList(curset); /* might as well recycle old cons cells */
141 /* Build the new set only when we know we must */
143 newset = makeList2(item1, item2);
145 root->equi_key_list = lcons(newset, root->equi_key_list);
149 * generate_implied_equalities
150 * Scan the completed equi_key_list for the query, and generate explicit
151 * qualifications (WHERE clauses) for all the pairwise equalities not
152 * already mentioned in the quals; or remove qualifications found to be
155 * Adding deduced equalities is useful because the additional clauses help
156 * the selectivity-estimation code and may allow better joins to be chosen;
157 * and in fact it's *necessary* to ensure that sort keys we think are
158 * equivalent really are (see src/backend/optimizer/README for more info).
160 * If an equi_key_list set includes any constants then we adopt a different
161 * strategy: we record all the "var = const" deductions we can make, and
162 * actively remove all the "var = var" clauses that are implied by the set
163 * (including the clauses that originally gave rise to the set!). The reason
164 * is that given input like "a = b AND b = 42", once we have deduced "a = 42"
165 * there is no longer any need to apply the clause "a = b"; not only is
166 * it a waste of time to check it, but we will misestimate selectivity if the
167 * clause is left in. So we must remove it. For this purpose, any pathkey
168 * item that mentions no Vars of the current level can be taken as a constant.
169 * (The only case where this would be risky is if the item contains volatile
170 * functions; but we will never consider such an expression to be a pathkey
171 * at all, because check_mergejoinable() will reject it.)
173 * This routine just walks the equi_key_list to find all pairwise equalities.
174 * We call process_implied_equality (in plan/initsplan.c) to adjust the
175 * restrictinfo datastructures for each pair.
178 generate_implied_equalities(Query *root)
182 foreach(cursetlink, root->equi_key_list)
184 List *curset = lfirst(cursetlink);
185 int nitems = length(curset);
192 * A set containing only two items cannot imply any equalities
193 * beyond the one that created the set, so we can skip it.
199 * Collect info about relids mentioned in each item. For this
200 * routine we only really care whether there are any at all in
201 * each item, but process_implied_equality() needs the exact sets,
202 * so we may as well pull them here.
204 relids = (Relids *) palloc(nitems * sizeof(Relids));
207 foreach(ptr1, curset)
209 PathKeyItem *item1 = (PathKeyItem *) lfirst(ptr1);
211 relids[i1] = pull_varnos(item1->key);
212 if (bms_is_empty(relids[i1]))
218 * Match each item in the set with all that appear after it (it's
219 * sufficient to generate A=B, need not process B=A too).
222 foreach(ptr1, curset)
224 PathKeyItem *item1 = (PathKeyItem *) lfirst(ptr1);
225 bool i1_is_variable = !bms_is_empty(relids[i1]);
229 foreach(ptr2, lnext(ptr1))
231 PathKeyItem *item2 = (PathKeyItem *) lfirst(ptr2);
232 bool i2_is_variable = !bms_is_empty(relids[i2]);
235 * If it's "const = const" then just ignore it altogether.
236 * There is no place in the restrictinfo structure to
237 * store it. (If the two consts are in fact unequal, then
238 * propagating the comparison to Vars will cause us to
239 * produce zero rows out, as expected.)
241 if (i1_is_variable || i2_is_variable)
244 * Tell process_implied_equality to delete the clause,
245 * not add it, if it's "var = var" and we have
246 * constants present in the list.
248 bool delete_it = (have_consts &&
252 process_implied_equality(root,
253 item1->key, item2->key,
254 item1->sortop, item2->sortop,
255 relids[i1], relids[i2],
267 * Detect whether two expressions are known equal due to equijoin clauses.
269 * Note: does not bother to check for "equal(item1, item2)"; caller must
270 * check that case if it's possible to pass identical items.
273 exprs_known_equal(Query *root, Node *item1, Node *item2)
277 foreach(cursetlink, root->equi_key_list)
279 List *curset = lfirst(cursetlink);
280 bool item1member = false;
281 bool item2member = false;
286 PathKeyItem *pitem = (PathKeyItem *) lfirst(ptr);
288 if (equal(item1, pitem->key))
290 else if (equal(item2, pitem->key))
292 /* Exit as soon as equality is proven */
293 if (item1member && item2member)
302 * make_canonical_pathkey
303 * Given a PathKeyItem, find the equi_key_list subset it is a member of,
304 * if any. If so, return a pointer to that sublist, which is the
305 * canonical representation (for this query) of that PathKeyItem's
306 * equivalence set. If it is not found, add a singleton "equivalence set"
307 * to the equi_key_list and return that --- see compare_pathkeys.
309 * Note that this function must not be used until after we have completed
310 * scanning the WHERE clause for equijoin operators.
313 make_canonical_pathkey(Query *root, PathKeyItem *item)
318 foreach(cursetlink, root->equi_key_list)
320 List *curset = lfirst(cursetlink);
322 if (member(item, curset))
325 newset = makeList1(item);
326 root->equi_key_list = lcons(newset, root->equi_key_list);
331 * canonicalize_pathkeys
332 * Convert a not-necessarily-canonical pathkeys list to canonical form.
334 * Note that this function must not be used until after we have completed
335 * scanning the WHERE clause for equijoin operators.
338 canonicalize_pathkeys(Query *root, List *pathkeys)
340 List *new_pathkeys = NIL;
345 List *pathkey = (List *) lfirst(i);
350 * It's sufficient to look at the first entry in the sublist; if
351 * there are more entries, they're already part of an equivalence
354 Assert(pathkey != NIL);
355 item = (PathKeyItem *) lfirst(pathkey);
356 cpathkey = make_canonical_pathkey(root, item);
359 * Eliminate redundant ordering requests --- ORDER BY A,A is the
360 * same as ORDER BY A. We want to check this only after we have
361 * canonicalized the keys, so that equivalent-key knowledge is
362 * used when deciding if an item is redundant.
364 if (!ptrMember(cpathkey, new_pathkeys))
365 new_pathkeys = lappend(new_pathkeys, cpathkey);
372 * count_canonical_peers
373 * Given a PathKeyItem, find the equi_key_list subset it is a member of,
374 * if any. If so, return the number of other members of the set.
375 * If not, return 0 (without actually adding it to our equi_key_list).
377 * This is a hack to support the rather bogus heuristics in
378 * build_subquery_pathkeys.
381 count_canonical_peers(Query *root, PathKeyItem *item)
385 foreach(cursetlink, root->equi_key_list)
387 List *curset = lfirst(cursetlink);
389 if (member(item, curset))
390 return length(curset) - 1;
395 /****************************************************************************
396 * PATHKEY COMPARISONS
397 ****************************************************************************/
401 * Compare two pathkeys to see if they are equivalent, and if not whether
402 * one is "better" than the other.
404 * This function may only be applied to canonicalized pathkey lists.
405 * In the canonical representation, sublists can be checked for equality
406 * by simple pointer comparison.
409 compare_pathkeys(List *keys1, List *keys2)
414 for (key1 = keys1, key2 = keys2;
415 key1 != NIL && key2 != NIL;
416 key1 = lnext(key1), key2 = lnext(key2))
418 List *subkey1 = lfirst(key1);
419 List *subkey2 = lfirst(key2);
422 * XXX would like to check that we've been given canonicalized
423 * input, but query root not accessible here...
426 Assert(ptrMember(subkey1, root->equi_key_list));
427 Assert(ptrMember(subkey2, root->equi_key_list));
431 * We will never have two subkeys where one is a subset of the
432 * other, because of the canonicalization process. Either they
433 * are equal or they ain't. Furthermore, we only need pointer
434 * comparison to detect equality.
436 if (subkey1 != subkey2)
437 return PATHKEYS_DIFFERENT; /* no need to keep looking */
441 * If we reached the end of only one list, the other is longer and
442 * therefore not a subset. (We assume the additional sublist(s) of
443 * the other list are not NIL --- no pathkey list should ever have a
446 if (key1 == NIL && key2 == NIL)
447 return PATHKEYS_EQUAL;
449 return PATHKEYS_BETTER1; /* key1 is longer */
450 return PATHKEYS_BETTER2; /* key2 is longer */
454 * compare_noncanonical_pathkeys
455 * Compare two pathkeys to see if they are equivalent, and if not whether
456 * one is "better" than the other. This is used when we must compare
457 * non-canonicalized pathkeys.
459 * A pathkey can be considered better than another if it is a superset:
460 * it contains all the keys of the other plus more. For example, either
461 * ((A) (B)) or ((A B)) is better than ((A)).
463 * Currently, the only user of this routine is grouping_planner(),
464 * and it will only pass single-element sublists (from
465 * make_pathkeys_for_sortclauses). Therefore we don't have to do the
466 * full two-way-subset-inclusion test on each pair of sublists that is
467 * implied by the above statement. Instead we just verify they are
468 * singleton lists and then do an equal(). This could be improved if
472 compare_noncanonical_pathkeys(List *keys1, List *keys2)
477 for (key1 = keys1, key2 = keys2;
478 key1 != NIL && key2 != NIL;
479 key1 = lnext(key1), key2 = lnext(key2))
481 List *subkey1 = lfirst(key1);
482 List *subkey2 = lfirst(key2);
484 Assert(length(subkey1) == 1);
485 Assert(length(subkey2) == 1);
486 if (!equal(subkey1, subkey2))
487 return PATHKEYS_DIFFERENT; /* no need to keep looking */
491 * If we reached the end of only one list, the other is longer and
492 * therefore not a subset. (We assume the additional sublist(s) of
493 * the other list are not NIL --- no pathkey list should ever have a
496 if (key1 == NIL && key2 == NIL)
497 return PATHKEYS_EQUAL;
499 return PATHKEYS_BETTER1; /* key1 is longer */
500 return PATHKEYS_BETTER2; /* key2 is longer */
504 * pathkeys_contained_in
505 * Common special case of compare_pathkeys: we just want to know
506 * if keys2 are at least as well sorted as keys1.
509 pathkeys_contained_in(List *keys1, List *keys2)
511 switch (compare_pathkeys(keys1, keys2))
514 case PATHKEYS_BETTER2:
523 * noncanonical_pathkeys_contained_in
524 * The same, when we don't have canonical pathkeys.
527 noncanonical_pathkeys_contained_in(List *keys1, List *keys2)
529 switch (compare_noncanonical_pathkeys(keys1, keys2))
532 case PATHKEYS_BETTER2:
541 * get_cheapest_path_for_pathkeys
542 * Find the cheapest path (according to the specified criterion) that
543 * satisfies the given pathkeys. Return NULL if no such path.
545 * 'paths' is a list of possible paths that all generate the same relation
546 * 'pathkeys' represents a required ordering (already canonicalized!)
547 * 'cost_criterion' is STARTUP_COST or TOTAL_COST
550 get_cheapest_path_for_pathkeys(List *paths, List *pathkeys,
551 CostSelector cost_criterion)
553 Path *matched_path = NULL;
558 Path *path = (Path *) lfirst(i);
561 * Since cost comparison is a lot cheaper than pathkey comparison,
562 * do that first. (XXX is that still true?)
564 if (matched_path != NULL &&
565 compare_path_costs(matched_path, path, cost_criterion) <= 0)
568 if (pathkeys_contained_in(pathkeys, path->pathkeys))
575 * get_cheapest_fractional_path_for_pathkeys
576 * Find the cheapest path (for retrieving a specified fraction of all
577 * the tuples) that satisfies the given pathkeys.
578 * Return NULL if no such path.
580 * See compare_fractional_path_costs() for the interpretation of the fraction
583 * 'paths' is a list of possible paths that all generate the same relation
584 * 'pathkeys' represents a required ordering (already canonicalized!)
585 * 'fraction' is the fraction of the total tuples expected to be retrieved
588 get_cheapest_fractional_path_for_pathkeys(List *paths,
592 Path *matched_path = NULL;
597 Path *path = (Path *) lfirst(i);
600 * Since cost comparison is a lot cheaper than pathkey comparison,
603 if (matched_path != NULL &&
604 compare_fractional_path_costs(matched_path, path, fraction) <= 0)
607 if (pathkeys_contained_in(pathkeys, path->pathkeys))
613 /****************************************************************************
614 * NEW PATHKEY FORMATION
615 ****************************************************************************/
618 * build_index_pathkeys
619 * Build a pathkeys list that describes the ordering induced by an index
620 * scan using the given index. (Note that an unordered index doesn't
621 * induce any ordering; such an index will have no sortop OIDS in
622 * its "ordering" field, and we will return NIL.)
624 * If 'scandir' is BackwardScanDirection, attempt to build pathkeys
625 * representing a backwards scan of the index. Return NIL if can't do it.
627 * We generate the full pathkeys list whether or not all are useful for the
628 * current query. Caller should do truncate_useless_pathkeys().
631 build_index_pathkeys(Query *root,
634 ScanDirection scandir)
637 int *indexkeys = index->indexkeys;
638 Oid *ordering = index->ordering;
639 List *indexprs = index->indexprs;
641 while (*ordering != InvalidOid)
649 if (ScanDirectionIsBackward(scandir))
651 sortop = get_commutator(sortop);
652 if (sortop == InvalidOid)
653 break; /* oops, no reverse sort operator? */
658 /* simple index column */
659 indexkey = (Node *) find_indexkey_var(root, rel, *indexkeys);
663 /* expression --- assume we need not copy it */
665 elog(ERROR, "wrong number of index expressions");
666 indexkey = (Node *) lfirst(indexprs);
667 indexprs = lnext(indexprs);
670 /* OK, make a sublist for this sort key */
671 item = makePathKeyItem(indexkey, sortop);
672 cpathkey = make_canonical_pathkey(root, item);
675 * Eliminate redundant ordering info; could happen if query is
676 * such that index keys are equijoined...
678 if (!ptrMember(cpathkey, retval))
679 retval = lappend(retval, cpathkey);
689 * Find or make a Var node for the specified attribute of the rel.
691 * We first look for the var in the rel's target list, because that's
692 * easy and fast. But the var might not be there (this should normally
693 * only happen for vars that are used in WHERE restriction clauses,
694 * but not in join clauses or in the SELECT target list). In that case,
695 * gin up a Var node the hard way.
698 find_indexkey_var(Query *root, RelOptInfo *rel, AttrNumber varattno)
706 foreach(temp, FastListValue(&rel->reltargetlist))
708 Var *var = (Var *) lfirst(temp);
711 var->varattno == varattno)
716 reloid = getrelid(relid, root->rtable);
717 get_atttypetypmod(reloid, varattno, &vartypeid, &type_mod);
719 return makeVar(relid, varattno, vartypeid, type_mod, 0);
723 * build_subquery_pathkeys
724 * Build a pathkeys list that describes the ordering of a subquery's
725 * result (in the terms of the outer query). The subquery must already
726 * have been planned, so that its query_pathkeys field has been set.
728 * It is not necessary for caller to do truncate_useless_pathkeys(),
729 * because we select keys in a way that takes usefulness of the keys into
733 build_subquery_pathkeys(Query *root, RelOptInfo *rel, Query *subquery)
737 int outer_query_keys = length(root->query_pathkeys);
740 foreach(l, subquery->query_pathkeys)
742 List *sub_pathkey = (List *) lfirst(l);
744 PathKeyItem *best_item = NULL;
749 * The sub_pathkey could contain multiple elements (representing
750 * knowledge that multiple items are effectively equal). Each
751 * element might match none, one, or more of the output columns
752 * that are visible to the outer query. This means we may have
753 * multiple possible representations of the sub_pathkey in the
754 * context of the outer query. Ideally we would generate them all
755 * and put them all into a pathkey list of the outer query,
756 * thereby propagating equality knowledge up to the outer query.
757 * Right now we cannot do so, because the outer query's canonical
758 * pathkey sets are already frozen when this is called. Instead
759 * we prefer the one that has the highest "score" (number of
760 * canonical pathkey peers, plus one if it matches the outer
761 * query_pathkeys). This is the most likely to be useful in the
764 foreach(j, sub_pathkey)
766 PathKeyItem *sub_item = (PathKeyItem *) lfirst(j);
767 Node *sub_key = sub_item->key;
770 foreach(k, subquery->targetList)
772 TargetEntry *tle = (TargetEntry *) lfirst(k);
774 if (!tle->resdom->resjunk &&
775 equal(tle->expr, sub_key))
777 /* Found a representation for this sub_key */
779 PathKeyItem *outer_item;
782 outer_var = makeVar(rel->relid,
784 tle->resdom->restype,
785 tle->resdom->restypmod,
787 outer_item = makePathKeyItem((Node *) outer_var,
789 /* score = # of mergejoin peers */
790 score = count_canonical_peers(root, outer_item);
791 /* +1 if it matches the proper query_pathkeys item */
792 if (retvallen < outer_query_keys &&
794 nth(retvallen, root->query_pathkeys)))
796 if (score > best_score)
798 best_item = outer_item;
806 * If we couldn't find a representation of this sub_pathkey, we're
807 * done (we can't use the ones to its right, either).
812 /* Canonicalize the chosen item (we did not before) */
813 cpathkey = make_canonical_pathkey(root, best_item);
816 * Eliminate redundant ordering info; could happen if outer query
817 * equijoins subquery keys...
819 if (!ptrMember(cpathkey, retval))
821 retval = lappend(retval, cpathkey);
830 * build_join_pathkeys
831 * Build the path keys for a join relation constructed by mergejoin or
832 * nestloop join. These keys should include all the path key vars of the
833 * outer path (since the join will retain the ordering of the outer path)
834 * plus any vars of the inner path that are equijoined to the outer vars.
836 * Per the discussion in backend/optimizer/README, equijoined inner vars
837 * can be considered path keys of the result, just the same as the outer
838 * vars they were joined with; furthermore, it doesn't matter what kind
839 * of join algorithm is actually used.
841 * 'joinrel' is the join relation that paths are being formed for
842 * 'outer_pathkeys' is the list of the current outer path's path keys
844 * Returns the list of new path keys.
847 build_join_pathkeys(Query *root,
849 List *outer_pathkeys)
852 * This used to be quite a complex bit of code, but now that all
853 * pathkey sublists start out life canonicalized, we don't have to do
854 * a darn thing here! The inner-rel vars we used to need to add are
855 * *already* part of the outer pathkey!
857 * We do, however, need to truncate the pathkeys list, since it may
858 * contain pathkeys that were useful for forming this joinrel but are
859 * uninteresting to higher levels.
861 return truncate_useless_pathkeys(root, joinrel, outer_pathkeys);
864 /****************************************************************************
865 * PATHKEYS AND SORT CLAUSES
866 ****************************************************************************/
869 * make_pathkeys_for_sortclauses
870 * Generate a pathkeys list that represents the sort order specified
871 * by a list of SortClauses (GroupClauses will work too!)
873 * NB: the result is NOT in canonical form, but must be passed through
874 * canonicalize_pathkeys() before it can be used for comparisons or
875 * labeling relation sort orders. (We do things this way because
876 * grouping_planner needs to be able to construct requested pathkeys
877 * before the pathkey equivalence sets have been created for the query.)
879 * 'sortclauses' is a list of SortClause or GroupClause nodes
880 * 'tlist' is the targetlist to find the referenced tlist entries in
883 make_pathkeys_for_sortclauses(List *sortclauses,
886 List *pathkeys = NIL;
889 foreach(i, sortclauses)
891 SortClause *sortcl = (SortClause *) lfirst(i);
893 PathKeyItem *pathkey;
895 sortkey = get_sortgroupclause_expr(sortcl, tlist);
896 pathkey = makePathKeyItem(sortkey, sortcl->sortop);
899 * The pathkey becomes a one-element sublist, for now;
900 * canonicalize_pathkeys() might replace it with a longer sublist
903 pathkeys = lappend(pathkeys, makeList1(pathkey));
908 /****************************************************************************
909 * PATHKEYS AND MERGECLAUSES
910 ****************************************************************************/
913 * cache_mergeclause_pathkeys
914 * Make the cached pathkeys valid in a mergeclause restrictinfo.
916 * RestrictInfo contains fields in which we may cache the result
917 * of looking up the canonical pathkeys for the left and right sides
918 * of the mergeclause. (Note that in normal cases they will be the
919 * same, but not if the mergeclause appears above an OUTER JOIN.)
920 * This is a worthwhile savings because these routines will be invoked
921 * many times when dealing with a many-relation query.
923 * We have to be careful that the cached values are palloc'd in the same
924 * context the RestrictInfo node itself is in. This is not currently a
925 * problem for normal planning, but it is an issue for GEQO planning.
928 cache_mergeclause_pathkeys(Query *root, RestrictInfo *restrictinfo)
932 MemoryContext oldcontext;
934 Assert(restrictinfo->mergejoinoperator != InvalidOid);
936 if (restrictinfo->left_pathkey == NIL)
938 oldcontext = MemoryContextSwitchTo(GetMemoryChunkContext(restrictinfo));
939 key = get_leftop(restrictinfo->clause);
940 item = makePathKeyItem(key, restrictinfo->left_sortop);
941 restrictinfo->left_pathkey = make_canonical_pathkey(root, item);
942 MemoryContextSwitchTo(oldcontext);
944 if (restrictinfo->right_pathkey == NIL)
946 oldcontext = MemoryContextSwitchTo(GetMemoryChunkContext(restrictinfo));
947 key = get_rightop(restrictinfo->clause);
948 item = makePathKeyItem(key, restrictinfo->right_sortop);
949 restrictinfo->right_pathkey = make_canonical_pathkey(root, item);
950 MemoryContextSwitchTo(oldcontext);
955 * find_mergeclauses_for_pathkeys
956 * This routine attempts to find a set of mergeclauses that can be
957 * used with a specified ordering for one of the input relations.
958 * If successful, it returns a list of mergeclauses.
960 * 'pathkeys' is a pathkeys list showing the ordering of an input path.
961 * It doesn't matter whether it is for the inner or outer path.
962 * 'restrictinfos' is a list of mergejoinable restriction clauses for the
963 * join relation being formed.
965 * The result is NIL if no merge can be done, else a maximal list of
966 * usable mergeclauses (represented as a list of their restrictinfo nodes).
968 * XXX Ideally we ought to be considering context, ie what path orderings
969 * are available on the other side of the join, rather than just making
970 * an arbitrary choice among the mergeclauses that will work for this side
974 find_mergeclauses_for_pathkeys(Query *root,
978 List *mergeclauses = NIL;
981 /* make sure we have pathkeys cached in the clauses */
982 foreach(i, restrictinfos)
984 RestrictInfo *restrictinfo = lfirst(i);
986 cache_mergeclause_pathkeys(root, restrictinfo);
991 List *pathkey = lfirst(i);
992 List *matched_restrictinfos = NIL;
996 * We can match a pathkey against either left or right side of any
997 * mergejoin clause. (We examine both sides since we aren't told
998 * if the given pathkeys are for inner or outer input path; no
999 * confusion is possible.) Furthermore, if there are multiple
1000 * matching clauses, take them all. In plain inner-join scenarios
1001 * we expect only one match, because redundant-mergeclause
1002 * elimination will have removed any redundant mergeclauses from
1003 * the input list. However, in outer-join scenarios there might be
1004 * multiple matches. An example is
1006 * select * from a full join b on a.v1 = b.v1 and a.v2 = b.v2 and
1009 * Given the pathkeys ((a.v1), (a.v2)) it is okay to return all three
1010 * clauses (in the order a.v1=b.v1, a.v1=b.v2, a.v2=b.v2) and
1011 * indeed we *must* do so or we will be unable to form a valid
1014 foreach(j, restrictinfos)
1016 RestrictInfo *restrictinfo = lfirst(j);
1019 * We can compare canonical pathkey sublists by simple pointer
1020 * equality; see compare_pathkeys.
1022 if ((pathkey == restrictinfo->left_pathkey ||
1023 pathkey == restrictinfo->right_pathkey) &&
1024 !ptrMember(restrictinfo, mergeclauses))
1026 matched_restrictinfos = lappend(matched_restrictinfos,
1032 * If we didn't find a mergeclause, we're done --- any additional
1033 * sort-key positions in the pathkeys are useless. (But we can
1034 * still mergejoin if we found at least one mergeclause.)
1036 if (matched_restrictinfos == NIL)
1040 * If we did find usable mergeclause(s) for this sort-key
1041 * position, add them to result list.
1043 mergeclauses = nconc(mergeclauses, matched_restrictinfos);
1046 return mergeclauses;
1050 * make_pathkeys_for_mergeclauses
1051 * Builds a pathkey list representing the explicit sort order that
1052 * must be applied to a path in order to make it usable for the
1053 * given mergeclauses.
1055 * 'mergeclauses' is a list of RestrictInfos for mergejoin clauses
1056 * that will be used in a merge join.
1057 * 'rel' is the relation the pathkeys will apply to (ie, either the inner
1058 * or outer side of the proposed join rel).
1060 * Returns a pathkeys list that can be applied to the indicated relation.
1062 * Note that it is not this routine's job to decide whether sorting is
1063 * actually needed for a particular input path. Assume a sort is necessary;
1064 * just make the keys, eh?
1067 make_pathkeys_for_mergeclauses(Query *root,
1071 List *pathkeys = NIL;
1074 foreach(i, mergeclauses)
1076 RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(i);
1079 cache_mergeclause_pathkeys(root, restrictinfo);
1081 if (bms_is_subset(restrictinfo->left_relids, rel->relids))
1083 /* Rel is left side of mergeclause */
1084 pathkey = restrictinfo->left_pathkey;
1086 else if (bms_is_subset(restrictinfo->right_relids, rel->relids))
1088 /* Rel is right side of mergeclause */
1089 pathkey = restrictinfo->right_pathkey;
1093 elog(ERROR, "could not identify which side of mergeclause to use");
1094 pathkey = NIL; /* keep compiler quiet */
1098 * When we are given multiple merge clauses, it's possible that
1099 * some clauses refer to the same vars as earlier clauses. There's
1100 * no reason for us to specify sort keys like (A,B,A) when (A,B)
1101 * will do --- and adding redundant sort keys makes add_path think
1102 * that this sort order is different from ones that are really the
1103 * same, so don't do it. Since we now have a canonicalized
1104 * pathkey, a simple ptrMember test is sufficient to detect
1107 if (!ptrMember(pathkey, pathkeys))
1108 pathkeys = lappend(pathkeys, pathkey);
1114 /****************************************************************************
1115 * PATHKEY USEFULNESS CHECKS
1117 * We only want to remember as many of the pathkeys of a path as have some
1118 * potential use, either for subsequent mergejoins or for meeting the query's
1119 * requested output ordering. This ensures that add_path() won't consider
1120 * a path to have a usefully different ordering unless it really is useful.
1121 * These routines check for usefulness of given pathkeys.
1122 ****************************************************************************/
1125 * pathkeys_useful_for_merging
1126 * Count the number of pathkeys that may be useful for mergejoins
1127 * above the given relation (by looking at its joininfo lists).
1129 * We consider a pathkey potentially useful if it corresponds to the merge
1130 * ordering of either side of any joinclause for the rel. This might be
1131 * overoptimistic, since joinclauses that appear in different join lists
1132 * might never be usable at the same time, but trying to be exact is likely
1133 * to be more trouble than it's worth.
1136 pathkeys_useful_for_merging(Query *root, RelOptInfo *rel, List *pathkeys)
1141 foreach(i, pathkeys)
1143 List *pathkey = lfirst(i);
1144 bool matched = false;
1147 foreach(j, rel->joininfo)
1149 JoinInfo *joininfo = (JoinInfo *) lfirst(j);
1152 foreach(k, joininfo->jinfo_restrictinfo)
1154 RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(k);
1156 if (restrictinfo->mergejoinoperator == InvalidOid)
1158 cache_mergeclause_pathkeys(root, restrictinfo);
1161 * We can compare canonical pathkey sublists by simple
1162 * pointer equality; see compare_pathkeys.
1164 if (pathkey == restrictinfo->left_pathkey ||
1165 pathkey == restrictinfo->right_pathkey)
1177 * If we didn't find a mergeclause, we're done --- any additional
1178 * sort-key positions in the pathkeys are useless. (But we can
1179 * still mergejoin if we found at least one mergeclause.)
1191 * pathkeys_useful_for_ordering
1192 * Count the number of pathkeys that are useful for meeting the
1193 * query's requested output ordering.
1195 * Unlike merge pathkeys, this is an all-or-nothing affair: it does us
1196 * no good to order by just the first key(s) of the requested ordering.
1197 * So the result is always either 0 or length(root->query_pathkeys).
1200 pathkeys_useful_for_ordering(Query *root, List *pathkeys)
1202 if (root->query_pathkeys == NIL)
1203 return 0; /* no special ordering requested */
1205 if (pathkeys == NIL)
1206 return 0; /* unordered path */
1208 if (pathkeys_contained_in(root->query_pathkeys, pathkeys))
1210 /* It's useful ... or at least the first N keys are */
1211 return length(root->query_pathkeys);
1214 return 0; /* path ordering not useful */
1218 * truncate_useless_pathkeys
1219 * Shorten the given pathkey list to just the useful pathkeys.
1222 truncate_useless_pathkeys(Query *root,
1229 nuseful = pathkeys_useful_for_merging(root, rel, pathkeys);
1230 nuseful2 = pathkeys_useful_for_ordering(root, pathkeys);
1231 if (nuseful2 > nuseful)
1235 * Note: not safe to modify input list destructively, but we can avoid
1236 * copying the list if we're not actually going to change it
1238 if (nuseful == length(pathkeys))
1241 return ltruncate(nuseful, listCopy(pathkeys));