OSDN Git Service

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