]> granicus.if.org Git - postgresql/blob - src/backend/optimizer/path/pathkeys.c
2fd3a9927486661ea38bd8c9daf44056d1a1ed1e
[postgresql] / src / backend / optimizer / path / pathkeys.c
1 /*-------------------------------------------------------------------------
2  *
3  * pathkeys.c
4  *        Utilities for matching and building path keys
5  *
6  * See src/backend/optimizer/README for a great deal of information about
7  * the nature and use of path keys.
8  *
9  *
10  * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
11  * Portions Copyright (c) 1994, Regents of the University of California
12  *
13  * IDENTIFICATION
14  *        $PostgreSQL: pgsql/src/backend/optimizer/path/pathkeys.c,v 1.58 2004/05/30 23:40:28 neilc Exp $
15  *
16  *-------------------------------------------------------------------------
17  */
18 #include "postgres.h"
19
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_expr.h"
29 #include "parser/parse_func.h"
30 #include "utils/lsyscache.h"
31 #include "utils/memutils.h"
32
33
34 static PathKeyItem *makePathKeyItem(Node *key, Oid sortop, bool checkType);
35 static List *make_canonical_pathkey(Query *root, PathKeyItem *item);
36 static Var *find_indexkey_var(Query *root, RelOptInfo *rel,
37                                   AttrNumber varattno);
38
39
40 /*
41  * makePathKeyItem
42  *              create a PathKeyItem node
43  */
44 static PathKeyItem *
45 makePathKeyItem(Node *key, Oid sortop, bool checkType)
46 {
47         PathKeyItem *item = makeNode(PathKeyItem);
48
49         /*
50          * Some callers pass expressions that are not necessarily of the same
51          * type as the sort operator expects as input (for example when dealing
52          * with an index that uses binary-compatible operators).  We must relabel
53          * these with the correct type so that the key expressions will be seen
54          * as equal() to expressions that have been correctly labeled.
55          */
56         if (checkType)
57         {
58                 Oid                     lefttype,
59                                         righttype;
60
61                 op_input_types(sortop, &lefttype, &righttype);
62                 if (exprType(key) != lefttype)
63                         key = (Node *) makeRelabelType((Expr *) key,
64                                                                                    lefttype, -1,
65                                                                                    COERCE_DONTCARE);
66         }
67
68         item->key = key;
69         item->sortop = sortop;
70         return item;
71 }
72
73 /*
74  * add_equijoined_keys
75  *        The given clause has a mergejoinable operator, so its two sides
76  *        can be considered equal after restriction clause application; in
77  *        particular, any pathkey mentioning one side (with the correct sortop)
78  *        can be expanded to include the other as well.  Record the exprs and
79  *        associated sortops in the query's equi_key_list for future use.
80  *
81  * The query's equi_key_list field points to a list of sublists of PathKeyItem
82  * nodes, where each sublist is a set of two or more exprs+sortops that have
83  * been identified as logically equivalent (and, therefore, we may consider
84  * any two in a set to be equal).  As described above, we will subsequently
85  * use direct pointers to one of these sublists to represent any pathkey
86  * that involves an equijoined variable.
87  */
88 void
89 add_equijoined_keys(Query *root, RestrictInfo *restrictinfo)
90 {
91         Expr       *clause = restrictinfo->clause;
92         PathKeyItem *item1 = makePathKeyItem(get_leftop(clause),
93                                                                                  restrictinfo->left_sortop,
94                                                                                  false);
95         PathKeyItem *item2 = makePathKeyItem(get_rightop(clause),
96                                                                                  restrictinfo->right_sortop,
97                                                                                  false);
98         List       *newset;
99         ListCell   *cursetlink;
100
101         /* We might see a clause X=X; don't make a single-element list from it */
102         if (equal(item1, item2))
103                 return;
104
105         /*
106          * Our plan is to make a two-element set, then sweep through the
107          * existing equijoin sets looking for matches to item1 or item2.  When
108          * we find one, we remove that set from equi_key_list and union it
109          * into our new set. When done, we add the new set to the front of
110          * equi_key_list.
111          *
112          * It may well be that the two items we're given are already known to be
113          * equijoin-equivalent, in which case we don't need to change our data
114          * structure.  If we find both of them in the same equivalence set to
115          * start with, we can quit immediately.
116          *
117          * This is a standard UNION-FIND problem, for which there exist better
118          * data structures than simple lists.  If this code ever proves to be
119          * a bottleneck then it could be sped up --- but for now, simple is
120          * beautiful.
121          */
122         newset = NIL;
123
124         /* cannot use foreach here because of possible lremove */
125         cursetlink = list_head(root->equi_key_list);
126         while (cursetlink)
127         {
128                 List       *curset = (List *) lfirst(cursetlink);
129                 bool            item1here = list_member(curset, item1);
130                 bool            item2here = list_member(curset, item2);
131
132                 /* must advance cursetlink before lremove possibly pfree's it */
133                 cursetlink = lnext(cursetlink);
134
135                 if (item1here || item2here)
136                 {
137                         /*
138                          * If find both in same equivalence set, no need to do any
139                          * more
140                          */
141                         if (item1here && item2here)
142                         {
143                                 /* Better not have seen only one in an earlier set... */
144                                 Assert(newset == NIL);
145                                 return;
146                         }
147
148                         /* Build the new set only when we know we must */
149                         if (newset == NIL)
150                                 newset = list_make2(item1, item2);
151
152                         /* Found a set to merge into our new set */
153                         newset = list_union(newset, curset);
154
155                         /*
156                          * Remove old set from equi_key_list.
157                          */
158                         root->equi_key_list = list_delete_ptr(root->equi_key_list, curset);
159                         list_free(curset);      /* might as well recycle old cons cells */
160                 }
161         }
162
163         /* Build the new set only when we know we must */
164         if (newset == NIL)
165                 newset = list_make2(item1, item2);
166
167         root->equi_key_list = lcons(newset, root->equi_key_list);
168 }
169
170 /*
171  * generate_implied_equalities
172  *        Scan the completed equi_key_list for the query, and generate explicit
173  *        qualifications (WHERE clauses) for all the pairwise equalities not
174  *        already mentioned in the quals; or remove qualifications found to be
175  *        redundant.
176  *
177  * Adding deduced equalities is useful because the additional clauses help
178  * the selectivity-estimation code and may allow better joins to be chosen;
179  * and in fact it's *necessary* to ensure that sort keys we think are
180  * equivalent really are (see src/backend/optimizer/README for more info).
181  *
182  * If an equi_key_list set includes any constants then we adopt a different
183  * strategy: we record all the "var = const" deductions we can make, and
184  * actively remove all the "var = var" clauses that are implied by the set
185  * (including the clauses that originally gave rise to the set!).  The reason
186  * is that given input like "a = b AND b = 42", once we have deduced "a = 42"
187  * there is no longer any need to apply the clause "a = b"; not only is
188  * it a waste of time to check it, but we will misestimate selectivity if the
189  * clause is left in.  So we must remove it.  For this purpose, any pathkey
190  * item that mentions no Vars of the current level can be taken as a constant.
191  * (The only case where this would be risky is if the item contains volatile
192  * functions; but we will never consider such an expression to be a pathkey
193  * at all, because check_mergejoinable() will reject it.)
194  *
195  * This routine just walks the equi_key_list to find all pairwise equalities.
196  * We call process_implied_equality (in plan/initsplan.c) to adjust the
197  * restrictinfo datastructures for each pair.
198  */
199 void
200 generate_implied_equalities(Query *root)
201 {
202         ListCell   *cursetlink;
203
204         foreach(cursetlink, root->equi_key_list)
205         {
206                 List       *curset = (List *) lfirst(cursetlink);
207                 int                     nitems = list_length(curset);
208                 Relids     *relids;
209                 bool            have_consts;
210                 ListCell   *ptr1;
211                 int                     i1;
212
213                 /*
214                  * A set containing only two items cannot imply any equalities
215                  * beyond the one that created the set, so we can skip it.
216                  */
217                 if (nitems < 3)
218                         continue;
219
220                 /*
221                  * Collect info about relids mentioned in each item.  For this
222                  * routine we only really care whether there are any at all in
223                  * each item, but process_implied_equality() needs the exact sets,
224                  * so we may as well pull them here.
225                  */
226                 relids = (Relids *) palloc(nitems * sizeof(Relids));
227                 have_consts = false;
228                 i1 = 0;
229                 foreach(ptr1, curset)
230                 {
231                         PathKeyItem *item1 = (PathKeyItem *) lfirst(ptr1);
232
233                         relids[i1] = pull_varnos(item1->key);
234                         if (bms_is_empty(relids[i1]))
235                                 have_consts = true;
236                         i1++;
237                 }
238
239                 /*
240                  * Match each item in the set with all that appear after it (it's
241                  * sufficient to generate A=B, need not process B=A too).
242                  */
243                 i1 = 0;
244                 foreach(ptr1, curset)
245                 {
246                         PathKeyItem *item1 = (PathKeyItem *) lfirst(ptr1);
247                         bool            i1_is_variable = !bms_is_empty(relids[i1]);
248                         ListCell   *ptr2;
249                         int                     i2 = i1 + 1;
250
251                         for_each_cell(ptr2, lnext(ptr1))
252                         {
253                                 PathKeyItem *item2 = (PathKeyItem *) lfirst(ptr2);
254                                 bool            i2_is_variable = !bms_is_empty(relids[i2]);
255
256                                 /*
257                                  * If it's "const = const" then just ignore it altogether.
258                                  * There is no place in the restrictinfo structure to
259                                  * store it.  (If the two consts are in fact unequal, then
260                                  * propagating the comparison to Vars will cause us to
261                                  * produce zero rows out, as expected.)
262                                  */
263                                 if (i1_is_variable || i2_is_variable)
264                                 {
265                                         /*
266                                          * Tell process_implied_equality to delete the clause,
267                                          * not add it, if it's "var = var" and we have
268                                          * constants present in the list.
269                                          */
270                                         bool            delete_it = (have_consts &&
271                                                                                          i1_is_variable &&
272                                                                                          i2_is_variable);
273
274                                         process_implied_equality(root,
275                                                                                          item1->key, item2->key,
276                                                                                          item1->sortop, item2->sortop,
277                                                                                          relids[i1], relids[i2],
278                                                                                          delete_it);
279                                 }
280                                 i2++;
281                         }
282                         i1++;
283                 }
284         }
285 }
286
287 /*
288  * exprs_known_equal
289  *        Detect whether two expressions are known equal due to equijoin clauses.
290  *
291  * Note: does not bother to check for "equal(item1, item2)"; caller must
292  * check that case if it's possible to pass identical items.
293  */
294 bool
295 exprs_known_equal(Query *root, Node *item1, Node *item2)
296 {
297         ListCell   *cursetlink;
298
299         foreach(cursetlink, root->equi_key_list)
300         {
301                 List       *curset = (List *) lfirst(cursetlink);
302                 bool            item1member = false;
303                 bool            item2member = false;
304                 ListCell   *ptr;
305
306                 foreach(ptr, curset)
307                 {
308                         PathKeyItem *pitem = (PathKeyItem *) lfirst(ptr);
309
310                         if (equal(item1, pitem->key))
311                                 item1member = true;
312                         else if (equal(item2, pitem->key))
313                                 item2member = true;
314                         /* Exit as soon as equality is proven */
315                         if (item1member && item2member)
316                                 return true;
317                 }
318         }
319         return false;
320 }
321
322
323 /*
324  * make_canonical_pathkey
325  *        Given a PathKeyItem, find the equi_key_list subset it is a member of,
326  *        if any.  If so, return a pointer to that sublist, which is the
327  *        canonical representation (for this query) of that PathKeyItem's
328  *        equivalence set.      If it is not found, add a singleton "equivalence set"
329  *        to the equi_key_list and return that --- see compare_pathkeys.
330  *
331  * Note that this function must not be used until after we have completed
332  * scanning the WHERE clause for equijoin operators.
333  */
334 static List *
335 make_canonical_pathkey(Query *root, PathKeyItem *item)
336 {
337         List       *newset;
338         ListCell   *cursetlink;
339
340         foreach(cursetlink, root->equi_key_list)
341         {
342                 List       *curset = (List *) lfirst(cursetlink);
343
344                 if (list_member(curset, item))
345                         return curset;
346         }
347         newset = list_make1(item);
348         root->equi_key_list = lcons(newset, root->equi_key_list);
349         return newset;
350 }
351
352 /*
353  * canonicalize_pathkeys
354  *         Convert a not-necessarily-canonical pathkeys list to canonical form.
355  *
356  * Note that this function must not be used until after we have completed
357  * scanning the WHERE clause for equijoin operators.
358  */
359 List *
360 canonicalize_pathkeys(Query *root, List *pathkeys)
361 {
362         List       *new_pathkeys = NIL;
363         ListCell   *l;
364
365         foreach(l, pathkeys)
366         {
367                 List       *pathkey = (List *) lfirst(l);
368                 PathKeyItem *item;
369                 List       *cpathkey;
370
371                 /*
372                  * It's sufficient to look at the first entry in the sublist; if
373                  * there are more entries, they're already part of an equivalence
374                  * set by definition.
375                  */
376                 Assert(pathkey != NIL);
377                 item = (PathKeyItem *) linitial(pathkey);
378                 cpathkey = make_canonical_pathkey(root, item);
379
380                 /*
381                  * Eliminate redundant ordering requests --- ORDER BY A,A is the
382                  * same as ORDER BY A.  We want to check this only after we have
383                  * canonicalized the keys, so that equivalent-key knowledge is
384                  * used when deciding if an item is redundant.
385                  */
386                 if (!list_member_ptr(new_pathkeys, cpathkey))
387                         new_pathkeys = lappend(new_pathkeys, cpathkey);
388         }
389         return new_pathkeys;
390 }
391
392
393 /*
394  * count_canonical_peers
395  *        Given a PathKeyItem, find the equi_key_list subset it is a member of,
396  *        if any.  If so, return the number of other members of the set.
397  *        If not, return 0 (without actually adding it to our equi_key_list).
398  *
399  * This is a hack to support the rather bogus heuristics in
400  * build_subquery_pathkeys.
401  */
402 static int
403 count_canonical_peers(Query *root, PathKeyItem *item)
404 {
405         ListCell   *cursetlink;
406
407         foreach(cursetlink, root->equi_key_list)
408         {
409                 List       *curset = (List *) lfirst(cursetlink);
410
411                 if (list_member(curset, item))
412                         return list_length(curset) - 1;
413         }
414         return 0;
415 }
416
417 /****************************************************************************
418  *              PATHKEY COMPARISONS
419  ****************************************************************************/
420
421 /*
422  * compare_pathkeys
423  *        Compare two pathkeys to see if they are equivalent, and if not whether
424  *        one is "better" than the other.
425  *
426  *        This function may only be applied to canonicalized pathkey lists.
427  *        In the canonical representation, sublists can be checked for equality
428  *        by simple pointer comparison.
429  */
430 PathKeysComparison
431 compare_pathkeys(List *keys1, List *keys2)
432 {
433         ListCell   *key1,
434                            *key2;
435
436         forboth(key1, keys1, key2, keys2)
437         {
438                 List       *subkey1 = (List *) lfirst(key1);
439                 List       *subkey2 = (List *) lfirst(key2);
440
441                 /*
442                  * XXX would like to check that we've been given canonicalized
443                  * input, but query root not accessible here...
444                  */
445 #ifdef NOT_USED
446                 Assert(list_member_ptr(root->equi_key_list, subkey1));
447                 Assert(list_member_ptr(root->equi_key_list, subkey2));
448 #endif
449
450                 /*
451                  * We will never have two subkeys where one is a subset of the
452                  * other, because of the canonicalization process.      Either they
453                  * are equal or they ain't.  Furthermore, we only need pointer
454                  * comparison to detect equality.
455                  */
456                 if (subkey1 != subkey2)
457                         return PATHKEYS_DIFFERENT;      /* no need to keep looking */
458         }
459
460         /*
461          * If we reached the end of only one list, the other is longer and
462          * therefore not a subset.      (We assume the additional sublist(s) of
463          * the other list are not NIL --- no pathkey list should ever have a
464          * NIL sublist.)
465          */
466         if (key1 == NULL && key2 == NULL)
467                 return PATHKEYS_EQUAL;
468         if (key1 != NULL)
469                 return PATHKEYS_BETTER1;        /* key1 is longer */
470         return PATHKEYS_BETTER2;        /* key2 is longer */
471 }
472
473 /*
474  * compare_noncanonical_pathkeys
475  *        Compare two pathkeys to see if they are equivalent, and if not whether
476  *        one is "better" than the other.  This is used when we must compare
477  *        non-canonicalized pathkeys.
478  *
479  *        A pathkey can be considered better than another if it is a superset:
480  *        it contains all the keys of the other plus more.      For example, either
481  *        ((A) (B)) or ((A B)) is better than ((A)).
482  *
483  *        Currently, the only user of this routine is grouping_planner(),
484  *        and it will only pass single-element sublists (from
485  *        make_pathkeys_for_sortclauses).  Therefore we don't have to do the
486  *        full two-way-subset-inclusion test on each pair of sublists that is
487  *        implied by the above statement.  Instead we just verify they are
488  *        singleton lists and then do an equal().  This could be improved if
489  *        necessary.
490  */
491 PathKeysComparison
492 compare_noncanonical_pathkeys(List *keys1, List *keys2)
493 {
494         ListCell   *key1,
495                            *key2;
496
497         forboth(key1, keys1, key2, keys2)
498         {
499                 List       *subkey1 = (List *) lfirst(key1);
500                 List       *subkey2 = (List *) lfirst(key2);
501
502                 Assert(list_length(subkey1) == 1);
503                 Assert(list_length(subkey2) == 1);
504                 if (!equal(subkey1, subkey2))
505                         return PATHKEYS_DIFFERENT;      /* no need to keep looking */
506         }
507
508         /*
509          * If we reached the end of only one list, the other is longer and
510          * therefore not a subset.      (We assume the additional sublist(s) of
511          * the other list are not NIL --- no pathkey list should ever have a
512          * NIL sublist.)
513          */
514         if (key1 == NULL && key2 == NULL)
515                 return PATHKEYS_EQUAL;
516         if (key1 != NULL)
517                 return PATHKEYS_BETTER1;        /* key1 is longer */
518         return PATHKEYS_BETTER2;        /* key2 is longer */
519 }
520
521 /*
522  * pathkeys_contained_in
523  *        Common special case of compare_pathkeys: we just want to know
524  *        if keys2 are at least as well sorted as keys1.
525  */
526 bool
527 pathkeys_contained_in(List *keys1, List *keys2)
528 {
529         switch (compare_pathkeys(keys1, keys2))
530         {
531                 case PATHKEYS_EQUAL:
532                 case PATHKEYS_BETTER2:
533                         return true;
534                 default:
535                         break;
536         }
537         return false;
538 }
539
540 /*
541  * noncanonical_pathkeys_contained_in
542  *        The same, when we don't have canonical pathkeys.
543  */
544 bool
545 noncanonical_pathkeys_contained_in(List *keys1, List *keys2)
546 {
547         switch (compare_noncanonical_pathkeys(keys1, keys2))
548         {
549                 case PATHKEYS_EQUAL:
550                 case PATHKEYS_BETTER2:
551                         return true;
552                 default:
553                         break;
554         }
555         return false;
556 }
557
558 /*
559  * get_cheapest_path_for_pathkeys
560  *        Find the cheapest path (according to the specified criterion) that
561  *        satisfies the given pathkeys.  Return NULL if no such path.
562  *
563  * 'paths' is a list of possible paths that all generate the same relation
564  * 'pathkeys' represents a required ordering (already canonicalized!)
565  * 'cost_criterion' is STARTUP_COST or TOTAL_COST
566  */
567 Path *
568 get_cheapest_path_for_pathkeys(List *paths, List *pathkeys,
569                                                            CostSelector cost_criterion)
570 {
571         Path       *matched_path = NULL;
572         ListCell   *l;
573
574         foreach(l, paths)
575         {
576                 Path       *path = (Path *) lfirst(l);
577
578                 /*
579                  * Since cost comparison is a lot cheaper than pathkey comparison,
580                  * do that first.  (XXX is that still true?)
581                  */
582                 if (matched_path != NULL &&
583                         compare_path_costs(matched_path, path, cost_criterion) <= 0)
584                         continue;
585
586                 if (pathkeys_contained_in(pathkeys, path->pathkeys))
587                         matched_path = path;
588         }
589         return matched_path;
590 }
591
592 /*
593  * get_cheapest_fractional_path_for_pathkeys
594  *        Find the cheapest path (for retrieving a specified fraction of all
595  *        the tuples) that satisfies the given pathkeys.
596  *        Return NULL if no such path.
597  *
598  * See compare_fractional_path_costs() for the interpretation of the fraction
599  * parameter.
600  *
601  * 'paths' is a list of possible paths that all generate the same relation
602  * 'pathkeys' represents a required ordering (already canonicalized!)
603  * 'fraction' is the fraction of the total tuples expected to be retrieved
604  */
605 Path *
606 get_cheapest_fractional_path_for_pathkeys(List *paths,
607                                                                                   List *pathkeys,
608                                                                                   double fraction)
609 {
610         Path       *matched_path = NULL;
611         ListCell   *l;
612
613         foreach(l, paths)
614         {
615                 Path       *path = (Path *) lfirst(l);
616
617                 /*
618                  * Since cost comparison is a lot cheaper than pathkey comparison,
619                  * do that first.
620                  */
621                 if (matched_path != NULL &&
622                 compare_fractional_path_costs(matched_path, path, fraction) <= 0)
623                         continue;
624
625                 if (pathkeys_contained_in(pathkeys, path->pathkeys))
626                         matched_path = path;
627         }
628         return matched_path;
629 }
630
631 /****************************************************************************
632  *              NEW PATHKEY FORMATION
633  ****************************************************************************/
634
635 /*
636  * build_index_pathkeys
637  *        Build a pathkeys list that describes the ordering induced by an index
638  *        scan using the given index.  (Note that an unordered index doesn't
639  *        induce any ordering; such an index will have no sortop OIDS in
640  *        its "ordering" field, and we will return NIL.)
641  *
642  * If 'scandir' is BackwardScanDirection, attempt to build pathkeys
643  * representing a backwards scan of the index.  Return NIL if can't do it.
644  *
645  * We generate the full pathkeys list whether or not all are useful for the
646  * current query.  Caller should do truncate_useless_pathkeys().
647  */
648 List *
649 build_index_pathkeys(Query *root,
650                                          RelOptInfo *rel,
651                                          IndexOptInfo *index,
652                                          ScanDirection scandir)
653 {
654         List       *retval = NIL;
655         int                *indexkeys = index->indexkeys;
656         Oid                *ordering = index->ordering;
657         ListCell   *indexprs_item = list_head(index->indexprs);
658
659         while (*ordering != InvalidOid)
660         {
661                 PathKeyItem *item;
662                 Oid                     sortop;
663                 Node       *indexkey;
664                 List       *cpathkey;
665
666                 sortop = *ordering;
667                 if (ScanDirectionIsBackward(scandir))
668                 {
669                         sortop = get_commutator(sortop);
670                         if (sortop == InvalidOid)
671                                 break;                  /* oops, no reverse sort operator? */
672                 }
673
674                 if (*indexkeys != 0)
675                 {
676                         /* simple index column */
677                         indexkey = (Node *) find_indexkey_var(root, rel, *indexkeys);
678                 }
679                 else
680                 {
681                         /* expression --- assume we need not copy it */
682                         if (indexprs_item == NULL)
683                                 elog(ERROR, "wrong number of index expressions");
684                         indexkey = (Node *) lfirst(indexprs_item);
685                         indexprs_item = lnext(indexprs_item);
686                 }
687
688                 /* OK, make a sublist for this sort key */
689                 item = makePathKeyItem(indexkey, sortop, true);
690                 cpathkey = make_canonical_pathkey(root, item);
691
692                 /*
693                  * Eliminate redundant ordering info; could happen if query is
694                  * such that index keys are equijoined...
695                  */
696                 if (!list_member_ptr(retval, cpathkey))
697                         retval = lappend(retval, cpathkey);
698
699                 indexkeys++;
700                 ordering++;
701         }
702
703         return retval;
704 }
705
706 /*
707  * Find or make a Var node for the specified attribute of the rel.
708  *
709  * We first look for the var in the rel's target list, because that's
710  * easy and fast.  But the var might not be there (this should normally
711  * only happen for vars that are used in WHERE restriction clauses,
712  * but not in join clauses or in the SELECT target list).  In that case,
713  * gin up a Var node the hard way.
714  */
715 static Var *
716 find_indexkey_var(Query *root, RelOptInfo *rel, AttrNumber varattno)
717 {
718         ListCell   *temp;
719         Index           relid;
720         Oid                     reloid,
721                                 vartypeid;
722         int32           type_mod;
723
724         foreach(temp, FastListValue(&rel->reltargetlist))
725         {
726                 Var                *var = (Var *) lfirst(temp);
727
728                 if (IsA(var, Var) &&
729                         var->varattno == varattno)
730                         return var;
731         }
732
733         relid = rel->relid;
734         reloid = getrelid(relid, root->rtable);
735         get_atttypetypmod(reloid, varattno, &vartypeid, &type_mod);
736
737         return makeVar(relid, varattno, vartypeid, type_mod, 0);
738 }
739
740 /*
741  * build_subquery_pathkeys
742  *        Build a pathkeys list that describes the ordering of a subquery's
743  *        result (in the terms of the outer query).  The subquery must already
744  *        have been planned, so that its query_pathkeys field has been set.
745  *
746  * It is not necessary for caller to do truncate_useless_pathkeys(),
747  * because we select keys in a way that takes usefulness of the keys into
748  * account.
749  */
750 List *
751 build_subquery_pathkeys(Query *root, RelOptInfo *rel, Query *subquery)
752 {
753         List       *retval = NIL;
754         int                     retvallen = 0;
755         int                     outer_query_keys = list_length(root->query_pathkeys);
756         List       *sub_tlist = rel->subplan->targetlist;
757         ListCell   *i;
758
759         foreach(i, subquery->query_pathkeys)
760         {
761                 List       *sub_pathkey = (List *) lfirst(i);
762                 ListCell   *j;
763                 PathKeyItem *best_item = NULL;
764                 int                     best_score = 0;
765                 List       *cpathkey;
766
767                 /*
768                  * The sub_pathkey could contain multiple elements (representing
769                  * knowledge that multiple items are effectively equal).  Each
770                  * element might match none, one, or more of the output columns
771                  * that are visible to the outer query.  This means we may have
772                  * multiple possible representations of the sub_pathkey in the
773                  * context of the outer query.  Ideally we would generate them all
774                  * and put them all into a pathkey list of the outer query,
775                  * thereby propagating equality knowledge up to the outer query.
776                  * Right now we cannot do so, because the outer query's canonical
777                  * pathkey sets are already frozen when this is called.  Instead
778                  * we prefer the one that has the highest "score" (number of
779                  * canonical pathkey peers, plus one if it matches the outer
780                  * query_pathkeys). This is the most likely to be useful in the
781                  * outer query.
782                  */
783                 foreach(j, sub_pathkey)
784                 {
785                         PathKeyItem *sub_item = (PathKeyItem *) lfirst(j);
786                         Node       *sub_key = sub_item->key;
787                         ListCell   *k;
788
789                         foreach(k, sub_tlist)
790                         {
791                                 TargetEntry *tle = (TargetEntry *) lfirst(k);
792
793                                 if (!tle->resdom->resjunk &&
794                                         equal(tle->expr, sub_key))
795                                 {
796                                         /* Found a representation for this sub_key */
797                                         Var                *outer_var;
798                                         PathKeyItem *outer_item;
799                                         int                     score;
800
801                                         outer_var = makeVar(rel->relid,
802                                                                                 tle->resdom->resno,
803                                                                                 tle->resdom->restype,
804                                                                                 tle->resdom->restypmod,
805                                                                                 0);
806                                         outer_item = makePathKeyItem((Node *) outer_var,
807                                                                                                  sub_item->sortop,
808                                                                                                  true);
809                                         /* score = # of mergejoin peers */
810                                         score = count_canonical_peers(root, outer_item);
811                                         /* +1 if it matches the proper query_pathkeys item */
812                                         if (retvallen < outer_query_keys &&
813                                                 list_member(list_nth(root->query_pathkeys, retvallen), outer_item))
814                                                 score++;
815                                         if (score > best_score)
816                                         {
817                                                 best_item = outer_item;
818                                                 best_score = score;
819                                         }
820                                 }
821                         }
822                 }
823
824                 /*
825                  * If we couldn't find a representation of this sub_pathkey, we're
826                  * done (we can't use the ones to its right, either).
827                  */
828                 if (!best_item)
829                         break;
830
831                 /* Canonicalize the chosen item (we did not before) */
832                 cpathkey = make_canonical_pathkey(root, best_item);
833
834                 /*
835                  * Eliminate redundant ordering info; could happen if outer query
836                  * equijoins subquery keys...
837                  */
838                 if (!list_member_ptr(retval, cpathkey))
839                 {
840                         retval = lappend(retval, cpathkey);
841                         retvallen++;
842                 }
843         }
844
845         return retval;
846 }
847
848 /*
849  * build_join_pathkeys
850  *        Build the path keys for a join relation constructed by mergejoin or
851  *        nestloop join.  These keys should include all the path key vars of the
852  *        outer path (since the join will retain the ordering of the outer path)
853  *        plus any vars of the inner path that are equijoined to the outer vars.
854  *
855  *        Per the discussion in backend/optimizer/README, equijoined inner vars
856  *        can be considered path keys of the result, just the same as the outer
857  *        vars they were joined with; furthermore, it doesn't matter what kind
858  *        of join algorithm is actually used.
859  *
860  * 'joinrel' is the join relation that paths are being formed for
861  * 'outer_pathkeys' is the list of the current outer path's path keys
862  *
863  * Returns the list of new path keys.
864  */
865 List *
866 build_join_pathkeys(Query *root,
867                                         RelOptInfo *joinrel,
868                                         List *outer_pathkeys)
869 {
870         /*
871          * This used to be quite a complex bit of code, but now that all
872          * pathkey sublists start out life canonicalized, we don't have to do
873          * a darn thing here!  The inner-rel vars we used to need to add are
874          * *already* part of the outer pathkey!
875          *
876          * We do, however, need to truncate the pathkeys list, since it may
877          * contain pathkeys that were useful for forming this joinrel but are
878          * uninteresting to higher levels.
879          */
880         return truncate_useless_pathkeys(root, joinrel, outer_pathkeys);
881 }
882
883 /****************************************************************************
884  *              PATHKEYS AND SORT CLAUSES
885  ****************************************************************************/
886
887 /*
888  * make_pathkeys_for_sortclauses
889  *              Generate a pathkeys list that represents the sort order specified
890  *              by a list of SortClauses (GroupClauses will work too!)
891  *
892  * NB: the result is NOT in canonical form, but must be passed through
893  * canonicalize_pathkeys() before it can be used for comparisons or
894  * labeling relation sort orders.  (We do things this way because
895  * grouping_planner needs to be able to construct requested pathkeys
896  * before the pathkey equivalence sets have been created for the query.)
897  *
898  * 'sortclauses' is a list of SortClause or GroupClause nodes
899  * 'tlist' is the targetlist to find the referenced tlist entries in
900  */
901 List *
902 make_pathkeys_for_sortclauses(List *sortclauses,
903                                                           List *tlist)
904 {
905         List       *pathkeys = NIL;
906         ListCell   *l;
907
908         foreach(l, sortclauses)
909         {
910                 SortClause *sortcl = (SortClause *) lfirst(l);
911                 Node       *sortkey;
912                 PathKeyItem *pathkey;
913
914                 sortkey = get_sortgroupclause_expr(sortcl, tlist);
915                 pathkey = makePathKeyItem(sortkey, sortcl->sortop, true);
916
917                 /*
918                  * The pathkey becomes a one-element sublist, for now;
919                  * canonicalize_pathkeys() might replace it with a longer sublist
920                  * later.
921                  */
922                 pathkeys = lappend(pathkeys, list_make1(pathkey));
923         }
924         return pathkeys;
925 }
926
927 /****************************************************************************
928  *              PATHKEYS AND MERGECLAUSES
929  ****************************************************************************/
930
931 /*
932  * cache_mergeclause_pathkeys
933  *              Make the cached pathkeys valid in a mergeclause restrictinfo.
934  *
935  * RestrictInfo contains fields in which we may cache the result
936  * of looking up the canonical pathkeys for the left and right sides
937  * of the mergeclause.  (Note that in normal cases they will be the
938  * same, but not if the mergeclause appears above an OUTER JOIN.)
939  * This is a worthwhile savings because these routines will be invoked
940  * many times when dealing with a many-relation query.
941  *
942  * We have to be careful that the cached values are palloc'd in the same
943  * context the RestrictInfo node itself is in.  This is not currently a
944  * problem for normal planning, but it is an issue for GEQO planning.
945  */
946 void
947 cache_mergeclause_pathkeys(Query *root, RestrictInfo *restrictinfo)
948 {
949         Node       *key;
950         PathKeyItem *item;
951         MemoryContext oldcontext;
952
953         Assert(restrictinfo->mergejoinoperator != InvalidOid);
954
955         if (restrictinfo->left_pathkey == NIL)
956         {
957                 oldcontext = MemoryContextSwitchTo(GetMemoryChunkContext(restrictinfo));
958                 key = get_leftop(restrictinfo->clause);
959                 item = makePathKeyItem(key, restrictinfo->left_sortop, false);
960                 restrictinfo->left_pathkey = make_canonical_pathkey(root, item);
961                 MemoryContextSwitchTo(oldcontext);
962         }
963         if (restrictinfo->right_pathkey == NIL)
964         {
965                 oldcontext = MemoryContextSwitchTo(GetMemoryChunkContext(restrictinfo));
966                 key = get_rightop(restrictinfo->clause);
967                 item = makePathKeyItem(key, restrictinfo->right_sortop, false);
968                 restrictinfo->right_pathkey = make_canonical_pathkey(root, item);
969                 MemoryContextSwitchTo(oldcontext);
970         }
971 }
972
973 /*
974  * find_mergeclauses_for_pathkeys
975  *        This routine attempts to find a set of mergeclauses that can be
976  *        used with a specified ordering for one of the input relations.
977  *        If successful, it returns a list of mergeclauses.
978  *
979  * 'pathkeys' is a pathkeys list showing the ordering of an input path.
980  *                      It doesn't matter whether it is for the inner or outer path.
981  * 'restrictinfos' is a list of mergejoinable restriction clauses for the
982  *                      join relation being formed.
983  *
984  * The result is NIL if no merge can be done, else a maximal list of
985  * usable mergeclauses (represented as a list of their restrictinfo nodes).
986  *
987  * XXX Ideally we ought to be considering context, ie what path orderings
988  * are available on the other side of the join, rather than just making
989  * an arbitrary choice among the mergeclauses that will work for this side
990  * of the join.
991  */
992 List *
993 find_mergeclauses_for_pathkeys(Query *root,
994                                                            List *pathkeys,
995                                                            List *restrictinfos)
996 {
997         List       *mergeclauses = NIL;
998         ListCell   *i;
999
1000         /* make sure we have pathkeys cached in the clauses */
1001         foreach(i, restrictinfos)
1002         {
1003                 RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(i);
1004
1005                 cache_mergeclause_pathkeys(root, restrictinfo);
1006         }
1007
1008         foreach(i, pathkeys)
1009         {
1010                 List       *pathkey = (List *) lfirst(i);
1011                 List       *matched_restrictinfos = NIL;
1012                 ListCell   *j;
1013
1014                 /*
1015                  * We can match a pathkey against either left or right side of any
1016                  * mergejoin clause.  (We examine both sides since we aren't told
1017                  * if the given pathkeys are for inner or outer input path; no
1018                  * confusion is possible.)      Furthermore, if there are multiple
1019                  * matching clauses, take them all.  In plain inner-join scenarios
1020                  * we expect only one match, because redundant-mergeclause
1021                  * elimination will have removed any redundant mergeclauses from
1022                  * the input list. However, in outer-join scenarios there might be
1023                  * multiple matches. An example is
1024                  *
1025                  * select * from a full join b on a.v1 = b.v1 and a.v2 = b.v2 and
1026                  * a.v1 = b.v2;
1027                  *
1028                  * Given the pathkeys ((a.v1), (a.v2)) it is okay to return all three
1029                  * clauses (in the order a.v1=b.v1, a.v1=b.v2, a.v2=b.v2) and
1030                  * indeed we *must* do so or we will be unable to form a valid
1031                  * plan.
1032                  */
1033                 foreach(j, restrictinfos)
1034                 {
1035                         RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(j);
1036
1037                         /*
1038                          * We can compare canonical pathkey sublists by simple pointer
1039                          * equality; see compare_pathkeys.
1040                          */
1041                         if ((pathkey == restrictinfo->left_pathkey ||
1042                                  pathkey == restrictinfo->right_pathkey) &&
1043                                 !list_member_ptr(mergeclauses, restrictinfo))
1044                         {
1045                                 matched_restrictinfos = lappend(matched_restrictinfos,
1046                                                                                                 restrictinfo);
1047                         }
1048                 }
1049
1050                 /*
1051                  * If we didn't find a mergeclause, we're done --- any additional
1052                  * sort-key positions in the pathkeys are useless.      (But we can
1053                  * still mergejoin if we found at least one mergeclause.)
1054                  */
1055                 if (matched_restrictinfos == NIL)
1056                         break;
1057
1058                 /*
1059                  * If we did find usable mergeclause(s) for this sort-key
1060                  * position, add them to result list.
1061                  */
1062                 mergeclauses = list_concat(mergeclauses, matched_restrictinfos);
1063         }
1064
1065         return mergeclauses;
1066 }
1067
1068 /*
1069  * make_pathkeys_for_mergeclauses
1070  *        Builds a pathkey list representing the explicit sort order that
1071  *        must be applied to a path in order to make it usable for the
1072  *        given mergeclauses.
1073  *
1074  * 'mergeclauses' is a list of RestrictInfos for mergejoin clauses
1075  *                      that will be used in a merge join.
1076  * 'rel' is the relation the pathkeys will apply to (ie, either the inner
1077  *                      or outer side of the proposed join rel).
1078  *
1079  * Returns a pathkeys list that can be applied to the indicated relation.
1080  *
1081  * Note that it is not this routine's job to decide whether sorting is
1082  * actually needed for a particular input path.  Assume a sort is necessary;
1083  * just make the keys, eh?
1084  */
1085 List *
1086 make_pathkeys_for_mergeclauses(Query *root,
1087                                                            List *mergeclauses,
1088                                                            RelOptInfo *rel)
1089 {
1090         List       *pathkeys = NIL;
1091         ListCell   *l;
1092
1093         foreach(l, mergeclauses)
1094         {
1095                 RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(l);
1096                 List       *pathkey;
1097
1098                 cache_mergeclause_pathkeys(root, restrictinfo);
1099
1100                 if (bms_is_subset(restrictinfo->left_relids, rel->relids))
1101                 {
1102                         /* Rel is left side of mergeclause */
1103                         pathkey = restrictinfo->left_pathkey;
1104                 }
1105                 else if (bms_is_subset(restrictinfo->right_relids, rel->relids))
1106                 {
1107                         /* Rel is right side of mergeclause */
1108                         pathkey = restrictinfo->right_pathkey;
1109                 }
1110                 else
1111                 {
1112                         elog(ERROR, "could not identify which side of mergeclause to use");
1113                         pathkey = NIL;          /* keep compiler quiet */
1114                 }
1115
1116                 /*
1117                  * When we are given multiple merge clauses, it's possible that
1118                  * some clauses refer to the same vars as earlier clauses. There's
1119                  * no reason for us to specify sort keys like (A,B,A) when (A,B)
1120                  * will do --- and adding redundant sort keys makes add_path think
1121                  * that this sort order is different from ones that are really the
1122                  * same, so don't do it.  Since we now have a canonicalized
1123                  * pathkey, a simple ptrMember test is sufficient to detect
1124                  * redundant keys.
1125                  */
1126                 if (!list_member_ptr(pathkeys, pathkey))
1127                         pathkeys = lappend(pathkeys, pathkey);
1128         }
1129
1130         return pathkeys;
1131 }
1132
1133 /****************************************************************************
1134  *              PATHKEY USEFULNESS CHECKS
1135  *
1136  * We only want to remember as many of the pathkeys of a path as have some
1137  * potential use, either for subsequent mergejoins or for meeting the query's
1138  * requested output ordering.  This ensures that add_path() won't consider
1139  * a path to have a usefully different ordering unless it really is useful.
1140  * These routines check for usefulness of given pathkeys.
1141  ****************************************************************************/
1142
1143 /*
1144  * pathkeys_useful_for_merging
1145  *              Count the number of pathkeys that may be useful for mergejoins
1146  *              above the given relation (by looking at its joininfo lists).
1147  *
1148  * We consider a pathkey potentially useful if it corresponds to the merge
1149  * ordering of either side of any joinclause for the rel.  This might be
1150  * overoptimistic, since joinclauses that appear in different join lists
1151  * might never be usable at the same time, but trying to be exact is likely
1152  * to be more trouble than it's worth.
1153  */
1154 int
1155 pathkeys_useful_for_merging(Query *root, RelOptInfo *rel, List *pathkeys)
1156 {
1157         int                     useful = 0;
1158         ListCell   *i;
1159
1160         foreach(i, pathkeys)
1161         {
1162                 List       *pathkey = (List *) lfirst(i);
1163                 bool            matched = false;
1164                 ListCell   *j;
1165
1166                 foreach(j, rel->joininfo)
1167                 {
1168                         JoinInfo   *joininfo = (JoinInfo *) lfirst(j);
1169                         ListCell   *k;
1170
1171                         foreach(k, joininfo->jinfo_restrictinfo)
1172                         {
1173                                 RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(k);
1174
1175                                 if (restrictinfo->mergejoinoperator == InvalidOid)
1176                                         continue;
1177                                 cache_mergeclause_pathkeys(root, restrictinfo);
1178
1179                                 /*
1180                                  * We can compare canonical pathkey sublists by simple
1181                                  * pointer equality; see compare_pathkeys.
1182                                  */
1183                                 if (pathkey == restrictinfo->left_pathkey ||
1184                                         pathkey == restrictinfo->right_pathkey)
1185                                 {
1186                                         matched = true;
1187                                         break;
1188                                 }
1189                         }
1190
1191                         if (matched)
1192                                 break;
1193                 }
1194
1195                 /*
1196                  * If we didn't find a mergeclause, we're done --- any additional
1197                  * sort-key positions in the pathkeys are useless.      (But we can
1198                  * still mergejoin if we found at least one mergeclause.)
1199                  */
1200                 if (matched)
1201                         useful++;
1202                 else
1203                         break;
1204         }
1205
1206         return useful;
1207 }
1208
1209 /*
1210  * pathkeys_useful_for_ordering
1211  *              Count the number of pathkeys that are useful for meeting the
1212  *              query's requested output ordering.
1213  *
1214  * Unlike merge pathkeys, this is an all-or-nothing affair: it does us
1215  * no good to order by just the first key(s) of the requested ordering.
1216  * So the result is always either 0 or list_length(root->query_pathkeys).
1217  */
1218 int
1219 pathkeys_useful_for_ordering(Query *root, List *pathkeys)
1220 {
1221         if (root->query_pathkeys == NIL)
1222                 return 0;                               /* no special ordering requested */
1223
1224         if (pathkeys == NIL)
1225                 return 0;                               /* unordered path */
1226
1227         if (pathkeys_contained_in(root->query_pathkeys, pathkeys))
1228         {
1229                 /* It's useful ... or at least the first N keys are */
1230                 return list_length(root->query_pathkeys);
1231         }
1232
1233         return 0;                                       /* path ordering not useful */
1234 }
1235
1236 /*
1237  * truncate_useless_pathkeys
1238  *              Shorten the given pathkey list to just the useful pathkeys.
1239  */
1240 List *
1241 truncate_useless_pathkeys(Query *root,
1242                                                   RelOptInfo *rel,
1243                                                   List *pathkeys)
1244 {
1245         int                     nuseful;
1246         int                     nuseful2;
1247
1248         nuseful = pathkeys_useful_for_merging(root, rel, pathkeys);
1249         nuseful2 = pathkeys_useful_for_ordering(root, pathkeys);
1250         if (nuseful2 > nuseful)
1251                 nuseful = nuseful2;
1252
1253         /*
1254          * Note: not safe to modify input list destructively, but we can avoid
1255          * copying the list if we're not actually going to change it
1256          */
1257         if (nuseful == list_length(pathkeys))
1258                 return pathkeys;
1259         else
1260                 return list_truncate(list_copy(pathkeys), nuseful);
1261 }