]> granicus.if.org Git - postgresql/blob - src/backend/optimizer/path/pathkeys.c
Planner failed to be smart about binary-compatible expressions in pathkeys
[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.55 2003/12/03 17:45:07 tgl 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                            *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 = root->equi_key_list;
126         while (cursetlink)
127         {
128                 List       *curset = lfirst(cursetlink);
129                 bool            item1here = member(item1, curset);
130                 bool            item2here = member(item2, curset);
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 = makeList2(item1, item2);
151
152                         /* Found a set to merge into our new set */
153                         newset = set_union(newset, curset);
154
155                         /*
156                          * Remove old set from equi_key_list.
157                          */
158                         root->equi_key_list = lremove(curset, root->equi_key_list);
159                         freeList(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 = makeList2(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         List       *cursetlink;
203
204         foreach(cursetlink, root->equi_key_list)
205         {
206                 List       *curset = lfirst(cursetlink);
207                 int                     nitems = length(curset);
208                 Relids     *relids;
209                 bool            have_consts;
210                 List       *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                         List       *ptr2;
249                         int                     i2 = i1 + 1;
250
251                         foreach(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         List       *cursetlink;
298
299         foreach(cursetlink, root->equi_key_list)
300         {
301                 List       *curset = lfirst(cursetlink);
302                 bool            item1member = false;
303                 bool            item2member = false;
304                 List       *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       *cursetlink;
338         List       *newset;
339
340         foreach(cursetlink, root->equi_key_list)
341         {
342                 List       *curset = lfirst(cursetlink);
343
344                 if (member(item, curset))
345                         return curset;
346         }
347         newset = makeList1(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         List       *i;
364
365         foreach(i, pathkeys)
366         {
367                 List       *pathkey = (List *) lfirst(i);
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 *) lfirst(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 (!ptrMember(cpathkey, new_pathkeys))
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         List       *cursetlink;
406
407         foreach(cursetlink, root->equi_key_list)
408         {
409                 List       *curset = lfirst(cursetlink);
410
411                 if (member(item, curset))
412                         return 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         List       *key1,
434                            *key2;
435
436         for (key1 = keys1, key2 = keys2;
437                  key1 != NIL && key2 != NIL;
438                  key1 = lnext(key1), key2 = lnext(key2))
439         {
440                 List       *subkey1 = lfirst(key1);
441                 List       *subkey2 = lfirst(key2);
442
443                 /*
444                  * XXX would like to check that we've been given canonicalized
445                  * input, but query root not accessible here...
446                  */
447 #ifdef NOT_USED
448                 Assert(ptrMember(subkey1, root->equi_key_list));
449                 Assert(ptrMember(subkey2, root->equi_key_list));
450 #endif
451
452                 /*
453                  * We will never have two subkeys where one is a subset of the
454                  * other, because of the canonicalization process.      Either they
455                  * are equal or they ain't.  Furthermore, we only need pointer
456                  * comparison to detect equality.
457                  */
458                 if (subkey1 != subkey2)
459                         return PATHKEYS_DIFFERENT;      /* no need to keep looking */
460         }
461
462         /*
463          * If we reached the end of only one list, the other is longer and
464          * therefore not a subset.      (We assume the additional sublist(s) of
465          * the other list are not NIL --- no pathkey list should ever have a
466          * NIL sublist.)
467          */
468         if (key1 == NIL && key2 == NIL)
469                 return PATHKEYS_EQUAL;
470         if (key1 != NIL)
471                 return PATHKEYS_BETTER1;        /* key1 is longer */
472         return PATHKEYS_BETTER2;        /* key2 is longer */
473 }
474
475 /*
476  * compare_noncanonical_pathkeys
477  *        Compare two pathkeys to see if they are equivalent, and if not whether
478  *        one is "better" than the other.  This is used when we must compare
479  *        non-canonicalized pathkeys.
480  *
481  *        A pathkey can be considered better than another if it is a superset:
482  *        it contains all the keys of the other plus more.      For example, either
483  *        ((A) (B)) or ((A B)) is better than ((A)).
484  *
485  *        Currently, the only user of this routine is grouping_planner(),
486  *        and it will only pass single-element sublists (from
487  *        make_pathkeys_for_sortclauses).  Therefore we don't have to do the
488  *        full two-way-subset-inclusion test on each pair of sublists that is
489  *        implied by the above statement.  Instead we just verify they are
490  *        singleton lists and then do an equal().  This could be improved if
491  *        necessary.
492  */
493 PathKeysComparison
494 compare_noncanonical_pathkeys(List *keys1, List *keys2)
495 {
496         List       *key1,
497                            *key2;
498
499         for (key1 = keys1, key2 = keys2;
500                  key1 != NIL && key2 != NIL;
501                  key1 = lnext(key1), key2 = lnext(key2))
502         {
503                 List       *subkey1 = lfirst(key1);
504                 List       *subkey2 = lfirst(key2);
505
506                 Assert(length(subkey1) == 1);
507                 Assert(length(subkey2) == 1);
508                 if (!equal(subkey1, subkey2))
509                         return PATHKEYS_DIFFERENT;      /* no need to keep looking */
510         }
511
512         /*
513          * If we reached the end of only one list, the other is longer and
514          * therefore not a subset.      (We assume the additional sublist(s) of
515          * the other list are not NIL --- no pathkey list should ever have a
516          * NIL sublist.)
517          */
518         if (key1 == NIL && key2 == NIL)
519                 return PATHKEYS_EQUAL;
520         if (key1 != NIL)
521                 return PATHKEYS_BETTER1;        /* key1 is longer */
522         return PATHKEYS_BETTER2;        /* key2 is longer */
523 }
524
525 /*
526  * pathkeys_contained_in
527  *        Common special case of compare_pathkeys: we just want to know
528  *        if keys2 are at least as well sorted as keys1.
529  */
530 bool
531 pathkeys_contained_in(List *keys1, List *keys2)
532 {
533         switch (compare_pathkeys(keys1, keys2))
534         {
535                 case PATHKEYS_EQUAL:
536                 case PATHKEYS_BETTER2:
537                         return true;
538                 default:
539                         break;
540         }
541         return false;
542 }
543
544 /*
545  * noncanonical_pathkeys_contained_in
546  *        The same, when we don't have canonical pathkeys.
547  */
548 bool
549 noncanonical_pathkeys_contained_in(List *keys1, List *keys2)
550 {
551         switch (compare_noncanonical_pathkeys(keys1, keys2))
552         {
553                 case PATHKEYS_EQUAL:
554                 case PATHKEYS_BETTER2:
555                         return true;
556                 default:
557                         break;
558         }
559         return false;
560 }
561
562 /*
563  * get_cheapest_path_for_pathkeys
564  *        Find the cheapest path (according to the specified criterion) that
565  *        satisfies the given pathkeys.  Return NULL if no such path.
566  *
567  * 'paths' is a list of possible paths that all generate the same relation
568  * 'pathkeys' represents a required ordering (already canonicalized!)
569  * 'cost_criterion' is STARTUP_COST or TOTAL_COST
570  */
571 Path *
572 get_cheapest_path_for_pathkeys(List *paths, List *pathkeys,
573                                                            CostSelector cost_criterion)
574 {
575         Path       *matched_path = NULL;
576         List       *i;
577
578         foreach(i, paths)
579         {
580                 Path       *path = (Path *) lfirst(i);
581
582                 /*
583                  * Since cost comparison is a lot cheaper than pathkey comparison,
584                  * do that first.  (XXX is that still true?)
585                  */
586                 if (matched_path != NULL &&
587                         compare_path_costs(matched_path, path, cost_criterion) <= 0)
588                         continue;
589
590                 if (pathkeys_contained_in(pathkeys, path->pathkeys))
591                         matched_path = path;
592         }
593         return matched_path;
594 }
595
596 /*
597  * get_cheapest_fractional_path_for_pathkeys
598  *        Find the cheapest path (for retrieving a specified fraction of all
599  *        the tuples) that satisfies the given pathkeys.
600  *        Return NULL if no such path.
601  *
602  * See compare_fractional_path_costs() for the interpretation of the fraction
603  * parameter.
604  *
605  * 'paths' is a list of possible paths that all generate the same relation
606  * 'pathkeys' represents a required ordering (already canonicalized!)
607  * 'fraction' is the fraction of the total tuples expected to be retrieved
608  */
609 Path *
610 get_cheapest_fractional_path_for_pathkeys(List *paths,
611                                                                                   List *pathkeys,
612                                                                                   double fraction)
613 {
614         Path       *matched_path = NULL;
615         List       *i;
616
617         foreach(i, paths)
618         {
619                 Path       *path = (Path *) lfirst(i);
620
621                 /*
622                  * Since cost comparison is a lot cheaper than pathkey comparison,
623                  * do that first.
624                  */
625                 if (matched_path != NULL &&
626                 compare_fractional_path_costs(matched_path, path, fraction) <= 0)
627                         continue;
628
629                 if (pathkeys_contained_in(pathkeys, path->pathkeys))
630                         matched_path = path;
631         }
632         return matched_path;
633 }
634
635 /****************************************************************************
636  *              NEW PATHKEY FORMATION
637  ****************************************************************************/
638
639 /*
640  * build_index_pathkeys
641  *        Build a pathkeys list that describes the ordering induced by an index
642  *        scan using the given index.  (Note that an unordered index doesn't
643  *        induce any ordering; such an index will have no sortop OIDS in
644  *        its "ordering" field, and we will return NIL.)
645  *
646  * If 'scandir' is BackwardScanDirection, attempt to build pathkeys
647  * representing a backwards scan of the index.  Return NIL if can't do it.
648  *
649  * We generate the full pathkeys list whether or not all are useful for the
650  * current query.  Caller should do truncate_useless_pathkeys().
651  */
652 List *
653 build_index_pathkeys(Query *root,
654                                          RelOptInfo *rel,
655                                          IndexOptInfo *index,
656                                          ScanDirection scandir)
657 {
658         List       *retval = NIL;
659         int                *indexkeys = index->indexkeys;
660         Oid                *ordering = index->ordering;
661         List       *indexprs = index->indexprs;
662
663         while (*ordering != InvalidOid)
664         {
665                 PathKeyItem *item;
666                 Oid                     sortop;
667                 Node       *indexkey;
668                 List       *cpathkey;
669
670                 sortop = *ordering;
671                 if (ScanDirectionIsBackward(scandir))
672                 {
673                         sortop = get_commutator(sortop);
674                         if (sortop == InvalidOid)
675                                 break;                  /* oops, no reverse sort operator? */
676                 }
677
678                 if (*indexkeys != 0)
679                 {
680                         /* simple index column */
681                         indexkey = (Node *) find_indexkey_var(root, rel, *indexkeys);
682                 }
683                 else
684                 {
685                         /* expression --- assume we need not copy it */
686                         if (indexprs == NIL)
687                                 elog(ERROR, "wrong number of index expressions");
688                         indexkey = (Node *) lfirst(indexprs);
689                         indexprs = lnext(indexprs);
690                 }
691
692                 /* OK, make a sublist for this sort key */
693                 item = makePathKeyItem(indexkey, sortop, true);
694                 cpathkey = make_canonical_pathkey(root, item);
695
696                 /*
697                  * Eliminate redundant ordering info; could happen if query is
698                  * such that index keys are equijoined...
699                  */
700                 if (!ptrMember(cpathkey, retval))
701                         retval = lappend(retval, cpathkey);
702
703                 indexkeys++;
704                 ordering++;
705         }
706
707         return retval;
708 }
709
710 /*
711  * Find or make a Var node for the specified attribute of the rel.
712  *
713  * We first look for the var in the rel's target list, because that's
714  * easy and fast.  But the var might not be there (this should normally
715  * only happen for vars that are used in WHERE restriction clauses,
716  * but not in join clauses or in the SELECT target list).  In that case,
717  * gin up a Var node the hard way.
718  */
719 static Var *
720 find_indexkey_var(Query *root, RelOptInfo *rel, AttrNumber varattno)
721 {
722         List       *temp;
723         Index           relid;
724         Oid                     reloid,
725                                 vartypeid;
726         int32           type_mod;
727
728         foreach(temp, FastListValue(&rel->reltargetlist))
729         {
730                 Var                *var = (Var *) lfirst(temp);
731
732                 if (IsA(var, Var) &&
733                         var->varattno == varattno)
734                         return var;
735         }
736
737         relid = rel->relid;
738         reloid = getrelid(relid, root->rtable);
739         get_atttypetypmod(reloid, varattno, &vartypeid, &type_mod);
740
741         return makeVar(relid, varattno, vartypeid, type_mod, 0);
742 }
743
744 /*
745  * build_subquery_pathkeys
746  *        Build a pathkeys list that describes the ordering of a subquery's
747  *        result (in the terms of the outer query).  The subquery must already
748  *        have been planned, so that its query_pathkeys field has been set.
749  *
750  * It is not necessary for caller to do truncate_useless_pathkeys(),
751  * because we select keys in a way that takes usefulness of the keys into
752  * account.
753  */
754 List *
755 build_subquery_pathkeys(Query *root, RelOptInfo *rel, Query *subquery)
756 {
757         List       *retval = NIL;
758         int                     retvallen = 0;
759         int                     outer_query_keys = length(root->query_pathkeys);
760         List       *l;
761
762         foreach(l, subquery->query_pathkeys)
763         {
764                 List       *sub_pathkey = (List *) lfirst(l);
765                 List       *j;
766                 PathKeyItem *best_item = NULL;
767                 int                     best_score = 0;
768                 List       *cpathkey;
769
770                 /*
771                  * The sub_pathkey could contain multiple elements (representing
772                  * knowledge that multiple items are effectively equal).  Each
773                  * element might match none, one, or more of the output columns
774                  * that are visible to the outer query.  This means we may have
775                  * multiple possible representations of the sub_pathkey in the
776                  * context of the outer query.  Ideally we would generate them all
777                  * and put them all into a pathkey list of the outer query,
778                  * thereby propagating equality knowledge up to the outer query.
779                  * Right now we cannot do so, because the outer query's canonical
780                  * pathkey sets are already frozen when this is called.  Instead
781                  * we prefer the one that has the highest "score" (number of
782                  * canonical pathkey peers, plus one if it matches the outer
783                  * query_pathkeys). This is the most likely to be useful in the
784                  * outer query.
785                  */
786                 foreach(j, sub_pathkey)
787                 {
788                         PathKeyItem *sub_item = (PathKeyItem *) lfirst(j);
789                         Node       *sub_key = sub_item->key;
790                         List       *k;
791
792                         foreach(k, subquery->targetList)
793                         {
794                                 TargetEntry *tle = (TargetEntry *) lfirst(k);
795
796                                 if (!tle->resdom->resjunk &&
797                                         equal(tle->expr, sub_key))
798                                 {
799                                         /* Found a representation for this sub_key */
800                                         Var                *outer_var;
801                                         PathKeyItem *outer_item;
802                                         int                     score;
803
804                                         outer_var = makeVar(rel->relid,
805                                                                                 tle->resdom->resno,
806                                                                                 tle->resdom->restype,
807                                                                                 tle->resdom->restypmod,
808                                                                                 0);
809                                         outer_item = makePathKeyItem((Node *) outer_var,
810                                                                                                  sub_item->sortop,
811                                                                                                  true);
812                                         /* score = # of mergejoin peers */
813                                         score = count_canonical_peers(root, outer_item);
814                                         /* +1 if it matches the proper query_pathkeys item */
815                                         if (retvallen < outer_query_keys &&
816                                                 member(outer_item,
817                                                            nth(retvallen, root->query_pathkeys)))
818                                                 score++;
819                                         if (score > best_score)
820                                         {
821                                                 best_item = outer_item;
822                                                 best_score = score;
823                                         }
824                                 }
825                         }
826                 }
827
828                 /*
829                  * If we couldn't find a representation of this sub_pathkey, we're
830                  * done (we can't use the ones to its right, either).
831                  */
832                 if (!best_item)
833                         break;
834
835                 /* Canonicalize the chosen item (we did not before) */
836                 cpathkey = make_canonical_pathkey(root, best_item);
837
838                 /*
839                  * Eliminate redundant ordering info; could happen if outer query
840                  * equijoins subquery keys...
841                  */
842                 if (!ptrMember(cpathkey, retval))
843                 {
844                         retval = lappend(retval, cpathkey);
845                         retvallen++;
846                 }
847         }
848
849         return retval;
850 }
851
852 /*
853  * build_join_pathkeys
854  *        Build the path keys for a join relation constructed by mergejoin or
855  *        nestloop join.  These keys should include all the path key vars of the
856  *        outer path (since the join will retain the ordering of the outer path)
857  *        plus any vars of the inner path that are equijoined to the outer vars.
858  *
859  *        Per the discussion in backend/optimizer/README, equijoined inner vars
860  *        can be considered path keys of the result, just the same as the outer
861  *        vars they were joined with; furthermore, it doesn't matter what kind
862  *        of join algorithm is actually used.
863  *
864  * 'joinrel' is the join relation that paths are being formed for
865  * 'outer_pathkeys' is the list of the current outer path's path keys
866  *
867  * Returns the list of new path keys.
868  */
869 List *
870 build_join_pathkeys(Query *root,
871                                         RelOptInfo *joinrel,
872                                         List *outer_pathkeys)
873 {
874         /*
875          * This used to be quite a complex bit of code, but now that all
876          * pathkey sublists start out life canonicalized, we don't have to do
877          * a darn thing here!  The inner-rel vars we used to need to add are
878          * *already* part of the outer pathkey!
879          *
880          * We do, however, need to truncate the pathkeys list, since it may
881          * contain pathkeys that were useful for forming this joinrel but are
882          * uninteresting to higher levels.
883          */
884         return truncate_useless_pathkeys(root, joinrel, outer_pathkeys);
885 }
886
887 /****************************************************************************
888  *              PATHKEYS AND SORT CLAUSES
889  ****************************************************************************/
890
891 /*
892  * make_pathkeys_for_sortclauses
893  *              Generate a pathkeys list that represents the sort order specified
894  *              by a list of SortClauses (GroupClauses will work too!)
895  *
896  * NB: the result is NOT in canonical form, but must be passed through
897  * canonicalize_pathkeys() before it can be used for comparisons or
898  * labeling relation sort orders.  (We do things this way because
899  * grouping_planner needs to be able to construct requested pathkeys
900  * before the pathkey equivalence sets have been created for the query.)
901  *
902  * 'sortclauses' is a list of SortClause or GroupClause nodes
903  * 'tlist' is the targetlist to find the referenced tlist entries in
904  */
905 List *
906 make_pathkeys_for_sortclauses(List *sortclauses,
907                                                           List *tlist)
908 {
909         List       *pathkeys = NIL;
910         List       *i;
911
912         foreach(i, sortclauses)
913         {
914                 SortClause *sortcl = (SortClause *) lfirst(i);
915                 Node       *sortkey;
916                 PathKeyItem *pathkey;
917
918                 sortkey = get_sortgroupclause_expr(sortcl, tlist);
919                 pathkey = makePathKeyItem(sortkey, sortcl->sortop, true);
920
921                 /*
922                  * The pathkey becomes a one-element sublist, for now;
923                  * canonicalize_pathkeys() might replace it with a longer sublist
924                  * later.
925                  */
926                 pathkeys = lappend(pathkeys, makeList1(pathkey));
927         }
928         return pathkeys;
929 }
930
931 /****************************************************************************
932  *              PATHKEYS AND MERGECLAUSES
933  ****************************************************************************/
934
935 /*
936  * cache_mergeclause_pathkeys
937  *              Make the cached pathkeys valid in a mergeclause restrictinfo.
938  *
939  * RestrictInfo contains fields in which we may cache the result
940  * of looking up the canonical pathkeys for the left and right sides
941  * of the mergeclause.  (Note that in normal cases they will be the
942  * same, but not if the mergeclause appears above an OUTER JOIN.)
943  * This is a worthwhile savings because these routines will be invoked
944  * many times when dealing with a many-relation query.
945  *
946  * We have to be careful that the cached values are palloc'd in the same
947  * context the RestrictInfo node itself is in.  This is not currently a
948  * problem for normal planning, but it is an issue for GEQO planning.
949  */
950 void
951 cache_mergeclause_pathkeys(Query *root, RestrictInfo *restrictinfo)
952 {
953         Node       *key;
954         PathKeyItem *item;
955         MemoryContext oldcontext;
956
957         Assert(restrictinfo->mergejoinoperator != InvalidOid);
958
959         if (restrictinfo->left_pathkey == NIL)
960         {
961                 oldcontext = MemoryContextSwitchTo(GetMemoryChunkContext(restrictinfo));
962                 key = get_leftop(restrictinfo->clause);
963                 item = makePathKeyItem(key, restrictinfo->left_sortop, false);
964                 restrictinfo->left_pathkey = make_canonical_pathkey(root, item);
965                 MemoryContextSwitchTo(oldcontext);
966         }
967         if (restrictinfo->right_pathkey == NIL)
968         {
969                 oldcontext = MemoryContextSwitchTo(GetMemoryChunkContext(restrictinfo));
970                 key = get_rightop(restrictinfo->clause);
971                 item = makePathKeyItem(key, restrictinfo->right_sortop, false);
972                 restrictinfo->right_pathkey = make_canonical_pathkey(root, item);
973                 MemoryContextSwitchTo(oldcontext);
974         }
975 }
976
977 /*
978  * find_mergeclauses_for_pathkeys
979  *        This routine attempts to find a set of mergeclauses that can be
980  *        used with a specified ordering for one of the input relations.
981  *        If successful, it returns a list of mergeclauses.
982  *
983  * 'pathkeys' is a pathkeys list showing the ordering of an input path.
984  *                      It doesn't matter whether it is for the inner or outer path.
985  * 'restrictinfos' is a list of mergejoinable restriction clauses for the
986  *                      join relation being formed.
987  *
988  * The result is NIL if no merge can be done, else a maximal list of
989  * usable mergeclauses (represented as a list of their restrictinfo nodes).
990  *
991  * XXX Ideally we ought to be considering context, ie what path orderings
992  * are available on the other side of the join, rather than just making
993  * an arbitrary choice among the mergeclauses that will work for this side
994  * of the join.
995  */
996 List *
997 find_mergeclauses_for_pathkeys(Query *root,
998                                                            List *pathkeys,
999                                                            List *restrictinfos)
1000 {
1001         List       *mergeclauses = NIL;
1002         List       *i;
1003
1004         /* make sure we have pathkeys cached in the clauses */
1005         foreach(i, restrictinfos)
1006         {
1007                 RestrictInfo *restrictinfo = lfirst(i);
1008
1009                 cache_mergeclause_pathkeys(root, restrictinfo);
1010         }
1011
1012         foreach(i, pathkeys)
1013         {
1014                 List       *pathkey = lfirst(i);
1015                 List       *matched_restrictinfos = NIL;
1016                 List       *j;
1017
1018                 /*
1019                  * We can match a pathkey against either left or right side of any
1020                  * mergejoin clause.  (We examine both sides since we aren't told
1021                  * if the given pathkeys are for inner or outer input path; no
1022                  * confusion is possible.)      Furthermore, if there are multiple
1023                  * matching clauses, take them all.  In plain inner-join scenarios
1024                  * we expect only one match, because redundant-mergeclause
1025                  * elimination will have removed any redundant mergeclauses from
1026                  * the input list. However, in outer-join scenarios there might be
1027                  * multiple matches. An example is
1028                  *
1029                  * select * from a full join b on a.v1 = b.v1 and a.v2 = b.v2 and
1030                  * a.v1 = b.v2;
1031                  *
1032                  * Given the pathkeys ((a.v1), (a.v2)) it is okay to return all three
1033                  * clauses (in the order a.v1=b.v1, a.v1=b.v2, a.v2=b.v2) and
1034                  * indeed we *must* do so or we will be unable to form a valid
1035                  * plan.
1036                  */
1037                 foreach(j, restrictinfos)
1038                 {
1039                         RestrictInfo *restrictinfo = lfirst(j);
1040
1041                         /*
1042                          * We can compare canonical pathkey sublists by simple pointer
1043                          * equality; see compare_pathkeys.
1044                          */
1045                         if ((pathkey == restrictinfo->left_pathkey ||
1046                                  pathkey == restrictinfo->right_pathkey) &&
1047                                 !ptrMember(restrictinfo, mergeclauses))
1048                         {
1049                                 matched_restrictinfos = lappend(matched_restrictinfos,
1050                                                                                                 restrictinfo);
1051                         }
1052                 }
1053
1054                 /*
1055                  * If we didn't find a mergeclause, we're done --- any additional
1056                  * sort-key positions in the pathkeys are useless.      (But we can
1057                  * still mergejoin if we found at least one mergeclause.)
1058                  */
1059                 if (matched_restrictinfos == NIL)
1060                         break;
1061
1062                 /*
1063                  * If we did find usable mergeclause(s) for this sort-key
1064                  * position, add them to result list.
1065                  */
1066                 mergeclauses = nconc(mergeclauses, matched_restrictinfos);
1067         }
1068
1069         return mergeclauses;
1070 }
1071
1072 /*
1073  * make_pathkeys_for_mergeclauses
1074  *        Builds a pathkey list representing the explicit sort order that
1075  *        must be applied to a path in order to make it usable for the
1076  *        given mergeclauses.
1077  *
1078  * 'mergeclauses' is a list of RestrictInfos for mergejoin clauses
1079  *                      that will be used in a merge join.
1080  * 'rel' is the relation the pathkeys will apply to (ie, either the inner
1081  *                      or outer side of the proposed join rel).
1082  *
1083  * Returns a pathkeys list that can be applied to the indicated relation.
1084  *
1085  * Note that it is not this routine's job to decide whether sorting is
1086  * actually needed for a particular input path.  Assume a sort is necessary;
1087  * just make the keys, eh?
1088  */
1089 List *
1090 make_pathkeys_for_mergeclauses(Query *root,
1091                                                            List *mergeclauses,
1092                                                            RelOptInfo *rel)
1093 {
1094         List       *pathkeys = NIL;
1095         List       *i;
1096
1097         foreach(i, mergeclauses)
1098         {
1099                 RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(i);
1100                 List       *pathkey;
1101
1102                 cache_mergeclause_pathkeys(root, restrictinfo);
1103
1104                 if (bms_is_subset(restrictinfo->left_relids, rel->relids))
1105                 {
1106                         /* Rel is left side of mergeclause */
1107                         pathkey = restrictinfo->left_pathkey;
1108                 }
1109                 else if (bms_is_subset(restrictinfo->right_relids, rel->relids))
1110                 {
1111                         /* Rel is right side of mergeclause */
1112                         pathkey = restrictinfo->right_pathkey;
1113                 }
1114                 else
1115                 {
1116                         elog(ERROR, "could not identify which side of mergeclause to use");
1117                         pathkey = NIL;          /* keep compiler quiet */
1118                 }
1119
1120                 /*
1121                  * When we are given multiple merge clauses, it's possible that
1122                  * some clauses refer to the same vars as earlier clauses. There's
1123                  * no reason for us to specify sort keys like (A,B,A) when (A,B)
1124                  * will do --- and adding redundant sort keys makes add_path think
1125                  * that this sort order is different from ones that are really the
1126                  * same, so don't do it.  Since we now have a canonicalized
1127                  * pathkey, a simple ptrMember test is sufficient to detect
1128                  * redundant keys.
1129                  */
1130                 if (!ptrMember(pathkey, pathkeys))
1131                         pathkeys = lappend(pathkeys, pathkey);
1132         }
1133
1134         return pathkeys;
1135 }
1136
1137 /****************************************************************************
1138  *              PATHKEY USEFULNESS CHECKS
1139  *
1140  * We only want to remember as many of the pathkeys of a path as have some
1141  * potential use, either for subsequent mergejoins or for meeting the query's
1142  * requested output ordering.  This ensures that add_path() won't consider
1143  * a path to have a usefully different ordering unless it really is useful.
1144  * These routines check for usefulness of given pathkeys.
1145  ****************************************************************************/
1146
1147 /*
1148  * pathkeys_useful_for_merging
1149  *              Count the number of pathkeys that may be useful for mergejoins
1150  *              above the given relation (by looking at its joininfo lists).
1151  *
1152  * We consider a pathkey potentially useful if it corresponds to the merge
1153  * ordering of either side of any joinclause for the rel.  This might be
1154  * overoptimistic, since joinclauses that appear in different join lists
1155  * might never be usable at the same time, but trying to be exact is likely
1156  * to be more trouble than it's worth.
1157  */
1158 int
1159 pathkeys_useful_for_merging(Query *root, RelOptInfo *rel, List *pathkeys)
1160 {
1161         int                     useful = 0;
1162         List       *i;
1163
1164         foreach(i, pathkeys)
1165         {
1166                 List       *pathkey = lfirst(i);
1167                 bool            matched = false;
1168                 List       *j;
1169
1170                 foreach(j, rel->joininfo)
1171                 {
1172                         JoinInfo   *joininfo = (JoinInfo *) lfirst(j);
1173                         List       *k;
1174
1175                         foreach(k, joininfo->jinfo_restrictinfo)
1176                         {
1177                                 RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(k);
1178
1179                                 if (restrictinfo->mergejoinoperator == InvalidOid)
1180                                         continue;
1181                                 cache_mergeclause_pathkeys(root, restrictinfo);
1182
1183                                 /*
1184                                  * We can compare canonical pathkey sublists by simple
1185                                  * pointer equality; see compare_pathkeys.
1186                                  */
1187                                 if (pathkey == restrictinfo->left_pathkey ||
1188                                         pathkey == restrictinfo->right_pathkey)
1189                                 {
1190                                         matched = true;
1191                                         break;
1192                                 }
1193                         }
1194
1195                         if (matched)
1196                                 break;
1197                 }
1198
1199                 /*
1200                  * If we didn't find a mergeclause, we're done --- any additional
1201                  * sort-key positions in the pathkeys are useless.      (But we can
1202                  * still mergejoin if we found at least one mergeclause.)
1203                  */
1204                 if (matched)
1205                         useful++;
1206                 else
1207                         break;
1208         }
1209
1210         return useful;
1211 }
1212
1213 /*
1214  * pathkeys_useful_for_ordering
1215  *              Count the number of pathkeys that are useful for meeting the
1216  *              query's requested output ordering.
1217  *
1218  * Unlike merge pathkeys, this is an all-or-nothing affair: it does us
1219  * no good to order by just the first key(s) of the requested ordering.
1220  * So the result is always either 0 or length(root->query_pathkeys).
1221  */
1222 int
1223 pathkeys_useful_for_ordering(Query *root, List *pathkeys)
1224 {
1225         if (root->query_pathkeys == NIL)
1226                 return 0;                               /* no special ordering requested */
1227
1228         if (pathkeys == NIL)
1229                 return 0;                               /* unordered path */
1230
1231         if (pathkeys_contained_in(root->query_pathkeys, pathkeys))
1232         {
1233                 /* It's useful ... or at least the first N keys are */
1234                 return length(root->query_pathkeys);
1235         }
1236
1237         return 0;                                       /* path ordering not useful */
1238 }
1239
1240 /*
1241  * truncate_useless_pathkeys
1242  *              Shorten the given pathkey list to just the useful pathkeys.
1243  */
1244 List *
1245 truncate_useless_pathkeys(Query *root,
1246                                                   RelOptInfo *rel,
1247                                                   List *pathkeys)
1248 {
1249         int                     nuseful;
1250         int                     nuseful2;
1251
1252         nuseful = pathkeys_useful_for_merging(root, rel, pathkeys);
1253         nuseful2 = pathkeys_useful_for_ordering(root, pathkeys);
1254         if (nuseful2 > nuseful)
1255                 nuseful = nuseful2;
1256
1257         /*
1258          * Note: not safe to modify input list destructively, but we can avoid
1259          * copying the list if we're not actually going to change it
1260          */
1261         if (nuseful == length(pathkeys))
1262                 return pathkeys;
1263         else
1264                 return ltruncate(nuseful, listCopy(pathkeys));
1265 }