OSDN Git Service

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