PostgreSQL Source Code  git master
relnode.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * relnode.c
4  * Relation-node lookup/construction routines
5  *
6  * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  * src/backend/optimizer/util/relnode.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16 
17 #include <limits.h>
18 
19 #include "miscadmin.h"
20 #include "nodes/nodeFuncs.h"
21 #include "optimizer/appendinfo.h"
22 #include "optimizer/clauses.h"
23 #include "optimizer/cost.h"
24 #include "optimizer/inherit.h"
25 #include "optimizer/pathnode.h"
26 #include "optimizer/paths.h"
27 #include "optimizer/placeholder.h"
28 #include "optimizer/plancat.h"
29 #include "optimizer/restrictinfo.h"
30 #include "optimizer/tlist.h"
31 #include "utils/hsearch.h"
32 #include "utils/lsyscache.h"
33 
34 
35 typedef struct JoinHashEntry
36 {
37  Relids join_relids; /* hash key --- MUST BE FIRST */
40 
41 static void build_joinrel_tlist(PlannerInfo *root, RelOptInfo *joinrel,
42  RelOptInfo *input_rel);
44  RelOptInfo *joinrel,
45  RelOptInfo *outer_rel,
46  RelOptInfo *inner_rel);
47 static void build_joinrel_joinlist(RelOptInfo *joinrel,
48  RelOptInfo *outer_rel,
49  RelOptInfo *inner_rel);
51  List *joininfo_list,
52  List *new_restrictlist);
54  List *joininfo_list,
55  List *new_joininfo);
56 static void set_foreign_rel_properties(RelOptInfo *joinrel,
57  RelOptInfo *outer_rel, RelOptInfo *inner_rel);
58 static void add_join_rel(PlannerInfo *root, RelOptInfo *joinrel);
59 static void build_joinrel_partition_info(RelOptInfo *joinrel,
60  RelOptInfo *outer_rel, RelOptInfo *inner_rel,
61  List *restrictlist, JoinType jointype);
62 static bool have_partkey_equi_join(RelOptInfo *joinrel,
63  RelOptInfo *rel1, RelOptInfo *rel2,
64  JoinType jointype, List *restrictlist);
65 static int match_expr_to_partition_keys(Expr *expr, RelOptInfo *rel,
66  bool strict_op);
67 static void set_joinrel_partition_key_exprs(RelOptInfo *joinrel,
68  RelOptInfo *outer_rel, RelOptInfo *inner_rel,
69  JoinType jointype);
70 static void build_child_join_reltarget(PlannerInfo *root,
71  RelOptInfo *parentrel,
72  RelOptInfo *childrel,
73  int nappinfos,
74  AppendRelInfo **appinfos);
75 
76 
77 /*
78  * setup_simple_rel_arrays
79  * Prepare the arrays we use for quickly accessing base relations
80  * and AppendRelInfos.
81  */
82 void
84 {
85  int size;
86  Index rti;
87  ListCell *lc;
88 
89  /* Arrays are accessed using RT indexes (1..N) */
90  size = list_length(root->parse->rtable) + 1;
91  root->simple_rel_array_size = size;
92 
93  /*
94  * simple_rel_array is initialized to all NULLs, since no RelOptInfos
95  * exist yet. It'll be filled by later calls to build_simple_rel().
96  */
97  root->simple_rel_array = (RelOptInfo **)
98  palloc0(size * sizeof(RelOptInfo *));
99 
100  /* simple_rte_array is an array equivalent of the rtable list */
101  root->simple_rte_array = (RangeTblEntry **)
102  palloc0(size * sizeof(RangeTblEntry *));
103  rti = 1;
104  foreach(lc, root->parse->rtable)
105  {
106  RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
107 
108  root->simple_rte_array[rti++] = rte;
109  }
110 
111  /* append_rel_array is not needed if there are no AppendRelInfos */
112  if (root->append_rel_list == NIL)
113  {
114  root->append_rel_array = NULL;
115  return;
116  }
117 
118  root->append_rel_array = (AppendRelInfo **)
119  palloc0(size * sizeof(AppendRelInfo *));
120 
121  /*
122  * append_rel_array is filled with any already-existing AppendRelInfos,
123  * which currently could only come from UNION ALL flattening. We might
124  * add more later during inheritance expansion, but it's the
125  * responsibility of the expansion code to update the array properly.
126  */
127  foreach(lc, root->append_rel_list)
128  {
129  AppendRelInfo *appinfo = lfirst_node(AppendRelInfo, lc);
130  int child_relid = appinfo->child_relid;
131 
132  /* Sanity check */
133  Assert(child_relid < size);
134 
135  if (root->append_rel_array[child_relid])
136  elog(ERROR, "child relation already exists");
137 
138  root->append_rel_array[child_relid] = appinfo;
139  }
140 }
141 
142 /*
143  * expand_planner_arrays
144  * Expand the PlannerInfo's per-RTE arrays by add_size members
145  * and initialize the newly added entries to NULLs
146  *
147  * Note: this causes the append_rel_array to become allocated even if
148  * it was not before. This is okay for current uses, because we only call
149  * this when adding child relations, which always have AppendRelInfos.
150  */
151 void
153 {
154  int new_size;
155 
156  Assert(add_size > 0);
157 
158  new_size = root->simple_rel_array_size + add_size;
159 
160  root->simple_rel_array = (RelOptInfo **)
162  sizeof(RelOptInfo *) * new_size);
164  0, sizeof(RelOptInfo *) * add_size);
165 
166  root->simple_rte_array = (RangeTblEntry **)
168  sizeof(RangeTblEntry *) * new_size);
170  0, sizeof(RangeTblEntry *) * add_size);
171 
172  if (root->append_rel_array)
173  {
174  root->append_rel_array = (AppendRelInfo **)
176  sizeof(AppendRelInfo *) * new_size);
178  0, sizeof(AppendRelInfo *) * add_size);
179  }
180  else
181  {
182  root->append_rel_array = (AppendRelInfo **)
183  palloc0(sizeof(AppendRelInfo *) * new_size);
184  }
185 
186  root->simple_rel_array_size = new_size;
187 }
188 
189 /*
190  * build_simple_rel
191  * Construct a new RelOptInfo for a base relation or 'other' relation.
192  */
193 RelOptInfo *
194 build_simple_rel(PlannerInfo *root, int relid, RelOptInfo *parent)
195 {
196  RelOptInfo *rel;
197  RangeTblEntry *rte;
198 
199  /* Rel should not exist already */
200  Assert(relid > 0 && relid < root->simple_rel_array_size);
201  if (root->simple_rel_array[relid] != NULL)
202  elog(ERROR, "rel %d already exists", relid);
203 
204  /* Fetch RTE for relation */
205  rte = root->simple_rte_array[relid];
206  Assert(rte != NULL);
207 
208  rel = makeNode(RelOptInfo);
210  rel->relids = bms_make_singleton(relid);
211  rel->rows = 0;
212  /* cheap startup cost is interesting iff not all tuples to be retrieved */
213  rel->consider_startup = (root->tuple_fraction > 0);
214  rel->consider_param_startup = false; /* might get changed later */
215  rel->consider_parallel = false; /* might get changed later */
217  rel->pathlist = NIL;
218  rel->ppilist = NIL;
219  rel->partial_pathlist = NIL;
220  rel->cheapest_startup_path = NULL;
221  rel->cheapest_total_path = NULL;
222  rel->cheapest_unique_path = NULL;
224  rel->relid = relid;
225  rel->rtekind = rte->rtekind;
226  /* min_attr, max_attr, attr_needed, attr_widths are set below */
227  rel->lateral_vars = NIL;
228  rel->indexlist = NIL;
229  rel->statlist = NIL;
230  rel->pages = 0;
231  rel->tuples = 0;
232  rel->allvisfrac = 0;
233  rel->eclass_indexes = NULL;
234  rel->subroot = NULL;
235  rel->subplan_params = NIL;
236  rel->rel_parallel_workers = -1; /* set up in get_relation_info */
237  rel->amflags = 0;
238  rel->serverid = InvalidOid;
239  rel->userid = rte->checkAsUser;
240  rel->useridiscurrent = false;
241  rel->fdwroutine = NULL;
242  rel->fdw_private = NULL;
243  rel->unique_for_rels = NIL;
244  rel->non_unique_for_rels = NIL;
245  rel->baserestrictinfo = NIL;
246  rel->baserestrictcost.startup = 0;
247  rel->baserestrictcost.per_tuple = 0;
248  rel->baserestrict_min_security = UINT_MAX;
249  rel->joininfo = NIL;
250  rel->has_eclass_joins = false;
251  rel->consider_partitionwise_join = false; /* might get changed later */
252  rel->part_scheme = NULL;
253  rel->nparts = -1;
254  rel->boundinfo = NULL;
255  rel->partbounds_merged = false;
256  rel->partition_qual = NIL;
257  rel->part_rels = NULL;
258  rel->live_parts = NULL;
259  rel->all_partrels = NULL;
260  rel->partexprs = NULL;
261  rel->nullable_partexprs = NULL;
262 
263  /*
264  * Pass assorted information down the inheritance hierarchy.
265  */
266  if (parent)
267  {
268  /*
269  * Each direct or indirect child wants to know the relids of its
270  * topmost parent.
271  */
272  if (parent->top_parent_relids)
273  rel->top_parent_relids = parent->top_parent_relids;
274  else
275  rel->top_parent_relids = bms_copy(parent->relids);
276 
277  /*
278  * Also propagate lateral-reference information from appendrel parent
279  * rels to their child rels. We intentionally give each child rel the
280  * same minimum parameterization, even though it's quite possible that
281  * some don't reference all the lateral rels. This is because any
282  * append path for the parent will have to have the same
283  * parameterization for every child anyway, and there's no value in
284  * forcing extra reparameterize_path() calls. Similarly, a lateral
285  * reference to the parent prevents use of otherwise-movable join rels
286  * for each child.
287  *
288  * It's possible for child rels to have their own children, in which
289  * case the topmost parent's lateral info propagates all the way down.
290  */
292  rel->lateral_relids = parent->lateral_relids;
294  }
295  else
296  {
297  rel->top_parent_relids = NULL;
298  rel->direct_lateral_relids = NULL;
299  rel->lateral_relids = NULL;
300  rel->lateral_referencers = NULL;
301  }
302 
303  /* Check type of rtable entry */
304  switch (rte->rtekind)
305  {
306  case RTE_RELATION:
307  /* Table --- retrieve statistics from the system catalogs */
308  get_relation_info(root, rte->relid, rte->inh, rel);
309  break;
310  case RTE_SUBQUERY:
311  case RTE_FUNCTION:
312  case RTE_TABLEFUNC:
313  case RTE_VALUES:
314  case RTE_CTE:
315  case RTE_NAMEDTUPLESTORE:
316 
317  /*
318  * Subquery, function, tablefunc, values list, CTE, or ENR --- set
319  * up attr range and arrays
320  *
321  * Note: 0 is included in range to support whole-row Vars
322  */
323  rel->min_attr = 0;
324  rel->max_attr = list_length(rte->eref->colnames);
325  rel->attr_needed = (Relids *)
326  palloc0((rel->max_attr - rel->min_attr + 1) * sizeof(Relids));
327  rel->attr_widths = (int32 *)
328  palloc0((rel->max_attr - rel->min_attr + 1) * sizeof(int32));
329  break;
330  case RTE_RESULT:
331  /* RTE_RESULT has no columns, nor could it have whole-row Var */
332  rel->min_attr = 0;
333  rel->max_attr = -1;
334  rel->attr_needed = NULL;
335  rel->attr_widths = NULL;
336  break;
337  default:
338  elog(ERROR, "unrecognized RTE kind: %d",
339  (int) rte->rtekind);
340  break;
341  }
342 
343  /*
344  * Copy the parent's quals to the child, with appropriate substitution of
345  * variables. If any constant false or NULL clauses turn up, we can mark
346  * the child as dummy right away. (We must do this immediately so that
347  * pruning works correctly when recursing in expand_partitioned_rtentry.)
348  */
349  if (parent)
350  {
351  AppendRelInfo *appinfo = root->append_rel_array[relid];
352 
353  Assert(appinfo != NULL);
354  if (!apply_child_basequals(root, parent, rel, rte, appinfo))
355  {
356  /*
357  * Some restriction clause reduced to constant FALSE or NULL after
358  * substitution, so this child need not be scanned.
359  */
360  mark_dummy_rel(rel);
361  }
362  }
363 
364  /* Save the finished struct in the query's simple_rel_array */
365  root->simple_rel_array[relid] = rel;
366 
367  return rel;
368 }
369 
370 /*
371  * find_base_rel
372  * Find a base or other relation entry, which must already exist.
373  */
374 RelOptInfo *
375 find_base_rel(PlannerInfo *root, int relid)
376 {
377  RelOptInfo *rel;
378 
379  Assert(relid > 0);
380 
381  if (relid < root->simple_rel_array_size)
382  {
383  rel = root->simple_rel_array[relid];
384  if (rel)
385  return rel;
386  }
387 
388  elog(ERROR, "no relation entry for relid %d", relid);
389 
390  return NULL; /* keep compiler quiet */
391 }
392 
393 /*
394  * build_join_rel_hash
395  * Construct the auxiliary hash table for join relations.
396  */
397 static void
399 {
400  HTAB *hashtab;
401  HASHCTL hash_ctl;
402  ListCell *l;
403 
404  /* Create the hash table */
405  hash_ctl.keysize = sizeof(Relids);
406  hash_ctl.entrysize = sizeof(JoinHashEntry);
407  hash_ctl.hash = bitmap_hash;
408  hash_ctl.match = bitmap_match;
409  hash_ctl.hcxt = CurrentMemoryContext;
410  hashtab = hash_create("JoinRelHashTable",
411  256L,
412  &hash_ctl,
414 
415  /* Insert all the already-existing joinrels */
416  foreach(l, root->join_rel_list)
417  {
418  RelOptInfo *rel = (RelOptInfo *) lfirst(l);
419  JoinHashEntry *hentry;
420  bool found;
421 
422  hentry = (JoinHashEntry *) hash_search(hashtab,
423  &(rel->relids),
424  HASH_ENTER,
425  &found);
426  Assert(!found);
427  hentry->join_rel = rel;
428  }
429 
430  root->join_rel_hash = hashtab;
431 }
432 
433 /*
434  * find_join_rel
435  * Returns relation entry corresponding to 'relids' (a set of RT indexes),
436  * or NULL if none exists. This is for join relations.
437  */
438 RelOptInfo *
440 {
441  /*
442  * Switch to using hash lookup when list grows "too long". The threshold
443  * is arbitrary and is known only here.
444  */
445  if (!root->join_rel_hash && list_length(root->join_rel_list) > 32)
446  build_join_rel_hash(root);
447 
448  /*
449  * Use either hashtable lookup or linear search, as appropriate.
450  *
451  * Note: the seemingly redundant hashkey variable is used to avoid taking
452  * the address of relids; unless the compiler is exceedingly smart, doing
453  * so would force relids out of a register and thus probably slow down the
454  * list-search case.
455  */
456  if (root->join_rel_hash)
457  {
458  Relids hashkey = relids;
459  JoinHashEntry *hentry;
460 
461  hentry = (JoinHashEntry *) hash_search(root->join_rel_hash,
462  &hashkey,
463  HASH_FIND,
464  NULL);
465  if (hentry)
466  return hentry->join_rel;
467  }
468  else
469  {
470  ListCell *l;
471 
472  foreach(l, root->join_rel_list)
473  {
474  RelOptInfo *rel = (RelOptInfo *) lfirst(l);
475 
476  if (bms_equal(rel->relids, relids))
477  return rel;
478  }
479  }
480 
481  return NULL;
482 }
483 
484 /*
485  * set_foreign_rel_properties
486  * Set up foreign-join fields if outer and inner relation are foreign
487  * tables (or joins) belonging to the same server and assigned to the same
488  * user to check access permissions as.
489  *
490  * In addition to an exact match of userid, we allow the case where one side
491  * has zero userid (implying current user) and the other side has explicit
492  * userid that happens to equal the current user; but in that case, pushdown of
493  * the join is only valid for the current user. The useridiscurrent field
494  * records whether we had to make such an assumption for this join or any
495  * sub-join.
496  *
497  * Otherwise these fields are left invalid, so GetForeignJoinPaths will not be
498  * called for the join relation.
499  *
500  */
501 static void
503  RelOptInfo *inner_rel)
504 {
505  if (OidIsValid(outer_rel->serverid) &&
506  inner_rel->serverid == outer_rel->serverid)
507  {
508  if (inner_rel->userid == outer_rel->userid)
509  {
510  joinrel->serverid = outer_rel->serverid;
511  joinrel->userid = outer_rel->userid;
512  joinrel->useridiscurrent = outer_rel->useridiscurrent || inner_rel->useridiscurrent;
513  joinrel->fdwroutine = outer_rel->fdwroutine;
514  }
515  else if (!OidIsValid(inner_rel->userid) &&
516  outer_rel->userid == GetUserId())
517  {
518  joinrel->serverid = outer_rel->serverid;
519  joinrel->userid = outer_rel->userid;
520  joinrel->useridiscurrent = true;
521  joinrel->fdwroutine = outer_rel->fdwroutine;
522  }
523  else if (!OidIsValid(outer_rel->userid) &&
524  inner_rel->userid == GetUserId())
525  {
526  joinrel->serverid = outer_rel->serverid;
527  joinrel->userid = inner_rel->userid;
528  joinrel->useridiscurrent = true;
529  joinrel->fdwroutine = outer_rel->fdwroutine;
530  }
531  }
532 }
533 
534 /*
535  * add_join_rel
536  * Add given join relation to the list of join relations in the given
537  * PlannerInfo. Also add it to the auxiliary hashtable if there is one.
538  */
539 static void
541 {
542  /* GEQO requires us to append the new joinrel to the end of the list! */
543  root->join_rel_list = lappend(root->join_rel_list, joinrel);
544 
545  /* store it into the auxiliary hashtable if there is one. */
546  if (root->join_rel_hash)
547  {
548  JoinHashEntry *hentry;
549  bool found;
550 
551  hentry = (JoinHashEntry *) hash_search(root->join_rel_hash,
552  &(joinrel->relids),
553  HASH_ENTER,
554  &found);
555  Assert(!found);
556  hentry->join_rel = joinrel;
557  }
558 }
559 
560 /*
561  * build_join_rel
562  * Returns relation entry corresponding to the union of two given rels,
563  * creating a new relation entry if none already exists.
564  *
565  * 'joinrelids' is the Relids set that uniquely identifies the join
566  * 'outer_rel' and 'inner_rel' are relation nodes for the relations to be
567  * joined
568  * 'sjinfo': join context info
569  * 'restrictlist_ptr': result variable. If not NULL, *restrictlist_ptr
570  * receives the list of RestrictInfo nodes that apply to this
571  * particular pair of joinable relations.
572  *
573  * restrictlist_ptr makes the routine's API a little grotty, but it saves
574  * duplicated calculation of the restrictlist...
575  */
576 RelOptInfo *
578  Relids joinrelids,
579  RelOptInfo *outer_rel,
580  RelOptInfo *inner_rel,
581  SpecialJoinInfo *sjinfo,
582  List **restrictlist_ptr)
583 {
584  RelOptInfo *joinrel;
585  List *restrictlist;
586 
587  /* This function should be used only for join between parents. */
588  Assert(!IS_OTHER_REL(outer_rel) && !IS_OTHER_REL(inner_rel));
589 
590  /*
591  * See if we already have a joinrel for this set of base rels.
592  */
593  joinrel = find_join_rel(root, joinrelids);
594 
595  if (joinrel)
596  {
597  /*
598  * Yes, so we only need to figure the restrictlist for this particular
599  * pair of component relations.
600  */
601  if (restrictlist_ptr)
602  *restrictlist_ptr = build_joinrel_restrictlist(root,
603  joinrel,
604  outer_rel,
605  inner_rel);
606  return joinrel;
607  }
608 
609  /*
610  * Nope, so make one.
611  */
612  joinrel = makeNode(RelOptInfo);
613  joinrel->reloptkind = RELOPT_JOINREL;
614  joinrel->relids = bms_copy(joinrelids);
615  joinrel->rows = 0;
616  /* cheap startup cost is interesting iff not all tuples to be retrieved */
617  joinrel->consider_startup = (root->tuple_fraction > 0);
618  joinrel->consider_param_startup = false;
619  joinrel->consider_parallel = false;
620  joinrel->reltarget = create_empty_pathtarget();
621  joinrel->pathlist = NIL;
622  joinrel->ppilist = NIL;
623  joinrel->partial_pathlist = NIL;
624  joinrel->cheapest_startup_path = NULL;
625  joinrel->cheapest_total_path = NULL;
626  joinrel->cheapest_unique_path = NULL;
628  /* init direct_lateral_relids from children; we'll finish it up below */
629  joinrel->direct_lateral_relids =
630  bms_union(outer_rel->direct_lateral_relids,
631  inner_rel->direct_lateral_relids);
632  joinrel->lateral_relids = min_join_parameterization(root, joinrel->relids,
633  outer_rel, inner_rel);
634  joinrel->relid = 0; /* indicates not a baserel */
635  joinrel->rtekind = RTE_JOIN;
636  joinrel->min_attr = 0;
637  joinrel->max_attr = 0;
638  joinrel->attr_needed = NULL;
639  joinrel->attr_widths = NULL;
640  joinrel->lateral_vars = NIL;
641  joinrel->lateral_referencers = NULL;
642  joinrel->indexlist = NIL;
643  joinrel->statlist = NIL;
644  joinrel->pages = 0;
645  joinrel->tuples = 0;
646  joinrel->allvisfrac = 0;
647  joinrel->eclass_indexes = NULL;
648  joinrel->subroot = NULL;
649  joinrel->subplan_params = NIL;
650  joinrel->rel_parallel_workers = -1;
651  joinrel->amflags = 0;
652  joinrel->serverid = InvalidOid;
653  joinrel->userid = InvalidOid;
654  joinrel->useridiscurrent = false;
655  joinrel->fdwroutine = NULL;
656  joinrel->fdw_private = NULL;
657  joinrel->unique_for_rels = NIL;
658  joinrel->non_unique_for_rels = NIL;
659  joinrel->baserestrictinfo = NIL;
660  joinrel->baserestrictcost.startup = 0;
661  joinrel->baserestrictcost.per_tuple = 0;
662  joinrel->baserestrict_min_security = UINT_MAX;
663  joinrel->joininfo = NIL;
664  joinrel->has_eclass_joins = false;
665  joinrel->consider_partitionwise_join = false; /* might get changed later */
666  joinrel->top_parent_relids = NULL;
667  joinrel->part_scheme = NULL;
668  joinrel->nparts = -1;
669  joinrel->boundinfo = NULL;
670  joinrel->partbounds_merged = false;
671  joinrel->partition_qual = NIL;
672  joinrel->part_rels = NULL;
673  joinrel->live_parts = NULL;
674  joinrel->all_partrels = NULL;
675  joinrel->partexprs = NULL;
676  joinrel->nullable_partexprs = NULL;
677 
678  /* Compute information relevant to the foreign relations. */
679  set_foreign_rel_properties(joinrel, outer_rel, inner_rel);
680 
681  /*
682  * Create a new tlist containing just the vars that need to be output from
683  * this join (ie, are needed for higher joinclauses or final output).
684  *
685  * NOTE: the tlist order for a join rel will depend on which pair of outer
686  * and inner rels we first try to build it from. But the contents should
687  * be the same regardless.
688  */
689  build_joinrel_tlist(root, joinrel, outer_rel);
690  build_joinrel_tlist(root, joinrel, inner_rel);
691  add_placeholders_to_joinrel(root, joinrel, outer_rel, inner_rel);
692 
693  /*
694  * add_placeholders_to_joinrel also took care of adding the ph_lateral
695  * sets of any PlaceHolderVars computed here to direct_lateral_relids, so
696  * now we can finish computing that. This is much like the computation of
697  * the transitively-closed lateral_relids in min_join_parameterization,
698  * except that here we *do* have to consider the added PHVs.
699  */
700  joinrel->direct_lateral_relids =
701  bms_del_members(joinrel->direct_lateral_relids, joinrel->relids);
702  if (bms_is_empty(joinrel->direct_lateral_relids))
703  joinrel->direct_lateral_relids = NULL;
704 
705  /*
706  * Construct restrict and join clause lists for the new joinrel. (The
707  * caller might or might not need the restrictlist, but I need it anyway
708  * for set_joinrel_size_estimates().)
709  */
710  restrictlist = build_joinrel_restrictlist(root, joinrel,
711  outer_rel, inner_rel);
712  if (restrictlist_ptr)
713  *restrictlist_ptr = restrictlist;
714  build_joinrel_joinlist(joinrel, outer_rel, inner_rel);
715 
716  /*
717  * This is also the right place to check whether the joinrel has any
718  * pending EquivalenceClass joins.
719  */
720  joinrel->has_eclass_joins = has_relevant_eclass_joinclause(root, joinrel);
721 
722  /* Store the partition information. */
723  build_joinrel_partition_info(joinrel, outer_rel, inner_rel, restrictlist,
724  sjinfo->jointype);
725 
726  /*
727  * Set estimates of the joinrel's size.
728  */
729  set_joinrel_size_estimates(root, joinrel, outer_rel, inner_rel,
730  sjinfo, restrictlist);
731 
732  /*
733  * Set the consider_parallel flag if this joinrel could potentially be
734  * scanned within a parallel worker. If this flag is false for either
735  * inner_rel or outer_rel, then it must be false for the joinrel also.
736  * Even if both are true, there might be parallel-restricted expressions
737  * in the targetlist or quals.
738  *
739  * Note that if there are more than two rels in this relation, they could
740  * be divided between inner_rel and outer_rel in any arbitrary way. We
741  * assume this doesn't matter, because we should hit all the same baserels
742  * and joinclauses while building up to this joinrel no matter which we
743  * take; therefore, we should make the same decision here however we get
744  * here.
745  */
746  if (inner_rel->consider_parallel && outer_rel->consider_parallel &&
747  is_parallel_safe(root, (Node *) restrictlist) &&
748  is_parallel_safe(root, (Node *) joinrel->reltarget->exprs))
749  joinrel->consider_parallel = true;
750 
751  /* Add the joinrel to the PlannerInfo. */
752  add_join_rel(root, joinrel);
753 
754  /*
755  * Also, if dynamic-programming join search is active, add the new joinrel
756  * to the appropriate sublist. Note: you might think the Assert on number
757  * of members should be for equality, but some of the level 1 rels might
758  * have been joinrels already, so we can only assert <=.
759  */
760  if (root->join_rel_level)
761  {
762  Assert(root->join_cur_level > 0);
763  Assert(root->join_cur_level <= bms_num_members(joinrel->relids));
764  root->join_rel_level[root->join_cur_level] =
765  lappend(root->join_rel_level[root->join_cur_level], joinrel);
766  }
767 
768  return joinrel;
769 }
770 
771 /*
772  * build_child_join_rel
773  * Builds RelOptInfo representing join between given two child relations.
774  *
775  * 'outer_rel' and 'inner_rel' are the RelOptInfos of child relations being
776  * joined
777  * 'parent_joinrel' is the RelOptInfo representing the join between parent
778  * relations. Some of the members of new RelOptInfo are produced by
779  * translating corresponding members of this RelOptInfo
780  * 'sjinfo': child-join context info
781  * 'restrictlist': list of RestrictInfo nodes that apply to this particular
782  * pair of joinable relations
783  * 'jointype' is the join type (inner, left, full, etc)
784  */
785 RelOptInfo *
787  RelOptInfo *inner_rel, RelOptInfo *parent_joinrel,
788  List *restrictlist, SpecialJoinInfo *sjinfo,
789  JoinType jointype)
790 {
791  RelOptInfo *joinrel = makeNode(RelOptInfo);
792  AppendRelInfo **appinfos;
793  int nappinfos;
794 
795  /* Only joins between "other" relations land here. */
796  Assert(IS_OTHER_REL(outer_rel) && IS_OTHER_REL(inner_rel));
797 
798  /* The parent joinrel should have consider_partitionwise_join set. */
799  Assert(parent_joinrel->consider_partitionwise_join);
800 
801  joinrel->reloptkind = RELOPT_OTHER_JOINREL;
802  joinrel->relids = bms_union(outer_rel->relids, inner_rel->relids);
803  joinrel->rows = 0;
804  /* cheap startup cost is interesting iff not all tuples to be retrieved */
805  joinrel->consider_startup = (root->tuple_fraction > 0);
806  joinrel->consider_param_startup = false;
807  joinrel->consider_parallel = false;
808  joinrel->reltarget = create_empty_pathtarget();
809  joinrel->pathlist = NIL;
810  joinrel->ppilist = NIL;
811  joinrel->partial_pathlist = NIL;
812  joinrel->cheapest_startup_path = NULL;
813  joinrel->cheapest_total_path = NULL;
814  joinrel->cheapest_unique_path = NULL;
816  joinrel->direct_lateral_relids = NULL;
817  joinrel->lateral_relids = NULL;
818  joinrel->relid = 0; /* indicates not a baserel */
819  joinrel->rtekind = RTE_JOIN;
820  joinrel->min_attr = 0;
821  joinrel->max_attr = 0;
822  joinrel->attr_needed = NULL;
823  joinrel->attr_widths = NULL;
824  joinrel->lateral_vars = NIL;
825  joinrel->lateral_referencers = NULL;
826  joinrel->indexlist = NIL;
827  joinrel->pages = 0;
828  joinrel->tuples = 0;
829  joinrel->allvisfrac = 0;
830  joinrel->eclass_indexes = NULL;
831  joinrel->subroot = NULL;
832  joinrel->subplan_params = NIL;
833  joinrel->amflags = 0;
834  joinrel->serverid = InvalidOid;
835  joinrel->userid = InvalidOid;
836  joinrel->useridiscurrent = false;
837  joinrel->fdwroutine = NULL;
838  joinrel->fdw_private = NULL;
839  joinrel->baserestrictinfo = NIL;
840  joinrel->baserestrictcost.startup = 0;
841  joinrel->baserestrictcost.per_tuple = 0;
842  joinrel->joininfo = NIL;
843  joinrel->has_eclass_joins = false;
844  joinrel->consider_partitionwise_join = false; /* might get changed later */
845  joinrel->top_parent_relids = NULL;
846  joinrel->part_scheme = NULL;
847  joinrel->nparts = -1;
848  joinrel->boundinfo = NULL;
849  joinrel->partbounds_merged = false;
850  joinrel->partition_qual = NIL;
851  joinrel->part_rels = NULL;
852  joinrel->live_parts = NULL;
853  joinrel->all_partrels = NULL;
854  joinrel->partexprs = NULL;
855  joinrel->nullable_partexprs = NULL;
856 
857  joinrel->top_parent_relids = bms_union(outer_rel->top_parent_relids,
858  inner_rel->top_parent_relids);
859 
860  /* Compute information relevant to foreign relations. */
861  set_foreign_rel_properties(joinrel, outer_rel, inner_rel);
862 
863  /* Compute information needed for mapping Vars to the child rel */
864  appinfos = find_appinfos_by_relids(root, joinrel->relids, &nappinfos);
865 
866  /* Set up reltarget struct */
867  build_child_join_reltarget(root, parent_joinrel, joinrel,
868  nappinfos, appinfos);
869 
870  /* Construct joininfo list. */
871  joinrel->joininfo = (List *) adjust_appendrel_attrs(root,
872  (Node *) parent_joinrel->joininfo,
873  nappinfos,
874  appinfos);
875 
876  /*
877  * Lateral relids referred in child join will be same as that referred in
878  * the parent relation.
879  */
880  joinrel->direct_lateral_relids = (Relids) bms_copy(parent_joinrel->direct_lateral_relids);
881  joinrel->lateral_relids = (Relids) bms_copy(parent_joinrel->lateral_relids);
882 
883  /*
884  * If the parent joinrel has pending equivalence classes, so does the
885  * child.
886  */
887  joinrel->has_eclass_joins = parent_joinrel->has_eclass_joins;
888 
889  /* Is the join between partitions itself partitioned? */
890  build_joinrel_partition_info(joinrel, outer_rel, inner_rel, restrictlist,
891  jointype);
892 
893  /* Child joinrel is parallel safe if parent is parallel safe. */
894  joinrel->consider_parallel = parent_joinrel->consider_parallel;
895 
896  /* Set estimates of the child-joinrel's size. */
897  set_joinrel_size_estimates(root, joinrel, outer_rel, inner_rel,
898  sjinfo, restrictlist);
899 
900  /* We build the join only once. */
901  Assert(!find_join_rel(root, joinrel->relids));
902 
903  /* Add the relation to the PlannerInfo. */
904  add_join_rel(root, joinrel);
905 
906  /*
907  * We might need EquivalenceClass members corresponding to the child join,
908  * so that we can represent sort pathkeys for it. As with children of
909  * baserels, we shouldn't need this unless there are relevant eclass joins
910  * (implying that a merge join might be possible) or pathkeys to sort by.
911  */
912  if (joinrel->has_eclass_joins || has_useful_pathkeys(root, parent_joinrel))
914  nappinfos, appinfos,
915  parent_joinrel, joinrel);
916 
917  pfree(appinfos);
918 
919  return joinrel;
920 }
921 
922 /*
923  * min_join_parameterization
924  *
925  * Determine the minimum possible parameterization of a joinrel, that is, the
926  * set of other rels it contains LATERAL references to. We save this value in
927  * the join's RelOptInfo. This function is split out of build_join_rel()
928  * because join_is_legal() needs the value to check a prospective join.
929  */
930 Relids
932  Relids joinrelids,
933  RelOptInfo *outer_rel,
934  RelOptInfo *inner_rel)
935 {
936  Relids result;
937 
938  /*
939  * Basically we just need the union of the inputs' lateral_relids, less
940  * whatever is already in the join.
941  *
942  * It's not immediately obvious that this is a valid way to compute the
943  * result, because it might seem that we're ignoring possible lateral refs
944  * of PlaceHolderVars that are due to be computed at the join but not in
945  * either input. However, because create_lateral_join_info() already
946  * charged all such PHV refs to each member baserel of the join, they'll
947  * be accounted for already in the inputs' lateral_relids. Likewise, we
948  * do not need to worry about doing transitive closure here, because that
949  * was already accounted for in the original baserel lateral_relids.
950  */
951  result = bms_union(outer_rel->lateral_relids, inner_rel->lateral_relids);
952  result = bms_del_members(result, joinrelids);
953 
954  /* Maintain invariant that result is exactly NULL if empty */
955  if (bms_is_empty(result))
956  result = NULL;
957 
958  return result;
959 }
960 
961 /*
962  * build_joinrel_tlist
963  * Builds a join relation's target list from an input relation.
964  * (This is invoked twice to handle the two input relations.)
965  *
966  * The join's targetlist includes all Vars of its member relations that
967  * will still be needed above the join. This subroutine adds all such
968  * Vars from the specified input rel's tlist to the join rel's tlist.
969  *
970  * We also compute the expected width of the join's output, making use
971  * of data that was cached at the baserel level by set_rel_width().
972  */
973 static void
975  RelOptInfo *input_rel)
976 {
977  Relids relids = joinrel->relids;
978  ListCell *vars;
979 
980  foreach(vars, input_rel->reltarget->exprs)
981  {
982  Var *var = (Var *) lfirst(vars);
983 
984  /*
985  * Ignore PlaceHolderVars in the input tlists; we'll make our own
986  * decisions about whether to copy them.
987  */
988  if (IsA(var, PlaceHolderVar))
989  continue;
990 
991  /*
992  * Otherwise, anything in a baserel or joinrel targetlist ought to be
993  * a Var. (More general cases can only appear in appendrel child
994  * rels, which will never be seen here.)
995  */
996  if (!IsA(var, Var))
997  elog(ERROR, "unexpected node type in rel targetlist: %d",
998  (int) nodeTag(var));
999 
1000  if (var->varno == ROWID_VAR)
1001  {
1002  /* UPDATE/DELETE row identity vars are always needed */
1003  RowIdentityVarInfo *ridinfo = (RowIdentityVarInfo *)
1004  list_nth(root->row_identity_vars, var->varattno - 1);
1005 
1006  joinrel->reltarget->exprs = lappend(joinrel->reltarget->exprs,
1007  var);
1008  /* Vars have cost zero, so no need to adjust reltarget->cost */
1009  joinrel->reltarget->width += ridinfo->rowidwidth;
1010  }
1011  else
1012  {
1013  RelOptInfo *baserel;
1014  int ndx;
1015 
1016  /* Get the Var's original base rel */
1017  baserel = find_base_rel(root, var->varno);
1018 
1019  /* Is it still needed above this joinrel? */
1020  ndx = var->varattno - baserel->min_attr;
1021  if (bms_nonempty_difference(baserel->attr_needed[ndx], relids))
1022  {
1023  /* Yup, add it to the output */
1024  joinrel->reltarget->exprs = lappend(joinrel->reltarget->exprs,
1025  var);
1026  /* Vars have cost zero, so no need to adjust reltarget->cost */
1027  joinrel->reltarget->width += baserel->attr_widths[ndx];
1028  }
1029  }
1030  }
1031 }
1032 
1033 /*
1034  * build_joinrel_restrictlist
1035  * build_joinrel_joinlist
1036  * These routines build lists of restriction and join clauses for a
1037  * join relation from the joininfo lists of the relations it joins.
1038  *
1039  * These routines are separate because the restriction list must be
1040  * built afresh for each pair of input sub-relations we consider, whereas
1041  * the join list need only be computed once for any join RelOptInfo.
1042  * The join list is fully determined by the set of rels making up the
1043  * joinrel, so we should get the same results (up to ordering) from any
1044  * candidate pair of sub-relations. But the restriction list is whatever
1045  * is not handled in the sub-relations, so it depends on which
1046  * sub-relations are considered.
1047  *
1048  * If a join clause from an input relation refers to base rels still not
1049  * present in the joinrel, then it is still a join clause for the joinrel;
1050  * we put it into the joininfo list for the joinrel. Otherwise,
1051  * the clause is now a restrict clause for the joined relation, and we
1052  * return it to the caller of build_joinrel_restrictlist() to be stored in
1053  * join paths made from this pair of sub-relations. (It will not need to
1054  * be considered further up the join tree.)
1055  *
1056  * In many cases we will find the same RestrictInfos in both input
1057  * relations' joinlists, so be careful to eliminate duplicates.
1058  * Pointer equality should be a sufficient test for dups, since all
1059  * the various joinlist entries ultimately refer to RestrictInfos
1060  * pushed into them by distribute_restrictinfo_to_rels().
1061  *
1062  * 'joinrel' is a join relation node
1063  * 'outer_rel' and 'inner_rel' are a pair of relations that can be joined
1064  * to form joinrel.
1065  *
1066  * build_joinrel_restrictlist() returns a list of relevant restrictinfos,
1067  * whereas build_joinrel_joinlist() stores its results in the joinrel's
1068  * joininfo list. One or the other must accept each given clause!
1069  *
1070  * NB: Formerly, we made deep(!) copies of each input RestrictInfo to pass
1071  * up to the join relation. I believe this is no longer necessary, because
1072  * RestrictInfo nodes are no longer context-dependent. Instead, just include
1073  * the original nodes in the lists made for the join relation.
1074  */
1075 static List *
1077  RelOptInfo *joinrel,
1078  RelOptInfo *outer_rel,
1079  RelOptInfo *inner_rel)
1080 {
1081  List *result;
1082 
1083  /*
1084  * Collect all the clauses that syntactically belong at this level,
1085  * eliminating any duplicates (important since we will see many of the
1086  * same clauses arriving from both input relations).
1087  */
1088  result = subbuild_joinrel_restrictlist(joinrel, outer_rel->joininfo, NIL);
1089  result = subbuild_joinrel_restrictlist(joinrel, inner_rel->joininfo, result);
1090 
1091  /*
1092  * Add on any clauses derived from EquivalenceClasses. These cannot be
1093  * redundant with the clauses in the joininfo lists, so don't bother
1094  * checking.
1095  */
1096  result = list_concat(result,
1098  joinrel->relids,
1099  outer_rel->relids,
1100  inner_rel));
1101 
1102  return result;
1103 }
1104 
1105 static void
1107  RelOptInfo *outer_rel,
1108  RelOptInfo *inner_rel)
1109 {
1110  List *result;
1111 
1112  /*
1113  * Collect all the clauses that syntactically belong above this level,
1114  * eliminating any duplicates (important since we will see many of the
1115  * same clauses arriving from both input relations).
1116  */
1117  result = subbuild_joinrel_joinlist(joinrel, outer_rel->joininfo, NIL);
1118  result = subbuild_joinrel_joinlist(joinrel, inner_rel->joininfo, result);
1119 
1120  joinrel->joininfo = result;
1121 }
1122 
1123 static List *
1125  List *joininfo_list,
1126  List *new_restrictlist)
1127 {
1128  ListCell *l;
1129 
1130  foreach(l, joininfo_list)
1131  {
1132  RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
1133 
1134  if (bms_is_subset(rinfo->required_relids, joinrel->relids))
1135  {
1136  /*
1137  * This clause becomes a restriction clause for the joinrel, since
1138  * it refers to no outside rels. Add it to the list, being
1139  * careful to eliminate duplicates. (Since RestrictInfo nodes in
1140  * different joinlists will have been multiply-linked rather than
1141  * copied, pointer equality should be a sufficient test.)
1142  */
1143  new_restrictlist = list_append_unique_ptr(new_restrictlist, rinfo);
1144  }
1145  else
1146  {
1147  /*
1148  * This clause is still a join clause at this level, so we ignore
1149  * it in this routine.
1150  */
1151  }
1152  }
1153 
1154  return new_restrictlist;
1155 }
1156 
1157 static List *
1159  List *joininfo_list,
1160  List *new_joininfo)
1161 {
1162  ListCell *l;
1163 
1164  /* Expected to be called only for join between parent relations. */
1165  Assert(joinrel->reloptkind == RELOPT_JOINREL);
1166 
1167  foreach(l, joininfo_list)
1168  {
1169  RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
1170 
1171  if (bms_is_subset(rinfo->required_relids, joinrel->relids))
1172  {
1173  /*
1174  * This clause becomes a restriction clause for the joinrel, since
1175  * it refers to no outside rels. So we can ignore it in this
1176  * routine.
1177  */
1178  }
1179  else
1180  {
1181  /*
1182  * This clause is still a join clause at this level, so add it to
1183  * the new joininfo list, being careful to eliminate duplicates.
1184  * (Since RestrictInfo nodes in different joinlists will have been
1185  * multiply-linked rather than copied, pointer equality should be
1186  * a sufficient test.)
1187  */
1188  new_joininfo = list_append_unique_ptr(new_joininfo, rinfo);
1189  }
1190  }
1191 
1192  return new_joininfo;
1193 }
1194 
1195 
1196 /*
1197  * fetch_upper_rel
1198  * Build a RelOptInfo describing some post-scan/join query processing,
1199  * or return a pre-existing one if somebody already built it.
1200  *
1201  * An "upper" relation is identified by an UpperRelationKind and a Relids set.
1202  * The meaning of the Relids set is not specified here, and very likely will
1203  * vary for different relation kinds.
1204  *
1205  * Most of the fields in an upper-level RelOptInfo are not used and are not
1206  * set here (though makeNode should ensure they're zeroes). We basically only
1207  * care about fields that are of interest to add_path() and set_cheapest().
1208  */
1209 RelOptInfo *
1211 {
1212  RelOptInfo *upperrel;
1213  ListCell *lc;
1214 
1215  /*
1216  * For the moment, our indexing data structure is just a List for each
1217  * relation kind. If we ever get so many of one kind that this stops
1218  * working well, we can improve it. No code outside this function should
1219  * assume anything about how to find a particular upperrel.
1220  */
1221 
1222  /* If we already made this upperrel for the query, return it */
1223  foreach(lc, root->upper_rels[kind])
1224  {
1225  upperrel = (RelOptInfo *) lfirst(lc);
1226 
1227  if (bms_equal(upperrel->relids, relids))
1228  return upperrel;
1229  }
1230 
1231  upperrel = makeNode(RelOptInfo);
1232  upperrel->reloptkind = RELOPT_UPPER_REL;
1233  upperrel->relids = bms_copy(relids);
1234 
1235  /* cheap startup cost is interesting iff not all tuples to be retrieved */
1236  upperrel->consider_startup = (root->tuple_fraction > 0);
1237  upperrel->consider_param_startup = false;
1238  upperrel->consider_parallel = false; /* might get changed later */
1239  upperrel->reltarget = create_empty_pathtarget();
1240  upperrel->pathlist = NIL;
1241  upperrel->cheapest_startup_path = NULL;
1242  upperrel->cheapest_total_path = NULL;
1243  upperrel->cheapest_unique_path = NULL;
1244  upperrel->cheapest_parameterized_paths = NIL;
1245 
1246  root->upper_rels[kind] = lappend(root->upper_rels[kind], upperrel);
1247 
1248  return upperrel;
1249 }
1250 
1251 
1252 /*
1253  * find_childrel_parents
1254  * Compute the set of parent relids of an appendrel child rel.
1255  *
1256  * Since appendrels can be nested, a child could have multiple levels of
1257  * appendrel ancestors. This function computes a Relids set of all the
1258  * parent relation IDs.
1259  */
1260 Relids
1262 {
1263  Relids result = NULL;
1264 
1266  Assert(rel->relid > 0 && rel->relid < root->simple_rel_array_size);
1267 
1268  do
1269  {
1270  AppendRelInfo *appinfo = root->append_rel_array[rel->relid];
1271  Index prelid = appinfo->parent_relid;
1272 
1273  result = bms_add_member(result, prelid);
1274 
1275  /* traverse up to the parent rel, loop if it's also a child rel */
1276  rel = find_base_rel(root, prelid);
1277  } while (rel->reloptkind == RELOPT_OTHER_MEMBER_REL);
1278 
1279  Assert(rel->reloptkind == RELOPT_BASEREL);
1280 
1281  return result;
1282 }
1283 
1284 
1285 /*
1286  * get_baserel_parampathinfo
1287  * Get the ParamPathInfo for a parameterized path for a base relation,
1288  * constructing one if we don't have one already.
1289  *
1290  * This centralizes estimating the rowcounts for parameterized paths.
1291  * We need to cache those to be sure we use the same rowcount for all paths
1292  * of the same parameterization for a given rel. This is also a convenient
1293  * place to determine which movable join clauses the parameterized path will
1294  * be responsible for evaluating.
1295  */
1296 ParamPathInfo *
1298  Relids required_outer)
1299 {
1300  ParamPathInfo *ppi;
1301  Relids joinrelids;
1302  List *pclauses;
1303  double rows;
1304  ListCell *lc;
1305 
1306  /* If rel has LATERAL refs, every path for it should account for them */
1307  Assert(bms_is_subset(baserel->lateral_relids, required_outer));
1308 
1309  /* Unparameterized paths have no ParamPathInfo */
1310  if (bms_is_empty(required_outer))
1311  return NULL;
1312 
1313  Assert(!bms_overlap(baserel->relids, required_outer));
1314 
1315  /* If we already have a PPI for this parameterization, just return it */
1316  if ((ppi = find_param_path_info(baserel, required_outer)))
1317  return ppi;
1318 
1319  /*
1320  * Identify all joinclauses that are movable to this base rel given this
1321  * parameterization.
1322  */
1323  joinrelids = bms_union(baserel->relids, required_outer);
1324  pclauses = NIL;
1325  foreach(lc, baserel->joininfo)
1326  {
1327  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1328 
1329  if (join_clause_is_movable_into(rinfo,
1330  baserel->relids,
1331  joinrelids))
1332  pclauses = lappend(pclauses, rinfo);
1333  }
1334 
1335  /*
1336  * Add in joinclauses generated by EquivalenceClasses, too. (These
1337  * necessarily satisfy join_clause_is_movable_into.)
1338  */
1339  pclauses = list_concat(pclauses,
1341  joinrelids,
1342  required_outer,
1343  baserel));
1344 
1345  /* Estimate the number of rows returned by the parameterized scan */
1346  rows = get_parameterized_baserel_size(root, baserel, pclauses);
1347 
1348  /* And now we can build the ParamPathInfo */
1349  ppi = makeNode(ParamPathInfo);
1350  ppi->ppi_req_outer = required_outer;
1351  ppi->ppi_rows = rows;
1352  ppi->ppi_clauses = pclauses;
1353  baserel->ppilist = lappend(baserel->ppilist, ppi);
1354 
1355  return ppi;
1356 }
1357 
1358 /*
1359  * get_joinrel_parampathinfo
1360  * Get the ParamPathInfo for a parameterized path for a join relation,
1361  * constructing one if we don't have one already.
1362  *
1363  * This centralizes estimating the rowcounts for parameterized paths.
1364  * We need to cache those to be sure we use the same rowcount for all paths
1365  * of the same parameterization for a given rel. This is also a convenient
1366  * place to determine which movable join clauses the parameterized path will
1367  * be responsible for evaluating.
1368  *
1369  * outer_path and inner_path are a pair of input paths that can be used to
1370  * construct the join, and restrict_clauses is the list of regular join
1371  * clauses (including clauses derived from EquivalenceClasses) that must be
1372  * applied at the join node when using these inputs.
1373  *
1374  * Unlike the situation for base rels, the set of movable join clauses to be
1375  * enforced at a join varies with the selected pair of input paths, so we
1376  * must calculate that and pass it back, even if we already have a matching
1377  * ParamPathInfo. We handle this by adding any clauses moved down to this
1378  * join to *restrict_clauses, which is an in/out parameter. (The addition
1379  * is done in such a way as to not modify the passed-in List structure.)
1380  *
1381  * Note: when considering a nestloop join, the caller must have removed from
1382  * restrict_clauses any movable clauses that are themselves scheduled to be
1383  * pushed into the right-hand path. We do not do that here since it's
1384  * unnecessary for other join types.
1385  */
1386 ParamPathInfo *
1388  Path *outer_path,
1389  Path *inner_path,
1390  SpecialJoinInfo *sjinfo,
1391  Relids required_outer,
1392  List **restrict_clauses)
1393 {
1394  ParamPathInfo *ppi;
1395  Relids join_and_req;
1396  Relids outer_and_req;
1397  Relids inner_and_req;
1398  List *pclauses;
1399  List *eclauses;
1400  List *dropped_ecs;
1401  double rows;
1402  ListCell *lc;
1403 
1404  /* If rel has LATERAL refs, every path for it should account for them */
1405  Assert(bms_is_subset(joinrel->lateral_relids, required_outer));
1406 
1407  /* Unparameterized paths have no ParamPathInfo or extra join clauses */
1408  if (bms_is_empty(required_outer))
1409  return NULL;
1410 
1411  Assert(!bms_overlap(joinrel->relids, required_outer));
1412 
1413  /*
1414  * Identify all joinclauses that are movable to this join rel given this
1415  * parameterization. These are the clauses that are movable into this
1416  * join, but not movable into either input path. Treat an unparameterized
1417  * input path as not accepting parameterized clauses (because it won't,
1418  * per the shortcut exit above), even though the joinclause movement rules
1419  * might allow the same clauses to be moved into a parameterized path for
1420  * that rel.
1421  */
1422  join_and_req = bms_union(joinrel->relids, required_outer);
1423  if (outer_path->param_info)
1424  outer_and_req = bms_union(outer_path->parent->relids,
1425  PATH_REQ_OUTER(outer_path));
1426  else
1427  outer_and_req = NULL; /* outer path does not accept parameters */
1428  if (inner_path->param_info)
1429  inner_and_req = bms_union(inner_path->parent->relids,
1430  PATH_REQ_OUTER(inner_path));
1431  else
1432  inner_and_req = NULL; /* inner path does not accept parameters */
1433 
1434  pclauses = NIL;
1435  foreach(lc, joinrel->joininfo)
1436  {
1437  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1438 
1439  if (join_clause_is_movable_into(rinfo,
1440  joinrel->relids,
1441  join_and_req) &&
1443  outer_path->parent->relids,
1444  outer_and_req) &&
1446  inner_path->parent->relids,
1447  inner_and_req))
1448  pclauses = lappend(pclauses, rinfo);
1449  }
1450 
1451  /* Consider joinclauses generated by EquivalenceClasses, too */
1452  eclauses = generate_join_implied_equalities(root,
1453  join_and_req,
1454  required_outer,
1455  joinrel);
1456  /* We only want ones that aren't movable to lower levels */
1457  dropped_ecs = NIL;
1458  foreach(lc, eclauses)
1459  {
1460  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1461 
1462  /*
1463  * In principle, join_clause_is_movable_into() should accept anything
1464  * returned by generate_join_implied_equalities(); but because its
1465  * analysis is only approximate, sometimes it doesn't. So we
1466  * currently cannot use this Assert; instead just assume it's okay to
1467  * apply the joinclause at this level.
1468  */
1469 #ifdef NOT_USED
1471  joinrel->relids,
1472  join_and_req));
1473 #endif
1474  if (join_clause_is_movable_into(rinfo,
1475  outer_path->parent->relids,
1476  outer_and_req))
1477  continue; /* drop if movable into LHS */
1478  if (join_clause_is_movable_into(rinfo,
1479  inner_path->parent->relids,
1480  inner_and_req))
1481  {
1482  /* drop if movable into RHS, but remember EC for use below */
1483  Assert(rinfo->left_ec == rinfo->right_ec);
1484  dropped_ecs = lappend(dropped_ecs, rinfo->left_ec);
1485  continue;
1486  }
1487  pclauses = lappend(pclauses, rinfo);
1488  }
1489 
1490  /*
1491  * EquivalenceClasses are harder to deal with than we could wish, because
1492  * of the fact that a given EC can generate different clauses depending on
1493  * context. Suppose we have an EC {X.X, Y.Y, Z.Z} where X and Y are the
1494  * LHS and RHS of the current join and Z is in required_outer, and further
1495  * suppose that the inner_path is parameterized by both X and Z. The code
1496  * above will have produced either Z.Z = X.X or Z.Z = Y.Y from that EC,
1497  * and in the latter case will have discarded it as being movable into the
1498  * RHS. However, the EC machinery might have produced either Y.Y = X.X or
1499  * Y.Y = Z.Z as the EC enforcement clause within the inner_path; it will
1500  * not have produced both, and we can't readily tell from here which one
1501  * it did pick. If we add no clause to this join, we'll end up with
1502  * insufficient enforcement of the EC; either Z.Z or X.X will fail to be
1503  * constrained to be equal to the other members of the EC. (When we come
1504  * to join Z to this X/Y path, we will certainly drop whichever EC clause
1505  * is generated at that join, so this omission won't get fixed later.)
1506  *
1507  * To handle this, for each EC we discarded such a clause from, try to
1508  * generate a clause connecting the required_outer rels to the join's LHS
1509  * ("Z.Z = X.X" in the terms of the above example). If successful, and if
1510  * the clause can't be moved to the LHS, add it to the current join's
1511  * restriction clauses. (If an EC cannot generate such a clause then it
1512  * has nothing that needs to be enforced here, while if the clause can be
1513  * moved into the LHS then it should have been enforced within that path.)
1514  *
1515  * Note that we don't need similar processing for ECs whose clause was
1516  * considered to be movable into the LHS, because the LHS can't refer to
1517  * the RHS so there is no comparable ambiguity about what it might
1518  * actually be enforcing internally.
1519  */
1520  if (dropped_ecs)
1521  {
1522  Relids real_outer_and_req;
1523 
1524  real_outer_and_req = bms_union(outer_path->parent->relids,
1525  required_outer);
1526  eclauses =
1528  dropped_ecs,
1529  real_outer_and_req,
1530  required_outer,
1531  outer_path->parent);
1532  foreach(lc, eclauses)
1533  {
1534  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1535 
1536  /* As above, can't quite assert this here */
1537 #ifdef NOT_USED
1539  outer_path->parent->relids,
1540  real_outer_and_req));
1541 #endif
1542  if (!join_clause_is_movable_into(rinfo,
1543  outer_path->parent->relids,
1544  outer_and_req))
1545  pclauses = lappend(pclauses, rinfo);
1546  }
1547  }
1548 
1549  /*
1550  * Now, attach the identified moved-down clauses to the caller's
1551  * restrict_clauses list. By using list_concat in this order, we leave
1552  * the original list structure of restrict_clauses undamaged.
1553  */
1554  *restrict_clauses = list_concat(pclauses, *restrict_clauses);
1555 
1556  /* If we already have a PPI for this parameterization, just return it */
1557  if ((ppi = find_param_path_info(joinrel, required_outer)))
1558  return ppi;
1559 
1560  /* Estimate the number of rows returned by the parameterized join */
1561  rows = get_parameterized_joinrel_size(root, joinrel,
1562  outer_path,
1563  inner_path,
1564  sjinfo,
1565  *restrict_clauses);
1566 
1567  /*
1568  * And now we can build the ParamPathInfo. No point in saving the
1569  * input-pair-dependent clause list, though.
1570  *
1571  * Note: in GEQO mode, we'll be called in a temporary memory context, but
1572  * the joinrel structure is there too, so no problem.
1573  */
1574  ppi = makeNode(ParamPathInfo);
1575  ppi->ppi_req_outer = required_outer;
1576  ppi->ppi_rows = rows;
1577  ppi->ppi_clauses = NIL;
1578  joinrel->ppilist = lappend(joinrel->ppilist, ppi);
1579 
1580  return ppi;
1581 }
1582 
1583 /*
1584  * get_appendrel_parampathinfo
1585  * Get the ParamPathInfo for a parameterized path for an append relation.
1586  *
1587  * For an append relation, the rowcount estimate will just be the sum of
1588  * the estimates for its children. However, we still need a ParamPathInfo
1589  * to flag the fact that the path requires parameters. So this just creates
1590  * a suitable struct with zero ppi_rows (and no ppi_clauses either, since
1591  * the Append node isn't responsible for checking quals).
1592  */
1593 ParamPathInfo *
1594 get_appendrel_parampathinfo(RelOptInfo *appendrel, Relids required_outer)
1595 {
1596  ParamPathInfo *ppi;
1597 
1598  /* If rel has LATERAL refs, every path for it should account for them */
1599  Assert(bms_is_subset(appendrel->lateral_relids, required_outer));
1600 
1601  /* Unparameterized paths have no ParamPathInfo */
1602  if (bms_is_empty(required_outer))
1603  return NULL;
1604 
1605  Assert(!bms_overlap(appendrel->relids, required_outer));
1606 
1607  /* If we already have a PPI for this parameterization, just return it */
1608  if ((ppi = find_param_path_info(appendrel, required_outer)))
1609  return ppi;
1610 
1611  /* Else build the ParamPathInfo */
1612  ppi = makeNode(ParamPathInfo);
1613  ppi->ppi_req_outer = required_outer;
1614  ppi->ppi_rows = 0;
1615  ppi->ppi_clauses = NIL;
1616  appendrel->ppilist = lappend(appendrel->ppilist, ppi);
1617 
1618  return ppi;
1619 }
1620 
1621 /*
1622  * Returns a ParamPathInfo for the parameterization given by required_outer, if
1623  * already available in the given rel. Returns NULL otherwise.
1624  */
1625 ParamPathInfo *
1627 {
1628  ListCell *lc;
1629 
1630  foreach(lc, rel->ppilist)
1631  {
1632  ParamPathInfo *ppi = (ParamPathInfo *) lfirst(lc);
1633 
1634  if (bms_equal(ppi->ppi_req_outer, required_outer))
1635  return ppi;
1636  }
1637 
1638  return NULL;
1639 }
1640 
1641 /*
1642  * build_joinrel_partition_info
1643  * Checks if the two relations being joined can use partitionwise join
1644  * and if yes, initialize partitioning information of the resulting
1645  * partitioned join relation.
1646  */
1647 static void
1649  RelOptInfo *inner_rel, List *restrictlist,
1650  JoinType jointype)
1651 {
1652  PartitionScheme part_scheme;
1653 
1654  /* Nothing to do if partitionwise join technique is disabled. */
1656  {
1657  Assert(!IS_PARTITIONED_REL(joinrel));
1658  return;
1659  }
1660 
1661  /*
1662  * We can only consider this join as an input to further partitionwise
1663  * joins if (a) the input relations are partitioned and have
1664  * consider_partitionwise_join=true, (b) the partition schemes match, and
1665  * (c) we can identify an equi-join between the partition keys. Note that
1666  * if it were possible for have_partkey_equi_join to return different
1667  * answers for the same joinrel depending on which join ordering we try
1668  * first, this logic would break. That shouldn't happen, though, because
1669  * of the way the query planner deduces implied equalities and reorders
1670  * the joins. Please see optimizer/README for details.
1671  */
1672  if (outer_rel->part_scheme == NULL || inner_rel->part_scheme == NULL ||
1673  !outer_rel->consider_partitionwise_join ||
1674  !inner_rel->consider_partitionwise_join ||
1675  outer_rel->part_scheme != inner_rel->part_scheme ||
1676  !have_partkey_equi_join(joinrel, outer_rel, inner_rel,
1677  jointype, restrictlist))
1678  {
1679  Assert(!IS_PARTITIONED_REL(joinrel));
1680  return;
1681  }
1682 
1683  part_scheme = outer_rel->part_scheme;
1684 
1685  /*
1686  * This function will be called only once for each joinrel, hence it
1687  * should not have partitioning fields filled yet.
1688  */
1689  Assert(!joinrel->part_scheme && !joinrel->partexprs &&
1690  !joinrel->nullable_partexprs && !joinrel->part_rels &&
1691  !joinrel->boundinfo);
1692 
1693  /*
1694  * If the join relation is partitioned, it uses the same partitioning
1695  * scheme as the joining relations.
1696  *
1697  * Note: we calculate the partition bounds, number of partitions, and
1698  * child-join relations of the join relation in try_partitionwise_join().
1699  */
1700  joinrel->part_scheme = part_scheme;
1701  set_joinrel_partition_key_exprs(joinrel, outer_rel, inner_rel, jointype);
1702 
1703  /*
1704  * Set the consider_partitionwise_join flag.
1705  */
1706  Assert(outer_rel->consider_partitionwise_join);
1707  Assert(inner_rel->consider_partitionwise_join);
1708  joinrel->consider_partitionwise_join = true;
1709 }
1710 
1711 /*
1712  * have_partkey_equi_join
1713  *
1714  * Returns true if there exist equi-join conditions involving pairs
1715  * of matching partition keys of the relations being joined for all
1716  * partition keys.
1717  */
1718 static bool
1720  RelOptInfo *rel1, RelOptInfo *rel2,
1721  JoinType jointype, List *restrictlist)
1722 {
1723  PartitionScheme part_scheme = rel1->part_scheme;
1724  ListCell *lc;
1725  int cnt_pks;
1726  bool pk_has_clause[PARTITION_MAX_KEYS];
1727  bool strict_op;
1728 
1729  /*
1730  * This function must only be called when the joined relations have same
1731  * partitioning scheme.
1732  */
1733  Assert(rel1->part_scheme == rel2->part_scheme);
1734  Assert(part_scheme);
1735 
1736  memset(pk_has_clause, 0, sizeof(pk_has_clause));
1737  foreach(lc, restrictlist)
1738  {
1739  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
1740  OpExpr *opexpr;
1741  Expr *expr1;
1742  Expr *expr2;
1743  int ipk1;
1744  int ipk2;
1745 
1746  /* If processing an outer join, only use its own join clauses. */
1747  if (IS_OUTER_JOIN(jointype) &&
1748  RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
1749  continue;
1750 
1751  /* Skip clauses which can not be used for a join. */
1752  if (!rinfo->can_join)
1753  continue;
1754 
1755  /* Skip clauses which are not equality conditions. */
1756  if (!rinfo->mergeopfamilies && !OidIsValid(rinfo->hashjoinoperator))
1757  continue;
1758 
1759  /* Should be OK to assume it's an OpExpr. */
1760  opexpr = castNode(OpExpr, rinfo->clause);
1761 
1762  /* Match the operands to the relation. */
1763  if (bms_is_subset(rinfo->left_relids, rel1->relids) &&
1764  bms_is_subset(rinfo->right_relids, rel2->relids))
1765  {
1766  expr1 = linitial(opexpr->args);
1767  expr2 = lsecond(opexpr->args);
1768  }
1769  else if (bms_is_subset(rinfo->left_relids, rel2->relids) &&
1770  bms_is_subset(rinfo->right_relids, rel1->relids))
1771  {
1772  expr1 = lsecond(opexpr->args);
1773  expr2 = linitial(opexpr->args);
1774  }
1775  else
1776  continue;
1777 
1778  /*
1779  * Now we need to know whether the join operator is strict; see
1780  * comments in pathnodes.h.
1781  */
1782  strict_op = op_strict(opexpr->opno);
1783 
1784  /*
1785  * Only clauses referencing the partition keys are useful for
1786  * partitionwise join.
1787  */
1788  ipk1 = match_expr_to_partition_keys(expr1, rel1, strict_op);
1789  if (ipk1 < 0)
1790  continue;
1791  ipk2 = match_expr_to_partition_keys(expr2, rel2, strict_op);
1792  if (ipk2 < 0)
1793  continue;
1794 
1795  /*
1796  * If the clause refers to keys at different ordinal positions, it can
1797  * not be used for partitionwise join.
1798  */
1799  if (ipk1 != ipk2)
1800  continue;
1801 
1802  /*
1803  * The clause allows partitionwise join only if it uses the same
1804  * operator family as that specified by the partition key.
1805  */
1807  {
1808  if (!OidIsValid(rinfo->hashjoinoperator) ||
1810  part_scheme->partopfamily[ipk1]))
1811  continue;
1812  }
1813  else if (!list_member_oid(rinfo->mergeopfamilies,
1814  part_scheme->partopfamily[ipk1]))
1815  continue;
1816 
1817  /* Mark the partition key as having an equi-join clause. */
1818  pk_has_clause[ipk1] = true;
1819  }
1820 
1821  /* Check whether every partition key has an equi-join condition. */
1822  for (cnt_pks = 0; cnt_pks < part_scheme->partnatts; cnt_pks++)
1823  {
1824  if (!pk_has_clause[cnt_pks])
1825  return false;
1826  }
1827 
1828  return true;
1829 }
1830 
1831 /*
1832  * match_expr_to_partition_keys
1833  *
1834  * Tries to match an expression to one of the nullable or non-nullable
1835  * partition keys of "rel". Returns the matched key's ordinal position,
1836  * or -1 if the expression could not be matched to any of the keys.
1837  *
1838  * strict_op must be true if the expression will be compared with the
1839  * partition key using a strict operator. This allows us to consider
1840  * nullable as well as nonnullable partition keys.
1841  */
1842 static int
1843 match_expr_to_partition_keys(Expr *expr, RelOptInfo *rel, bool strict_op)
1844 {
1845  int cnt;
1846 
1847  /* This function should be called only for partitioned relations. */
1848  Assert(rel->part_scheme);
1849  Assert(rel->partexprs);
1850  Assert(rel->nullable_partexprs);
1851 
1852  /* Remove any relabel decorations. */
1853  while (IsA(expr, RelabelType))
1854  expr = (Expr *) (castNode(RelabelType, expr))->arg;
1855 
1856  for (cnt = 0; cnt < rel->part_scheme->partnatts; cnt++)
1857  {
1858  ListCell *lc;
1859 
1860  /* We can always match to the non-nullable partition keys. */
1861  foreach(lc, rel->partexprs[cnt])
1862  {
1863  if (equal(lfirst(lc), expr))
1864  return cnt;
1865  }
1866 
1867  if (!strict_op)
1868  continue;
1869 
1870  /*
1871  * If it's a strict join operator then a NULL partition key on one
1872  * side will not join to any partition key on the other side, and in
1873  * particular such a row can't join to a row from a different
1874  * partition on the other side. So, it's okay to search the nullable
1875  * partition keys as well.
1876  */
1877  foreach(lc, rel->nullable_partexprs[cnt])
1878  {
1879  if (equal(lfirst(lc), expr))
1880  return cnt;
1881  }
1882  }
1883 
1884  return -1;
1885 }
1886 
1887 /*
1888  * set_joinrel_partition_key_exprs
1889  * Initialize partition key expressions for a partitioned joinrel.
1890  */
1891 static void
1893  RelOptInfo *outer_rel, RelOptInfo *inner_rel,
1894  JoinType jointype)
1895 {
1896  PartitionScheme part_scheme = joinrel->part_scheme;
1897  int partnatts = part_scheme->partnatts;
1898 
1899  joinrel->partexprs = (List **) palloc0(sizeof(List *) * partnatts);
1900  joinrel->nullable_partexprs =
1901  (List **) palloc0(sizeof(List *) * partnatts);
1902 
1903  /*
1904  * The joinrel's partition expressions are the same as those of the input
1905  * rels, but we must properly classify them as nullable or not in the
1906  * joinrel's output. (Also, we add some more partition expressions if
1907  * it's a FULL JOIN.)
1908  */
1909  for (int cnt = 0; cnt < partnatts; cnt++)
1910  {
1911  /* mark these const to enforce that we copy them properly */
1912  const List *outer_expr = outer_rel->partexprs[cnt];
1913  const List *outer_null_expr = outer_rel->nullable_partexprs[cnt];
1914  const List *inner_expr = inner_rel->partexprs[cnt];
1915  const List *inner_null_expr = inner_rel->nullable_partexprs[cnt];
1916  List *partexpr = NIL;
1917  List *nullable_partexpr = NIL;
1918  ListCell *lc;
1919 
1920  switch (jointype)
1921  {
1922  /*
1923  * A join relation resulting from an INNER join may be
1924  * regarded as partitioned by either of the inner and outer
1925  * relation keys. For example, A INNER JOIN B ON A.a = B.b
1926  * can be regarded as partitioned on either A.a or B.b. So we
1927  * add both keys to the joinrel's partexpr lists. However,
1928  * anything that was already nullable still has to be treated
1929  * as nullable.
1930  */
1931  case JOIN_INNER:
1932  partexpr = list_concat_copy(outer_expr, inner_expr);
1933  nullable_partexpr = list_concat_copy(outer_null_expr,
1934  inner_null_expr);
1935  break;
1936 
1937  /*
1938  * A join relation resulting from a SEMI or ANTI join may be
1939  * regarded as partitioned by the outer relation keys. The
1940  * inner relation's keys are no longer interesting; since they
1941  * aren't visible in the join output, nothing could join to
1942  * them.
1943  */
1944  case JOIN_SEMI:
1945  case JOIN_ANTI:
1946  partexpr = list_copy(outer_expr);
1947  nullable_partexpr = list_copy(outer_null_expr);
1948  break;
1949 
1950  /*
1951  * A join relation resulting from a LEFT OUTER JOIN likewise
1952  * may be regarded as partitioned on the (non-nullable) outer
1953  * relation keys. The inner (nullable) relation keys are okay
1954  * as partition keys for further joins as long as they involve
1955  * strict join operators.
1956  */
1957  case JOIN_LEFT:
1958  partexpr = list_copy(outer_expr);
1959  nullable_partexpr = list_concat_copy(inner_expr,
1960  outer_null_expr);
1961  nullable_partexpr = list_concat(nullable_partexpr,
1962  inner_null_expr);
1963  break;
1964 
1965  /*
1966  * For FULL OUTER JOINs, both relations are nullable, so the
1967  * resulting join relation may be regarded as partitioned on
1968  * either of inner and outer relation keys, but only for joins
1969  * that involve strict join operators.
1970  */
1971  case JOIN_FULL:
1972  nullable_partexpr = list_concat_copy(outer_expr,
1973  inner_expr);
1974  nullable_partexpr = list_concat(nullable_partexpr,
1975  outer_null_expr);
1976  nullable_partexpr = list_concat(nullable_partexpr,
1977  inner_null_expr);
1978 
1979  /*
1980  * Also add CoalesceExprs corresponding to each possible
1981  * full-join output variable (that is, left side coalesced to
1982  * right side), so that we can match equijoin expressions
1983  * using those variables. We really only need these for
1984  * columns merged by JOIN USING, and only with the pairs of
1985  * input items that correspond to the data structures that
1986  * parse analysis would build for such variables. But it's
1987  * hard to tell which those are, so just make all the pairs.
1988  * Extra items in the nullable_partexprs list won't cause big
1989  * problems. (It's possible that such items will get matched
1990  * to user-written COALESCEs, but it should still be valid to
1991  * partition on those, since they're going to be either the
1992  * partition column or NULL; it's the same argument as for
1993  * partitionwise nesting of any outer join.) We assume no
1994  * type coercions are needed to make the coalesce expressions,
1995  * since columns of different types won't have gotten
1996  * classified as the same PartitionScheme.
1997  */
1998  foreach(lc, list_concat_copy(outer_expr, outer_null_expr))
1999  {
2000  Node *larg = (Node *) lfirst(lc);
2001  ListCell *lc2;
2002 
2003  foreach(lc2, list_concat_copy(inner_expr, inner_null_expr))
2004  {
2005  Node *rarg = (Node *) lfirst(lc2);
2007 
2008  c->coalescetype = exprType(larg);
2009  c->coalescecollid = exprCollation(larg);
2010  c->args = list_make2(larg, rarg);
2011  c->location = -1;
2012  nullable_partexpr = lappend(nullable_partexpr, c);
2013  }
2014  }
2015  break;
2016 
2017  default:
2018  elog(ERROR, "unrecognized join type: %d", (int) jointype);
2019  }
2020 
2021  joinrel->partexprs[cnt] = partexpr;
2022  joinrel->nullable_partexprs[cnt] = nullable_partexpr;
2023  }
2024 }
2025 
2026 /*
2027  * build_child_join_reltarget
2028  * Set up a child-join relation's reltarget from a parent-join relation.
2029  */
2030 static void
2032  RelOptInfo *parentrel,
2033  RelOptInfo *childrel,
2034  int nappinfos,
2035  AppendRelInfo **appinfos)
2036 {
2037  /* Build the targetlist */
2038  childrel->reltarget->exprs = (List *)
2040  (Node *) parentrel->reltarget->exprs,
2041  nappinfos, appinfos);
2042 
2043  /* Set the cost and width fields */
2044  childrel->reltarget->cost.startup = parentrel->reltarget->cost.startup;
2045  childrel->reltarget->cost.per_tuple = parentrel->reltarget->cost.per_tuple;
2046  childrel->reltarget->width = parentrel->reltarget->width;
2047 }
#define list_make2(x1, x2)
Definition: pg_list.h:208
bool has_eclass_joins
Definition: pathnodes.h:751
struct Path * cheapest_unique_path
Definition: pathnodes.h:700
PathTarget * create_empty_pathtarget(void)
Definition: tlist.c:670
int varno
Definition: primnodes.h:189
#define NIL
Definition: pg_list.h:65
bool op_in_opfamily(Oid opno, Oid opfamily)
Definition: lsyscache.c:64
ParamPathInfo * find_param_path_info(RelOptInfo *rel, Relids required_outer)
Definition: relnode.c:1626
UpperRelationKind
Definition: pathnodes.h:67
int join_cur_level
Definition: pathnodes.h:240
List * unique_for_rels
Definition: pathnodes.h:740
bool op_strict(Oid opno)
Definition: lsyscache.c:1448
#define IsA(nodeptr, _type_)
Definition: nodes.h:587
Query * parse
Definition: pathnodes.h:162
List * statlist
Definition: pathnodes.h:719
Bitmapset * bms_copy(const Bitmapset *a)
Definition: bitmapset.c:74
ParamPathInfo * get_baserel_parampathinfo(PlannerInfo *root, RelOptInfo *baserel, Relids required_outer)
Definition: relnode.c:1297
RelOptKind reloptkind
Definition: pathnodes.h:678
Relids * attr_needed
Definition: pathnodes.h:714
#define ROWID_VAR
Definition: primnodes.h:178
Relids required_relids
Definition: pathnodes.h:2077
#define HASH_CONTEXT
Definition: hsearch.h:102
#define HASH_ELEM
Definition: hsearch.h:95
List * colnames
Definition: primnodes.h:43
MemoryContext hcxt
Definition: hsearch.h:86
RelOptInfo * find_join_rel(PlannerInfo *root, Relids relids)
Definition: relnode.c:439
ParamPathInfo * get_joinrel_parampathinfo(PlannerInfo *root, RelOptInfo *joinrel, Path *outer_path, Path *inner_path, SpecialJoinInfo *sjinfo, Relids required_outer, List **restrict_clauses)
Definition: relnode.c:1387
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3149
Oid GetUserId(void)
Definition: miscinit.c:495
#define castNode(_type_, nodeptr)
Definition: nodes.h:605
static List * subbuild_joinrel_restrictlist(RelOptInfo *joinrel, List *joininfo_list, List *new_restrictlist)
Definition: relnode.c:1124
static void set_joinrel_partition_key_exprs(RelOptInfo *joinrel, RelOptInfo *outer_rel, RelOptInfo *inner_rel, JoinType jointype)
Definition: relnode.c:1892
#define IS_OTHER_REL(rel)
Definition: pathnodes.h:669
void set_joinrel_size_estimates(PlannerInfo *root, RelOptInfo *rel, RelOptInfo *outer_rel, RelOptInfo *inner_rel, SpecialJoinInfo *sjinfo, List *restrictlist)
Definition: costsize.c:5002
struct Path * cheapest_startup_path
Definition: pathnodes.h:698
Oid userid
Definition: pathnodes.h:733
Relids join_relids
Definition: relnode.c:37
List * baserestrictinfo
Definition: pathnodes.h:745
bool consider_param_startup
Definition: pathnodes.h:688
#define IS_OUTER_JOIN(jointype)
Definition: nodes.h:753
ParamPathInfo * param_info
Definition: pathnodes.h:1185
Size entrysize
Definition: hsearch.h:76
List * list_copy(const List *oldlist)
Definition: list.c:1418
Definition: nodes.h:536
List * list_concat(List *list1, const List *list2)
Definition: list.c:530
List * partial_pathlist
Definition: pathnodes.h:697
#define PARTITION_MAX_KEYS
#define MemSet(start, val, len)
Definition: c.h:1008
Relids left_relids
Definition: pathnodes.h:2086
AttrNumber varattno
Definition: primnodes.h:191
List * join_rel_list
Definition: pathnodes.h:229
EquivalenceClass * right_ec
Definition: pathnodes.h:2108
List * cheapest_parameterized_paths
Definition: pathnodes.h:701
Index baserestrict_min_security
Definition: pathnodes.h:747
Relids all_partrels
Definition: pathnodes.h:773
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:954
bool useridiscurrent
Definition: pathnodes.h:734
Cardinality ppi_rows
Definition: pathnodes.h:1142
List ** nullable_partexprs
Definition: pathnodes.h:775
Definition: primnodes.h:186
#define OidIsValid(objectId)
Definition: c.h:710
Bitmapset * live_parts
Definition: pathnodes.h:770
void add_placeholders_to_joinrel(PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outer_rel, RelOptInfo *inner_rel)
Definition: placeholder.c:413
List * mergeopfamilies
Definition: pathnodes.h:2104
#define lsecond(l)
Definition: pg_list.h:179
Cost startup
Definition: pathnodes.h:45
double allvisfrac
Definition: pathnodes.h:722
signed int int32
Definition: c.h:429
JoinType
Definition: nodes.h:704
struct RelOptInfo ** simple_rel_array
Definition: pathnodes.h:186
void add_child_join_rel_equivalences(PlannerInfo *root, int nappinfos, AppendRelInfo **appinfos, RelOptInfo *parent_joinrel, RelOptInfo *child_joinrel)
Definition: equivclass.c:2696
PlannerInfo * subroot
Definition: pathnodes.h:725
bool consider_startup
Definition: pathnodes.h:687
Definition: dynahash.c:219
bool apply_child_basequals(PlannerInfo *root, RelOptInfo *parentrel, RelOptInfo *childrel, RangeTblEntry *childRTE, AppendRelInfo *appinfo)
Definition: inherit.c:754
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition: clauses.c:639
Relids lateral_relids
Definition: pathnodes.h:706
Cost per_tuple
Definition: pathnodes.h:46
static void set_foreign_rel_properties(RelOptInfo *joinrel, RelOptInfo *outer_rel, RelOptInfo *inner_rel)
Definition: relnode.c:502
uint32 amflags
Definition: pathnodes.h:728
struct JoinHashEntry JoinHashEntry
void pfree(void *pointer)
Definition: mcxt.c:1169
List ** partexprs
Definition: pathnodes.h:774
#define linitial(l)
Definition: pg_list.h:174
List * rtable
Definition: parsenodes.h:147
#define ERROR
Definition: elog.h:46
static void build_joinrel_tlist(PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *input_rel)
Definition: relnode.c:974
List * row_identity_vars
Definition: pathnodes.h:286
List * list_append_unique_ptr(List *list, void *datum)
Definition: list.c:1208
List * generate_join_implied_equalities(PlannerInfo *root, Relids join_relids, Relids outer_relids, RelOptInfo *inner_rel)
Definition: equivclass.c:1421
static void * list_nth(const List *list, int n)
Definition: pg_list.h:278
List * args
Definition: primnodes.h:1132
Relids min_join_parameterization(PlannerInfo *root, Relids joinrelids, RelOptInfo *outer_rel, RelOptInfo *inner_rel)
Definition: relnode.c:931
RelOptInfo * build_child_join_rel(PlannerInfo *root, RelOptInfo *outer_rel, RelOptInfo *inner_rel, RelOptInfo *parent_joinrel, List *restrictlist, SpecialJoinInfo *sjinfo, JoinType jointype)
Definition: relnode.c:786
RelOptInfo * parent
Definition: pathnodes.h:1182
RelOptInfo * join_rel
Definition: relnode.c:38
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:315
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1210
#define lfirst_node(type, lc)
Definition: pg_list.h:172
int bms_num_members(const Bitmapset *a)
Definition: bitmapset.c:646
double get_parameterized_joinrel_size(PlannerInfo *root, RelOptInfo *rel, Path *outer_path, Path *inner_path, SpecialJoinInfo *sjinfo, List *restrict_clauses)
Definition: costsize.c:5034
struct Path * cheapest_total_path
Definition: pathnodes.h:699
static List * build_joinrel_restrictlist(PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outer_rel, RelOptInfo *inner_rel)
Definition: relnode.c:1076
#define PATH_REQ_OUTER(path)
Definition: pathnodes.h:1201
char * c
Bitmapset * bms_make_singleton(int x)
Definition: bitmapset.c:186
List * joininfo
Definition: pathnodes.h:749
static int match_expr_to_partition_keys(Expr *expr, RelOptInfo *rel, bool strict_op)
Definition: relnode.c:1843
List * list_concat_copy(const List *list1, const List *list2)
Definition: list.c:567
struct FdwRoutine * fdwroutine
Definition: pathnodes.h:736
int nparts
Definition: pathnodes.h:761
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:349
Relids relids
Definition: pathnodes.h:681
RelOptInfo * build_simple_rel(PlannerInfo *root, int relid, RelOptInfo *parent)
Definition: relnode.c:194
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
bool partbounds_merged
Definition: pathnodes.h:765
bool has_relevant_eclass_joinclause(PlannerInfo *root, RelOptInfo *rel1)
Definition: equivclass.c:3047
int simple_rel_array_size
Definition: pathnodes.h:187
List * non_unique_for_rels
Definition: pathnodes.h:742
bool join_clause_is_movable_into(RestrictInfo *rinfo, Relids currentrelids, Relids current_and_outer)
Definition: restrictinfo.c:598
List * ppilist
Definition: pathnodes.h:696
Index relid
Definition: pathnodes.h:709
List * lappend(List *list, void *datum)
Definition: list.c:336
RangeTblEntry ** simple_rte_array
Definition: pathnodes.h:194
AppendRelInfo ** find_appinfos_by_relids(PlannerInfo *root, Relids relids, int *nappinfos)
Definition: appendinfo.c:715
Relids lateral_referencers
Definition: pathnodes.h:717
Expr * clause
Definition: pathnodes.h:2056
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:701
Oid serverid
Definition: pathnodes.h:732
List * exprs
Definition: pathnodes.h:1110
Relids direct_lateral_relids
Definition: pathnodes.h:705
bool consider_partitionwise_join
Definition: pathnodes.h:754
int bitmap_match(const void *key1, const void *key2, Size keysize)
Definition: bitmapset.c:1187
void * palloc0(Size size)
Definition: mcxt.c:1093
List * generate_join_implied_equalities_for_ecs(PlannerInfo *root, List *eclasses, Relids join_relids, Relids outer_relids, RelOptInfo *inner_rel)
Definition: equivclass.c:1499
void mark_dummy_rel(RelOptInfo *rel)
Definition: joinrels.c:1261
int rel_parallel_workers
Definition: pathnodes.h:727
List * append_rel_list
Definition: pathnodes.h:284
struct AppendRelInfo ** append_rel_array
Definition: pathnodes.h:202
Size add_size(Size s1, Size s2)
Definition: shmem.c:502
double get_parameterized_baserel_size(PlannerInfo *root, RelOptInfo *rel, List *param_clauses)
Definition: costsize.c:4953
struct PartitionBoundInfoData * boundinfo
Definition: pathnodes.h:764
Size keysize
Definition: hsearch.h:75
RelOptInfo * build_join_rel(PlannerInfo *root, Relids joinrelids, RelOptInfo *outer_rel, RelOptInfo *inner_rel, SpecialJoinInfo *sjinfo, List **restrictlist_ptr)
Definition: relnode.c:577
unsigned int Index
Definition: c.h:549
HashCompareFunc match
Definition: hsearch.h:80
#define PARTITION_STRATEGY_HASH
Definition: parsenodes.h:826
RTEKind rtekind
Definition: pathnodes.h:711
Relids find_childrel_parents(PlannerInfo *root, RelOptInfo *rel)
Definition: relnode.c:1261
List * indexlist
Definition: pathnodes.h:718
#define RINFO_IS_PUSHED_DOWN(rinfo, joinrelids)
Definition: pathnodes.h:2139
#define InvalidOid
Definition: postgres_ext.h:36
static void build_join_rel_hash(PlannerInfo *root)
Definition: relnode.c:398
void * fdw_private
Definition: pathnodes.h:737
#define makeNode(_type_)
Definition: nodes.h:584
Relids right_relids
Definition: pathnodes.h:2087
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:689
BlockNumber pages
Definition: pathnodes.h:720
Selectivity tuple_fraction
Definition: pathnodes.h:340
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
List ** join_rel_level
Definition: pathnodes.h:239
void setup_simple_rel_arrays(PlannerInfo *root)
Definition: relnode.c:83
List * lateral_vars
Definition: pathnodes.h:716
Cardinality rows
Definition: pathnodes.h:684
#define HASH_COMPARE
Definition: hsearch.h:99
JoinType jointype
Definition: pathnodes.h:2256
List * ppi_clauses
Definition: pathnodes.h:1143
struct RelOptInfo ** part_rels
Definition: pathnodes.h:768
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:225
Oid hashjoinoperator
Definition: pathnodes.h:2117
bool enable_partitionwise_join
Definition: costsize.c:147
QualCost cost
Definition: pathnodes.h:1112
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
static int list_length(const List *l)
Definition: pg_list.h:149
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:759
struct HTAB * join_rel_hash
Definition: pathnodes.h:230
bool consider_parallel
Definition: pathnodes.h:689
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:736
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1182
Bitmapset * Relids
Definition: pathnodes.h:28
#define nodeTag(nodeptr)
Definition: nodes.h:541
Bitmapset * bms_del_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:928
RTEKind rtekind
Definition: parsenodes.h:1007
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:494
AttrNumber max_attr
Definition: pathnodes.h:713
void expand_planner_arrays(PlannerInfo *root, int add_size)
Definition: relnode.c:152
EquivalenceClass * left_ec
Definition: pathnodes.h:2107
static List * subbuild_joinrel_joinlist(RelOptInfo *joinrel, List *joininfo_list, List *new_joininfo)
Definition: relnode.c:1158
#define IS_PARTITIONED_REL(rel)
Definition: pathnodes.h:786
#define elog(elevel,...)
Definition: elog.h:232
static void build_joinrel_partition_info(RelOptInfo *joinrel, RelOptInfo *outer_rel, RelOptInfo *inner_rel, List *restrictlist, JoinType jointype)
Definition: relnode.c:1648
Oid coalescetype
Definition: primnodes.h:1130
uint32 bitmap_hash(const void *key, Size keysize)
Definition: bitmapset.c:1177
void * arg
bool has_useful_pathkeys(PlannerInfo *root, RelOptInfo *rel)
Definition: pathkeys.c:1910
PartitionScheme part_scheme
Definition: pathnodes.h:760
List * pathlist
Definition: pathnodes.h:695
Oid opno
Definition: primnodes.h:542
Relids ppi_req_outer
Definition: pathnodes.h:1141
Index child_relid
Definition: pathnodes.h:2307
ParamPathInfo * get_appendrel_parampathinfo(RelOptInfo *appendrel, Relids required_outer)
Definition: relnode.c:1594
Alias * eref
Definition: parsenodes.h:1153
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:375
List * partition_qual
Definition: pathnodes.h:767
List * args
Definition: primnodes.h:548
Index parent_relid
Definition: pathnodes.h:2306
int32 * attr_widths
Definition: pathnodes.h:715
Definition: regcomp.c:237
Definition: pg_list.h:50
struct PathTarget * reltarget
Definition: pathnodes.h:692
QualCost baserestrictcost
Definition: pathnodes.h:746
static void add_join_rel(PlannerInfo *root, RelOptInfo *joinrel)
Definition: relnode.c:540
List * subplan_params
Definition: pathnodes.h:726
static void build_child_join_reltarget(PlannerInfo *root, RelOptInfo *parentrel, RelOptInfo *childrel, int nappinfos, AppendRelInfo **appinfos)
Definition: relnode.c:2031
Bitmapset * eclass_indexes
Definition: pathnodes.h:723
Oid coalescecollid
Definition: primnodes.h:1131
static void build_joinrel_joinlist(RelOptInfo *joinrel, RelOptInfo *outer_rel, RelOptInfo *inner_rel)
Definition: relnode.c:1106
void get_relation_info(PlannerInfo *root, Oid relationObjectId, bool inhparent, RelOptInfo *rel)
Definition: plancat.c:113
bool bms_equal(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:94
static bool have_partkey_equi_join(RelOptInfo *joinrel, RelOptInfo *rel1, RelOptInfo *rel2, JoinType jointype, List *restrictlist)
Definition: relnode.c:1719
Node * adjust_appendrel_attrs(PlannerInfo *root, Node *node, int nappinfos, AppendRelInfo **appinfos)
Definition: appendinfo.c:195
Relids top_parent_relids
Definition: pathnodes.h:756
bool bms_nonempty_difference(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:545
HashValueFunc hash
Definition: hsearch.h:78
#define HASH_FUNCTION
Definition: hsearch.h:98
List * upper_rels[UPPERREL_FINAL+1]
Definition: pathnodes.h:307
AttrNumber min_attr
Definition: pathnodes.h:712
Cardinality tuples
Definition: pathnodes.h:721