OSDN Git Service

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