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