OSDN Git Service

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