OSDN Git Service

Edit copyright years.
[pghintplan/pg_hint_plan.git] / core.c
1 /*-------------------------------------------------------------------------
2  *
3  * core.c
4  *        Routines copied from PostgreSQL core distribution.
5  *
6  * src/backend/optimizer/path/allpaths.c
7  *     set_append_rel_pathlist()
8  *     generate_mergeappend_paths()
9  *     get_cheapest_parameterized_child_path()
10  *     accumulate_append_subpath()
11  *     standard_join_search()
12  *
13  * src/backend/optimizer/path/joinrels.c
14  *     join_search_one_level()
15  *     make_rels_by_clause_joins()
16  *     make_rels_by_clauseless_joins()
17  *     join_is_legal()
18  *     has_join_restriction()
19  *     is_dummy_rel()
20  *     mark_dummy_rel()
21  *     restriction_is_constant_false()
22  *
23  * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group
24  * Portions Copyright (c) 1994, Regents of the University of California
25  *
26  *-------------------------------------------------------------------------
27  */
28
29 /*
30  * set_append_rel_pathlist
31  *        Build access paths for an "append relation"
32  */
33 static void
34 set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
35                                                 Index rti, RangeTblEntry *rte)
36 {
37         int                     parentRTindex = rti;
38         List       *live_childrels = NIL;
39         List       *subpaths = NIL;
40         bool            subpaths_valid = true;
41         List       *all_child_pathkeys = NIL;
42         List       *all_child_outers = NIL;
43         ListCell   *l;
44
45         /*
46          * Generate access paths for each member relation, and remember the
47          * cheapest path for each one.  Also, identify all pathkeys (orderings)
48          * and parameterizations (required_outer sets) available for the member
49          * relations.
50          */
51         foreach(l, root->append_rel_list)
52         {
53                 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
54                 int                     childRTindex;
55                 RangeTblEntry *childRTE;
56                 RelOptInfo *childrel;
57                 ListCell   *lcp;
58
59                 /* append_rel_list contains all append rels; ignore others */
60                 if (appinfo->parent_relid != parentRTindex)
61                         continue;
62
63                 /* Re-locate the child RTE and RelOptInfo */
64                 childRTindex = appinfo->child_relid;
65                 childRTE = root->simple_rte_array[childRTindex];
66                 childrel = root->simple_rel_array[childRTindex];
67
68                 /*
69                  * Compute the child's access paths.
70                  */
71                 set_rel_pathlist(root, childrel, childRTindex, childRTE);
72
73                 /*
74                  * If child is dummy, ignore it.
75                  */
76                 if (IS_DUMMY_REL(childrel))
77                         continue;
78
79                 /*
80                  * Child is live, so add it to the live_childrels list for use below.
81                  */
82                 live_childrels = lappend(live_childrels, childrel);
83
84                 /*
85                  * If child has an unparameterized cheapest-total path, add that to
86                  * the unparameterized Append path we are constructing for the parent.
87                  * If not, there's no workable unparameterized path.
88                  */
89                 if (childrel->cheapest_total_path->param_info == NULL)
90                         subpaths = accumulate_append_subpath(subpaths,
91                                                                                           childrel->cheapest_total_path);
92                 else
93                         subpaths_valid = false;
94
95                 /*
96                  * Collect lists of all the available path orderings and
97                  * parameterizations for all the children.  We use these as a
98                  * heuristic to indicate which sort orderings and parameterizations we
99                  * should build Append and MergeAppend paths for.
100                  */
101                 foreach(lcp, childrel->pathlist)
102                 {
103                         Path       *childpath = (Path *) lfirst(lcp);
104                         List       *childkeys = childpath->pathkeys;
105                         Relids          childouter = PATH_REQ_OUTER(childpath);
106
107                         /* Unsorted paths don't contribute to pathkey list */
108                         if (childkeys != NIL)
109                         {
110                                 ListCell   *lpk;
111                                 bool            found = false;
112
113                                 /* Have we already seen this ordering? */
114                                 foreach(lpk, all_child_pathkeys)
115                                 {
116                                         List       *existing_pathkeys = (List *) lfirst(lpk);
117
118                                         if (compare_pathkeys(existing_pathkeys,
119                                                                                  childkeys) == PATHKEYS_EQUAL)
120                                         {
121                                                 found = true;
122                                                 break;
123                                         }
124                                 }
125                                 if (!found)
126                                 {
127                                         /* No, so add it to all_child_pathkeys */
128                                         all_child_pathkeys = lappend(all_child_pathkeys,
129                                                                                                  childkeys);
130                                 }
131                         }
132
133                         /* Unparameterized paths don't contribute to param-set list */
134                         if (childouter)
135                         {
136                                 ListCell   *lco;
137                                 bool            found = false;
138
139                                 /* Have we already seen this param set? */
140                                 foreach(lco, all_child_outers)
141                                 {
142                                         Relids          existing_outers = (Relids) lfirst(lco);
143
144                                         if (bms_equal(existing_outers, childouter))
145                                         {
146                                                 found = true;
147                                                 break;
148                                         }
149                                 }
150                                 if (!found)
151                                 {
152                                         /* No, so add it to all_child_outers */
153                                         all_child_outers = lappend(all_child_outers,
154                                                                                            childouter);
155                                 }
156                         }
157                 }
158         }
159
160         /*
161          * If we found unparameterized paths for all children, build an unordered,
162          * unparameterized Append path for the rel.  (Note: this is correct even
163          * if we have zero or one live subpath due to constraint exclusion.)
164          */
165         if (subpaths_valid)
166                 add_path(rel, (Path *) create_append_path(rel, subpaths, NULL));
167
168         /*
169          * Also build unparameterized MergeAppend paths based on the collected
170          * list of child pathkeys.
171          */
172         if (subpaths_valid)
173                 generate_mergeappend_paths(root, rel, live_childrels,
174                                                                    all_child_pathkeys);
175
176         /*
177          * Build Append paths for each parameterization seen among the child rels.
178          * (This may look pretty expensive, but in most cases of practical
179          * interest, the child rels will expose mostly the same parameterizations,
180          * so that not that many cases actually get considered here.)
181          *
182          * The Append node itself cannot enforce quals, so all qual checking must
183          * be done in the child paths.  This means that to have a parameterized
184          * Append path, we must have the exact same parameterization for each
185          * child path; otherwise some children might be failing to check the
186          * moved-down quals.  To make them match up, we can try to increase the
187          * parameterization of lesser-parameterized paths.
188          */
189         foreach(l, all_child_outers)
190         {
191                 Relids          required_outer = (Relids) lfirst(l);
192                 ListCell   *lcr;
193
194                 /* Select the child paths for an Append with this parameterization */
195                 subpaths = NIL;
196                 subpaths_valid = true;
197                 foreach(lcr, live_childrels)
198                 {
199                         RelOptInfo *childrel = (RelOptInfo *) lfirst(lcr);
200                         Path       *subpath;
201
202                         subpath = get_cheapest_parameterized_child_path(root,
203                                                                                                                         childrel,
204                                                                                                                         required_outer);
205                         if (subpath == NULL)
206                         {
207                                 /* failed to make a suitable path for this child */
208                                 subpaths_valid = false;
209                                 break;
210                         }
211                         subpaths = accumulate_append_subpath(subpaths, subpath);
212                 }
213
214                 if (subpaths_valid)
215                         add_path(rel, (Path *)
216                                          create_append_path(rel, subpaths, required_outer));
217         }
218 }
219
220 /*
221  * generate_mergeappend_paths
222  *              Generate MergeAppend paths for an append relation
223  *
224  * Generate a path for each ordering (pathkey list) appearing in
225  * all_child_pathkeys.
226  *
227  * We consider both cheapest-startup and cheapest-total cases, ie, for each
228  * interesting ordering, collect all the cheapest startup subpaths and all the
229  * cheapest total paths, and build a MergeAppend path for each case.
230  *
231  * We don't currently generate any parameterized MergeAppend paths.  While
232  * it would not take much more code here to do so, it's very unclear that it
233  * is worth the planning cycles to investigate such paths: there's little
234  * use for an ordered path on the inside of a nestloop.  In fact, it's likely
235  * that the current coding of add_path would reject such paths out of hand,
236  * because add_path gives no credit for sort ordering of parameterized paths,
237  * and a parameterized MergeAppend is going to be more expensive than the
238  * corresponding parameterized Append path.  If we ever try harder to support
239  * parameterized mergejoin plans, it might be worth adding support for
240  * parameterized MergeAppends to feed such joins.  (See notes in
241  * optimizer/README for why that might not ever happen, though.)
242  */
243 static void
244 generate_mergeappend_paths(PlannerInfo *root, RelOptInfo *rel,
245                                                    List *live_childrels,
246                                                    List *all_child_pathkeys)
247 {
248         ListCell   *lcp;
249
250         foreach(lcp, all_child_pathkeys)
251         {
252                 List       *pathkeys = (List *) lfirst(lcp);
253                 List       *startup_subpaths = NIL;
254                 List       *total_subpaths = NIL;
255                 bool            startup_neq_total = false;
256                 ListCell   *lcr;
257
258                 /* Select the child paths for this ordering... */
259                 foreach(lcr, live_childrels)
260                 {
261                         RelOptInfo *childrel = (RelOptInfo *) lfirst(lcr);
262                         Path       *cheapest_startup,
263                                            *cheapest_total;
264
265                         /* Locate the right paths, if they are available. */
266                         cheapest_startup =
267                                 get_cheapest_path_for_pathkeys(childrel->pathlist,
268                                                                                            pathkeys,
269                                                                                            NULL,
270                                                                                            STARTUP_COST);
271                         cheapest_total =
272                                 get_cheapest_path_for_pathkeys(childrel->pathlist,
273                                                                                            pathkeys,
274                                                                                            NULL,
275                                                                                            TOTAL_COST);
276
277                         /*
278                          * If we can't find any paths with the right order just use the
279                          * cheapest-total path; we'll have to sort it later.
280                          */
281                         if (cheapest_startup == NULL || cheapest_total == NULL)
282                         {
283                                 cheapest_startup = cheapest_total =
284                                         childrel->cheapest_total_path;
285                                 /* Assert we do have an unparameterized path for this child */
286                                 Assert(cheapest_total->param_info == NULL);
287                         }
288
289                         /*
290                          * Notice whether we actually have different paths for the
291                          * "cheapest" and "total" cases; frequently there will be no point
292                          * in two create_merge_append_path() calls.
293                          */
294                         if (cheapest_startup != cheapest_total)
295                                 startup_neq_total = true;
296
297                         startup_subpaths =
298                                 accumulate_append_subpath(startup_subpaths, cheapest_startup);
299                         total_subpaths =
300                                 accumulate_append_subpath(total_subpaths, cheapest_total);
301                 }
302
303                 /* ... and build the MergeAppend paths */
304                 add_path(rel, (Path *) create_merge_append_path(root,
305                                                                                                                 rel,
306                                                                                                                 startup_subpaths,
307                                                                                                                 pathkeys,
308                                                                                                                 NULL));
309                 if (startup_neq_total)
310                         add_path(rel, (Path *) create_merge_append_path(root,
311                                                                                                                         rel,
312                                                                                                                         total_subpaths,
313                                                                                                                         pathkeys,
314                                                                                                                         NULL));
315         }
316 }
317
318 /*
319  * get_cheapest_parameterized_child_path
320  *              Get cheapest path for this relation that has exactly the requested
321  *              parameterization.
322  *
323  * Returns NULL if unable to create such a path.
324  */
325 static Path *
326 get_cheapest_parameterized_child_path(PlannerInfo *root, RelOptInfo *rel,
327                                                                           Relids required_outer)
328 {
329         Path       *cheapest;
330         ListCell   *lc;
331
332         /*
333          * Look up the cheapest existing path with no more than the needed
334          * parameterization.  If it has exactly the needed parameterization, we're
335          * done.
336          */
337         cheapest = get_cheapest_path_for_pathkeys(rel->pathlist,
338                                                                                           NIL,
339                                                                                           required_outer,
340                                                                                           TOTAL_COST);
341         Assert(cheapest != NULL);
342         if (bms_equal(PATH_REQ_OUTER(cheapest), required_outer))
343                 return cheapest;
344
345         /*
346          * Otherwise, we can "reparameterize" an existing path to match the given
347          * parameterization, which effectively means pushing down additional
348          * joinquals to be checked within the path's scan.  However, some existing
349          * paths might check the available joinquals already while others don't;
350          * therefore, it's not clear which existing path will be cheapest after
351          * reparameterization.  We have to go through them all and find out.
352          */
353         cheapest = NULL;
354         foreach(lc, rel->pathlist)
355         {
356                 Path       *path = (Path *) lfirst(lc);
357
358                 /* Can't use it if it needs more than requested parameterization */
359                 if (!bms_is_subset(PATH_REQ_OUTER(path), required_outer))
360                         continue;
361
362                 /*
363                  * Reparameterization can only increase the path's cost, so if it's
364                  * already more expensive than the current cheapest, forget it.
365                  */
366                 if (cheapest != NULL &&
367                         compare_path_costs(cheapest, path, TOTAL_COST) <= 0)
368                         continue;
369
370                 /* Reparameterize if needed, then recheck cost */
371                 if (!bms_equal(PATH_REQ_OUTER(path), required_outer))
372                 {
373                         path = reparameterize_path(root, path, required_outer, 1.0);
374                         if (path == NULL)
375                                 continue;               /* failed to reparameterize this one */
376                         Assert(bms_equal(PATH_REQ_OUTER(path), required_outer));
377
378                         if (cheapest != NULL &&
379                                 compare_path_costs(cheapest, path, TOTAL_COST) <= 0)
380                                 continue;
381                 }
382
383                 /* We have a new best path */
384                 cheapest = path;
385         }
386
387         /* Return the best path, or NULL if we found no suitable candidate */
388         return cheapest;
389 }
390
391 /*
392  * accumulate_append_subpath
393  *              Add a subpath to the list being built for an Append or MergeAppend
394  *
395  * It's possible that the child is itself an Append or MergeAppend path, in
396  * which case we can "cut out the middleman" and just add its child paths to
397  * our own list.  (We don't try to do this earlier because we need to apply
398  * both levels of transformation to the quals.)
399  *
400  * Note that if we omit a child MergeAppend in this way, we are effectively
401  * omitting a sort step, which seems fine: if the parent is to be an Append,
402  * its result would be unsorted anyway, while if the parent is to be a
403  * MergeAppend, there's no point in a separate sort on a child.
404  */
405 static List *
406 accumulate_append_subpath(List *subpaths, Path *path)
407 {
408         if (IsA(path, AppendPath))
409         {
410                 AppendPath *apath = (AppendPath *) path;
411
412                 /* list_copy is important here to avoid sharing list substructure */
413                 return list_concat(subpaths, list_copy(apath->subpaths));
414         }
415         else if (IsA(path, MergeAppendPath))
416         {
417                 MergeAppendPath *mpath = (MergeAppendPath *) path;
418
419                 /* list_copy is important here to avoid sharing list substructure */
420                 return list_concat(subpaths, list_copy(mpath->subpaths));
421         }
422         else
423                 return lappend(subpaths, path);
424 }
425
426 /*
427  * standard_join_search
428  *        Find possible joinpaths for a query by successively finding ways
429  *        to join component relations into join relations.
430  *
431  * 'levels_needed' is the number of iterations needed, ie, the number of
432  *              independent jointree items in the query.  This is > 1.
433  *
434  * 'initial_rels' is a list of RelOptInfo nodes for each independent
435  *              jointree item.  These are the components to be joined together.
436  *              Note that levels_needed == list_length(initial_rels).
437  *
438  * Returns the final level of join relations, i.e., the relation that is
439  * the result of joining all the original relations together.
440  * At least one implementation path must be provided for this relation and
441  * all required sub-relations.
442  *
443  * To support loadable plugins that modify planner behavior by changing the
444  * join searching algorithm, we provide a hook variable that lets a plugin
445  * replace or supplement this function.  Any such hook must return the same
446  * final join relation as the standard code would, but it might have a
447  * different set of implementation paths attached, and only the sub-joinrels
448  * needed for these paths need have been instantiated.
449  *
450  * Note to plugin authors: the functions invoked during standard_join_search()
451  * modify root->join_rel_list and root->join_rel_hash.  If you want to do more
452  * than one join-order search, you'll probably need to save and restore the
453  * original states of those data structures.  See geqo_eval() for an example.
454  */
455 RelOptInfo *
456 standard_join_search(PlannerInfo *root, int levels_needed, List *initial_rels)
457 {
458         int                     lev;
459         RelOptInfo *rel;
460
461         /*
462          * This function cannot be invoked recursively within any one planning
463          * problem, so join_rel_level[] can't be in use already.
464          */
465         Assert(root->join_rel_level == NULL);
466
467         /*
468          * We employ a simple "dynamic programming" algorithm: we first find all
469          * ways to build joins of two jointree items, then all ways to build joins
470          * of three items (from two-item joins and single items), then four-item
471          * joins, and so on until we have considered all ways to join all the
472          * items into one rel.
473          *
474          * root->join_rel_level[j] is a list of all the j-item rels.  Initially we
475          * set root->join_rel_level[1] to represent all the single-jointree-item
476          * relations.
477          */
478         root->join_rel_level = (List **) palloc0((levels_needed + 1) * sizeof(List *));
479
480         root->join_rel_level[1] = initial_rels;
481
482         for (lev = 2; lev <= levels_needed; lev++)
483         {
484                 ListCell   *lc;
485
486                 /*
487                  * Determine all possible pairs of relations to be joined at this
488                  * level, and build paths for making each one from every available
489                  * pair of lower-level relations.
490                  */
491                 join_search_one_level(root, lev);
492
493                 /*
494                  * Do cleanup work on each just-processed rel.
495                  */
496                 foreach(lc, root->join_rel_level[lev])
497                 {
498                         rel = (RelOptInfo *) lfirst(lc);
499
500                         /* Find and save the cheapest paths for this rel */
501                         set_cheapest(rel);
502
503 #ifdef OPTIMIZER_DEBUG
504                         debug_print_rel(root, rel);
505 #endif
506                 }
507         }
508
509         /*
510          * We should have a single rel at the final level.
511          */
512         if (root->join_rel_level[levels_needed] == NIL)
513                 elog(ERROR, "failed to build any %d-way joins", levels_needed);
514         Assert(list_length(root->join_rel_level[levels_needed]) == 1);
515
516         rel = (RelOptInfo *) linitial(root->join_rel_level[levels_needed]);
517
518         root->join_rel_level = NULL;
519
520         return rel;
521 }
522
523 /*
524  * join_search_one_level
525  *        Consider ways to produce join relations containing exactly 'level'
526  *        jointree items.  (This is one step of the dynamic-programming method
527  *        embodied in standard_join_search.)  Join rel nodes for each feasible
528  *        combination of lower-level rels are created and returned in a list.
529  *        Implementation paths are created for each such joinrel, too.
530  *
531  * level: level of rels we want to make this time
532  * root->join_rel_level[j], 1 <= j < level, is a list of rels containing j items
533  *
534  * The result is returned in root->join_rel_level[level].
535  */
536 void
537 join_search_one_level(PlannerInfo *root, int level)
538 {
539         List      **joinrels = root->join_rel_level;
540         ListCell   *r;
541         int                     k;
542
543         Assert(joinrels[level] == NIL);
544
545         /* Set join_cur_level so that new joinrels are added to proper list */
546         root->join_cur_level = level;
547
548         /*
549          * First, consider left-sided and right-sided plans, in which rels of
550          * exactly level-1 member relations are joined against initial relations.
551          * We prefer to join using join clauses, but if we find a rel of level-1
552          * members that has no join clauses, we will generate Cartesian-product
553          * joins against all initial rels not already contained in it.
554          */
555         foreach(r, joinrels[level - 1])
556         {
557                 RelOptInfo *old_rel = (RelOptInfo *) lfirst(r);
558
559                 if (old_rel->joininfo != NIL || old_rel->has_eclass_joins ||
560                         has_join_restriction(root, old_rel))
561                 {
562                         /*
563                          * There are join clauses or join order restrictions relevant to
564                          * this rel, so consider joins between this rel and (only) those
565                          * initial rels it is linked to by a clause or restriction.
566                          *
567                          * At level 2 this condition is symmetric, so there is no need to
568                          * look at initial rels before this one in the list; we already
569                          * considered such joins when we were at the earlier rel.  (The
570                          * mirror-image joins are handled automatically by make_join_rel.)
571                          * In later passes (level > 2), we join rels of the previous level
572                          * to each initial rel they don't already include but have a join
573                          * clause or restriction with.
574                          */
575                         ListCell   *other_rels;
576
577                         if (level == 2)         /* consider remaining initial rels */
578                                 other_rels = lnext(r);
579                         else    /* consider all initial rels */
580                                 other_rels = list_head(joinrels[1]);
581
582                         make_rels_by_clause_joins(root,
583                                                                           old_rel,
584                                                                           other_rels);
585                 }
586                 else
587                 {
588                         /*
589                          * Oops, we have a relation that is not joined to any other
590                          * relation, either directly or by join-order restrictions.
591                          * Cartesian product time.
592                          *
593                          * We consider a cartesian product with each not-already-included
594                          * initial rel, whether it has other join clauses or not.  At
595                          * level 2, if there are two or more clauseless initial rels, we
596                          * will redundantly consider joining them in both directions; but
597                          * such cases aren't common enough to justify adding complexity to
598                          * avoid the duplicated effort.
599                          */
600                         make_rels_by_clauseless_joins(root,
601                                                                                   old_rel,
602                                                                                   list_head(joinrels[1]));
603                 }
604         }
605
606         /*
607          * Now, consider "bushy plans" in which relations of k initial rels are
608          * joined to relations of level-k initial rels, for 2 <= k <= level-2.
609          *
610          * We only consider bushy-plan joins for pairs of rels where there is a
611          * suitable join clause (or join order restriction), in order to avoid
612          * unreasonable growth of planning time.
613          */
614         for (k = 2;; k++)
615         {
616                 int                     other_level = level - k;
617
618                 /*
619                  * Since make_join_rel(x, y) handles both x,y and y,x cases, we only
620                  * need to go as far as the halfway point.
621                  */
622                 if (k > other_level)
623                         break;
624
625                 foreach(r, joinrels[k])
626                 {
627                         RelOptInfo *old_rel = (RelOptInfo *) lfirst(r);
628                         ListCell   *other_rels;
629                         ListCell   *r2;
630
631                         /*
632                          * We can ignore relations without join clauses here, unless they
633                          * participate in join-order restrictions --- then we might have
634                          * to force a bushy join plan.
635                          */
636                         if (old_rel->joininfo == NIL && !old_rel->has_eclass_joins &&
637                                 !has_join_restriction(root, old_rel))
638                                 continue;
639
640                         if (k == other_level)
641                                 other_rels = lnext(r);  /* only consider remaining rels */
642                         else
643                                 other_rels = list_head(joinrels[other_level]);
644
645                         for_each_cell(r2, other_rels)
646                         {
647                                 RelOptInfo *new_rel = (RelOptInfo *) lfirst(r2);
648
649                                 if (!bms_overlap(old_rel->relids, new_rel->relids))
650                                 {
651                                         /*
652                                          * OK, we can build a rel of the right level from this
653                                          * pair of rels.  Do so if there is at least one relevant
654                                          * join clause or join order restriction.
655                                          */
656                                         if (have_relevant_joinclause(root, old_rel, new_rel) ||
657                                                 have_join_order_restriction(root, old_rel, new_rel))
658                                         {
659                                                 (void) make_join_rel(root, old_rel, new_rel);
660                                         }
661                                 }
662                         }
663                 }
664         }
665
666         /*----------
667          * Last-ditch effort: if we failed to find any usable joins so far, force
668          * a set of cartesian-product joins to be generated.  This handles the
669          * special case where all the available rels have join clauses but we
670          * cannot use any of those clauses yet.  This can only happen when we are
671          * considering a join sub-problem (a sub-joinlist) and all the rels in the
672          * sub-problem have only join clauses with rels outside the sub-problem.
673          * An example is
674          *
675          *              SELECT ... FROM a INNER JOIN b ON TRUE, c, d, ...
676          *              WHERE a.w = c.x and b.y = d.z;
677          *
678          * If the "a INNER JOIN b" sub-problem does not get flattened into the
679          * upper level, we must be willing to make a cartesian join of a and b;
680          * but the code above will not have done so, because it thought that both
681          * a and b have joinclauses.  We consider only left-sided and right-sided
682          * cartesian joins in this case (no bushy).
683          *----------
684          */
685         if (joinrels[level] == NIL)
686         {
687                 /*
688                  * This loop is just like the first one, except we always call
689                  * make_rels_by_clauseless_joins().
690                  */
691                 foreach(r, joinrels[level - 1])
692                 {
693                         RelOptInfo *old_rel = (RelOptInfo *) lfirst(r);
694
695                         make_rels_by_clauseless_joins(root,
696                                                                                   old_rel,
697                                                                                   list_head(joinrels[1]));
698                 }
699
700                 /*----------
701                  * When special joins are involved, there may be no legal way
702                  * to make an N-way join for some values of N.  For example consider
703                  *
704                  * SELECT ... FROM t1 WHERE
705                  *       x IN (SELECT ... FROM t2,t3 WHERE ...) AND
706                  *       y IN (SELECT ... FROM t4,t5 WHERE ...)
707                  *
708                  * We will flatten this query to a 5-way join problem, but there are
709                  * no 4-way joins that join_is_legal() will consider legal.  We have
710                  * to accept failure at level 4 and go on to discover a workable
711                  * bushy plan at level 5.
712                  *
713                  * However, if there are no special joins and no lateral references
714                  * then join_is_legal() should never fail, and so the following sanity
715                  * check is useful.
716                  *----------
717                  */
718                 if (joinrels[level] == NIL &&
719                         root->join_info_list == NIL &&
720                         !root->hasLateralRTEs)
721                         elog(ERROR, "failed to build any %d-way joins", level);
722         }
723 }
724
725 /*
726  * make_rels_by_clause_joins
727  *        Build joins between the given relation 'old_rel' and other relations
728  *        that participate in join clauses that 'old_rel' also participates in
729  *        (or participate in join-order restrictions with it).
730  *        The join rels are returned in root->join_rel_level[join_cur_level].
731  *
732  * Note: at levels above 2 we will generate the same joined relation in
733  * multiple ways --- for example (a join b) join c is the same RelOptInfo as
734  * (b join c) join a, though the second case will add a different set of Paths
735  * to it.  This is the reason for using the join_rel_level mechanism, which
736  * automatically ensures that each new joinrel is only added to the list once.
737  *
738  * 'old_rel' is the relation entry for the relation to be joined
739  * 'other_rels': the first cell in a linked list containing the other
740  * rels to be considered for joining
741  *
742  * Currently, this is only used with initial rels in other_rels, but it
743  * will work for joining to joinrels too.
744  */
745 static void
746 make_rels_by_clause_joins(PlannerInfo *root,
747                                                   RelOptInfo *old_rel,
748                                                   ListCell *other_rels)
749 {
750         ListCell   *l;
751
752         for_each_cell(l, other_rels)
753         {
754                 RelOptInfo *other_rel = (RelOptInfo *) lfirst(l);
755
756                 if (!bms_overlap(old_rel->relids, other_rel->relids) &&
757                         (have_relevant_joinclause(root, old_rel, other_rel) ||
758                          have_join_order_restriction(root, old_rel, other_rel)))
759                 {
760                         (void) make_join_rel(root, old_rel, other_rel);
761                 }
762         }
763 }
764
765 /*
766  * make_rels_by_clauseless_joins
767  *        Given a relation 'old_rel' and a list of other relations
768  *        'other_rels', create a join relation between 'old_rel' and each
769  *        member of 'other_rels' that isn't already included in 'old_rel'.
770  *        The join rels are returned in root->join_rel_level[join_cur_level].
771  *
772  * 'old_rel' is the relation entry for the relation to be joined
773  * 'other_rels': the first cell of a linked list containing the
774  * other rels to be considered for joining
775  *
776  * Currently, this is only used with initial rels in other_rels, but it would
777  * work for joining to joinrels too.
778  */
779 static void
780 make_rels_by_clauseless_joins(PlannerInfo *root,
781                                                           RelOptInfo *old_rel,
782                                                           ListCell *other_rels)
783 {
784         ListCell   *l;
785
786         for_each_cell(l, other_rels)
787         {
788                 RelOptInfo *other_rel = (RelOptInfo *) lfirst(l);
789
790                 if (!bms_overlap(other_rel->relids, old_rel->relids))
791                 {
792                         (void) make_join_rel(root, old_rel, other_rel);
793                 }
794         }
795 }
796
797 /*
798  * join_is_legal
799  *         Determine whether a proposed join is legal given the query's
800  *         join order constraints; and if it is, determine the join type.
801  *
802  * Caller must supply not only the two rels, but the union of their relids.
803  * (We could simplify the API by computing joinrelids locally, but this
804  * would be redundant work in the normal path through make_join_rel.)
805  *
806  * On success, *sjinfo_p is set to NULL if this is to be a plain inner join,
807  * else it's set to point to the associated SpecialJoinInfo node.  Also,
808  * *reversed_p is set TRUE if the given relations need to be swapped to
809  * match the SpecialJoinInfo node.
810  */
811 static bool
812 join_is_legal(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2,
813                           Relids joinrelids,
814                           SpecialJoinInfo **sjinfo_p, bool *reversed_p)
815 {
816         SpecialJoinInfo *match_sjinfo;
817         bool            reversed;
818         bool            unique_ified;
819         bool            must_be_leftjoin;
820         ListCell   *l;
821
822         /*
823          * Ensure output params are set on failure return.  This is just to
824          * suppress uninitialized-variable warnings from overly anal compilers.
825          */
826         *sjinfo_p = NULL;
827         *reversed_p = false;
828
829         /*
830          * If we have any special joins, the proposed join might be illegal; and
831          * in any case we have to determine its join type.  Scan the join info
832          * list for matches and conflicts.
833          */
834         match_sjinfo = NULL;
835         reversed = false;
836         unique_ified = false;
837         must_be_leftjoin = false;
838
839         foreach(l, root->join_info_list)
840         {
841                 SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(l);
842
843                 /*
844                  * This special join is not relevant unless its RHS overlaps the
845                  * proposed join.  (Check this first as a fast path for dismissing
846                  * most irrelevant SJs quickly.)
847                  */
848                 if (!bms_overlap(sjinfo->min_righthand, joinrelids))
849                         continue;
850
851                 /*
852                  * Also, not relevant if proposed join is fully contained within RHS
853                  * (ie, we're still building up the RHS).
854                  */
855                 if (bms_is_subset(joinrelids, sjinfo->min_righthand))
856                         continue;
857
858                 /*
859                  * Also, not relevant if SJ is already done within either input.
860                  */
861                 if (bms_is_subset(sjinfo->min_lefthand, rel1->relids) &&
862                         bms_is_subset(sjinfo->min_righthand, rel1->relids))
863                         continue;
864                 if (bms_is_subset(sjinfo->min_lefthand, rel2->relids) &&
865                         bms_is_subset(sjinfo->min_righthand, rel2->relids))
866                         continue;
867
868                 /*
869                  * If it's a semijoin and we already joined the RHS to any other rels
870                  * within either input, then we must have unique-ified the RHS at that
871                  * point (see below).  Therefore the semijoin is no longer relevant in
872                  * this join path.
873                  */
874                 if (sjinfo->jointype == JOIN_SEMI)
875                 {
876                         if (bms_is_subset(sjinfo->syn_righthand, rel1->relids) &&
877                                 !bms_equal(sjinfo->syn_righthand, rel1->relids))
878                                 continue;
879                         if (bms_is_subset(sjinfo->syn_righthand, rel2->relids) &&
880                                 !bms_equal(sjinfo->syn_righthand, rel2->relids))
881                                 continue;
882                 }
883
884                 /*
885                  * If one input contains min_lefthand and the other contains
886                  * min_righthand, then we can perform the SJ at this join.
887                  *
888                  * Reject if we get matches to more than one SJ; that implies we're
889                  * considering something that's not really valid.
890                  */
891                 if (bms_is_subset(sjinfo->min_lefthand, rel1->relids) &&
892                         bms_is_subset(sjinfo->min_righthand, rel2->relids))
893                 {
894                         if (match_sjinfo)
895                                 return false;   /* invalid join path */
896                         match_sjinfo = sjinfo;
897                         reversed = false;
898                 }
899                 else if (bms_is_subset(sjinfo->min_lefthand, rel2->relids) &&
900                                  bms_is_subset(sjinfo->min_righthand, rel1->relids))
901                 {
902                         if (match_sjinfo)
903                                 return false;   /* invalid join path */
904                         match_sjinfo = sjinfo;
905                         reversed = true;
906                 }
907                 else if (sjinfo->jointype == JOIN_SEMI &&
908                                  bms_equal(sjinfo->syn_righthand, rel2->relids) &&
909                                  create_unique_path(root, rel2, rel2->cheapest_total_path,
910                                                                         sjinfo) != NULL)
911                 {
912                         /*----------
913                          * For a semijoin, we can join the RHS to anything else by
914                          * unique-ifying the RHS (if the RHS can be unique-ified).
915                          * We will only get here if we have the full RHS but less
916                          * than min_lefthand on the LHS.
917                          *
918                          * The reason to consider such a join path is exemplified by
919                          *      SELECT ... FROM a,b WHERE (a.x,b.y) IN (SELECT c1,c2 FROM c)
920                          * If we insist on doing this as a semijoin we will first have
921                          * to form the cartesian product of A*B.  But if we unique-ify
922                          * C then the semijoin becomes a plain innerjoin and we can join
923                          * in any order, eg C to A and then to B.  When C is much smaller
924                          * than A and B this can be a huge win.  So we allow C to be
925                          * joined to just A or just B here, and then make_join_rel has
926                          * to handle the case properly.
927                          *
928                          * Note that actually we'll allow unique-ified C to be joined to
929                          * some other relation D here, too.  That is legal, if usually not
930                          * very sane, and this routine is only concerned with legality not
931                          * with whether the join is good strategy.
932                          *----------
933                          */
934                         if (match_sjinfo)
935                                 return false;   /* invalid join path */
936                         match_sjinfo = sjinfo;
937                         reversed = false;
938                         unique_ified = true;
939                 }
940                 else if (sjinfo->jointype == JOIN_SEMI &&
941                                  bms_equal(sjinfo->syn_righthand, rel1->relids) &&
942                                  create_unique_path(root, rel1, rel1->cheapest_total_path,
943                                                                         sjinfo) != NULL)
944                 {
945                         /* Reversed semijoin case */
946                         if (match_sjinfo)
947                                 return false;   /* invalid join path */
948                         match_sjinfo = sjinfo;
949                         reversed = true;
950                         unique_ified = true;
951                 }
952                 else
953                 {
954                         /*
955                          * Otherwise, the proposed join overlaps the RHS but isn't a valid
956                          * implementation of this SJ.  But don't panic quite yet: the RHS
957                          * violation might have occurred previously, in one or both input
958                          * relations, in which case we must have previously decided that
959                          * it was OK to commute some other SJ with this one.  If we need
960                          * to perform this join to finish building up the RHS, rejecting
961                          * it could lead to not finding any plan at all.  (This can occur
962                          * because of the heuristics elsewhere in this file that postpone
963                          * clauseless joins: we might not consider doing a clauseless join
964                          * within the RHS until after we've performed other, validly
965                          * commutable SJs with one or both sides of the clauseless join.)
966                          * This consideration boils down to the rule that if both inputs
967                          * overlap the RHS, we can allow the join --- they are either
968                          * fully within the RHS, or represent previously-allowed joins to
969                          * rels outside it.
970                          */
971                         if (bms_overlap(rel1->relids, sjinfo->min_righthand) &&
972                                 bms_overlap(rel2->relids, sjinfo->min_righthand))
973                                 continue;               /* assume valid previous violation of RHS */
974
975                         /*
976                          * The proposed join could still be legal, but only if we're
977                          * allowed to associate it into the RHS of this SJ.  That means
978                          * this SJ must be a LEFT join (not SEMI or ANTI, and certainly
979                          * not FULL) and the proposed join must not overlap the LHS.
980                          */
981                         if (sjinfo->jointype != JOIN_LEFT ||
982                                 bms_overlap(joinrelids, sjinfo->min_lefthand))
983                                 return false;   /* invalid join path */
984
985                         /*
986                          * To be valid, the proposed join must be a LEFT join; otherwise
987                          * it can't associate into this SJ's RHS.  But we may not yet have
988                          * found the SpecialJoinInfo matching the proposed join, so we
989                          * can't test that yet.  Remember the requirement for later.
990                          */
991                         must_be_leftjoin = true;
992                 }
993         }
994
995         /*
996          * Fail if violated any SJ's RHS and didn't match to a LEFT SJ: the
997          * proposed join can't associate into an SJ's RHS.
998          *
999          * Also, fail if the proposed join's predicate isn't strict; we're
1000          * essentially checking to see if we can apply outer-join identity 3, and
1001          * that's a requirement.  (This check may be redundant with checks in
1002          * make_outerjoininfo, but I'm not quite sure, and it's cheap to test.)
1003          */
1004         if (must_be_leftjoin &&
1005                 (match_sjinfo == NULL ||
1006                  match_sjinfo->jointype != JOIN_LEFT ||
1007                  !match_sjinfo->lhs_strict))
1008                 return false;                   /* invalid join path */
1009
1010         /*
1011          * We also have to check for constraints imposed by LATERAL references.
1012          */
1013         if (root->hasLateralRTEs)
1014         {
1015                 bool            lateral_fwd;
1016                 bool            lateral_rev;
1017                 Relids          join_lateral_rels;
1018
1019                 /*
1020                  * The proposed rels could each contain lateral references to the
1021                  * other, in which case the join is impossible.  If there are lateral
1022                  * references in just one direction, then the join has to be done with
1023                  * a nestloop with the lateral referencer on the inside.  If the join
1024                  * matches an SJ that cannot be implemented by such a nestloop, the
1025                  * join is impossible.
1026                  *
1027                  * Also, if the lateral reference is only indirect, we should reject
1028                  * the join; whatever rel(s) the reference chain goes through must be
1029                  * joined to first.
1030                  *
1031                  * Another case that might keep us from building a valid plan is the
1032                  * implementation restriction described by have_dangerous_phv().
1033                  */
1034                 lateral_fwd = bms_overlap(rel1->relids, rel2->lateral_relids);
1035                 lateral_rev = bms_overlap(rel2->relids, rel1->lateral_relids);
1036                 if (lateral_fwd && lateral_rev)
1037                         return false;           /* have lateral refs in both directions */
1038                 if (lateral_fwd)
1039                 {
1040                         /* has to be implemented as nestloop with rel1 on left */
1041                         if (match_sjinfo &&
1042                                 (reversed ||
1043                                  unique_ified ||
1044                                  match_sjinfo->jointype == JOIN_FULL))
1045                                 return false;   /* not implementable as nestloop */
1046                         /* check there is a direct reference from rel2 to rel1 */
1047                         if (!bms_overlap(rel1->relids, rel2->direct_lateral_relids))
1048                                 return false;   /* only indirect refs, so reject */
1049                         /* check we won't have a dangerous PHV */
1050                         if (have_dangerous_phv(root, rel1->relids, rel2->lateral_relids))
1051                                 return false;   /* might be unable to handle required PHV */
1052                 }
1053                 else if (lateral_rev)
1054                 {
1055                         /* has to be implemented as nestloop with rel2 on left */
1056                         if (match_sjinfo &&
1057                                 (!reversed ||
1058                                  unique_ified ||
1059                                  match_sjinfo->jointype == JOIN_FULL))
1060                                 return false;   /* not implementable as nestloop */
1061                         /* check there is a direct reference from rel1 to rel2 */
1062                         if (!bms_overlap(rel2->relids, rel1->direct_lateral_relids))
1063                                 return false;   /* only indirect refs, so reject */
1064                         /* check we won't have a dangerous PHV */
1065                         if (have_dangerous_phv(root, rel2->relids, rel1->lateral_relids))
1066                                 return false;   /* might be unable to handle required PHV */
1067                 }
1068
1069                 /*
1070                  * LATERAL references could also cause problems later on if we accept
1071                  * this join: if the join's minimum parameterization includes any rels
1072                  * that would have to be on the inside of an outer join with this join
1073                  * rel, then it's never going to be possible to build the complete
1074                  * query using this join.  We should reject this join not only because
1075                  * it'll save work, but because if we don't, the clauseless-join
1076                  * heuristics might think that legality of this join means that some
1077                  * other join rel need not be formed, and that could lead to failure
1078                  * to find any plan at all.  We have to consider not only rels that
1079                  * are directly on the inner side of an OJ with the joinrel, but also
1080                  * ones that are indirectly so, so search to find all such rels.
1081                  */
1082                 join_lateral_rels = min_join_parameterization(root, joinrelids,
1083                                                                                                           rel1, rel2);
1084                 if (join_lateral_rels)
1085                 {
1086                         Relids          join_plus_rhs = bms_copy(joinrelids);
1087                         bool            more;
1088
1089                         do
1090                         {
1091                                 more = false;
1092                                 foreach(l, root->join_info_list)
1093                                 {
1094                                         SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(l);
1095
1096                                         if (bms_overlap(sjinfo->min_lefthand, join_plus_rhs) &&
1097                                                 !bms_is_subset(sjinfo->min_righthand, join_plus_rhs))
1098                                         {
1099                                                 join_plus_rhs = bms_add_members(join_plus_rhs,
1100                                                                                                           sjinfo->min_righthand);
1101                                                 more = true;
1102                                         }
1103                                         /* full joins constrain both sides symmetrically */
1104                                         if (sjinfo->jointype == JOIN_FULL &&
1105                                                 bms_overlap(sjinfo->min_righthand, join_plus_rhs) &&
1106                                                 !bms_is_subset(sjinfo->min_lefthand, join_plus_rhs))
1107                                         {
1108                                                 join_plus_rhs = bms_add_members(join_plus_rhs,
1109                                                                                                                 sjinfo->min_lefthand);
1110                                                 more = true;
1111                                         }
1112                                 }
1113                         } while (more);
1114                         if (bms_overlap(join_plus_rhs, join_lateral_rels))
1115                                 return false;   /* will not be able to join to some RHS rel */
1116                 }
1117         }
1118
1119         /* Otherwise, it's a valid join */
1120         *sjinfo_p = match_sjinfo;
1121         *reversed_p = reversed;
1122         return true;
1123 }
1124
1125 /*
1126  * has_join_restriction
1127  *              Detect whether the specified relation has join-order restrictions,
1128  *              due to being inside an outer join or an IN (sub-SELECT),
1129  *              or participating in any LATERAL references or multi-rel PHVs.
1130  *
1131  * Essentially, this tests whether have_join_order_restriction() could
1132  * succeed with this rel and some other one.  It's OK if we sometimes
1133  * say "true" incorrectly.  (Therefore, we don't bother with the relatively
1134  * expensive has_legal_joinclause test.)
1135  */
1136 static bool
1137 has_join_restriction(PlannerInfo *root, RelOptInfo *rel)
1138 {
1139         ListCell   *l;
1140
1141         if (rel->lateral_relids != NULL || rel->lateral_referencers != NULL)
1142                 return true;
1143
1144         foreach(l, root->placeholder_list)
1145         {
1146                 PlaceHolderInfo *phinfo = (PlaceHolderInfo *) lfirst(l);
1147
1148                 if (bms_is_subset(rel->relids, phinfo->ph_eval_at) &&
1149                         !bms_equal(rel->relids, phinfo->ph_eval_at))
1150                         return true;
1151         }
1152
1153         foreach(l, root->join_info_list)
1154         {
1155                 SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(l);
1156
1157                 /* ignore full joins --- other mechanisms preserve their ordering */
1158                 if (sjinfo->jointype == JOIN_FULL)
1159                         continue;
1160
1161                 /* ignore if SJ is already contained in rel */
1162                 if (bms_is_subset(sjinfo->min_lefthand, rel->relids) &&
1163                         bms_is_subset(sjinfo->min_righthand, rel->relids))
1164                         continue;
1165
1166                 /* restricted if it overlaps LHS or RHS, but doesn't contain SJ */
1167                 if (bms_overlap(sjinfo->min_lefthand, rel->relids) ||
1168                         bms_overlap(sjinfo->min_righthand, rel->relids))
1169                         return true;
1170         }
1171
1172         return false;
1173 }
1174
1175 /*
1176  * is_dummy_rel --- has relation been proven empty?
1177  */
1178 static bool
1179 is_dummy_rel(RelOptInfo *rel)
1180 {
1181         return IS_DUMMY_REL(rel);
1182 }
1183
1184 /*
1185  * Mark a relation as proven empty.
1186  *
1187  * During GEQO planning, this can get invoked more than once on the same
1188  * baserel struct, so it's worth checking to see if the rel is already marked
1189  * dummy.
1190  *
1191  * Also, when called during GEQO join planning, we are in a short-lived
1192  * memory context.  We must make sure that the dummy path attached to a
1193  * baserel survives the GEQO cycle, else the baserel is trashed for future
1194  * GEQO cycles.  On the other hand, when we are marking a joinrel during GEQO,
1195  * we don't want the dummy path to clutter the main planning context.  Upshot
1196  * is that the best solution is to explicitly make the dummy path in the same
1197  * context the given RelOptInfo is in.
1198  */
1199 static void
1200 mark_dummy_rel(RelOptInfo *rel)
1201 {
1202         MemoryContext oldcontext;
1203
1204         /* Already marked? */
1205         if (is_dummy_rel(rel))
1206                 return;
1207
1208         /* No, so choose correct context to make the dummy path in */
1209         oldcontext = MemoryContextSwitchTo(GetMemoryChunkContext(rel));
1210
1211         /* Set dummy size estimate */
1212         rel->rows = 0;
1213
1214         /* Evict any previously chosen paths */
1215         rel->pathlist = NIL;
1216
1217         /* Set up the dummy path */
1218         add_path(rel, (Path *) create_append_path(rel, NIL, NULL));
1219
1220         /* Set or update cheapest_total_path and related fields */
1221         set_cheapest(rel);
1222
1223         MemoryContextSwitchTo(oldcontext);
1224 }
1225
1226 /*
1227  * restriction_is_constant_false --- is a restrictlist just FALSE?
1228  *
1229  * In cases where a qual is provably constant FALSE, eval_const_expressions
1230  * will generally have thrown away anything that's ANDed with it.  In outer
1231  * join situations this will leave us computing cartesian products only to
1232  * decide there's no match for an outer row, which is pretty stupid.  So,
1233  * we need to detect the case.
1234  *
1235  * If only_pushed_down is TRUE, then consider only pushed-down quals.
1236  */
1237 static bool
1238 restriction_is_constant_false(List *restrictlist, bool only_pushed_down)
1239 {
1240         ListCell   *lc;
1241
1242         /*
1243          * Despite the above comment, the restriction list we see here might
1244          * possibly have other members besides the FALSE constant, since other
1245          * quals could get "pushed down" to the outer join level.  So we check
1246          * each member of the list.
1247          */
1248         foreach(lc, restrictlist)
1249         {
1250                 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1251
1252                 Assert(IsA(rinfo, RestrictInfo));
1253                 if (only_pushed_down && !rinfo->is_pushed_down)
1254                         continue;
1255
1256                 if (rinfo->clause && IsA(rinfo->clause, Const))
1257                 {
1258                         Const      *con = (Const *) rinfo->clause;
1259
1260                         /* constant NULL is as good as constant FALSE for our purposes */
1261                         if (con->constisnull)
1262                                 return true;
1263                         if (!DatumGetBool(con->constvalue))
1264                                 return true;
1265                 }
1266         }
1267         return false;
1268 }