OSDN Git Service

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