Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * relnode.c
4 : : * Relation-node lookup/construction routines
5 : : *
6 : : * Portions Copyright (c) 1996-2026, 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 "access/nbtree.h"
20 : : #include "catalog/pg_constraint.h"
21 : : #include "miscadmin.h"
22 : : #include "nodes/nodeFuncs.h"
23 : : #include "optimizer/appendinfo.h"
24 : : #include "optimizer/clauses.h"
25 : : #include "optimizer/cost.h"
26 : : #include "optimizer/inherit.h"
27 : : #include "optimizer/optimizer.h"
28 : : #include "optimizer/pathnode.h"
29 : : #include "optimizer/paths.h"
30 : : #include "optimizer/placeholder.h"
31 : : #include "optimizer/plancat.h"
32 : : #include "optimizer/planner.h"
33 : : #include "optimizer/restrictinfo.h"
34 : : #include "optimizer/tlist.h"
35 : : #include "parser/parse_oper.h"
36 : : #include "parser/parse_relation.h"
37 : : #include "rewrite/rewriteManip.h"
38 : : #include "utils/hsearch.h"
39 : : #include "utils/lsyscache.h"
40 : : #include "utils/selfuncs.h"
41 : : #include "utils/typcache.h"
42 : :
43 : :
44 : : typedef struct JoinHashEntry
45 : : {
46 : : Relids join_relids; /* hash key --- MUST BE FIRST */
47 : : RelOptInfo *join_rel;
48 : : } JoinHashEntry;
49 : :
50 : : /* Hook for plugins to get control in build_simple_rel() */
51 : : build_simple_rel_hook_type build_simple_rel_hook = NULL;
52 : :
53 : : /* Hook for plugins to get control during joinrel setup */
54 : : joinrel_setup_hook_type joinrel_setup_hook = NULL;
55 : :
56 : : static void build_joinrel_tlist(PlannerInfo *root, RelOptInfo *joinrel,
57 : : RelOptInfo *input_rel,
58 : : SpecialJoinInfo *sjinfo,
59 : : List *pushed_down_joins,
60 : : bool can_null);
61 : : static List *build_joinrel_restrictlist(PlannerInfo *root,
62 : : RelOptInfo *joinrel,
63 : : RelOptInfo *outer_rel,
64 : : RelOptInfo *inner_rel,
65 : : SpecialJoinInfo *sjinfo);
66 : : #ifdef USE_ASSERT_CHECKING
67 : : static bool no_duplicate_clause_serials(List *clauses);
68 : : #endif
69 : : static void build_joinrel_joinlist(RelOptInfo *joinrel,
70 : : RelOptInfo *outer_rel,
71 : : RelOptInfo *inner_rel);
72 : : static List *subbuild_joinrel_restrictlist(PlannerInfo *root,
73 : : RelOptInfo *joinrel,
74 : : RelOptInfo *input_rel,
75 : : Relids both_input_relids,
76 : : List *new_restrictlist);
77 : : static List *subbuild_joinrel_joinlist(RelOptInfo *joinrel,
78 : : List *joininfo_list,
79 : : List *new_joininfo);
80 : : static void set_foreign_rel_properties(RelOptInfo *joinrel,
81 : : RelOptInfo *outer_rel, RelOptInfo *inner_rel);
82 : : static void add_join_rel(PlannerInfo *root, RelOptInfo *joinrel);
83 : : static void build_joinrel_partition_info(PlannerInfo *root,
84 : : RelOptInfo *joinrel,
85 : : RelOptInfo *outer_rel, RelOptInfo *inner_rel,
86 : : SpecialJoinInfo *sjinfo,
87 : : List *restrictlist);
88 : : static bool have_partkey_equi_join(PlannerInfo *root, RelOptInfo *joinrel,
89 : : RelOptInfo *rel1, RelOptInfo *rel2,
90 : : JoinType jointype, List *restrictlist);
91 : : static int match_expr_to_partition_keys(Expr *expr, RelOptInfo *rel,
92 : : bool strict_op);
93 : : static void set_joinrel_partition_key_exprs(RelOptInfo *joinrel,
94 : : RelOptInfo *outer_rel, RelOptInfo *inner_rel,
95 : : JoinType jointype);
96 : : static void build_child_join_reltarget(PlannerInfo *root,
97 : : RelOptInfo *parentrel,
98 : : RelOptInfo *childrel,
99 : : int nappinfos,
100 : : AppendRelInfo **appinfos);
101 : : static bool eager_aggregation_possible_for_relation(PlannerInfo *root,
102 : : RelOptInfo *rel);
103 : : static bool init_grouping_targets(PlannerInfo *root, RelOptInfo *rel,
104 : : PathTarget *target, PathTarget *agg_input,
105 : : List **group_clauses, List **group_exprs);
106 : : static bool is_var_in_aggref_only(PlannerInfo *root, Var *var);
107 : : static bool is_var_needed_by_join(PlannerInfo *root, Var *var, RelOptInfo *rel);
108 : : static Index get_expression_sortgroupref(PlannerInfo *root, Expr *expr);
109 : :
110 : :
111 : : /*
112 : : * setup_simple_rel_arrays
113 : : * Prepare the arrays we use for quickly accessing base relations
114 : : * and AppendRelInfos.
115 : : */
116 : : void
117 : 426235 : setup_simple_rel_arrays(PlannerInfo *root)
118 : : {
119 : : int size;
120 : : Index rti;
121 : : ListCell *lc;
122 : :
123 : : /* Arrays are accessed using RT indexes (1..N) */
124 : 426235 : size = list_length(root->parse->rtable) + 1;
125 : 426235 : root->simple_rel_array_size = size;
126 : :
127 : : /*
128 : : * simple_rel_array is initialized to all NULLs, since no RelOptInfos
129 : : * exist yet. It'll be filled by later calls to build_simple_rel().
130 : : */
131 : 426235 : root->simple_rel_array = (RelOptInfo **)
132 : 426235 : palloc0_array(RelOptInfo *, size);
133 : :
134 : : /* simple_rte_array is an array equivalent of the rtable list */
135 : 426235 : root->simple_rte_array = (RangeTblEntry **)
136 : 426235 : palloc0_array(RangeTblEntry *, size);
137 : 426235 : rti = 1;
138 [ + - + + : 1202118 : foreach(lc, root->parse->rtable)
+ + ]
139 : : {
140 : 775883 : RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
141 : :
142 : 775883 : root->simple_rte_array[rti++] = rte;
143 : : }
144 : :
145 : : /* append_rel_array is not needed if there are no AppendRelInfos */
146 [ + + ]: 426235 : if (root->append_rel_list == NIL)
147 : : {
148 : 421871 : root->append_rel_array = NULL;
149 : 421871 : return;
150 : : }
151 : :
152 : 4364 : root->append_rel_array = (AppendRelInfo **)
153 : 4364 : palloc0_array(AppendRelInfo *, size);
154 : :
155 : : /*
156 : : * append_rel_array is filled with any already-existing AppendRelInfos,
157 : : * which currently could only come from UNION ALL flattening. We might
158 : : * add more later during inheritance expansion, but it's the
159 : : * responsibility of the expansion code to update the array properly.
160 : : */
161 [ + - + + : 16111 : foreach(lc, root->append_rel_list)
+ + ]
162 : : {
163 : 11747 : AppendRelInfo *appinfo = lfirst_node(AppendRelInfo, lc);
164 : 11747 : int child_relid = appinfo->child_relid;
165 : :
166 : : /* Sanity check */
167 : : Assert(child_relid < size);
168 : :
169 [ - + ]: 11747 : if (root->append_rel_array[child_relid])
170 [ # # ]: 0 : elog(ERROR, "child relation already exists");
171 : :
172 : 11747 : root->append_rel_array[child_relid] = appinfo;
173 : : }
174 : : }
175 : :
176 : : /*
177 : : * expand_planner_arrays
178 : : * Expand the PlannerInfo's per-RTE arrays by add_size members
179 : : * and initialize the newly added entries to NULLs
180 : : *
181 : : * Note: this causes the append_rel_array to become allocated even if
182 : : * it was not before. This is okay for current uses, because we only call
183 : : * this when adding child relations, which always have AppendRelInfos.
184 : : */
185 : : void
186 : 15942 : expand_planner_arrays(PlannerInfo *root, int add_size)
187 : : {
188 : : int new_size;
189 : :
190 : : Assert(add_size > 0);
191 : :
192 : 15942 : new_size = root->simple_rel_array_size + add_size;
193 : :
194 : 15942 : root->simple_rel_array =
195 : 15942 : repalloc0_array(root->simple_rel_array, RelOptInfo *, root->simple_rel_array_size, new_size);
196 : :
197 : 15942 : root->simple_rte_array =
198 : 15942 : repalloc0_array(root->simple_rte_array, RangeTblEntry *, root->simple_rel_array_size, new_size);
199 : :
200 [ + + ]: 15942 : if (root->append_rel_array)
201 : 5084 : root->append_rel_array =
202 : 5084 : repalloc0_array(root->append_rel_array, AppendRelInfo *, root->simple_rel_array_size, new_size);
203 : : else
204 : 10858 : root->append_rel_array =
205 : 10858 : palloc0_array(AppendRelInfo *, new_size);
206 : :
207 : 15942 : root->simple_rel_array_size = new_size;
208 : 15942 : }
209 : :
210 : : /*
211 : : * build_simple_rel
212 : : * Construct a new RelOptInfo for a base relation or 'other' relation.
213 : : */
214 : : RelOptInfo *
215 : 607595 : build_simple_rel(PlannerInfo *root, int relid, RelOptInfo *parent)
216 : : {
217 : : RelOptInfo *rel;
218 : : RangeTblEntry *rte;
219 : :
220 : : /* Rel should not exist already */
221 : : Assert(relid > 0 && relid < root->simple_rel_array_size);
222 [ - + ]: 607595 : if (root->simple_rel_array[relid] != NULL)
223 [ # # ]: 0 : elog(ERROR, "rel %d already exists", relid);
224 : :
225 : : /* Fetch RTE for relation */
226 : 607595 : rte = root->simple_rte_array[relid];
227 : : Assert(rte != NULL);
228 : :
229 : 607595 : rel = makeNode(RelOptInfo);
230 [ + + ]: 607595 : rel->reloptkind = parent ? RELOPT_OTHER_MEMBER_REL : RELOPT_BASEREL;
231 : 607595 : rel->relids = bms_make_singleton(relid);
232 : 607595 : rel->rows = 0;
233 : : /* cheap startup cost is interesting iff not all tuples to be retrieved */
234 : 607595 : rel->consider_startup = (root->tuple_fraction > 0);
235 : 607595 : rel->consider_param_startup = false; /* might get changed later */
236 : 607595 : rel->consider_parallel = false; /* might get changed later */
237 : 607595 : rel->pgs_mask = root->glob->default_pgs_mask;
238 : 607595 : rel->reltarget = create_empty_pathtarget();
239 : 607595 : rel->pathlist = NIL;
240 : 607595 : rel->ppilist = NIL;
241 : 607595 : rel->partial_pathlist = NIL;
242 : 607595 : rel->cheapest_startup_path = NULL;
243 : 607595 : rel->cheapest_total_path = NULL;
244 : 607595 : rel->cheapest_parameterized_paths = NIL;
245 : 607595 : rel->relid = relid;
246 : 607595 : rel->rtekind = rte->rtekind;
247 : : /* min_attr, max_attr, attr_needed, attr_widths are set below */
248 : 607595 : rel->notnullattnums = NULL;
249 : 607595 : rel->lateral_vars = NIL;
250 : 607595 : rel->indexlist = NIL;
251 : 607595 : rel->statlist = NIL;
252 : 607595 : rel->pages = 0;
253 : 607595 : rel->tuples = 0;
254 : 607595 : rel->allvisfrac = 0;
255 : 607595 : rel->eclass_indexes = NULL;
256 : 607595 : rel->subroot = NULL;
257 : 607595 : rel->subplan_params = NIL;
258 : 607595 : rel->rel_parallel_workers = -1; /* set up in get_relation_info */
259 : 607595 : rel->amflags = 0;
260 : 607595 : rel->serverid = InvalidOid;
261 [ + + ]: 607595 : if (rte->rtekind == RTE_RELATION)
262 : : {
263 : : Assert(parent == NULL ||
264 : : parent->rtekind == RTE_RELATION ||
265 : : parent->rtekind == RTE_SUBQUERY);
266 : :
267 : : /*
268 : : * For any RELATION rte, we need a userid with which to check
269 : : * permission access. Baserels simply use their own
270 : : * RTEPermissionInfo's checkAsUser.
271 : : *
272 : : * For otherrels normally there's no RTEPermissionInfo, so we use the
273 : : * parent's, which normally has one. The exceptional case is that the
274 : : * parent is a subquery, in which case the otherrel will have its own.
275 : : */
276 [ + + ]: 377652 : if (rel->reloptkind == RELOPT_BASEREL ||
277 [ + - ]: 36365 : (rel->reloptkind == RELOPT_OTHER_MEMBER_REL &&
278 [ + + ]: 36365 : parent->rtekind == RTE_SUBQUERY))
279 : 342258 : {
280 : : RTEPermissionInfo *perminfo;
281 : :
282 : 342258 : perminfo = getRTEPermissionInfo(root->parse->rteperminfos, rte);
283 : 342258 : rel->userid = perminfo->checkAsUser;
284 : : }
285 : : else
286 : 35394 : rel->userid = parent->userid;
287 : : }
288 : : else
289 : 229943 : rel->userid = InvalidOid;
290 : 607595 : rel->useridiscurrent = false;
291 : 607595 : rel->fdwroutine = NULL;
292 : 607595 : rel->fdw_private = NULL;
293 : 607595 : rel->unique_for_rels = NIL;
294 : 607595 : rel->non_unique_for_rels = NIL;
295 : 607595 : rel->unique_rel = NULL;
296 : 607595 : rel->unique_pathkeys = NIL;
297 : 607595 : rel->unique_groupclause = NIL;
298 : 607595 : rel->baserestrictinfo = NIL;
299 : 607595 : rel->baserestrictcost.startup = 0;
300 : 607595 : rel->baserestrictcost.per_tuple = 0;
301 : 607595 : rel->baserestrict_min_security = UINT_MAX;
302 : 607595 : rel->joininfo = NIL;
303 : 607595 : rel->has_eclass_joins = false;
304 : 607595 : rel->consider_partitionwise_join = false; /* might get changed later */
305 : 607595 : rel->agg_info = NULL;
306 : 607595 : rel->grouped_rel = NULL;
307 : 607595 : rel->part_scheme = NULL;
308 : 607595 : rel->nparts = -1;
309 : 607595 : rel->boundinfo = NULL;
310 : 607595 : rel->partbounds_merged = false;
311 : 607595 : rel->partition_qual = NIL;
312 : 607595 : rel->part_rels = NULL;
313 : 607595 : rel->live_parts = NULL;
314 : 607595 : rel->all_partrels = NULL;
315 : 607595 : rel->partexprs = NULL;
316 : 607595 : rel->nullable_partexprs = NULL;
317 : :
318 : : /*
319 : : * Pass assorted information down the inheritance hierarchy.
320 : : */
321 [ + + ]: 607595 : if (parent)
322 : : {
323 : : /* We keep back-links to immediate parent and topmost parent. */
324 : 47121 : rel->parent = parent;
325 [ + + ]: 47121 : rel->top_parent = parent->top_parent ? parent->top_parent : parent;
326 : 47121 : rel->top_parent_relids = rel->top_parent->relids;
327 : :
328 : : /*
329 : : * A child rel is below the same outer joins as its parent. (We
330 : : * presume this info was already calculated for the parent.)
331 : : */
332 : 47121 : rel->nulling_relids = parent->nulling_relids;
333 : :
334 : : /*
335 : : * Also propagate lateral-reference information from appendrel parent
336 : : * rels to their child rels. We intentionally give each child rel the
337 : : * same minimum parameterization, even though it's quite possible that
338 : : * some don't reference all the lateral rels. This is because any
339 : : * append path for the parent will have to have the same
340 : : * parameterization for every child anyway, and there's no value in
341 : : * forcing extra reparameterize_path() calls. Similarly, a lateral
342 : : * reference to the parent prevents use of otherwise-movable join rels
343 : : * for each child.
344 : : *
345 : : * It's possible for child rels to have their own children, in which
346 : : * case the topmost parent's lateral info propagates all the way down.
347 : : */
348 : 47121 : rel->direct_lateral_relids = parent->direct_lateral_relids;
349 : 47121 : rel->lateral_relids = parent->lateral_relids;
350 : 47121 : rel->lateral_referencers = parent->lateral_referencers;
351 : : }
352 : : else
353 : : {
354 : 560474 : rel->parent = NULL;
355 : 560474 : rel->top_parent = NULL;
356 : 560474 : rel->top_parent_relids = NULL;
357 : 560474 : rel->nulling_relids = NULL;
358 : 560474 : rel->direct_lateral_relids = NULL;
359 : 560474 : rel->lateral_relids = NULL;
360 : 560474 : rel->lateral_referencers = NULL;
361 : : }
362 : :
363 : : /* Check type of rtable entry */
364 [ + + + - ]: 607595 : switch (rte->rtekind)
365 : : {
366 : 377652 : case RTE_RELATION:
367 : : /* Table --- retrieve statistics from the system catalogs */
368 : 377652 : get_relation_info(root, rte->relid, rte->inh, rel);
369 : 377640 : break;
370 : 84442 : case RTE_SUBQUERY:
371 : : case RTE_FUNCTION:
372 : : case RTE_TABLEFUNC:
373 : : case RTE_VALUES:
374 : : case RTE_CTE:
375 : : case RTE_NAMEDTUPLESTORE:
376 : :
377 : : /*
378 : : * Subquery, function, tablefunc, values list, CTE, or ENR --- set
379 : : * up attr range and arrays
380 : : *
381 : : * Note: 0 is included in range to support whole-row Vars
382 : : */
383 : 84442 : rel->min_attr = 0;
384 : 84442 : rel->max_attr = list_length(rte->eref->colnames);
385 : 84442 : rel->attr_needed = (Relids *)
386 : 84442 : palloc0_array(Relids, rel->max_attr - rel->min_attr + 1);
387 : 84442 : rel->attr_widths = (int32 *)
388 : 84442 : palloc0_array(int32, rel->max_attr - rel->min_attr + 1);
389 : 84442 : break;
390 : 145501 : case RTE_RESULT:
391 : : /* RTE_RESULT has no columns, nor could it have whole-row Var */
392 : 145501 : rel->min_attr = 0;
393 : 145501 : rel->max_attr = -1;
394 : 145501 : rel->attr_needed = NULL;
395 : 145501 : rel->attr_widths = NULL;
396 : 145501 : break;
397 : 0 : default:
398 [ # # ]: 0 : elog(ERROR, "unrecognized RTE kind: %d",
399 : : (int) rte->rtekind);
400 : : break;
401 : : }
402 : :
403 : : /*
404 : : * Allow a plugin to editorialize on the new RelOptInfo. This could
405 : : * involve editorializing on the information which get_relation_info
406 : : * obtained from the catalogs, such as altering the assumed relation size,
407 : : * removing an index, or adding a hypothetical index to the indexlist.
408 : : *
409 : : * An extension can also modify rel->pgs_mask here to control path
410 : : * generation.
411 : : */
412 [ + + ]: 607583 : if (build_simple_rel_hook)
413 : 163342 : (*build_simple_rel_hook) (root, rel, rte);
414 : :
415 : : /*
416 : : * Apply the parent's quals to the child, with appropriate substitution of
417 : : * variables. If any resulting clause is reduced to constant FALSE or
418 : : * NULL, apply_child_basequals returns false to indicate that scanning
419 : : * this relation won't yield any rows. In this case, we mark the child as
420 : : * dummy right away. (We must do this immediately so that pruning works
421 : : * correctly when recursing in expand_partitioned_rtentry.)
422 : : */
423 [ + + ]: 607583 : if (parent)
424 : : {
425 : 47121 : AppendRelInfo *appinfo = root->append_rel_array[relid];
426 : :
427 : : Assert(appinfo != NULL);
428 [ + + ]: 47121 : if (!apply_child_basequals(root, parent, rel, rte, appinfo))
429 : : {
430 : : /*
431 : : * A restriction clause reduced to constant FALSE or NULL after
432 : : * substitution. Mark the child as dummy so that it need not be
433 : : * scanned.
434 : : */
435 : 78 : mark_dummy_rel(rel);
436 : : }
437 : : }
438 : :
439 : : /* Save the finished struct in the query's simple_rel_array */
440 : 607583 : root->simple_rel_array[relid] = rel;
441 : :
442 : 607583 : return rel;
443 : : }
444 : :
445 : : /*
446 : : * build_simple_grouped_rel
447 : : * Construct a new RelOptInfo representing a grouped version of the input
448 : : * simple relation.
449 : : */
450 : : RelOptInfo *
451 : 2569 : build_simple_grouped_rel(PlannerInfo *root, RelOptInfo *rel)
452 : : {
453 : : RelOptInfo *grouped_rel;
454 : : RelAggInfo *agg_info;
455 : :
456 : : /*
457 : : * We should have available aggregate expressions and grouping
458 : : * expressions, otherwise we cannot reach here.
459 : : */
460 : : Assert(root->agg_clause_list != NIL);
461 : : Assert(root->group_expr_list != NIL);
462 : :
463 : : /* nothing to do for dummy rel */
464 [ - + ]: 2569 : if (IS_DUMMY_REL(rel))
465 : 0 : return NULL;
466 : :
467 : : /*
468 : : * Prepare the information needed to create grouped paths for this simple
469 : : * relation.
470 : : */
471 : 2569 : agg_info = create_rel_agg_info(root, rel, true);
472 [ + + ]: 2569 : if (agg_info == NULL)
473 : 1883 : return NULL;
474 : :
475 : : /*
476 : : * If grouped paths for the given simple relation are not considered
477 : : * useful, skip building the grouped relation.
478 : : */
479 [ + + ]: 686 : if (!agg_info->agg_useful)
480 : 152 : return NULL;
481 : :
482 : : /* Track the set of relids at which partial aggregation is applied */
483 : 534 : agg_info->apply_agg_at = bms_copy(rel->relids);
484 : :
485 : : /* build the grouped relation */
486 : 534 : grouped_rel = build_grouped_rel(root, rel);
487 : 534 : grouped_rel->reltarget = agg_info->target;
488 : 534 : grouped_rel->rows = agg_info->grouped_rows;
489 : 534 : grouped_rel->agg_info = agg_info;
490 : :
491 : 534 : rel->grouped_rel = grouped_rel;
492 : :
493 : 534 : return grouped_rel;
494 : : }
495 : :
496 : : /*
497 : : * build_grouped_rel
498 : : * Build a grouped relation by flat copying the input relation and resetting
499 : : * the necessary fields.
500 : : */
501 : : RelOptInfo *
502 : 14738 : build_grouped_rel(PlannerInfo *root, RelOptInfo *rel)
503 : : {
504 : : RelOptInfo *grouped_rel;
505 : :
506 : 14738 : grouped_rel = makeNode(RelOptInfo);
507 : 14738 : memcpy(grouped_rel, rel, sizeof(RelOptInfo));
508 : :
509 : : /*
510 : : * clear path info
511 : : */
512 : 14738 : grouped_rel->pathlist = NIL;
513 : 14738 : grouped_rel->ppilist = NIL;
514 : 14738 : grouped_rel->partial_pathlist = NIL;
515 : 14738 : grouped_rel->cheapest_startup_path = NULL;
516 : 14738 : grouped_rel->cheapest_total_path = NULL;
517 : 14738 : grouped_rel->cheapest_parameterized_paths = NIL;
518 : :
519 : : /*
520 : : * clear partition info
521 : : */
522 : 14738 : grouped_rel->part_scheme = NULL;
523 : 14738 : grouped_rel->nparts = -1;
524 : 14738 : grouped_rel->boundinfo = NULL;
525 : 14738 : grouped_rel->partbounds_merged = false;
526 : 14738 : grouped_rel->partition_qual = NIL;
527 : 14738 : grouped_rel->part_rels = NULL;
528 : 14738 : grouped_rel->live_parts = NULL;
529 : 14738 : grouped_rel->all_partrels = NULL;
530 : 14738 : grouped_rel->partexprs = NULL;
531 : 14738 : grouped_rel->nullable_partexprs = NULL;
532 : 14738 : grouped_rel->consider_partitionwise_join = false;
533 : :
534 : : /*
535 : : * clear FDW info; FDWs don't know how to handle grouped relations
536 : : */
537 : 14738 : grouped_rel->serverid = InvalidOid;
538 : 14738 : grouped_rel->fdwroutine = NULL;
539 : 14738 : grouped_rel->fdw_private = NULL;
540 : :
541 : : /*
542 : : * clear size estimates
543 : : */
544 : 14738 : grouped_rel->rows = 0;
545 : :
546 : 14738 : return grouped_rel;
547 : : }
548 : :
549 : : /*
550 : : * find_base_rel
551 : : * Find a base or otherrel relation entry, which must already exist.
552 : : */
553 : : RelOptInfo *
554 : 5648786 : find_base_rel(PlannerInfo *root, int relid)
555 : : {
556 : : RelOptInfo *rel;
557 : :
558 : : /* use an unsigned comparison to prevent negative array element access */
559 [ + - ]: 5648786 : if ((uint32) relid < (uint32) root->simple_rel_array_size)
560 : : {
561 : 5648786 : rel = root->simple_rel_array[relid];
562 [ + - ]: 5648786 : if (rel)
563 : 5648786 : return rel;
564 : : }
565 : :
566 [ # # ]: 0 : elog(ERROR, "no relation entry for relid %d", relid);
567 : :
568 : : return NULL; /* keep compiler quiet */
569 : : }
570 : :
571 : : /*
572 : : * find_base_rel_noerr
573 : : * Find a base or otherrel relation entry, returning NULL if there's none
574 : : */
575 : : RelOptInfo *
576 : 1250636 : find_base_rel_noerr(PlannerInfo *root, int relid)
577 : : {
578 : : /* use an unsigned comparison to prevent negative array element access */
579 [ + - ]: 1250636 : if ((uint32) relid < (uint32) root->simple_rel_array_size)
580 : 1250636 : return root->simple_rel_array[relid];
581 : 0 : return NULL;
582 : : }
583 : :
584 : : /*
585 : : * find_base_rel_ignore_join
586 : : * Find a base or otherrel relation entry, which must already exist.
587 : : *
588 : : * Unlike find_base_rel, if relid references an outer join then this
589 : : * will return NULL rather than raising an error. This is convenient
590 : : * for callers that must deal with relid sets including both base and
591 : : * outer joins.
592 : : */
593 : : RelOptInfo *
594 : 164017 : find_base_rel_ignore_join(PlannerInfo *root, int relid)
595 : : {
596 : : /* use an unsigned comparison to prevent negative array element access */
597 [ + - ]: 164017 : if ((uint32) relid < (uint32) root->simple_rel_array_size)
598 : : {
599 : : RelOptInfo *rel;
600 : : RangeTblEntry *rte;
601 : :
602 : 164017 : rel = root->simple_rel_array[relid];
603 [ + + ]: 164017 : if (rel)
604 : 151357 : return rel;
605 : :
606 : : /*
607 : : * We could just return NULL here, but for debugging purposes it seems
608 : : * best to actually verify that the relid is an outer join and not
609 : : * something weird.
610 : : */
611 : 12660 : rte = root->simple_rte_array[relid];
612 [ + - + - : 12660 : if (rte && rte->rtekind == RTE_JOIN && rte->jointype != JOIN_INNER)
+ - ]
613 : 12660 : return NULL;
614 : : }
615 : :
616 [ # # ]: 0 : elog(ERROR, "no relation entry for relid %d", relid);
617 : :
618 : : return NULL; /* keep compiler quiet */
619 : : }
620 : :
621 : : /*
622 : : * build_join_rel_hash
623 : : * Construct the auxiliary hash table for join relations.
624 : : */
625 : : static void
626 : 44 : build_join_rel_hash(PlannerInfo *root)
627 : : {
628 : : HTAB *hashtab;
629 : : HASHCTL hash_ctl;
630 : : ListCell *l;
631 : :
632 : : /* Create the hash table */
633 : 44 : hash_ctl.keysize = sizeof(Relids);
634 : 44 : hash_ctl.entrysize = sizeof(JoinHashEntry);
635 : 44 : hash_ctl.hash = bitmap_hash;
636 : 44 : hash_ctl.match = bitmap_match;
637 : 44 : hash_ctl.hcxt = CurrentMemoryContext;
638 : 44 : hashtab = hash_create("JoinRelHashTable",
639 : : 256L,
640 : : &hash_ctl,
641 : : HASH_ELEM | HASH_FUNCTION | HASH_COMPARE | HASH_CONTEXT);
642 : :
643 : : /* Insert all the already-existing joinrels */
644 [ + - + + : 1496 : foreach(l, root->join_rel_list)
+ + ]
645 : : {
646 : 1452 : RelOptInfo *rel = (RelOptInfo *) lfirst(l);
647 : : JoinHashEntry *hentry;
648 : : bool found;
649 : :
650 : 1452 : hentry = (JoinHashEntry *) hash_search(hashtab,
651 : 1452 : &(rel->relids),
652 : : HASH_ENTER,
653 : : &found);
654 : : Assert(!found);
655 : 1452 : hentry->join_rel = rel;
656 : : }
657 : :
658 : 44 : root->join_rel_hash = hashtab;
659 : 44 : }
660 : :
661 : : /*
662 : : * find_join_rel
663 : : * Returns relation entry corresponding to 'relids' (a set of RT indexes),
664 : : * or NULL if none exists. This is for join relations.
665 : : */
666 : : RelOptInfo *
667 : 280617 : find_join_rel(PlannerInfo *root, Relids relids)
668 : : {
669 : : /*
670 : : * Switch to using hash lookup when list grows "too long". The threshold
671 : : * is arbitrary and is known only here.
672 : : */
673 [ + + + + ]: 280617 : if (!root->join_rel_hash && list_length(root->join_rel_list) > 32)
674 : 44 : build_join_rel_hash(root);
675 : :
676 : : /*
677 : : * Use either hashtable lookup or linear search, as appropriate.
678 : : *
679 : : * Note: the seemingly redundant hashkey variable is used to avoid taking
680 : : * the address of relids; unless the compiler is exceedingly smart, doing
681 : : * so would force relids out of a register and thus probably slow down the
682 : : * list-search case.
683 : : */
684 [ + + ]: 280617 : if (root->join_rel_hash)
685 : : {
686 : 3264 : Relids hashkey = relids;
687 : : JoinHashEntry *hentry;
688 : :
689 : 3264 : hentry = (JoinHashEntry *) hash_search(root->join_rel_hash,
690 : : &hashkey,
691 : : HASH_FIND,
692 : : NULL);
693 [ + + ]: 3264 : if (hentry)
694 : 2873 : return hentry->join_rel;
695 : : }
696 : : else
697 : : {
698 : : ListCell *l;
699 : :
700 [ + + + + : 1536537 : foreach(l, root->join_rel_list)
+ + ]
701 : : {
702 : 1356829 : RelOptInfo *rel = (RelOptInfo *) lfirst(l);
703 : :
704 [ + + ]: 1356829 : if (bms_equal(rel->relids, relids))
705 : 97645 : return rel;
706 : : }
707 : : }
708 : :
709 : 180099 : return NULL;
710 : : }
711 : :
712 : : /*
713 : : * set_foreign_rel_properties
714 : : * Set up foreign-join fields if outer and inner relation are foreign
715 : : * tables (or joins) belonging to the same server and assigned to the same
716 : : * user to check access permissions as.
717 : : *
718 : : * In addition to an exact match of userid, we allow the case where one side
719 : : * has zero userid (implying current user) and the other side has explicit
720 : : * userid that happens to equal the current user; but in that case, pushdown of
721 : : * the join is only valid for the current user. The useridiscurrent field
722 : : * records whether we had to make such an assumption for this join or any
723 : : * sub-join.
724 : : *
725 : : * Otherwise these fields are left invalid, so GetForeignJoinPaths will not be
726 : : * called for the join relation.
727 : : */
728 : : static void
729 : 198708 : set_foreign_rel_properties(RelOptInfo *joinrel, RelOptInfo *outer_rel,
730 : : RelOptInfo *inner_rel)
731 : : {
732 [ + + ]: 198708 : if (OidIsValid(outer_rel->serverid) &&
733 [ + + ]: 490 : inner_rel->serverid == outer_rel->serverid)
734 : : {
735 [ + + ]: 410 : if (inner_rel->userid == outer_rel->userid)
736 : : {
737 : 404 : joinrel->serverid = outer_rel->serverid;
738 : 404 : joinrel->userid = outer_rel->userid;
739 [ + - - + ]: 404 : joinrel->useridiscurrent = outer_rel->useridiscurrent || inner_rel->useridiscurrent;
740 : 404 : joinrel->fdwroutine = outer_rel->fdwroutine;
741 : : }
742 [ + + + + ]: 10 : else if (!OidIsValid(inner_rel->userid) &&
743 : 4 : outer_rel->userid == GetUserId())
744 : : {
745 : 2 : joinrel->serverid = outer_rel->serverid;
746 : 2 : joinrel->userid = outer_rel->userid;
747 : 2 : joinrel->useridiscurrent = true;
748 : 2 : joinrel->fdwroutine = outer_rel->fdwroutine;
749 : : }
750 [ - + - - ]: 4 : else if (!OidIsValid(outer_rel->userid) &&
751 : 0 : inner_rel->userid == GetUserId())
752 : : {
753 : 0 : joinrel->serverid = outer_rel->serverid;
754 : 0 : joinrel->userid = inner_rel->userid;
755 : 0 : joinrel->useridiscurrent = true;
756 : 0 : joinrel->fdwroutine = outer_rel->fdwroutine;
757 : : }
758 : : }
759 [ + + ]: 198298 : else if (OidIsValid(outer_rel->serverid) &&
760 [ + + ]: 80 : inner_rel->rtekind == RTE_FUNCTION)
761 : : {
762 : : /*
763 : : * One side is a foreign relation, the other side is a function RTE.
764 : : * If the function is IMMUTABLE, the FDW can absorb the function call
765 : : * into the remote query (the result is identical regardless of which
766 : : * server evaluates it). Let the FDW decide whether the join is
767 : : * actually shippable; here we just propagate the FDW routine so the
768 : : * FDW gets a chance.
769 : : */
770 : 31 : joinrel->serverid = outer_rel->serverid;
771 : 31 : joinrel->userid = outer_rel->userid;
772 : 31 : joinrel->useridiscurrent = outer_rel->useridiscurrent;
773 : 31 : joinrel->fdwroutine = outer_rel->fdwroutine;
774 : : }
775 [ + + ]: 198267 : else if (OidIsValid(inner_rel->serverid) &&
776 [ + + ]: 51 : outer_rel->rtekind == RTE_FUNCTION)
777 : : {
778 : : /* Same as just above, with the two sides swapped. */
779 : 8 : joinrel->serverid = inner_rel->serverid;
780 : 8 : joinrel->userid = inner_rel->userid;
781 : 8 : joinrel->useridiscurrent = inner_rel->useridiscurrent;
782 : 8 : joinrel->fdwroutine = inner_rel->fdwroutine;
783 : : }
784 : 198708 : }
785 : :
786 : : /*
787 : : * add_join_rel
788 : : * Add given join relation to the list of join relations in the given
789 : : * PlannerInfo. Also add it to the auxiliary hashtable if there is one.
790 : : */
791 : : static void
792 : 198708 : add_join_rel(PlannerInfo *root, RelOptInfo *joinrel)
793 : : {
794 : : /* GEQO requires us to append the new joinrel to the end of the list! */
795 : 198708 : root->join_rel_list = lappend(root->join_rel_list, joinrel);
796 : :
797 : : /* store it into the auxiliary hashtable if there is one. */
798 [ + + ]: 198708 : if (root->join_rel_hash)
799 : : {
800 : : JoinHashEntry *hentry;
801 : : bool found;
802 : :
803 : 391 : hentry = (JoinHashEntry *) hash_search(root->join_rel_hash,
804 : 391 : &(joinrel->relids),
805 : : HASH_ENTER,
806 : : &found);
807 : : Assert(!found);
808 : 391 : hentry->join_rel = joinrel;
809 : : }
810 : 198708 : }
811 : :
812 : : /*
813 : : * build_join_rel
814 : : * Returns relation entry corresponding to the union of two given rels,
815 : : * creating a new relation entry if none already exists.
816 : : *
817 : : * 'joinrelids' is the Relids set that uniquely identifies the join
818 : : * 'outer_rel' and 'inner_rel' are relation nodes for the relations to be
819 : : * joined
820 : : * 'sjinfo': join context info
821 : : * 'pushed_down_joins': any pushed-down outer joins that are now completed
822 : : * 'restrictlist_ptr': result variable. If not NULL, *restrictlist_ptr
823 : : * receives the list of RestrictInfo nodes that apply to this
824 : : * particular pair of joinable relations.
825 : : *
826 : : * restrictlist_ptr makes the routine's API a little grotty, but it saves
827 : : * duplicated calculation of the restrictlist...
828 : : */
829 : : RelOptInfo *
830 : 266970 : build_join_rel(PlannerInfo *root,
831 : : Relids joinrelids,
832 : : RelOptInfo *outer_rel,
833 : : RelOptInfo *inner_rel,
834 : : SpecialJoinInfo *sjinfo,
835 : : List *pushed_down_joins,
836 : : List **restrictlist_ptr)
837 : : {
838 : : RelOptInfo *joinrel;
839 : : List *restrictlist;
840 : :
841 : : /* This function should be used only for join between parents. */
842 : : Assert(!IS_OTHER_REL(outer_rel) && !IS_OTHER_REL(inner_rel));
843 : :
844 : : /*
845 : : * See if we already have a joinrel for this set of base rels.
846 : : */
847 : 266970 : joinrel = find_join_rel(root, joinrelids);
848 : :
849 [ + + ]: 266970 : if (joinrel)
850 : : {
851 : : /*
852 : : * Yes, so we only need to figure the restrictlist for this particular
853 : : * pair of component relations.
854 : : */
855 [ + - ]: 90097 : if (restrictlist_ptr)
856 : 90097 : *restrictlist_ptr = build_joinrel_restrictlist(root,
857 : : joinrel,
858 : : outer_rel,
859 : : inner_rel,
860 : : sjinfo);
861 : 90097 : return joinrel;
862 : : }
863 : :
864 : : /*
865 : : * Nope, so make one.
866 : : */
867 : 176873 : joinrel = makeNode(RelOptInfo);
868 : 176873 : joinrel->reloptkind = RELOPT_JOINREL;
869 : 176873 : joinrel->relids = bms_copy(joinrelids);
870 : 176873 : joinrel->rows = 0;
871 : : /* cheap startup cost is interesting iff not all tuples to be retrieved */
872 : 176873 : joinrel->consider_startup = (root->tuple_fraction > 0);
873 : 176873 : joinrel->consider_param_startup = false;
874 : 176873 : joinrel->consider_parallel = false;
875 : 176873 : joinrel->pgs_mask = root->glob->default_pgs_mask;
876 : 176873 : joinrel->reltarget = create_empty_pathtarget();
877 : 176873 : joinrel->pathlist = NIL;
878 : 176873 : joinrel->ppilist = NIL;
879 : 176873 : joinrel->partial_pathlist = NIL;
880 : 176873 : joinrel->cheapest_startup_path = NULL;
881 : 176873 : joinrel->cheapest_total_path = NULL;
882 : 176873 : joinrel->cheapest_parameterized_paths = NIL;
883 : : /* init direct_lateral_relids from children; we'll finish it up below */
884 : 176873 : joinrel->direct_lateral_relids =
885 : 176873 : bms_union(outer_rel->direct_lateral_relids,
886 : 176873 : inner_rel->direct_lateral_relids);
887 : 176873 : joinrel->lateral_relids = min_join_parameterization(root, joinrel->relids,
888 : : outer_rel, inner_rel);
889 : 176873 : joinrel->relid = 0; /* indicates not a baserel */
890 : 176873 : joinrel->rtekind = RTE_JOIN;
891 : 176873 : joinrel->min_attr = 0;
892 : 176873 : joinrel->max_attr = 0;
893 : 176873 : joinrel->attr_needed = NULL;
894 : 176873 : joinrel->attr_widths = NULL;
895 : 176873 : joinrel->notnullattnums = NULL;
896 : 176873 : joinrel->nulling_relids = NULL;
897 : 176873 : joinrel->lateral_vars = NIL;
898 : 176873 : joinrel->lateral_referencers = NULL;
899 : 176873 : joinrel->indexlist = NIL;
900 : 176873 : joinrel->statlist = NIL;
901 : 176873 : joinrel->pages = 0;
902 : 176873 : joinrel->tuples = 0;
903 : 176873 : joinrel->allvisfrac = 0;
904 : 176873 : joinrel->eclass_indexes = NULL;
905 : 176873 : joinrel->subroot = NULL;
906 : 176873 : joinrel->subplan_params = NIL;
907 : 176873 : joinrel->rel_parallel_workers = -1;
908 : 176873 : joinrel->amflags = 0;
909 : 176873 : joinrel->serverid = InvalidOid;
910 : 176873 : joinrel->userid = InvalidOid;
911 : 176873 : joinrel->useridiscurrent = false;
912 : 176873 : joinrel->fdwroutine = NULL;
913 : 176873 : joinrel->fdw_private = NULL;
914 : 176873 : joinrel->unique_for_rels = NIL;
915 : 176873 : joinrel->non_unique_for_rels = NIL;
916 : 176873 : joinrel->unique_rel = NULL;
917 : 176873 : joinrel->unique_pathkeys = NIL;
918 : 176873 : joinrel->unique_groupclause = NIL;
919 : 176873 : joinrel->baserestrictinfo = NIL;
920 : 176873 : joinrel->baserestrictcost.startup = 0;
921 : 176873 : joinrel->baserestrictcost.per_tuple = 0;
922 : 176873 : joinrel->baserestrict_min_security = UINT_MAX;
923 : 176873 : joinrel->joininfo = NIL;
924 : 176873 : joinrel->has_eclass_joins = false;
925 : 176873 : joinrel->consider_partitionwise_join = false; /* might get changed later */
926 : 176873 : joinrel->agg_info = NULL;
927 : 176873 : joinrel->grouped_rel = NULL;
928 : 176873 : joinrel->parent = NULL;
929 : 176873 : joinrel->top_parent = NULL;
930 : 176873 : joinrel->top_parent_relids = NULL;
931 : 176873 : joinrel->part_scheme = NULL;
932 : 176873 : joinrel->nparts = -1;
933 : 176873 : joinrel->boundinfo = NULL;
934 : 176873 : joinrel->partbounds_merged = false;
935 : 176873 : joinrel->partition_qual = NIL;
936 : 176873 : joinrel->part_rels = NULL;
937 : 176873 : joinrel->live_parts = NULL;
938 : 176873 : joinrel->all_partrels = NULL;
939 : 176873 : joinrel->partexprs = NULL;
940 : 176873 : joinrel->nullable_partexprs = NULL;
941 : :
942 : : /* Compute information relevant to the foreign relations. */
943 : 176873 : set_foreign_rel_properties(joinrel, outer_rel, inner_rel);
944 : :
945 : : /*
946 : : * Fill the joinrel's tlist with just the Vars and PHVs that need to be
947 : : * output from this join (ie, are needed for higher joinclauses or final
948 : : * output).
949 : : *
950 : : * NOTE: the tlist order for a join rel will depend on which pair of outer
951 : : * and inner rels we first try to build it from. But the contents should
952 : : * be the same regardless.
953 : : */
954 : 176873 : build_joinrel_tlist(root, joinrel, outer_rel, sjinfo, pushed_down_joins,
955 : 176873 : (sjinfo->jointype == JOIN_FULL));
956 : 176873 : build_joinrel_tlist(root, joinrel, inner_rel, sjinfo, pushed_down_joins,
957 : 176873 : (sjinfo->jointype != JOIN_INNER));
958 : 176873 : add_placeholders_to_joinrel(root, joinrel, outer_rel, inner_rel, sjinfo);
959 : :
960 : : /*
961 : : * add_placeholders_to_joinrel also took care of adding the ph_lateral
962 : : * sets of any PlaceHolderVars computed here to direct_lateral_relids, so
963 : : * now we can finish computing that. This is much like the computation of
964 : : * the transitively-closed lateral_relids in min_join_parameterization,
965 : : * except that here we *do* have to consider the added PHVs.
966 : : */
967 : 176873 : joinrel->direct_lateral_relids =
968 : 176873 : bms_del_members(joinrel->direct_lateral_relids, joinrel->relids);
969 : :
970 : : /*
971 : : * Construct restrict and join clause lists for the new joinrel. (The
972 : : * caller might or might not need the restrictlist, but I need it anyway
973 : : * for set_joinrel_size_estimates().)
974 : : */
975 : 176873 : restrictlist = build_joinrel_restrictlist(root, joinrel,
976 : : outer_rel, inner_rel,
977 : : sjinfo);
978 [ + - ]: 176873 : if (restrictlist_ptr)
979 : 176873 : *restrictlist_ptr = restrictlist;
980 : 176873 : build_joinrel_joinlist(joinrel, outer_rel, inner_rel);
981 : :
982 : : /*
983 : : * This is also the right place to check whether the joinrel has any
984 : : * pending EquivalenceClass joins.
985 : : */
986 : 176873 : joinrel->has_eclass_joins = has_relevant_eclass_joinclause(root, joinrel);
987 : :
988 : : /*
989 : : * Set estimates of the joinrel's size.
990 : : */
991 : 176873 : set_joinrel_size_estimates(root, joinrel, outer_rel, inner_rel,
992 : : sjinfo, restrictlist);
993 : :
994 : : /*
995 : : * Set the consider_parallel flag if this joinrel could potentially be
996 : : * scanned within a parallel worker. If this flag is false for either
997 : : * inner_rel or outer_rel, then it must be false for the joinrel also.
998 : : * Even if both are true, there might be parallel-restricted expressions
999 : : * in the targetlist or quals.
1000 : : *
1001 : : * Note that if there are more than two rels in this relation, they could
1002 : : * be divided between inner_rel and outer_rel in any arbitrary way. We
1003 : : * assume this doesn't matter, because we should hit all the same baserels
1004 : : * and joinclauses while building up to this joinrel no matter which we
1005 : : * take; therefore, we should make the same decision here however we get
1006 : : * here.
1007 : : */
1008 [ + + + + : 325171 : if (inner_rel->consider_parallel && outer_rel->consider_parallel &&
+ + ]
1009 [ + + ]: 296215 : is_parallel_safe(root, (Node *) restrictlist) &&
1010 : 147917 : is_parallel_safe(root, (Node *) joinrel->reltarget->exprs))
1011 : 147907 : joinrel->consider_parallel = true;
1012 : :
1013 : : /*
1014 : : * Allow a plugin to editorialize on the new joinrel's properties. Actions
1015 : : * might include altering the size estimate, clearing consider_parallel,
1016 : : * or adjusting pgs_mask.
1017 : : */
1018 [ + + ]: 176873 : if (joinrel_setup_hook)
1019 : 45687 : (*joinrel_setup_hook) (root, joinrel, outer_rel, inner_rel, sjinfo,
1020 : : restrictlist);
1021 : :
1022 : : /* Store the partition information. */
1023 : 176873 : build_joinrel_partition_info(root, joinrel, outer_rel, inner_rel, sjinfo,
1024 : : restrictlist);
1025 : :
1026 : : /* Add the joinrel to the PlannerInfo. */
1027 : 176873 : add_join_rel(root, joinrel);
1028 : :
1029 : : /*
1030 : : * Also, if dynamic-programming join search is active, add the new joinrel
1031 : : * to the appropriate sublist. Note: you might think the Assert on number
1032 : : * of members should be for equality, but some of the level 1 rels might
1033 : : * have been joinrels already, so we can only assert <=.
1034 : : */
1035 [ + + ]: 176873 : if (root->join_rel_level)
1036 : : {
1037 : : Assert(root->join_cur_level > 0);
1038 : : Assert(root->join_cur_level <= bms_num_members(joinrel->relids));
1039 : 169243 : root->join_rel_level[root->join_cur_level] =
1040 : 169243 : lappend(root->join_rel_level[root->join_cur_level], joinrel);
1041 : : }
1042 : :
1043 : 176873 : return joinrel;
1044 : : }
1045 : :
1046 : : /*
1047 : : * build_child_join_rel
1048 : : * Builds RelOptInfo representing join between given two child relations.
1049 : : *
1050 : : * 'outer_rel' and 'inner_rel' are the RelOptInfos of child relations being
1051 : : * joined
1052 : : * 'parent_joinrel' is the RelOptInfo representing the join between parent
1053 : : * relations. Some of the members of new RelOptInfo are produced by
1054 : : * translating corresponding members of this RelOptInfo
1055 : : * 'restrictlist': list of RestrictInfo nodes that apply to this particular
1056 : : * pair of joinable relations
1057 : : * 'sjinfo': child join's join-type details
1058 : : * 'nappinfos' and 'appinfos': AppendRelInfo array for child relids
1059 : : */
1060 : : RelOptInfo *
1061 : 21835 : build_child_join_rel(PlannerInfo *root, RelOptInfo *outer_rel,
1062 : : RelOptInfo *inner_rel, RelOptInfo *parent_joinrel,
1063 : : List *restrictlist, SpecialJoinInfo *sjinfo,
1064 : : int nappinfos, AppendRelInfo **appinfos)
1065 : : {
1066 : 21835 : RelOptInfo *joinrel = makeNode(RelOptInfo);
1067 : :
1068 : : /* Only joins between "other" relations land here. */
1069 : : Assert(IS_OTHER_REL(outer_rel) && IS_OTHER_REL(inner_rel));
1070 : :
1071 : : /* The parent joinrel should have consider_partitionwise_join set. */
1072 : : Assert(parent_joinrel->consider_partitionwise_join);
1073 : :
1074 : 21835 : joinrel->reloptkind = RELOPT_OTHER_JOINREL;
1075 : 21835 : joinrel->relids = adjust_child_relids(parent_joinrel->relids,
1076 : : nappinfos, appinfos);
1077 : 21835 : joinrel->rows = 0;
1078 : : /* cheap startup cost is interesting iff not all tuples to be retrieved */
1079 : 21835 : joinrel->consider_startup = (root->tuple_fraction > 0);
1080 : 21835 : joinrel->consider_param_startup = false;
1081 : 21835 : joinrel->consider_parallel = false;
1082 : 21835 : joinrel->pgs_mask = root->glob->default_pgs_mask;
1083 : 21835 : joinrel->reltarget = create_empty_pathtarget();
1084 : 21835 : joinrel->pathlist = NIL;
1085 : 21835 : joinrel->ppilist = NIL;
1086 : 21835 : joinrel->partial_pathlist = NIL;
1087 : 21835 : joinrel->cheapest_startup_path = NULL;
1088 : 21835 : joinrel->cheapest_total_path = NULL;
1089 : 21835 : joinrel->cheapest_parameterized_paths = NIL;
1090 : 21835 : joinrel->direct_lateral_relids = NULL;
1091 : 21835 : joinrel->lateral_relids = NULL;
1092 : 21835 : joinrel->relid = 0; /* indicates not a baserel */
1093 : 21835 : joinrel->rtekind = RTE_JOIN;
1094 : 21835 : joinrel->min_attr = 0;
1095 : 21835 : joinrel->max_attr = 0;
1096 : 21835 : joinrel->attr_needed = NULL;
1097 : 21835 : joinrel->attr_widths = NULL;
1098 : 21835 : joinrel->notnullattnums = NULL;
1099 : 21835 : joinrel->nulling_relids = NULL;
1100 : 21835 : joinrel->lateral_vars = NIL;
1101 : 21835 : joinrel->lateral_referencers = NULL;
1102 : 21835 : joinrel->indexlist = NIL;
1103 : 21835 : joinrel->pages = 0;
1104 : 21835 : joinrel->tuples = 0;
1105 : 21835 : joinrel->allvisfrac = 0;
1106 : 21835 : joinrel->eclass_indexes = NULL;
1107 : 21835 : joinrel->subroot = NULL;
1108 : 21835 : joinrel->subplan_params = NIL;
1109 : 21835 : joinrel->amflags = 0;
1110 : 21835 : joinrel->serverid = InvalidOid;
1111 : 21835 : joinrel->userid = InvalidOid;
1112 : 21835 : joinrel->useridiscurrent = false;
1113 : 21835 : joinrel->fdwroutine = NULL;
1114 : 21835 : joinrel->fdw_private = NULL;
1115 : 21835 : joinrel->unique_rel = NULL;
1116 : 21835 : joinrel->unique_pathkeys = NIL;
1117 : 21835 : joinrel->unique_groupclause = NIL;
1118 : 21835 : joinrel->baserestrictinfo = NIL;
1119 : 21835 : joinrel->baserestrictcost.startup = 0;
1120 : 21835 : joinrel->baserestrictcost.per_tuple = 0;
1121 : 21835 : joinrel->joininfo = NIL;
1122 : 21835 : joinrel->has_eclass_joins = false;
1123 : 21835 : joinrel->consider_partitionwise_join = false; /* might get changed later */
1124 : 21835 : joinrel->agg_info = NULL;
1125 : 21835 : joinrel->grouped_rel = NULL;
1126 : 21835 : joinrel->parent = parent_joinrel;
1127 [ + + ]: 21835 : joinrel->top_parent = parent_joinrel->top_parent ? parent_joinrel->top_parent : parent_joinrel;
1128 : 21835 : joinrel->top_parent_relids = joinrel->top_parent->relids;
1129 : 21835 : joinrel->part_scheme = NULL;
1130 : 21835 : joinrel->nparts = -1;
1131 : 21835 : joinrel->boundinfo = NULL;
1132 : 21835 : joinrel->partbounds_merged = false;
1133 : 21835 : joinrel->partition_qual = NIL;
1134 : 21835 : joinrel->part_rels = NULL;
1135 : 21835 : joinrel->live_parts = NULL;
1136 : 21835 : joinrel->all_partrels = NULL;
1137 : 21835 : joinrel->partexprs = NULL;
1138 : 21835 : joinrel->nullable_partexprs = NULL;
1139 : :
1140 : : /* Compute information relevant to foreign relations. */
1141 : 21835 : set_foreign_rel_properties(joinrel, outer_rel, inner_rel);
1142 : :
1143 : : /* Set up reltarget struct */
1144 : 21835 : build_child_join_reltarget(root, parent_joinrel, joinrel,
1145 : : nappinfos, appinfos);
1146 : :
1147 : : /* Construct joininfo list. */
1148 : 43670 : joinrel->joininfo = (List *) adjust_appendrel_attrs(root,
1149 : 21835 : (Node *) parent_joinrel->joininfo,
1150 : : nappinfos,
1151 : : appinfos);
1152 : :
1153 : : /*
1154 : : * Lateral relids referred in child join will be same as that referred in
1155 : : * the parent relation.
1156 : : */
1157 : 21835 : joinrel->direct_lateral_relids = (Relids) bms_copy(parent_joinrel->direct_lateral_relids);
1158 : 21835 : joinrel->lateral_relids = (Relids) bms_copy(parent_joinrel->lateral_relids);
1159 : :
1160 : : /*
1161 : : * If the parent joinrel has pending equivalence classes, so does the
1162 : : * child.
1163 : : */
1164 : 21835 : joinrel->has_eclass_joins = parent_joinrel->has_eclass_joins;
1165 : :
1166 : : /* Child joinrel is parallel safe if parent is parallel safe. */
1167 : 21835 : joinrel->consider_parallel = parent_joinrel->consider_parallel;
1168 : :
1169 : : /* Set estimates of the child-joinrel's size. */
1170 : 21835 : set_joinrel_size_estimates(root, joinrel, outer_rel, inner_rel,
1171 : : sjinfo, restrictlist);
1172 : :
1173 : : /*
1174 : : * Allow a plugin to editorialize on the new joinrel's properties. Actions
1175 : : * might include altering the size estimate, clearing consider_parallel,
1176 : : * or adjusting pgs_mask. (However, note that clearing consider_parallel
1177 : : * would be better done in the parent joinrel rather than here.)
1178 : : */
1179 [ + + ]: 21835 : if (joinrel_setup_hook)
1180 : 8762 : (*joinrel_setup_hook) (root, joinrel, outer_rel, inner_rel, sjinfo,
1181 : : restrictlist);
1182 : :
1183 : : /* Is the join between partitions itself partitioned? */
1184 : 21835 : build_joinrel_partition_info(root, joinrel, outer_rel, inner_rel, sjinfo,
1185 : : restrictlist);
1186 : :
1187 : : /* We build the join only once. */
1188 : : Assert(!find_join_rel(root, joinrel->relids));
1189 : :
1190 : : /* Add the relation to the PlannerInfo. */
1191 : 21835 : add_join_rel(root, joinrel);
1192 : :
1193 : : /*
1194 : : * We might need EquivalenceClass members corresponding to the child join,
1195 : : * so that we can represent sort pathkeys for it. As with children of
1196 : : * baserels, we shouldn't need this unless there are relevant eclass joins
1197 : : * (implying that a merge join might be possible) or pathkeys to sort by.
1198 : : */
1199 [ + + + + ]: 21835 : if (joinrel->has_eclass_joins || has_useful_pathkeys(root, parent_joinrel))
1200 : 21365 : add_child_join_rel_equivalences(root,
1201 : : nappinfos, appinfos,
1202 : : parent_joinrel, joinrel);
1203 : :
1204 : 21835 : return joinrel;
1205 : : }
1206 : :
1207 : : /*
1208 : : * min_join_parameterization
1209 : : *
1210 : : * Determine the minimum possible parameterization of a joinrel, that is, the
1211 : : * set of other rels it contains LATERAL references to. We save this value in
1212 : : * the join's RelOptInfo. This function is split out of build_join_rel()
1213 : : * because join_is_legal() needs the value to check a prospective join.
1214 : : */
1215 : : Relids
1216 : 205110 : min_join_parameterization(PlannerInfo *root,
1217 : : Relids joinrelids,
1218 : : RelOptInfo *outer_rel,
1219 : : RelOptInfo *inner_rel)
1220 : : {
1221 : : Relids result;
1222 : :
1223 : : /*
1224 : : * Basically we just need the union of the inputs' lateral_relids, less
1225 : : * whatever is already in the join.
1226 : : *
1227 : : * It's not immediately obvious that this is a valid way to compute the
1228 : : * result, because it might seem that we're ignoring possible lateral refs
1229 : : * of PlaceHolderVars that are due to be computed at the join but not in
1230 : : * either input. However, because create_lateral_join_info() already
1231 : : * charged all such PHV refs to each member baserel of the join, they'll
1232 : : * be accounted for already in the inputs' lateral_relids. Likewise, we
1233 : : * do not need to worry about doing transitive closure here, because that
1234 : : * was already accounted for in the original baserel lateral_relids.
1235 : : */
1236 : 205110 : result = bms_union(outer_rel->lateral_relids, inner_rel->lateral_relids);
1237 : 205110 : result = bms_del_members(result, joinrelids);
1238 : 205110 : return result;
1239 : : }
1240 : :
1241 : : /*
1242 : : * build_joinrel_tlist
1243 : : * Builds a join relation's target list from an input relation.
1244 : : * (This is invoked twice to handle the two input relations.)
1245 : : *
1246 : : * The join's targetlist includes all Vars of its member relations that
1247 : : * will still be needed above the join. This subroutine adds all such
1248 : : * Vars from the specified input rel's tlist to the join rel's tlist.
1249 : : * Likewise for any PlaceHolderVars emitted by the input rel.
1250 : : *
1251 : : * We also compute the expected width of the join's output, making use
1252 : : * of data that was cached at the baserel level by set_rel_width().
1253 : : *
1254 : : * Pass can_null as true if the join is an outer join that can null Vars
1255 : : * from this input relation. If so, we will (normally) add the join's relid
1256 : : * to the nulling bitmaps of Vars and PHVs bubbled up from the input.
1257 : : *
1258 : : * When forming an outer join's target list, special handling is needed in
1259 : : * case the outer join was commuted with another one per outer join identity 3
1260 : : * (see optimizer/README). We must take steps to ensure that the output Vars
1261 : : * have the same nulling bitmaps that they would if the two joins had been
1262 : : * done in syntactic order; else they won't match Vars appearing higher in
1263 : : * the query tree. An exception to the match-the-syntactic-order rule is
1264 : : * that when an outer join is pushed down into another one's RHS per identity
1265 : : * 3, we can't mark its Vars as nulled until the now-upper outer join is also
1266 : : * completed. So we need to do three things:
1267 : : *
1268 : : * First, we add the outer join's relid to the nulling bitmap only if the
1269 : : * outer join has been completely performed and the Var or PHV actually
1270 : : * comes from within the syntactically nullable side(s) of the outer join.
1271 : : * This takes care of the possibility that we have transformed
1272 : : * (A leftjoin B on (Pab)) leftjoin C on (Pbc)
1273 : : * to
1274 : : * A leftjoin (B leftjoin C on (Pbc)) on (Pab)
1275 : : * Here the pushed-down B/C join cannot mark C columns as nulled yet,
1276 : : * while the now-upper A/B join must not mark C columns as nulled by itself.
1277 : : *
1278 : : * Second, perform the same operation for each SpecialJoinInfo listed in
1279 : : * pushed_down_joins (which, in this example, would be the B/C join when
1280 : : * we are at the now-upper A/B join). This allows the now-upper join to
1281 : : * complete the marking of "C" Vars that now have fully valid values.
1282 : : *
1283 : : * Third, any relid in sjinfo->commute_above_r that is already part of
1284 : : * the joinrel is added to the nulling bitmaps of nullable Vars and PHVs.
1285 : : * This takes care of the reverse case where we implement
1286 : : * A leftjoin (B leftjoin C on (Pbc)) on (Pab)
1287 : : * as
1288 : : * (A leftjoin B on (Pab)) leftjoin C on (Pbc)
1289 : : * The C columns emitted by the B/C join need to be shown as nulled by both
1290 : : * the B/C and A/B joins, even though they've not physically traversed the
1291 : : * A/B join.
1292 : : */
1293 : : static void
1294 : 353746 : build_joinrel_tlist(PlannerInfo *root, RelOptInfo *joinrel,
1295 : : RelOptInfo *input_rel,
1296 : : SpecialJoinInfo *sjinfo,
1297 : : List *pushed_down_joins,
1298 : : bool can_null)
1299 : : {
1300 : 353746 : Relids relids = joinrel->relids;
1301 : 353746 : int64 tuple_width = joinrel->reltarget->width;
1302 : : ListCell *vars;
1303 : : ListCell *lc;
1304 : :
1305 [ + + + + : 1639161 : foreach(vars, input_rel->reltarget->exprs)
+ + ]
1306 : : {
1307 : 1285415 : Var *var = (Var *) lfirst(vars);
1308 : :
1309 : : /*
1310 : : * For a PlaceHolderVar, we have to look up the PlaceHolderInfo.
1311 : : */
1312 [ + + ]: 1285415 : if (IsA(var, PlaceHolderVar))
1313 : 2611 : {
1314 : 2611 : PlaceHolderVar *phv = (PlaceHolderVar *) var;
1315 : 2611 : PlaceHolderInfo *phinfo = find_placeholder_info(root, phv);
1316 : :
1317 : : /* Is it still needed above this joinrel? */
1318 [ + + ]: 2611 : if (bms_nonempty_difference(phinfo->ph_needed, relids))
1319 : : {
1320 : : /*
1321 : : * Yup, add it to the output. If this join potentially nulls
1322 : : * this input, we have to update the PHV's phnullingrels,
1323 : : * which means making a copy.
1324 : : */
1325 [ + + ]: 2024 : if (can_null)
1326 : : {
1327 : 1078 : phv = copyObject(phv);
1328 : : /* See comments above to understand this logic */
1329 [ + - + + ]: 2156 : if (sjinfo->ojrelid != 0 &&
1330 [ + + ]: 2136 : bms_is_member(sjinfo->ojrelid, relids) &&
1331 : 1058 : (bms_is_subset(phv->phrels, sjinfo->syn_righthand) ||
1332 [ + + + - ]: 336 : (sjinfo->jointype == JOIN_FULL &&
1333 : 163 : bms_is_subset(phv->phrels, sjinfo->syn_lefthand))))
1334 : 1048 : phv->phnullingrels = bms_add_member(phv->phnullingrels,
1335 : 1048 : sjinfo->ojrelid);
1336 [ + + + + : 1093 : foreach(lc, pushed_down_joins)
+ + ]
1337 : : {
1338 : 15 : SpecialJoinInfo *othersj = (SpecialJoinInfo *) lfirst(lc);
1339 : :
1340 : : Assert(bms_is_member(othersj->ojrelid, relids));
1341 [ + + ]: 15 : if (bms_is_subset(phv->phrels, othersj->syn_righthand))
1342 : 10 : phv->phnullingrels = bms_add_member(phv->phnullingrels,
1343 : 10 : othersj->ojrelid);
1344 : : }
1345 : 1078 : phv->phnullingrels =
1346 : 1078 : bms_join(phv->phnullingrels,
1347 : 1078 : bms_intersect(sjinfo->commute_above_r,
1348 : : relids));
1349 : : }
1350 : :
1351 : 2024 : joinrel->reltarget->exprs = lappend(joinrel->reltarget->exprs,
1352 : : phv);
1353 : : /* Bubbling up the precomputed result has cost zero */
1354 : 2024 : tuple_width += phinfo->ph_width;
1355 : : }
1356 : 2611 : continue;
1357 : : }
1358 : :
1359 : : /*
1360 : : * Otherwise, anything in a baserel or joinrel targetlist ought to be
1361 : : * a Var. (More general cases can only appear in appendrel child
1362 : : * rels, which will never be seen here.)
1363 : : */
1364 [ - + ]: 1282804 : if (!IsA(var, Var))
1365 [ # # ]: 0 : elog(ERROR, "unexpected node type in rel targetlist: %d",
1366 : : (int) nodeTag(var));
1367 : :
1368 [ + + ]: 1282804 : if (var->varno == ROWID_VAR)
1369 : : {
1370 : : /* UPDATE/DELETE/MERGE row identity vars are always needed */
1371 : : RowIdentityVarInfo *ridinfo = (RowIdentityVarInfo *)
1372 : 998 : list_nth(root->row_identity_vars, var->varattno - 1);
1373 : :
1374 : : /* Update reltarget width estimate from RowIdentityVarInfo */
1375 : 998 : tuple_width += ridinfo->rowidwidth;
1376 : : }
1377 : : else
1378 : : {
1379 : : RelOptInfo *baserel;
1380 : : int ndx;
1381 : :
1382 : : /* Get the Var's original base rel */
1383 : 1281806 : baserel = find_base_rel(root, var->varno);
1384 : :
1385 : : /* Is it still needed above this joinrel? */
1386 : 1281806 : ndx = var->varattno - baserel->min_attr;
1387 [ + + ]: 1281806 : if (!bms_nonempty_difference(baserel->attr_needed[ndx], relids))
1388 : 264222 : continue; /* nope, skip it */
1389 : :
1390 : : /* Update reltarget width estimate from baserel's attr_widths */
1391 : 1017584 : tuple_width += baserel->attr_widths[ndx];
1392 : : }
1393 : :
1394 : : /*
1395 : : * Add the Var to the output. If this join potentially nulls this
1396 : : * input, we have to update the Var's varnullingrels, which means
1397 : : * making a copy. But note that we don't ever add nullingrel bits to
1398 : : * row identity Vars (cf. comments in setrefs.c).
1399 : : */
1400 [ + + + + ]: 1018582 : if (can_null && var->varno != ROWID_VAR)
1401 : : {
1402 : 91926 : var = copyObject(var);
1403 : : /* See comments above to understand this logic */
1404 [ + + + + ]: 183352 : if (sjinfo->ojrelid != 0 &&
1405 [ + + ]: 179551 : bms_is_member(sjinfo->ojrelid, relids) &&
1406 : 88125 : (bms_is_member(var->varno, sjinfo->syn_righthand) ||
1407 [ + + + - ]: 3308 : (sjinfo->jointype == JOIN_FULL &&
1408 : 1519 : bms_is_member(var->varno, sjinfo->syn_lefthand))))
1409 : 87855 : var->varnullingrels = bms_add_member(var->varnullingrels,
1410 : 87855 : sjinfo->ojrelid);
1411 [ + + + + : 92551 : foreach(lc, pushed_down_joins)
+ + ]
1412 : : {
1413 : 625 : SpecialJoinInfo *othersj = (SpecialJoinInfo *) lfirst(lc);
1414 : :
1415 : : Assert(bms_is_member(othersj->ojrelid, relids));
1416 [ + + ]: 625 : if (bms_is_member(var->varno, othersj->syn_righthand))
1417 : 260 : var->varnullingrels = bms_add_member(var->varnullingrels,
1418 : 260 : othersj->ojrelid);
1419 : : }
1420 : 91926 : var->varnullingrels =
1421 : 91926 : bms_join(var->varnullingrels,
1422 : 91926 : bms_intersect(sjinfo->commute_above_r,
1423 : : relids));
1424 : : }
1425 : :
1426 : 1018582 : joinrel->reltarget->exprs = lappend(joinrel->reltarget->exprs,
1427 : : var);
1428 : :
1429 : : /* Vars have cost zero, so no need to adjust reltarget->cost */
1430 : : }
1431 : :
1432 : 353746 : joinrel->reltarget->width = clamp_width_est(tuple_width);
1433 : 353746 : }
1434 : :
1435 : : #ifdef USE_ASSERT_CHECKING
1436 : : /*
1437 : : * Check that a list of restriction clauses contains no two clauses with the
1438 : : * same rinfo_serial, ie, that we have not accepted more than one clone of the
1439 : : * same clause for evaluation at the same plan level.
1440 : : */
1441 : : static bool
1442 : : no_duplicate_clause_serials(List *clauses)
1443 : : {
1444 : : Bitmapset *serials = NULL;
1445 : :
1446 : : foreach_node(RestrictInfo, rinfo, clauses)
1447 : : {
1448 : : if (bms_is_member(rinfo->rinfo_serial, serials))
1449 : : return false;
1450 : : serials = bms_add_member(serials, rinfo->rinfo_serial);
1451 : : }
1452 : : return true;
1453 : : }
1454 : : #endif
1455 : :
1456 : : /*
1457 : : * build_joinrel_restrictlist
1458 : : * build_joinrel_joinlist
1459 : : * These routines build lists of restriction and join clauses for a
1460 : : * join relation from the joininfo lists of the relations it joins.
1461 : : *
1462 : : * These routines are separate because the restriction list must be
1463 : : * built afresh for each pair of input sub-relations we consider, whereas
1464 : : * the join list need only be computed once for any join RelOptInfo.
1465 : : * The join list is fully determined by the set of rels making up the
1466 : : * joinrel, so we should get the same results (up to ordering) from any
1467 : : * candidate pair of sub-relations. But the restriction list is whatever
1468 : : * is not handled in the sub-relations, so it depends on which
1469 : : * sub-relations are considered.
1470 : : *
1471 : : * If a join clause from an input relation refers to base+OJ rels still not
1472 : : * present in the joinrel, then it is still a join clause for the joinrel;
1473 : : * we put it into the joininfo list for the joinrel. Otherwise,
1474 : : * the clause is now a restrict clause for the joined relation, and we
1475 : : * return it to the caller of build_joinrel_restrictlist() to be stored in
1476 : : * join paths made from this pair of sub-relations. (It will not need to
1477 : : * be considered further up the join tree.)
1478 : : *
1479 : : * In many cases we will find the same RestrictInfos in both input
1480 : : * relations' joinlists, so be careful to eliminate duplicates.
1481 : : * Pointer equality should be a sufficient test for dups, since all
1482 : : * the various joinlist entries ultimately refer to RestrictInfos
1483 : : * pushed into them by distribute_restrictinfo_to_rels().
1484 : : *
1485 : : * 'joinrel' is a join relation node
1486 : : * 'outer_rel' and 'inner_rel' are a pair of relations that can be joined
1487 : : * to form joinrel.
1488 : : * 'sjinfo': join context info
1489 : : *
1490 : : * build_joinrel_restrictlist() returns a list of relevant restrictinfos,
1491 : : * whereas build_joinrel_joinlist() stores its results in the joinrel's
1492 : : * joininfo list. One or the other must accept each given clause!
1493 : : *
1494 : : * NB: Formerly, we made deep(!) copies of each input RestrictInfo to pass
1495 : : * up to the join relation. I believe this is no longer necessary, because
1496 : : * RestrictInfo nodes are no longer context-dependent. Instead, just include
1497 : : * the original nodes in the lists made for the join relation.
1498 : : */
1499 : : static List *
1500 : 266970 : build_joinrel_restrictlist(PlannerInfo *root,
1501 : : RelOptInfo *joinrel,
1502 : : RelOptInfo *outer_rel,
1503 : : RelOptInfo *inner_rel,
1504 : : SpecialJoinInfo *sjinfo)
1505 : : {
1506 : : List *result;
1507 : : Relids both_input_relids;
1508 : :
1509 : 266970 : both_input_relids = bms_union(outer_rel->relids, inner_rel->relids);
1510 : :
1511 : : /*
1512 : : * Collect all the clauses that syntactically belong at this level,
1513 : : * eliminating any duplicates (important since we will see many of the
1514 : : * same clauses arriving from both input relations).
1515 : : */
1516 : 266970 : result = subbuild_joinrel_restrictlist(root, joinrel, outer_rel,
1517 : : both_input_relids, NIL);
1518 : 266970 : result = subbuild_joinrel_restrictlist(root, joinrel, inner_rel,
1519 : : both_input_relids, result);
1520 : :
1521 : : /*
1522 : : * Add on any clauses derived from EquivalenceClasses. These cannot be
1523 : : * redundant with the clauses in the joininfo lists, so don't bother
1524 : : * checking.
1525 : : */
1526 : 266970 : result = list_concat(result,
1527 : 266970 : generate_join_implied_equalities(root,
1528 : : joinrel->relids,
1529 : : outer_rel->relids,
1530 : : inner_rel,
1531 : : sjinfo));
1532 : :
1533 : : /* We should not have accepted multiple clones of the same clause */
1534 : : Assert(no_duplicate_clause_serials(result));
1535 : :
1536 : 266970 : return result;
1537 : : }
1538 : :
1539 : : static void
1540 : 176873 : build_joinrel_joinlist(RelOptInfo *joinrel,
1541 : : RelOptInfo *outer_rel,
1542 : : RelOptInfo *inner_rel)
1543 : : {
1544 : : List *result;
1545 : :
1546 : : /*
1547 : : * Collect all the clauses that syntactically belong above this level,
1548 : : * eliminating any duplicates (important since we will see many of the
1549 : : * same clauses arriving from both input relations).
1550 : : */
1551 : 176873 : result = subbuild_joinrel_joinlist(joinrel, outer_rel->joininfo, NIL);
1552 : 176873 : result = subbuild_joinrel_joinlist(joinrel, inner_rel->joininfo, result);
1553 : :
1554 : 176873 : joinrel->joininfo = result;
1555 : 176873 : }
1556 : :
1557 : : static List *
1558 : 533940 : subbuild_joinrel_restrictlist(PlannerInfo *root,
1559 : : RelOptInfo *joinrel,
1560 : : RelOptInfo *input_rel,
1561 : : Relids both_input_relids,
1562 : : List *new_restrictlist)
1563 : : {
1564 : : ListCell *l;
1565 : :
1566 [ + + + + : 1007717 : foreach(l, input_rel->joininfo)
+ + ]
1567 : : {
1568 : 473777 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
1569 : :
1570 [ + + ]: 473777 : if (bms_is_subset(rinfo->required_relids, joinrel->relids))
1571 : : {
1572 : : /*
1573 : : * This clause should become a restriction clause for the joinrel,
1574 : : * since it refers to no outside rels. However, if it's a clone
1575 : : * clause then it might be too late to evaluate it, so we have to
1576 : : * check. (If it is too late, just ignore the clause, taking it
1577 : : * on faith that another clone was or will be selected.) Clone
1578 : : * clauses should always be outer-join clauses, so we compare
1579 : : * against both_input_relids.
1580 : : */
1581 [ + + + + ]: 264124 : if (rinfo->has_clone || rinfo->is_clone)
1582 : : {
1583 : : Assert(!RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids));
1584 [ + + ]: 35884 : if (!bms_is_subset(rinfo->required_relids, both_input_relids))
1585 : 6012 : continue;
1586 [ + + ]: 29872 : if (bms_overlap(rinfo->incompatible_relids, both_input_relids))
1587 : 11746 : continue;
1588 : : }
1589 : : else
1590 : : {
1591 : : /*
1592 : : * For non-clone clauses, we just Assert it's OK. These might
1593 : : * be either join or filter clauses; if it's a join clause
1594 : : * then it should not refer to the current join's output.
1595 : : * (There is little point in checking incompatible_relids,
1596 : : * because it'll be NULL.)
1597 : : */
1598 : : Assert(RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids) ||
1599 : : bms_is_subset(rinfo->required_relids,
1600 : : both_input_relids));
1601 : : }
1602 : :
1603 : : /*
1604 : : * OK, so add it to the list, being careful to eliminate
1605 : : * duplicates. (Since RestrictInfo nodes in different joinlists
1606 : : * will have been multiply-linked rather than copied, pointer
1607 : : * equality should be a sufficient test.)
1608 : : */
1609 : 246366 : new_restrictlist = list_append_unique_ptr(new_restrictlist, rinfo);
1610 : : }
1611 : : else
1612 : : {
1613 : : /*
1614 : : * This clause is still a join clause at this level, so we ignore
1615 : : * it in this routine.
1616 : : */
1617 : : }
1618 : : }
1619 : :
1620 : 533940 : return new_restrictlist;
1621 : : }
1622 : :
1623 : : static List *
1624 : 353746 : subbuild_joinrel_joinlist(RelOptInfo *joinrel,
1625 : : List *joininfo_list,
1626 : : List *new_joininfo)
1627 : : {
1628 : : ListCell *l;
1629 : :
1630 : : /* Expected to be called only for join between parent relations. */
1631 : : Assert(joinrel->reloptkind == RELOPT_JOINREL);
1632 : :
1633 [ + + + + : 669929 : foreach(l, joininfo_list)
+ + ]
1634 : : {
1635 : 316183 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
1636 : :
1637 [ + + ]: 316183 : if (bms_is_subset(rinfo->required_relids, joinrel->relids))
1638 : : {
1639 : : /*
1640 : : * This clause becomes a restriction clause for the joinrel, since
1641 : : * it refers to no outside rels. So we can ignore it in this
1642 : : * routine.
1643 : : */
1644 : : }
1645 : : else
1646 : : {
1647 : : /*
1648 : : * This clause is still a join clause at this level, so add it to
1649 : : * the new joininfo list, being careful to eliminate duplicates.
1650 : : * (Since RestrictInfo nodes in different joinlists will have been
1651 : : * multiply-linked rather than copied, pointer equality should be
1652 : : * a sufficient test.)
1653 : : */
1654 : 132689 : new_joininfo = list_append_unique_ptr(new_joininfo, rinfo);
1655 : : }
1656 : : }
1657 : :
1658 : 353746 : return new_joininfo;
1659 : : }
1660 : :
1661 : :
1662 : : /*
1663 : : * fetch_upper_rel
1664 : : * Build a RelOptInfo describing some post-scan/join query processing,
1665 : : * or return a pre-existing one if somebody already built it.
1666 : : *
1667 : : * An "upper" relation is identified by an UpperRelationKind and a Relids set.
1668 : : * The meaning of the Relids set is not specified here, and very likely will
1669 : : * vary for different relation kinds.
1670 : : *
1671 : : * Most of the fields in an upper-level RelOptInfo are not used and are not
1672 : : * set here (though makeNode should ensure they're zeroes). We basically only
1673 : : * care about fields that are of interest to add_path() and set_cheapest().
1674 : : */
1675 : : RelOptInfo *
1676 : 1350439 : fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
1677 : : {
1678 : : RelOptInfo *upperrel;
1679 : : ListCell *lc;
1680 : :
1681 : : /*
1682 : : * For the moment, our indexing data structure is just a List for each
1683 : : * relation kind. If we ever get so many of one kind that this stops
1684 : : * working well, we can improve it. No code outside this function should
1685 : : * assume anything about how to find a particular upperrel.
1686 : : */
1687 : :
1688 : : /* If we already made this upperrel for the query, return it */
1689 [ + + + + : 1359946 : foreach(lc, root->upper_rels[kind])
+ + ]
1690 : : {
1691 : 857289 : upperrel = (RelOptInfo *) lfirst(lc);
1692 : :
1693 [ + + ]: 857289 : if (bms_equal(upperrel->relids, relids))
1694 : 847782 : return upperrel;
1695 : : }
1696 : :
1697 : 502657 : upperrel = makeNode(RelOptInfo);
1698 : 502657 : upperrel->reloptkind = RELOPT_UPPER_REL;
1699 : 502657 : upperrel->relids = bms_copy(relids);
1700 : 502657 : upperrel->pgs_mask = root->glob->default_pgs_mask;
1701 : :
1702 : : /* cheap startup cost is interesting iff not all tuples to be retrieved */
1703 : 502657 : upperrel->consider_startup = (root->tuple_fraction > 0);
1704 : 502657 : upperrel->consider_param_startup = false;
1705 : 502657 : upperrel->consider_parallel = false; /* might get changed later */
1706 : 502657 : upperrel->reltarget = create_empty_pathtarget();
1707 : 502657 : upperrel->pathlist = NIL;
1708 : 502657 : upperrel->cheapest_startup_path = NULL;
1709 : 502657 : upperrel->cheapest_total_path = NULL;
1710 : 502657 : upperrel->cheapest_parameterized_paths = NIL;
1711 : :
1712 : 502657 : root->upper_rels[kind] = lappend(root->upper_rels[kind], upperrel);
1713 : :
1714 : 502657 : return upperrel;
1715 : : }
1716 : :
1717 : :
1718 : : /*
1719 : : * find_childrel_parents
1720 : : * Compute the set of parent relids of an appendrel child rel.
1721 : : *
1722 : : * Since appendrels can be nested, a child could have multiple levels of
1723 : : * appendrel ancestors. This function computes a Relids set of all the
1724 : : * parent relation IDs.
1725 : : */
1726 : : Relids
1727 : 10756 : find_childrel_parents(PlannerInfo *root, RelOptInfo *rel)
1728 : : {
1729 : 10756 : Relids result = NULL;
1730 : :
1731 : : Assert(rel->reloptkind == RELOPT_OTHER_MEMBER_REL);
1732 : : Assert(rel->relid > 0 && rel->relid < root->simple_rel_array_size);
1733 : :
1734 : : do
1735 : : {
1736 : 12738 : AppendRelInfo *appinfo = root->append_rel_array[rel->relid];
1737 : 12738 : Index prelid = appinfo->parent_relid;
1738 : :
1739 : 12738 : result = bms_add_member(result, prelid);
1740 : :
1741 : : /* traverse up to the parent rel, loop if it's also a child rel */
1742 : 12738 : rel = find_base_rel(root, prelid);
1743 [ + + ]: 12738 : } while (rel->reloptkind == RELOPT_OTHER_MEMBER_REL);
1744 : :
1745 : : Assert(rel->reloptkind == RELOPT_BASEREL);
1746 : :
1747 : 10756 : return result;
1748 : : }
1749 : :
1750 : :
1751 : : /*
1752 : : * get_baserel_parampathinfo
1753 : : * Get the ParamPathInfo for a parameterized path for a base relation,
1754 : : * constructing one if we don't have one already.
1755 : : *
1756 : : * This centralizes estimating the rowcounts for parameterized paths.
1757 : : * We need to cache those to be sure we use the same rowcount for all paths
1758 : : * of the same parameterization for a given rel. This is also a convenient
1759 : : * place to determine which movable join clauses the parameterized path will
1760 : : * be responsible for evaluating.
1761 : : */
1762 : : ParamPathInfo *
1763 : 1502980 : get_baserel_parampathinfo(PlannerInfo *root, RelOptInfo *baserel,
1764 : : Relids required_outer)
1765 : : {
1766 : : ParamPathInfo *ppi;
1767 : : Relids joinrelids;
1768 : : List *pclauses;
1769 : : List *eqclauses;
1770 : : Bitmapset *pserials;
1771 : : double rows;
1772 : : ListCell *lc;
1773 : :
1774 : : /* If rel has LATERAL refs, every path for it should account for them */
1775 : : Assert(bms_is_subset(baserel->lateral_relids, required_outer));
1776 : :
1777 : : /* Unparameterized paths have no ParamPathInfo */
1778 [ + + ]: 1502980 : if (bms_is_empty(required_outer))
1779 : 1206787 : return NULL;
1780 : :
1781 : : Assert(!bms_overlap(baserel->relids, required_outer));
1782 : :
1783 : : /* If we already have a PPI for this parameterization, just return it */
1784 [ + + ]: 296193 : if ((ppi = find_param_path_info(baserel, required_outer)))
1785 : 161341 : return ppi;
1786 : :
1787 : : /*
1788 : : * Identify all joinclauses that are movable to this base rel given this
1789 : : * parameterization.
1790 : : */
1791 : 134852 : joinrelids = bms_union(baserel->relids, required_outer);
1792 : 134852 : pclauses = NIL;
1793 : 134852 : pserials = NULL;
1794 [ + + + + : 230168 : foreach(lc, baserel->joininfo)
+ + ]
1795 : : {
1796 : 95316 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1797 : :
1798 [ + + ]: 95316 : if (!join_clause_is_movable_into(rinfo,
1799 : : baserel->relids,
1800 : : joinrelids))
1801 : 53383 : continue;
1802 : :
1803 : : /*
1804 : : * If it's a clone clause, drop variants that are incompatible with an
1805 : : * outer join already computed below the point of evaluation; some
1806 : : * other variant is the right one to apply.
1807 : : *
1808 : : * Multiple variants can survive that test under one parameterization,
1809 : : * but only when they are parse-tree identical, which happens when a
1810 : : * commuting outer join nulls no Var actually referenced by the
1811 : : * clause. (Otherwise, a variant's extra nullingrels put that outer
1812 : : * join into its clause_relids, so being movable here means the join
1813 : : * is part of the parameterization, and the lesser variant is rejected
1814 : : * above.) Identical variants still differ in required_relids and
1815 : : * incompatible_relids, and join-level clause selection needs all of
1816 : : * them: each is the sole legal choice in some join order. Here,
1817 : : * though, that distinction is not meaningful, since the same
1818 : : * ParamPathInfo serves every join order that can use the path, and an
1819 : : * identical variant is correct in any of them. So enforce just the
1820 : : * first survivor, identifying later ones by matching rinfo_serial;
1821 : : * enforcing them too would waste execution effort and apply the
1822 : : * clause's selectivity multiple times.
1823 : : */
1824 [ + + + + ]: 41933 : if (rinfo->has_clone || rinfo->is_clone)
1825 : : {
1826 [ + + ]: 2805 : if (bms_overlap(rinfo->incompatible_relids, joinrelids))
1827 : 10 : continue;
1828 [ + + ]: 2795 : if (bms_is_member(rinfo->rinfo_serial, pserials))
1829 : 20 : continue;
1830 : : }
1831 : :
1832 : 41903 : pclauses = lappend(pclauses, rinfo);
1833 : 41903 : pserials = bms_add_member(pserials, rinfo->rinfo_serial);
1834 : : }
1835 : :
1836 : : /*
1837 : : * Add in joinclauses generated by EquivalenceClasses, too, folding their
1838 : : * serial numbers into pserials. (These clauses necessarily satisfy
1839 : : * join_clause_is_movable_into; but in assert-enabled builds, let's verify
1840 : : * that.)
1841 : : */
1842 : 134852 : eqclauses = generate_join_implied_equalities(root,
1843 : : joinrelids,
1844 : : required_outer,
1845 : : baserel,
1846 : : NULL);
1847 [ + + + + : 238784 : foreach(lc, eqclauses)
+ + ]
1848 : : {
1849 : 103932 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1850 : :
1851 : : Assert(join_clause_is_movable_into(rinfo,
1852 : : baserel->relids,
1853 : : joinrelids));
1854 : 103932 : pserials = bms_add_member(pserials, rinfo->rinfo_serial);
1855 : : }
1856 : 134852 : pclauses = list_concat(pclauses, eqclauses);
1857 : :
1858 : : /* We should not have accepted multiple clones of the same clause */
1859 : : Assert(no_duplicate_clause_serials(pclauses));
1860 : :
1861 : : /* Estimate the number of rows returned by the parameterized scan */
1862 : 134852 : rows = get_parameterized_baserel_size(root, baserel, pclauses);
1863 : :
1864 : : /* And now we can build the ParamPathInfo */
1865 : 134852 : ppi = makeNode(ParamPathInfo);
1866 : 134852 : ppi->ppi_req_outer = required_outer;
1867 : 134852 : ppi->ppi_rows = rows;
1868 : 134852 : ppi->ppi_clauses = pclauses;
1869 : 134852 : ppi->ppi_serials = pserials;
1870 : 134852 : baserel->ppilist = lappend(baserel->ppilist, ppi);
1871 : :
1872 : 134852 : return ppi;
1873 : : }
1874 : :
1875 : : /*
1876 : : * get_joinrel_parampathinfo
1877 : : * Get the ParamPathInfo for a parameterized path for a join relation,
1878 : : * constructing one if we don't have one already.
1879 : : *
1880 : : * This centralizes estimating the rowcounts for parameterized paths.
1881 : : * We need to cache those to be sure we use the same rowcount for all paths
1882 : : * of the same parameterization for a given rel. This is also a convenient
1883 : : * place to determine which movable join clauses the parameterized path will
1884 : : * be responsible for evaluating.
1885 : : *
1886 : : * outer_path and inner_path are a pair of input paths that can be used to
1887 : : * construct the join, and restrict_clauses is the list of regular join
1888 : : * clauses (including clauses derived from EquivalenceClasses) that must be
1889 : : * applied at the join node when using these inputs.
1890 : : *
1891 : : * Unlike the situation for base rels, the set of movable join clauses to be
1892 : : * enforced at a join varies with the selected pair of input paths, so we
1893 : : * must calculate that and pass it back, even if we already have a matching
1894 : : * ParamPathInfo. We handle this by adding any clauses moved down to this
1895 : : * join to *restrict_clauses, which is an in/out parameter. (The addition
1896 : : * is done in such a way as to not modify the passed-in List structure.)
1897 : : *
1898 : : * Note: when considering a nestloop join, the caller must have removed from
1899 : : * restrict_clauses any movable clauses that are themselves scheduled to be
1900 : : * pushed into the right-hand path. We do not do that here since it's
1901 : : * unnecessary for other join types.
1902 : : */
1903 : : ParamPathInfo *
1904 : 1891815 : get_joinrel_parampathinfo(PlannerInfo *root, RelOptInfo *joinrel,
1905 : : Path *outer_path,
1906 : : Path *inner_path,
1907 : : SpecialJoinInfo *sjinfo,
1908 : : Relids required_outer,
1909 : : List **restrict_clauses)
1910 : : {
1911 : : ParamPathInfo *ppi;
1912 : : Relids join_and_req;
1913 : : Relids outer_and_req;
1914 : : Relids inner_and_req;
1915 : : List *pclauses;
1916 : : Bitmapset *pserials;
1917 : : List *eclauses;
1918 : : List *dropped_ecs;
1919 : : double rows;
1920 : : ListCell *lc;
1921 : :
1922 : : /* If rel has LATERAL refs, every path for it should account for them */
1923 : : Assert(bms_is_subset(joinrel->lateral_relids, required_outer));
1924 : :
1925 : : /* Unparameterized paths have no ParamPathInfo or extra join clauses */
1926 [ + + ]: 1891815 : if (bms_is_empty(required_outer))
1927 : 1857809 : return NULL;
1928 : :
1929 : : Assert(!bms_overlap(joinrel->relids, required_outer));
1930 : :
1931 : : /*
1932 : : * Identify all joinclauses that are movable to this join rel given this
1933 : : * parameterization. These are the clauses that are movable into this
1934 : : * join, but not movable into either input path. Treat an unparameterized
1935 : : * input path as not accepting parameterized clauses (because it won't,
1936 : : * per the shortcut exit above), even though the joinclause movement rules
1937 : : * might allow the same clauses to be moved into a parameterized path for
1938 : : * that rel.
1939 : : */
1940 : 34006 : join_and_req = bms_union(joinrel->relids, required_outer);
1941 [ + + ]: 34006 : if (outer_path->param_info)
1942 : 26724 : outer_and_req = bms_union(outer_path->parent->relids,
1943 [ + - ]: 26724 : PATH_REQ_OUTER(outer_path));
1944 : : else
1945 : 7282 : outer_and_req = NULL; /* outer path does not accept parameters */
1946 [ + + ]: 34006 : if (inner_path->param_info)
1947 : 20283 : inner_and_req = bms_union(inner_path->parent->relids,
1948 [ + - ]: 20283 : PATH_REQ_OUTER(inner_path));
1949 : : else
1950 : 13723 : inner_and_req = NULL; /* inner path does not accept parameters */
1951 : :
1952 : 34006 : pclauses = NIL;
1953 : 34006 : pserials = NULL;
1954 [ + + + + : 64127 : foreach(lc, joinrel->joininfo)
+ + ]
1955 : : {
1956 : 30121 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1957 : :
1958 [ + + ]: 30121 : if (!join_clause_is_movable_into(rinfo,
1959 : : joinrel->relids,
1960 [ + + ]: 14586 : join_and_req) ||
1961 : 14586 : join_clause_is_movable_into(rinfo,
1962 : 14586 : outer_path->parent->relids,
1963 [ + + ]: 859 : outer_and_req) ||
1964 : 859 : join_clause_is_movable_into(rinfo,
1965 : 859 : inner_path->parent->relids,
1966 : : inner_and_req))
1967 : 29861 : continue;
1968 : :
1969 : : /* As above, apply only one variant of a clone clause */
1970 [ + + + + ]: 260 : if (rinfo->has_clone || rinfo->is_clone)
1971 : : {
1972 [ + + ]: 188 : if (bms_overlap(rinfo->incompatible_relids, join_and_req))
1973 : 60 : continue;
1974 [ + + ]: 128 : if (bms_is_member(rinfo->rinfo_serial, pserials))
1975 : 34 : continue;
1976 : : }
1977 : :
1978 : 166 : pclauses = lappend(pclauses, rinfo);
1979 : 166 : pserials = bms_add_member(pserials, rinfo->rinfo_serial);
1980 : : }
1981 : :
1982 : : /* Consider joinclauses generated by EquivalenceClasses, too */
1983 : 34006 : eclauses = generate_join_implied_equalities(root,
1984 : : join_and_req,
1985 : : required_outer,
1986 : : joinrel,
1987 : : NULL);
1988 : : /* We only want ones that aren't movable to lower levels */
1989 : 34006 : dropped_ecs = NIL;
1990 [ + + + + : 52529 : foreach(lc, eclauses)
+ + ]
1991 : : {
1992 : 18523 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1993 : :
1994 : : Assert(join_clause_is_movable_into(rinfo,
1995 : : joinrel->relids,
1996 : : join_and_req));
1997 [ + + ]: 18523 : if (join_clause_is_movable_into(rinfo,
1998 : 18523 : outer_path->parent->relids,
1999 : : outer_and_req))
2000 : 7814 : continue; /* drop if movable into LHS */
2001 [ + + ]: 10709 : if (join_clause_is_movable_into(rinfo,
2002 : 10709 : inner_path->parent->relids,
2003 : : inner_and_req))
2004 : : {
2005 : : /* drop if movable into RHS, but remember EC for use below */
2006 : : Assert(rinfo->left_ec == rinfo->right_ec);
2007 : 8452 : dropped_ecs = lappend(dropped_ecs, rinfo->left_ec);
2008 : 8452 : continue;
2009 : : }
2010 : 2257 : pclauses = lappend(pclauses, rinfo);
2011 : : }
2012 : :
2013 : : /*
2014 : : * EquivalenceClasses are harder to deal with than we could wish, because
2015 : : * of the fact that a given EC can generate different clauses depending on
2016 : : * context. Suppose we have an EC {X.X, Y.Y, Z.Z} where X and Y are the
2017 : : * LHS and RHS of the current join and Z is in required_outer, and further
2018 : : * suppose that the inner_path is parameterized by both X and Z. The code
2019 : : * above will have produced either Z.Z = X.X or Z.Z = Y.Y from that EC,
2020 : : * and in the latter case will have discarded it as being movable into the
2021 : : * RHS. However, the EC machinery might have produced either Y.Y = X.X or
2022 : : * Y.Y = Z.Z as the EC enforcement clause within the inner_path; it will
2023 : : * not have produced both, and we can't readily tell from here which one
2024 : : * it did pick. If we add no clause to this join, we'll end up with
2025 : : * insufficient enforcement of the EC; either Z.Z or X.X will fail to be
2026 : : * constrained to be equal to the other members of the EC. (When we come
2027 : : * to join Z to this X/Y path, we will certainly drop whichever EC clause
2028 : : * is generated at that join, so this omission won't get fixed later.)
2029 : : *
2030 : : * To handle this, for each EC we discarded such a clause from, try to
2031 : : * generate a clause connecting the required_outer rels to the join's LHS
2032 : : * ("Z.Z = X.X" in the terms of the above example). If successful, and if
2033 : : * the clause can't be moved to the LHS, add it to the current join's
2034 : : * restriction clauses. (If an EC cannot generate such a clause then it
2035 : : * has nothing that needs to be enforced here, while if the clause can be
2036 : : * moved into the LHS then it should have been enforced within that path.)
2037 : : *
2038 : : * In cases where an EC needs to constrain EC members that are newly
2039 : : * computable at this join, it can emit clauses that it already returned
2040 : : * above and we accepted into pclauses. Hence, do a final list-membership
2041 : : * check before accepting more clauses. (Pointer comparison should be
2042 : : * enough to detect duplicates, since ECs cache derived clauses.)
2043 : : *
2044 : : * Note that we don't need similar processing for ECs whose clause was
2045 : : * considered to be movable into the LHS, because the LHS can't refer to
2046 : : * the RHS so there is no comparable ambiguity about what it might
2047 : : * actually be enforcing internally.
2048 : : */
2049 [ + + ]: 34006 : if (dropped_ecs)
2050 : : {
2051 : : Relids real_outer_and_req;
2052 : :
2053 : 8014 : real_outer_and_req = bms_union(outer_path->parent->relids,
2054 : : required_outer);
2055 : : eclauses =
2056 : 8014 : generate_join_implied_equalities_for_ecs(root,
2057 : : dropped_ecs,
2058 : : real_outer_and_req,
2059 : : required_outer,
2060 : : outer_path->parent);
2061 [ + + + + : 10585 : foreach(lc, eclauses)
+ + ]
2062 : : {
2063 : 2571 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
2064 : :
2065 : : Assert(join_clause_is_movable_into(rinfo,
2066 : : outer_path->parent->relids,
2067 : : real_outer_and_req));
2068 [ + + ]: 2571 : if (join_clause_is_movable_into(rinfo,
2069 : 2571 : outer_path->parent->relids,
2070 : : outer_and_req))
2071 : 2096 : continue; /* drop if movable into LHS */
2072 [ + + ]: 475 : if (list_member_ptr(pclauses, rinfo))
2073 : 10 : continue; /* drop if already accepted */
2074 : 465 : pclauses = lappend(pclauses, rinfo);
2075 : : }
2076 : : }
2077 : :
2078 : : /*
2079 : : * Now, attach the identified moved-down clauses to the caller's
2080 : : * restrict_clauses list. By using list_concat in this order, we leave
2081 : : * the original list structure of restrict_clauses undamaged.
2082 : : */
2083 : 34006 : *restrict_clauses = list_concat(pclauses, *restrict_clauses);
2084 : :
2085 : : /* We should not have accepted multiple clones of the same clause */
2086 : : Assert(no_duplicate_clause_serials(*restrict_clauses));
2087 : :
2088 : : /* If we already have a PPI for this parameterization, just return it */
2089 [ + + ]: 34006 : if ((ppi = find_param_path_info(joinrel, required_outer)))
2090 : 22587 : return ppi;
2091 : :
2092 : : /* Estimate the number of rows returned by the parameterized join */
2093 : 11419 : rows = get_parameterized_joinrel_size(root, joinrel,
2094 : : outer_path,
2095 : : inner_path,
2096 : : sjinfo,
2097 : : *restrict_clauses);
2098 : :
2099 : : /*
2100 : : * And now we can build the ParamPathInfo. No point in saving the
2101 : : * input-pair-dependent clause list, though.
2102 : : *
2103 : : * Note: in GEQO mode, we'll be called in a temporary memory context, but
2104 : : * the joinrel structure is there too, so no problem.
2105 : : */
2106 : 11419 : ppi = makeNode(ParamPathInfo);
2107 : 11419 : ppi->ppi_req_outer = required_outer;
2108 : 11419 : ppi->ppi_rows = rows;
2109 : 11419 : ppi->ppi_clauses = NIL;
2110 : 11419 : ppi->ppi_serials = NULL;
2111 : 11419 : joinrel->ppilist = lappend(joinrel->ppilist, ppi);
2112 : :
2113 : 11419 : return ppi;
2114 : : }
2115 : :
2116 : : /*
2117 : : * get_appendrel_parampathinfo
2118 : : * Get the ParamPathInfo for a parameterized path for an append relation.
2119 : : *
2120 : : * For an append relation, the rowcount estimate will just be the sum of
2121 : : * the estimates for its children. However, we still need a ParamPathInfo
2122 : : * to flag the fact that the path requires parameters. So this just creates
2123 : : * a suitable struct with zero ppi_rows (and no ppi_clauses either, since
2124 : : * the Append node isn't responsible for checking quals).
2125 : : */
2126 : : ParamPathInfo *
2127 : 45402 : get_appendrel_parampathinfo(RelOptInfo *appendrel, Relids required_outer)
2128 : : {
2129 : : ParamPathInfo *ppi;
2130 : :
2131 : : /* If rel has LATERAL refs, every path for it should account for them */
2132 : : Assert(bms_is_subset(appendrel->lateral_relids, required_outer));
2133 : :
2134 : : /* Unparameterized paths have no ParamPathInfo */
2135 [ + + ]: 45402 : if (bms_is_empty(required_outer))
2136 : 44112 : return NULL;
2137 : :
2138 : : Assert(!bms_overlap(appendrel->relids, required_outer));
2139 : :
2140 : : /* If we already have a PPI for this parameterization, just return it */
2141 [ + + ]: 1290 : if ((ppi = find_param_path_info(appendrel, required_outer)))
2142 : 931 : return ppi;
2143 : :
2144 : : /* Else build the ParamPathInfo */
2145 : 359 : ppi = makeNode(ParamPathInfo);
2146 : 359 : ppi->ppi_req_outer = required_outer;
2147 : 359 : ppi->ppi_rows = 0;
2148 : 359 : ppi->ppi_clauses = NIL;
2149 : 359 : ppi->ppi_serials = NULL;
2150 : 359 : appendrel->ppilist = lappend(appendrel->ppilist, ppi);
2151 : :
2152 : 359 : return ppi;
2153 : : }
2154 : :
2155 : : /*
2156 : : * get_wrapper_parampathinfo
2157 : : * Get the ParamPathInfo for a parameterized wrapper path.
2158 : : *
2159 : : * If a wrapper-type path, such as a MaterialPath, might be parameterized,
2160 : : * use this function to compute its param_info. This is suitable only when
2161 : : * the wrapper path cannot add or remove any parameterization from its
2162 : : * subpath, which typically means that it evaluates no quals nor tlist
2163 : : * expressions.
2164 : : */
2165 : : ParamPathInfo *
2166 : 1268578 : get_wrapper_parampathinfo(Path *subpath)
2167 : : {
2168 : : /*
2169 : : * Currently we just re-use the subpath's ParamPathInfo, if any. The
2170 : : * ppi_req_outer value is correct given the assumption stated above, and
2171 : : * none of the other fields are required to be valid for a wrapper path.
2172 : : */
2173 : 1268578 : return subpath->param_info;
2174 : : }
2175 : :
2176 : : /*
2177 : : * Returns a ParamPathInfo for the parameterization given by required_outer, if
2178 : : * already available in the given rel. Returns NULL otherwise.
2179 : : */
2180 : : ParamPathInfo *
2181 : 332483 : find_param_path_info(RelOptInfo *rel, Relids required_outer)
2182 : : {
2183 : : ListCell *lc;
2184 : :
2185 [ + + + + : 406121 : foreach(lc, rel->ppilist)
+ + ]
2186 : : {
2187 : 258617 : ParamPathInfo *ppi = (ParamPathInfo *) lfirst(lc);
2188 : :
2189 [ + + ]: 258617 : if (bms_equal(ppi->ppi_req_outer, required_outer))
2190 : 184979 : return ppi;
2191 : : }
2192 : :
2193 : 147504 : return NULL;
2194 : : }
2195 : :
2196 : : /*
2197 : : * get_param_path_clause_serials
2198 : : * Given a parameterized Path, return the set of pushed-down clauses
2199 : : * (identified by rinfo_serial numbers) enforced within the Path.
2200 : : *
2201 : : * Callers should use this in preference to fetching ppi_serials themselves.
2202 : : */
2203 : : Bitmapset *
2204 : 663127 : get_param_path_clause_serials(Path *path)
2205 : : {
2206 [ + + ]: 663127 : if (path->param_info == NULL)
2207 : 2519 : return NULL; /* not parameterized */
2208 : :
2209 [ + + - - : 660608 : switch (nodeTag(path))
+ + + + -
+ + - + ]
2210 : : {
2211 : 11216 : case T_NestPath:
2212 : : case T_MergePath:
2213 : : case T_HashPath:
2214 : : {
2215 : : /*
2216 : : * For a join path, combine clauses enforced within either
2217 : : * input path with those enforced as joinrestrictinfo in this
2218 : : * path. Note that joinrestrictinfo may include some
2219 : : * non-pushed-down clauses, but for current purposes it's okay
2220 : : * if we include those in the result. (To be more careful, we
2221 : : * could check for clause_relids overlapping the path
2222 : : * parameterization, but it's not worth the cycles for now.)
2223 : : */
2224 : 11216 : JoinPath *jpath = (JoinPath *) path;
2225 : : Bitmapset *pserials;
2226 : : ListCell *lc;
2227 : :
2228 : 11216 : pserials = NULL;
2229 : 11216 : pserials = bms_add_members(pserials,
2230 : 11216 : get_param_path_clause_serials(jpath->outerjoinpath));
2231 : 11216 : pserials = bms_add_members(pserials,
2232 : 11216 : get_param_path_clause_serials(jpath->innerjoinpath));
2233 [ + + + + : 15107 : foreach(lc, jpath->joinrestrictinfo)
+ + ]
2234 : : {
2235 : 3891 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
2236 : :
2237 : 3891 : pserials = bms_add_member(pserials, rinfo->rinfo_serial);
2238 : : }
2239 : 11216 : return pserials;
2240 : : }
2241 : 12015 : case T_AppendPath:
2242 : : {
2243 : : /*
2244 : : * For an appendrel, take the intersection of the sets of
2245 : : * clauses enforced in each input path.
2246 : : */
2247 : 12015 : AppendPath *apath = (AppendPath *) path;
2248 : : Bitmapset *pserials;
2249 : : ListCell *lc;
2250 : :
2251 : 12015 : pserials = NULL;
2252 [ + + + + : 47073 : foreach(lc, apath->subpaths)
+ + ]
2253 : : {
2254 : 35375 : Path *subpath = (Path *) lfirst(lc);
2255 : : Bitmapset *subserials;
2256 : :
2257 : 35375 : subserials = get_param_path_clause_serials(subpath);
2258 [ + + ]: 35375 : if (lc == list_head(apath->subpaths))
2259 : 11973 : pserials = bms_copy(subserials);
2260 : : else
2261 : 23402 : pserials = bms_int_members(pserials, subserials);
2262 [ + + ]: 35375 : if (bms_is_empty(pserials))
2263 : 317 : break; /* no point in continuing */
2264 : : }
2265 : 12015 : return pserials;
2266 : : }
2267 : 0 : case T_MergeAppendPath:
2268 : :
2269 : : /*
2270 : : * We don't currently support parameterized MergeAppend paths, as
2271 : : * explained in the comments for generate_orderedappend_paths.
2272 : : */
2273 : : Assert(false);
2274 : 0 : return NULL;
2275 : 0 : case T_GatherPath:
2276 : : case T_GatherMergePath:
2277 : :
2278 : : /*
2279 : : * Gather and GatherMerge paths are never parameterized, since we
2280 : : * don't generate parameterized partial paths (see
2281 : : * add_partial_path).
2282 : : */
2283 : : Assert(false);
2284 : 0 : return NULL;
2285 : :
2286 : : /*
2287 : : * A path that merely wraps another path enforces no clauses of
2288 : : * its own, so recurse through such paths. We can't just use its
2289 : : * ppi_serials, as that is the same as the subpath's, and won't be
2290 : : * valid for join or append subpaths. The set of path types
2291 : : * listed here should match the set for which pathnode.c uses
2292 : : * get_wrapper_parampathinfo().
2293 : : */
2294 : 60 : case T_MaterialPath:
2295 : 60 : return get_param_path_clause_serials(((MaterialPath *) path)->subpath);
2296 : 91347 : case T_MemoizePath:
2297 : 91347 : return get_param_path_clause_serials(((MemoizePath *) path)->subpath);
2298 : 16 : case T_ProjectionPath:
2299 : 16 : return get_param_path_clause_serials(((ProjectionPath *) path)->subpath);
2300 : 4 : case T_SortPath:
2301 : 4 : return get_param_path_clause_serials(((SortPath *) path)->subpath);
2302 : 0 : case T_IncrementalSortPath:
2303 : 0 : return get_param_path_clause_serials(((IncrementalSortPath *) path)->spath.subpath);
2304 : 4 : case T_UniquePath:
2305 : 4 : return get_param_path_clause_serials(((UniquePath *) path)->subpath);
2306 : 12 : case T_AggPath:
2307 : 12 : return get_param_path_clause_serials(((AggPath *) path)->subpath);
2308 : 0 : case T_GroupingSetsPath:
2309 : 0 : return get_param_path_clause_serials(((GroupingSetsPath *) path)->subpath);
2310 : 545934 : default:
2311 : :
2312 : : /*
2313 : : * Otherwise, it's a baserel path and we can use the
2314 : : * previously-computed set of serial numbers.
2315 : : */
2316 : 545934 : return path->param_info->ppi_serials;
2317 : : }
2318 : : }
2319 : :
2320 : : /*
2321 : : * build_joinrel_partition_info
2322 : : * Checks if the two relations being joined can use partitionwise join
2323 : : * and if yes, initialize partitioning information of the resulting
2324 : : * partitioned join relation.
2325 : : */
2326 : : static void
2327 : 198708 : build_joinrel_partition_info(PlannerInfo *root,
2328 : : RelOptInfo *joinrel, RelOptInfo *outer_rel,
2329 : : RelOptInfo *inner_rel, SpecialJoinInfo *sjinfo,
2330 : : List *restrictlist)
2331 : : {
2332 : : PartitionScheme part_scheme;
2333 : :
2334 : : /* Nothing to do if partitionwise join technique is disabled. */
2335 [ + + ]: 198708 : if ((joinrel->pgs_mask & PGS_CONSIDER_PARTITIONWISE) == 0)
2336 : : {
2337 : : Assert(!IS_PARTITIONED_REL(joinrel));
2338 : 170634 : return;
2339 : : }
2340 : :
2341 : : /*
2342 : : * We can only consider this join as an input to further partitionwise
2343 : : * joins if (a) the input relations are partitioned and have
2344 : : * consider_partitionwise_join=true, (b) the partition schemes match, and
2345 : : * (c) we can identify an equi-join between the partition keys. Note that
2346 : : * if it were possible for have_partkey_equi_join to return different
2347 : : * answers for the same joinrel depending on which join ordering we try
2348 : : * first, this logic would break. That shouldn't happen, though, because
2349 : : * of the way the query planner deduces implied equalities and reorders
2350 : : * the joins. Please see optimizer/README for details.
2351 : : */
2352 [ + + + + ]: 28074 : if (outer_rel->part_scheme == NULL || inner_rel->part_scheme == NULL ||
2353 [ + + ]: 8572 : !outer_rel->consider_partitionwise_join ||
2354 [ + + ]: 8538 : !inner_rel->consider_partitionwise_join ||
2355 [ + + ]: 8508 : outer_rel->part_scheme != inner_rel->part_scheme ||
2356 [ + + ]: 8488 : !have_partkey_equi_join(root, joinrel, outer_rel, inner_rel,
2357 : : sjinfo->jointype, restrictlist))
2358 : : {
2359 : : Assert(!IS_PARTITIONED_REL(joinrel));
2360 : 19746 : return;
2361 : : }
2362 : :
2363 : 8328 : part_scheme = outer_rel->part_scheme;
2364 : :
2365 : : /*
2366 : : * This function will be called only once for each joinrel, hence it
2367 : : * should not have partitioning fields filled yet.
2368 : : */
2369 : : Assert(!joinrel->part_scheme && !joinrel->partexprs &&
2370 : : !joinrel->nullable_partexprs && !joinrel->part_rels &&
2371 : : !joinrel->boundinfo);
2372 : :
2373 : : /*
2374 : : * If the join relation is partitioned, it uses the same partitioning
2375 : : * scheme as the joining relations.
2376 : : *
2377 : : * Note: we calculate the partition bounds, number of partitions, and
2378 : : * child-join relations of the join relation in try_partitionwise_join().
2379 : : */
2380 : 8328 : joinrel->part_scheme = part_scheme;
2381 : 8328 : set_joinrel_partition_key_exprs(joinrel, outer_rel, inner_rel,
2382 : : sjinfo->jointype);
2383 : :
2384 : : /*
2385 : : * Set the consider_partitionwise_join flag.
2386 : : */
2387 : : Assert(outer_rel->consider_partitionwise_join);
2388 : : Assert(inner_rel->consider_partitionwise_join);
2389 : 8328 : joinrel->consider_partitionwise_join = true;
2390 : : }
2391 : :
2392 : : /*
2393 : : * have_partkey_equi_join
2394 : : *
2395 : : * Returns true if there exist equi-join conditions involving pairs
2396 : : * of matching partition keys of the relations being joined for all
2397 : : * partition keys.
2398 : : */
2399 : : static bool
2400 : 8488 : have_partkey_equi_join(PlannerInfo *root, RelOptInfo *joinrel,
2401 : : RelOptInfo *rel1, RelOptInfo *rel2,
2402 : : JoinType jointype, List *restrictlist)
2403 : : {
2404 : 8488 : PartitionScheme part_scheme = rel1->part_scheme;
2405 : : bool pk_known_equal[PARTITION_MAX_KEYS];
2406 : : int num_equal_pks;
2407 : : ListCell *lc;
2408 : :
2409 : : /*
2410 : : * This function must only be called when the joined relations have same
2411 : : * partitioning scheme.
2412 : : */
2413 : : Assert(rel1->part_scheme == rel2->part_scheme);
2414 : : Assert(part_scheme);
2415 : :
2416 : : /* We use a bool array to track which partkey columns are known equal */
2417 : 8488 : memset(pk_known_equal, 0, sizeof(pk_known_equal));
2418 : : /* ... as well as a count of how many are known equal */
2419 : 8488 : num_equal_pks = 0;
2420 : :
2421 : : /* First, look through the join's restriction clauses */
2422 [ + + + + : 9543 : foreach(lc, restrictlist)
+ + ]
2423 : : {
2424 : 9348 : RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
2425 : : OpExpr *opexpr;
2426 : : Expr *expr1;
2427 : : Expr *expr2;
2428 : : bool strict_op;
2429 : : int ipk1;
2430 : : int ipk2;
2431 : :
2432 : : /* If processing an outer join, only use its own join clauses. */
2433 [ + + ]: 9348 : if (IS_OUTER_JOIN(jointype) &&
2434 [ + + - + ]: 1409 : RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
2435 : 205 : continue;
2436 : :
2437 : : /* Skip clauses which can not be used for a join. */
2438 [ + + ]: 9143 : if (!rinfo->can_join)
2439 : 15 : continue;
2440 : :
2441 : : /* Skip clauses which are not equality conditions. */
2442 [ + + + - ]: 9128 : if (!rinfo->mergeopfamilies && !OidIsValid(rinfo->hashjoinoperator))
2443 : 25 : continue;
2444 : :
2445 : : /* Should be OK to assume it's an OpExpr. */
2446 : 9103 : opexpr = castNode(OpExpr, rinfo->clause);
2447 : :
2448 : : /* Match the operands to the relation. */
2449 [ + + + - ]: 14891 : if (bms_is_subset(rinfo->left_relids, rel1->relids) &&
2450 : 5788 : bms_is_subset(rinfo->right_relids, rel2->relids))
2451 : : {
2452 : 5788 : expr1 = linitial(opexpr->args);
2453 : 5788 : expr2 = lsecond(opexpr->args);
2454 : : }
2455 [ + - + - ]: 6630 : else if (bms_is_subset(rinfo->left_relids, rel2->relids) &&
2456 : 3315 : bms_is_subset(rinfo->right_relids, rel1->relids))
2457 : : {
2458 : 3315 : expr1 = lsecond(opexpr->args);
2459 : 3315 : expr2 = linitial(opexpr->args);
2460 : : }
2461 : : else
2462 : 0 : continue;
2463 : :
2464 : : /*
2465 : : * Now we need to know whether the join operator is strict; see
2466 : : * comments in pathnodes.h.
2467 : : */
2468 : 9103 : strict_op = op_strict(opexpr->opno);
2469 : :
2470 : : /*
2471 : : * Vars appearing in the relation's partition keys will not have any
2472 : : * varnullingrels, but those in expr1 and expr2 will if we're above
2473 : : * outer joins that could null the respective rels. It's okay to
2474 : : * match anyway, if the join operator is strict.
2475 : : */
2476 [ + - ]: 9103 : if (strict_op)
2477 : : {
2478 [ + + ]: 9103 : if (bms_overlap(rel1->relids, root->outer_join_rels))
2479 : 170 : expr1 = (Expr *) remove_nulling_relids((Node *) expr1,
2480 : 170 : root->outer_join_rels,
2481 : : NULL);
2482 [ - + ]: 9103 : if (bms_overlap(rel2->relids, root->outer_join_rels))
2483 : 0 : expr2 = (Expr *) remove_nulling_relids((Node *) expr2,
2484 : 0 : root->outer_join_rels,
2485 : : NULL);
2486 : : }
2487 : :
2488 : : /*
2489 : : * Only clauses referencing the partition keys are useful for
2490 : : * partitionwise join.
2491 : : */
2492 : 9103 : ipk1 = match_expr_to_partition_keys(expr1, rel1, strict_op);
2493 [ + + ]: 9103 : if (ipk1 < 0)
2494 : 750 : continue;
2495 : 8353 : ipk2 = match_expr_to_partition_keys(expr2, rel2, strict_op);
2496 [ + + ]: 8353 : if (ipk2 < 0)
2497 : 40 : continue;
2498 : :
2499 : : /*
2500 : : * If the clause refers to keys at different ordinal positions, it can
2501 : : * not be used for partitionwise join.
2502 : : */
2503 [ + + ]: 8313 : if (ipk1 != ipk2)
2504 : 5 : continue;
2505 : :
2506 : : /* Ignore clause if we already proved these keys equal. */
2507 [ - + ]: 8308 : if (pk_known_equal[ipk1])
2508 : 0 : continue;
2509 : :
2510 : : /* Reject if the partition key collation differs from the clause's. */
2511 [ + + ]: 8308 : if (rel1->part_scheme->partcollation[ipk1] != opexpr->inputcollid)
2512 : 8293 : return false;
2513 : :
2514 : : /*
2515 : : * The clause allows partitionwise join only if it uses the same
2516 : : * operator family as that specified by the partition key.
2517 : : */
2518 [ + + ]: 8298 : if (part_scheme->strategy == PARTITION_STRATEGY_HASH)
2519 : : {
2520 [ + - ]: 60 : if (!OidIsValid(rinfo->hashjoinoperator) ||
2521 [ - + ]: 60 : !op_in_opfamily(rinfo->hashjoinoperator,
2522 : 60 : part_scheme->partopfamily[ipk1]))
2523 : 0 : continue;
2524 : : }
2525 [ - + ]: 8238 : else if (!list_member_oid(rinfo->mergeopfamilies,
2526 : 8238 : part_scheme->partopfamily[ipk1]))
2527 : 0 : continue;
2528 : :
2529 : : /* Mark the partition key as having an equi-join clause. */
2530 : 8298 : pk_known_equal[ipk1] = true;
2531 : :
2532 : : /* We can stop examining clauses once we prove all keys equal. */
2533 [ + + ]: 8298 : if (++num_equal_pks == part_scheme->partnatts)
2534 : 8283 : return true;
2535 : : }
2536 : :
2537 : : /*
2538 : : * Also check to see if any keys are known equal by equivclass.c. In most
2539 : : * cases there would have been a join restriction clause generated from
2540 : : * any EC that had such knowledge, but there might be no such clause, or
2541 : : * it might happen to constrain other members of the ECs than the ones we
2542 : : * are looking for.
2543 : : */
2544 [ + - ]: 200 : for (int ipk = 0; ipk < part_scheme->partnatts; ipk++)
2545 : : {
2546 : : Oid btree_opfamily;
2547 : :
2548 : : /* Ignore if we already proved these keys equal. */
2549 [ + + ]: 200 : if (pk_known_equal[ipk])
2550 : 5 : continue;
2551 : :
2552 : : /*
2553 : : * We need a btree opfamily to ask equivclass.c about. If the
2554 : : * partopfamily is a hash opfamily, look up its equality operator, and
2555 : : * select some btree opfamily that that operator is part of. (Any
2556 : : * such opfamily should be good enough, since equivclass.c will track
2557 : : * multiple opfamilies as appropriate.)
2558 : : */
2559 [ - + ]: 195 : if (part_scheme->strategy == PARTITION_STRATEGY_HASH)
2560 : : {
2561 : : Oid eq_op;
2562 : : List *eq_opfamilies;
2563 : :
2564 : 0 : eq_op = get_opfamily_member(part_scheme->partopfamily[ipk],
2565 : 0 : part_scheme->partopcintype[ipk],
2566 : 0 : part_scheme->partopcintype[ipk],
2567 : : HTEqualStrategyNumber);
2568 [ # # ]: 0 : if (!OidIsValid(eq_op))
2569 : 0 : break; /* we're not going to succeed */
2570 : 0 : eq_opfamilies = get_mergejoin_opfamilies(eq_op);
2571 [ # # ]: 0 : if (eq_opfamilies == NIL)
2572 : 0 : break; /* we're not going to succeed */
2573 : 0 : btree_opfamily = linitial_oid(eq_opfamilies);
2574 : : }
2575 : : else
2576 : 195 : btree_opfamily = part_scheme->partopfamily[ipk];
2577 : :
2578 : : /*
2579 : : * We consider only non-nullable partition keys here; nullable ones
2580 : : * would not be treated as part of the same equivalence classes as
2581 : : * non-nullable ones.
2582 : : */
2583 [ + - + + : 345 : foreach(lc, rel1->partexprs[ipk])
+ + ]
2584 : : {
2585 : 195 : Node *expr1 = (Node *) lfirst(lc);
2586 : : ListCell *lc2;
2587 : 195 : Oid partcoll1 = rel1->part_scheme->partcollation[ipk];
2588 : 195 : Oid exprcoll1 = exprCollation(expr1);
2589 : :
2590 [ + - + + : 355 : foreach(lc2, rel2->partexprs[ipk])
+ + ]
2591 : : {
2592 : 205 : Node *expr2 = (Node *) lfirst(lc2);
2593 : :
2594 [ + + ]: 205 : if (exprs_known_equal(root, expr1, expr2, btree_opfamily))
2595 : : {
2596 : : /*
2597 : : * Ensure that the collation of the expression matches
2598 : : * that of the partition key. Checking just one collation
2599 : : * (partcoll1 and exprcoll1) suffices because partcoll1
2600 : : * and partcoll2, as well as exprcoll1 and exprcoll2,
2601 : : * should be identical. This holds because both rel1 and
2602 : : * rel2 use the same PartitionScheme and expr1 and expr2
2603 : : * are equal.
2604 : : */
2605 [ + + ]: 55 : if (partcoll1 == exprcoll1)
2606 : : {
2607 : 45 : Oid partcoll2 PG_USED_FOR_ASSERTS_ONLY =
2608 : 45 : rel2->part_scheme->partcollation[ipk];
2609 : : Oid exprcoll2 PG_USED_FOR_ASSERTS_ONLY =
2610 : 45 : exprCollation(expr2);
2611 : :
2612 : : Assert(partcoll2 == exprcoll2);
2613 : 45 : pk_known_equal[ipk] = true;
2614 : 45 : break;
2615 : : }
2616 : : }
2617 : : }
2618 [ + + ]: 195 : if (pk_known_equal[ipk])
2619 : 45 : break;
2620 : : }
2621 : :
2622 [ + + ]: 195 : if (pk_known_equal[ipk])
2623 : : {
2624 : : /* We can stop examining keys once we prove all keys equal. */
2625 [ + - ]: 45 : if (++num_equal_pks == part_scheme->partnatts)
2626 : 45 : return true;
2627 : : }
2628 : : else
2629 : 150 : break; /* no chance to succeed, give up */
2630 : : }
2631 : :
2632 : 150 : return false;
2633 : : }
2634 : :
2635 : : /*
2636 : : * match_expr_to_partition_keys
2637 : : *
2638 : : * Tries to match an expression to one of the nullable or non-nullable
2639 : : * partition keys of "rel". Returns the matched key's ordinal position,
2640 : : * or -1 if the expression could not be matched to any of the keys.
2641 : : *
2642 : : * strict_op must be true if the expression will be compared with the
2643 : : * partition key using a strict operator. This allows us to consider
2644 : : * nullable as well as nonnullable partition keys.
2645 : : */
2646 : : static int
2647 : 17456 : match_expr_to_partition_keys(Expr *expr, RelOptInfo *rel, bool strict_op)
2648 : : {
2649 : : int cnt;
2650 : :
2651 : : /* This function should be called only for partitioned relations. */
2652 : : Assert(rel->part_scheme);
2653 : : Assert(rel->partexprs);
2654 : : Assert(rel->nullable_partexprs);
2655 : :
2656 : : /* Remove any relabel decorations. */
2657 [ + + ]: 17696 : while (IsA(expr, RelabelType))
2658 : 240 : expr = (Expr *) (castNode(RelabelType, expr))->arg;
2659 : :
2660 [ + + ]: 18276 : for (cnt = 0; cnt < rel->part_scheme->partnatts; cnt++)
2661 : : {
2662 : : ListCell *lc;
2663 : :
2664 : : /* We can always match to the non-nullable partition keys. */
2665 [ + + + + : 18746 : foreach(lc, rel->partexprs[cnt])
+ + ]
2666 : : {
2667 [ + + ]: 17856 : if (equal(lfirst(lc), expr))
2668 : 16596 : return cnt;
2669 : : }
2670 : :
2671 [ - + ]: 890 : if (!strict_op)
2672 : 0 : continue;
2673 : :
2674 : : /*
2675 : : * If it's a strict join operator then a NULL partition key on one
2676 : : * side will not join to any partition key on the other side, and in
2677 : : * particular such a row can't join to a row from a different
2678 : : * partition on the other side. So, it's okay to search the nullable
2679 : : * partition keys as well.
2680 : : */
2681 [ + + + + : 1020 : foreach(lc, rel->nullable_partexprs[cnt])
+ + ]
2682 : : {
2683 [ + + ]: 200 : if (equal(lfirst(lc), expr))
2684 : 70 : return cnt;
2685 : : }
2686 : : }
2687 : :
2688 : 790 : return -1;
2689 : : }
2690 : :
2691 : : /*
2692 : : * set_joinrel_partition_key_exprs
2693 : : * Initialize partition key expressions for a partitioned joinrel.
2694 : : */
2695 : : static void
2696 : 8328 : set_joinrel_partition_key_exprs(RelOptInfo *joinrel,
2697 : : RelOptInfo *outer_rel, RelOptInfo *inner_rel,
2698 : : JoinType jointype)
2699 : : {
2700 : 8328 : PartitionScheme part_scheme = joinrel->part_scheme;
2701 : 8328 : int partnatts = part_scheme->partnatts;
2702 : :
2703 : 8328 : joinrel->partexprs = palloc0_array(List *, partnatts);
2704 : 8328 : joinrel->nullable_partexprs = palloc0_array(List *, partnatts);
2705 : :
2706 : : /*
2707 : : * The joinrel's partition expressions are the same as those of the input
2708 : : * rels, but we must properly classify them as nullable or not in the
2709 : : * joinrel's output. (Also, we add some more partition expressions if
2710 : : * it's a FULL JOIN.)
2711 : : */
2712 [ + + ]: 16666 : for (int cnt = 0; cnt < partnatts; cnt++)
2713 : : {
2714 : : /* mark these const to enforce that we copy them properly */
2715 : 8338 : const List *outer_expr = outer_rel->partexprs[cnt];
2716 : 8338 : const List *outer_null_expr = outer_rel->nullable_partexprs[cnt];
2717 : 8338 : const List *inner_expr = inner_rel->partexprs[cnt];
2718 : 8338 : const List *inner_null_expr = inner_rel->nullable_partexprs[cnt];
2719 : 8338 : List *partexpr = NIL;
2720 : 8338 : List *nullable_partexpr = NIL;
2721 : : ListCell *lc;
2722 : :
2723 [ + + + + : 8338 : switch (jointype)
- ]
2724 : : {
2725 : : /*
2726 : : * A join relation resulting from an INNER join may be
2727 : : * regarded as partitioned by either of the inner and outer
2728 : : * relation keys. For example, A INNER JOIN B ON A.a = B.b
2729 : : * can be regarded as partitioned on either A.a or B.b. So we
2730 : : * add both keys to the joinrel's partexpr lists. However,
2731 : : * anything that was already nullable still has to be treated
2732 : : * as nullable.
2733 : : */
2734 : 7349 : case JOIN_INNER:
2735 : 7349 : partexpr = list_concat_copy(outer_expr, inner_expr);
2736 : 7349 : nullable_partexpr = list_concat_copy(outer_null_expr,
2737 : : inner_null_expr);
2738 : 7349 : break;
2739 : :
2740 : : /*
2741 : : * A join relation resulting from a SEMI or ANTI join may be
2742 : : * regarded as partitioned by the outer relation keys. The
2743 : : * inner relation's keys are no longer interesting; since they
2744 : : * aren't visible in the join output, nothing could join to
2745 : : * them.
2746 : : */
2747 : 260 : case JOIN_SEMI:
2748 : : case JOIN_ANTI:
2749 : 260 : partexpr = list_copy(outer_expr);
2750 : 260 : nullable_partexpr = list_copy(outer_null_expr);
2751 : 260 : break;
2752 : :
2753 : : /*
2754 : : * A join relation resulting from a LEFT OUTER JOIN likewise
2755 : : * may be regarded as partitioned on the (non-nullable) outer
2756 : : * relation keys. The inner (nullable) relation keys are okay
2757 : : * as partition keys for further joins as long as they involve
2758 : : * strict join operators.
2759 : : */
2760 : 492 : case JOIN_LEFT:
2761 : 492 : partexpr = list_copy(outer_expr);
2762 : 492 : nullable_partexpr = list_concat_copy(inner_expr,
2763 : : outer_null_expr);
2764 : 492 : nullable_partexpr = list_concat(nullable_partexpr,
2765 : : inner_null_expr);
2766 : 492 : break;
2767 : :
2768 : : /*
2769 : : * For FULL OUTER JOINs, both relations are nullable, so the
2770 : : * resulting join relation may be regarded as partitioned on
2771 : : * either of inner and outer relation keys, but only for joins
2772 : : * that involve strict join operators.
2773 : : */
2774 : 237 : case JOIN_FULL:
2775 : 237 : nullable_partexpr = list_concat_copy(outer_expr,
2776 : : inner_expr);
2777 : 237 : nullable_partexpr = list_concat(nullable_partexpr,
2778 : : outer_null_expr);
2779 : 237 : nullable_partexpr = list_concat(nullable_partexpr,
2780 : : inner_null_expr);
2781 : :
2782 : : /*
2783 : : * Also add CoalesceExprs corresponding to each possible
2784 : : * full-join output variable (that is, left side coalesced to
2785 : : * right side), so that we can match equijoin expressions
2786 : : * using those variables. We really only need these for
2787 : : * columns merged by JOIN USING, and only with the pairs of
2788 : : * input items that correspond to the data structures that
2789 : : * parse analysis would build for such variables. But it's
2790 : : * hard to tell which those are, so just make all the pairs.
2791 : : * Extra items in the nullable_partexprs list won't cause big
2792 : : * problems. (It's possible that such items will get matched
2793 : : * to user-written COALESCEs, but it should still be valid to
2794 : : * partition on those, since they're going to be either the
2795 : : * partition column or NULL; it's the same argument as for
2796 : : * partitionwise nesting of any outer join.) We assume no
2797 : : * type coercions are needed to make the coalesce expressions,
2798 : : * since columns of different types won't have gotten
2799 : : * classified as the same PartitionScheme. Note that we
2800 : : * intentionally leave out the varnullingrels decoration that
2801 : : * would ordinarily appear on the Vars inside these
2802 : : * CoalesceExprs, because have_partkey_equi_join will strip
2803 : : * varnullingrels from the expressions it will compare to the
2804 : : * partexprs.
2805 : : */
2806 [ + - + + : 604 : foreach(lc, list_concat_copy(outer_expr, outer_null_expr))
+ + ]
2807 : : {
2808 : 367 : Node *larg = (Node *) lfirst(lc);
2809 : : ListCell *lc2;
2810 : :
2811 [ + - + + : 734 : foreach(lc2, list_concat_copy(inner_expr, inner_null_expr))
+ + ]
2812 : : {
2813 : 367 : Node *rarg = (Node *) lfirst(lc2);
2814 : 367 : CoalesceExpr *c = makeNode(CoalesceExpr);
2815 : :
2816 : 367 : c->coalescetype = exprType(larg);
2817 : 367 : c->coalescecollid = exprCollation(larg);
2818 : 367 : c->args = list_make2(larg, rarg);
2819 : 367 : c->location = -1;
2820 : 367 : nullable_partexpr = lappend(nullable_partexpr, c);
2821 : : }
2822 : : }
2823 : 237 : break;
2824 : :
2825 : 0 : default:
2826 [ # # ]: 0 : elog(ERROR, "unrecognized join type: %d", (int) jointype);
2827 : : }
2828 : :
2829 : 8338 : joinrel->partexprs[cnt] = partexpr;
2830 : 8338 : joinrel->nullable_partexprs[cnt] = nullable_partexpr;
2831 : : }
2832 : 8328 : }
2833 : :
2834 : : /*
2835 : : * build_child_join_reltarget
2836 : : * Set up a child-join relation's reltarget from a parent-join relation.
2837 : : */
2838 : : static void
2839 : 21835 : build_child_join_reltarget(PlannerInfo *root,
2840 : : RelOptInfo *parentrel,
2841 : : RelOptInfo *childrel,
2842 : : int nappinfos,
2843 : : AppendRelInfo **appinfos)
2844 : : {
2845 : : /* Build the targetlist */
2846 : 43670 : childrel->reltarget->exprs = (List *)
2847 : 21835 : adjust_appendrel_attrs(root,
2848 : 21835 : (Node *) parentrel->reltarget->exprs,
2849 : : nappinfos, appinfos);
2850 : :
2851 : : /* Set the cost and width fields */
2852 : 21835 : childrel->reltarget->cost.startup = parentrel->reltarget->cost.startup;
2853 : 21835 : childrel->reltarget->cost.per_tuple = parentrel->reltarget->cost.per_tuple;
2854 : 21835 : childrel->reltarget->width = parentrel->reltarget->width;
2855 : 21835 : }
2856 : :
2857 : : /*
2858 : : * create_rel_agg_info
2859 : : * Create the RelAggInfo structure for the given relation if it can produce
2860 : : * grouped paths. The given relation is the non-grouped one which has the
2861 : : * reltarget already constructed.
2862 : : *
2863 : : * calculate_grouped_rows: if true, calculate the estimated number of grouped
2864 : : * rows for the relation. If false, skip the estimation to avoid unnecessary
2865 : : * planning overhead.
2866 : : */
2867 : : RelAggInfo *
2868 : 17691 : create_rel_agg_info(PlannerInfo *root, RelOptInfo *rel,
2869 : : bool calculate_grouped_rows)
2870 : : {
2871 : : ListCell *lc;
2872 : : RelAggInfo *result;
2873 : : PathTarget *agg_input;
2874 : : PathTarget *target;
2875 : 17691 : List *group_clauses = NIL;
2876 : 17691 : List *group_exprs = NIL;
2877 : :
2878 : : /*
2879 : : * The lists of aggregate expressions and grouping expressions should have
2880 : : * been constructed.
2881 : : */
2882 : : Assert(root->agg_clause_list != NIL);
2883 : : Assert(root->group_expr_list != NIL);
2884 : :
2885 : : /*
2886 : : * If this is a child rel, the grouped rel for its parent rel must have
2887 : : * been created if it can. So we can just use parent's RelAggInfo if
2888 : : * there is one, with appropriate variable substitutions.
2889 : : */
2890 [ + + + + : 17691 : if (IS_OTHER_REL(rel))
- + ]
2891 : : {
2892 : : RelOptInfo *grouped_rel;
2893 : : RelAggInfo *agg_info;
2894 : :
2895 : 12660 : grouped_rel = rel->top_parent->grouped_rel;
2896 [ + + ]: 12660 : if (grouped_rel == NULL)
2897 : 1480 : return NULL;
2898 : :
2899 : : Assert(IS_GROUPED_REL(grouped_rel));
2900 : :
2901 : : /* Must do multi-level transformation */
2902 : : agg_info = (RelAggInfo *)
2903 : 11180 : adjust_appendrel_attrs_multilevel(root,
2904 : 11180 : (Node *) grouped_rel->agg_info,
2905 : : rel,
2906 : 11180 : rel->top_parent);
2907 : :
2908 : 11180 : agg_info->apply_agg_at = NULL; /* caller will change this later */
2909 : :
2910 [ + + ]: 11180 : if (calculate_grouped_rows)
2911 : : {
2912 : 790 : agg_info->grouped_rows =
2913 : 790 : estimate_num_groups(root, agg_info->group_exprs,
2914 : : rel->rows, NULL, NULL);
2915 : :
2916 : : /*
2917 : : * The grouped paths for the given relation are considered useful
2918 : : * iff the average group size is no less than
2919 : : * min_eager_agg_group_size.
2920 : : */
2921 : 790 : agg_info->agg_useful =
2922 : 790 : (rel->rows / agg_info->grouped_rows) >= min_eager_agg_group_size;
2923 : : }
2924 : :
2925 : 11180 : return agg_info;
2926 : : }
2927 : :
2928 : : /* Check if it's possible to produce grouped paths for this relation. */
2929 [ + + ]: 5031 : if (!eager_aggregation_possible_for_relation(root, rel))
2930 : 973 : return NULL;
2931 : :
2932 : : /*
2933 : : * Create targets for the grouped paths and for the input paths of the
2934 : : * grouped paths.
2935 : : */
2936 : 4058 : target = create_empty_pathtarget();
2937 : 4058 : agg_input = create_empty_pathtarget();
2938 : :
2939 : : /* ... and initialize these targets */
2940 [ + + ]: 4058 : if (!init_grouping_targets(root, rel, target, agg_input,
2941 : : &group_clauses, &group_exprs))
2942 : 145 : return NULL;
2943 : :
2944 : : /*
2945 : : * Eager aggregation is not applicable if there are no available grouping
2946 : : * expressions.
2947 : : */
2948 [ + + ]: 3913 : if (group_clauses == NIL)
2949 : 15 : return NULL;
2950 : :
2951 : : /* Add aggregates to the grouping target */
2952 [ + - + + : 10026 : foreach(lc, root->agg_clause_list)
+ + ]
2953 : : {
2954 : 6128 : AggClauseInfo *ac_info = lfirst_node(AggClauseInfo, lc);
2955 : : Aggref *aggref;
2956 : :
2957 : : Assert(IsA(ac_info->aggref, Aggref));
2958 : :
2959 : 6128 : aggref = (Aggref *) copyObject(ac_info->aggref);
2960 : 6128 : mark_partial_aggref(aggref, AGGSPLIT_INITIAL_SERIAL);
2961 : :
2962 : 6128 : add_column_to_pathtarget(target, (Expr *) aggref, 0);
2963 : : }
2964 : :
2965 : : /* Set the estimated eval cost and output width for both targets */
2966 : 3898 : set_pathtarget_cost_width(root, target);
2967 : 3898 : set_pathtarget_cost_width(root, agg_input);
2968 : :
2969 : : /* build the RelAggInfo result */
2970 : 3898 : result = makeNode(RelAggInfo);
2971 : 3898 : result->target = target;
2972 : 3898 : result->agg_input = agg_input;
2973 : 3898 : result->group_clauses = group_clauses;
2974 : 3898 : result->group_exprs = group_exprs;
2975 : 3898 : result->apply_agg_at = NULL; /* caller will change this later */
2976 : :
2977 [ + + ]: 3898 : if (calculate_grouped_rows)
2978 : : {
2979 : 694 : result->grouped_rows = estimate_num_groups(root, result->group_exprs,
2980 : : rel->rows, NULL, NULL);
2981 : :
2982 : : /*
2983 : : * The grouped paths for the given relation are considered useful iff
2984 : : * the average group size is no less than min_eager_agg_group_size.
2985 : : */
2986 : 694 : result->agg_useful =
2987 : 694 : (rel->rows / result->grouped_rows) >= min_eager_agg_group_size;
2988 : : }
2989 : :
2990 : 3898 : return result;
2991 : : }
2992 : :
2993 : : /*
2994 : : * eager_aggregation_possible_for_relation
2995 : : * Check if it's possible to produce grouped paths for the given relation.
2996 : : */
2997 : : static bool
2998 : 5031 : eager_aggregation_possible_for_relation(PlannerInfo *root, RelOptInfo *rel)
2999 : : {
3000 : : ListCell *lc;
3001 : : int cur_relid;
3002 : :
3003 : : /*
3004 : : * Check to see if the given relation is in the nullable side of an outer
3005 : : * join. In this case, we cannot push a partial aggregation down to the
3006 : : * relation, because the NULL-extended rows produced by the outer join
3007 : : * would not be available when we perform the partial aggregation, while
3008 : : * with a non-eager-aggregation plan these rows are available for the
3009 : : * top-level aggregation. Doing so may result in the rows being grouped
3010 : : * differently than expected, or produce incorrect values from the
3011 : : * aggregate functions.
3012 : : */
3013 : 5031 : cur_relid = -1;
3014 [ + + ]: 14304 : while ((cur_relid = bms_next_member(rel->relids, cur_relid)) >= 0)
3015 : : {
3016 : 9471 : RelOptInfo *baserel = find_base_rel_ignore_join(root, cur_relid);
3017 : :
3018 [ + + ]: 9471 : if (baserel == NULL)
3019 : 378 : continue; /* ignore outer joins in rel->relids */
3020 : :
3021 [ + + ]: 9093 : if (!bms_is_subset(baserel->nulling_relids, rel->relids))
3022 : 198 : return false;
3023 : : }
3024 : :
3025 : : /*
3026 : : * Similarly, we cannot push a partial aggregation down to a relation on
3027 : : * the inner (RHS) side of a semi/anti join. A semi/anti join does not
3028 : : * preserve its inner rows in the join output, so a partial aggregate
3029 : : * computed on the inner side would not survive the join and could not be
3030 : : * combined by the final aggregation.
3031 : : *
3032 : : * Note that the inner side of an anti join already carries nulling_relids
3033 : : * and so is handled by the outer-join check above. The case this check
3034 : : * adds is a semi join, which has no relid.
3035 : : */
3036 [ + + + + : 5549 : foreach(lc, root->join_info_list)
+ + ]
3037 : : {
3038 : 731 : SpecialJoinInfo *sjinfo = lfirst_node(SpecialJoinInfo, lc);
3039 : :
3040 [ + + + + ]: 731 : if (sjinfo->jointype != JOIN_SEMI && sjinfo->jointype != JOIN_ANTI)
3041 : 666 : continue;
3042 : :
3043 : : /* rel includes inner-side rels of this join but not its outer side */
3044 [ + + ]: 65 : if (bms_overlap(rel->relids, sjinfo->min_righthand) &&
3045 [ + + ]: 40 : !bms_is_subset(sjinfo->min_lefthand, rel->relids))
3046 : 15 : return false;
3047 : : }
3048 : :
3049 : : /*
3050 : : * We cannot push a partial aggregation down below a join clause that
3051 : : * contains volatile functions, because the clause would then be evaluated
3052 : : * once per group rather than once per input row.
3053 : : */
3054 [ + + + + : 5176 : foreach(lc, rel->joininfo)
+ + ]
3055 : : {
3056 : 368 : RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
3057 : :
3058 [ + + ]: 368 : if (contain_volatile_functions((Node *) rinfo))
3059 : 10 : return false;
3060 : : }
3061 : :
3062 : : /*
3063 : : * For now we don't try to support PlaceHolderVars.
3064 : : */
3065 [ + - + + : 14833 : foreach(lc, rel->reltarget->exprs)
+ + ]
3066 : : {
3067 : 10040 : Expr *expr = lfirst(lc);
3068 : :
3069 [ + + ]: 10040 : if (IsA(expr, PlaceHolderVar))
3070 : 15 : return false;
3071 : : }
3072 : :
3073 : : /* Caller should only pass base relations or joins. */
3074 : : Assert(rel->reloptkind == RELOPT_BASEREL ||
3075 : : rel->reloptkind == RELOPT_JOINREL);
3076 : :
3077 : : /*
3078 : : * Check if all aggregate expressions can be evaluated on this relation
3079 : : * level.
3080 : : */
3081 [ + - + + : 11126 : foreach(lc, root->agg_clause_list)
+ + ]
3082 : : {
3083 : 7068 : AggClauseInfo *ac_info = lfirst_node(AggClauseInfo, lc);
3084 : :
3085 : : Assert(IsA(ac_info->aggref, Aggref));
3086 : :
3087 : : /*
3088 : : * Give up if any aggregate requires relations other than the current
3089 : : * one. If the aggregate requires the current relation plus
3090 : : * additional relations, grouping the current relation could make some
3091 : : * input rows unavailable for the higher aggregate and may reduce the
3092 : : * number of input rows it receives. If the aggregate does not
3093 : : * require the current relation at all, it should not be grouped, as
3094 : : * we do not support joining two grouped relations.
3095 : : */
3096 [ + + ]: 7068 : if (!bms_is_subset(ac_info->agg_eval_at, rel->relids))
3097 : 735 : return false;
3098 : : }
3099 : :
3100 : 4058 : return true;
3101 : : }
3102 : :
3103 : : /*
3104 : : * init_grouping_targets
3105 : : * Initialize the target for grouped paths (target) as well as the target
3106 : : * for paths that generate input for the grouped paths (agg_input).
3107 : : *
3108 : : * We also construct the list of SortGroupClauses and the list of grouping
3109 : : * expressions for the partial aggregation, and return them in *group_clause
3110 : : * and *group_exprs.
3111 : : *
3112 : : * Return true if the targets could be initialized, false otherwise.
3113 : : */
3114 : : static bool
3115 : 4058 : init_grouping_targets(PlannerInfo *root, RelOptInfo *rel,
3116 : : PathTarget *target, PathTarget *agg_input,
3117 : : List **group_clauses, List **group_exprs)
3118 : : {
3119 : : ListCell *lc;
3120 : 4058 : List *possibly_dependent = NIL;
3121 : : Index maxSortGroupRef;
3122 : :
3123 : : /* Identify the max sortgroupref */
3124 : 4058 : maxSortGroupRef = 0;
3125 [ + - + + : 18935 : foreach(lc, root->processed_tlist)
+ + ]
3126 : : {
3127 : 14877 : Index ref = ((TargetEntry *) lfirst(lc))->ressortgroupref;
3128 : :
3129 [ + + ]: 14877 : if (ref > maxSortGroupRef)
3130 : 4430 : maxSortGroupRef = ref;
3131 : : }
3132 : :
3133 : : /*
3134 : : * At this point, all Vars from this relation that are needed by upper
3135 : : * joins or are required in the final targetlist should already be present
3136 : : * in its reltarget. Therefore, we can safely iterate over this
3137 : : * relation's reltarget->exprs to construct the PathTarget and grouping
3138 : : * clauses for the grouped paths.
3139 : : */
3140 [ + - + + : 12505 : foreach(lc, rel->reltarget->exprs)
+ + ]
3141 : : {
3142 : 8472 : Expr *expr = (Expr *) lfirst(lc);
3143 : : Index sortgroupref;
3144 : :
3145 : : /*
3146 : : * Given that PlaceHolderVar currently prevents us from doing eager
3147 : : * aggregation, the source target cannot contain anything more complex
3148 : : * than a Var.
3149 : : */
3150 : : Assert(IsA(expr, Var));
3151 : :
3152 : : /*
3153 : : * Get the sortgroupref of the expr if it is found among, or can be
3154 : : * deduced from, the original grouping expressions.
3155 : : */
3156 : 8472 : sortgroupref = get_expression_sortgroupref(root, expr);
3157 [ + + ]: 8472 : if (sortgroupref > 0)
3158 : : {
3159 : : SortGroupClause *sgc;
3160 : :
3161 : : /* Find the matching SortGroupClause */
3162 : 3887 : sgc = get_sortgroupref_clause(sortgroupref, root->processed_groupClause);
3163 : : Assert(sgc->tleSortGroupRef <= maxSortGroupRef);
3164 : :
3165 : : /*
3166 : : * If the target expression is to be used as a grouping key, it
3167 : : * should be emitted by the grouped paths that have been pushed
3168 : : * down to this relation level.
3169 : : */
3170 : 3887 : add_column_to_pathtarget(target, expr, sortgroupref);
3171 : :
3172 : : /*
3173 : : * ... and it also should be emitted by the input paths.
3174 : : */
3175 : 3887 : add_column_to_pathtarget(agg_input, expr, sortgroupref);
3176 : :
3177 : : /*
3178 : : * Record this SortGroupClause and grouping expression. Note that
3179 : : * this SortGroupClause might have already been recorded.
3180 : : */
3181 [ + + ]: 3887 : if (!list_member(*group_clauses, sgc))
3182 : : {
3183 : 3857 : *group_clauses = lappend(*group_clauses, sgc);
3184 : 3857 : *group_exprs = lappend(*group_exprs, expr);
3185 : : }
3186 : : }
3187 [ + + ]: 4585 : else if (is_var_needed_by_join(root, (Var *) expr, rel))
3188 : : {
3189 : : /*
3190 : : * The expression is needed for an upper join but is neither in
3191 : : * the GROUP BY clause nor derivable from it using EC (otherwise,
3192 : : * it would have already been included in the targets above). We
3193 : : * need to create a special SortGroupClause for this expression.
3194 : : *
3195 : : * It is important to include such expressions in the grouping
3196 : : * keys. This is essential to ensure that an aggregated row from
3197 : : * the partial aggregation matches the other side of the join if
3198 : : * and only if each row in the partial group does. This ensures
3199 : : * that all rows within the same partial group share the same
3200 : : * 'destiny', which is crucial for maintaining correctness.
3201 : : */
3202 : : SortGroupClause *sgc;
3203 : : TypeCacheEntry *tce;
3204 : : Oid equalimageproc;
3205 : :
3206 : : /*
3207 : : * But first, check if equality implies image equality for this
3208 : : * expression. If not, we cannot use it as a grouping key. See
3209 : : * comments in create_grouping_expr_infos().
3210 : : */
3211 : 374 : tce = lookup_type_cache(exprType((Node *) expr),
3212 : : TYPECACHE_BTREE_OPFAMILY);
3213 [ + - ]: 374 : if (!OidIsValid(tce->btree_opf) ||
3214 [ - + ]: 374 : !OidIsValid(tce->btree_opintype))
3215 : 25 : return false;
3216 : :
3217 : 374 : equalimageproc = get_opfamily_proc(tce->btree_opf,
3218 : : tce->btree_opintype,
3219 : : tce->btree_opintype,
3220 : : BTEQUALIMAGE_PROC);
3221 : :
3222 : : /*
3223 : : * If there is no BTEQUALIMAGE_PROC, eager aggregation is assumed
3224 : : * to be unsafe. Otherwise, we call the procedure to check. We
3225 : : * must be careful to pass the expression's actual collation,
3226 : : * rather than the data type's default collation, to ensure that
3227 : : * non-deterministic collations are correctly handled.
3228 : : */
3229 [ + + ]: 374 : if (!OidIsValid(equalimageproc) ||
3230 [ + + ]: 369 : !DatumGetBool(OidFunctionCall1Coll(equalimageproc,
3231 : : exprCollation((Node *) expr),
3232 : : ObjectIdGetDatum(tce->btree_opintype))))
3233 : 25 : return false;
3234 : :
3235 : : /* Create the SortGroupClause. */
3236 : 349 : sgc = makeNode(SortGroupClause);
3237 : :
3238 : : /* Initialize the SortGroupClause. */
3239 : 349 : sgc->tleSortGroupRef = ++maxSortGroupRef;
3240 : 349 : get_sort_group_operators(exprType((Node *) expr),
3241 : : false, true, false,
3242 : : &sgc->sortop, &sgc->eqop, NULL,
3243 : : &sgc->hashable);
3244 : :
3245 : : /* This expression should be emitted by the grouped paths */
3246 : 349 : add_column_to_pathtarget(target, expr, sgc->tleSortGroupRef);
3247 : :
3248 : : /* ... and it also should be emitted by the input paths. */
3249 : 349 : add_column_to_pathtarget(agg_input, expr, sgc->tleSortGroupRef);
3250 : :
3251 : : /* Record this SortGroupClause and grouping expression */
3252 : 349 : *group_clauses = lappend(*group_clauses, sgc);
3253 : 349 : *group_exprs = lappend(*group_exprs, expr);
3254 : : }
3255 [ + + ]: 4211 : else if (is_var_in_aggref_only(root, (Var *) expr))
3256 : : {
3257 : : /*
3258 : : * The expression is referenced by an aggregate function pushed
3259 : : * down to this relation and does not appear elsewhere in the
3260 : : * targetlist or havingQual. Add it to 'agg_input' but not to
3261 : : * 'target'.
3262 : : */
3263 : 3931 : add_new_column_to_pathtarget(agg_input, expr);
3264 : : }
3265 : : else
3266 : : {
3267 : : /*
3268 : : * The expression may be functionally dependent on other
3269 : : * expressions in the target, but we cannot verify this until all
3270 : : * target expressions have been constructed.
3271 : : */
3272 : 280 : possibly_dependent = lappend(possibly_dependent, expr);
3273 : : }
3274 : : }
3275 : :
3276 : : /*
3277 : : * Now we can verify whether an expression is functionally dependent on
3278 : : * others.
3279 : : */
3280 [ + + + + : 4073 : foreach(lc, possibly_dependent)
+ + ]
3281 : : {
3282 : : Var *tvar;
3283 : 160 : List *deps = NIL;
3284 : : RangeTblEntry *rte;
3285 : :
3286 : 160 : tvar = lfirst_node(Var, lc);
3287 : 160 : rte = root->simple_rte_array[tvar->varno];
3288 : :
3289 [ + + ]: 160 : if (check_functional_grouping(rte->relid, tvar->varno,
3290 : : tvar->varlevelsup,
3291 : : target->exprs, &deps))
3292 : : {
3293 : : /*
3294 : : * The expression is functionally dependent on other target
3295 : : * expressions, so it can be included in the targets. Since it
3296 : : * will not be used as a grouping key, a sortgroupref is not
3297 : : * needed for it.
3298 : : */
3299 : 40 : add_new_column_to_pathtarget(target, (Expr *) tvar);
3300 : 40 : add_new_column_to_pathtarget(agg_input, (Expr *) tvar);
3301 : : }
3302 : : else
3303 : : {
3304 : : /*
3305 : : * We may arrive here with a grouping expression that is proven
3306 : : * redundant by EquivalenceClass processing, such as 't1.a' in the
3307 : : * query below.
3308 : : *
3309 : : * select max(t1.c) from t t1, t t2 where t1.a = 1 group by t1.a,
3310 : : * t1.b;
3311 : : *
3312 : : * For now we just give up in this case.
3313 : : */
3314 : 120 : return false;
3315 : : }
3316 : : }
3317 : :
3318 : 3913 : return true;
3319 : : }
3320 : :
3321 : : /*
3322 : : * is_var_in_aggref_only
3323 : : * Check whether the given Var appears in aggregate expressions and not
3324 : : * elsewhere in the targetlist or havingQual.
3325 : : */
3326 : : static bool
3327 : 4211 : is_var_in_aggref_only(PlannerInfo *root, Var *var)
3328 : : {
3329 : : ListCell *lc;
3330 : :
3331 : : /*
3332 : : * Search the list of aggregate expressions for the Var.
3333 : : */
3334 [ + - + + : 4611 : foreach(lc, root->agg_clause_list)
+ + ]
3335 : : {
3336 : 4331 : AggClauseInfo *ac_info = lfirst_node(AggClauseInfo, lc);
3337 : : List *vars;
3338 : :
3339 : : Assert(IsA(ac_info->aggref, Aggref));
3340 : :
3341 [ + + ]: 4331 : if (!bms_is_member(var->varno, ac_info->agg_eval_at))
3342 : 400 : continue;
3343 : :
3344 : 3931 : vars = pull_var_clause((Node *) ac_info->aggref,
3345 : : PVC_RECURSE_AGGREGATES |
3346 : : PVC_RECURSE_WINDOWFUNCS |
3347 : : PVC_RECURSE_PLACEHOLDERS);
3348 : :
3349 [ + - ]: 3931 : if (list_member(vars, var))
3350 : : {
3351 : 3931 : list_free(vars);
3352 : 3931 : break;
3353 : : }
3354 : :
3355 : 0 : list_free(vars);
3356 : : }
3357 : :
3358 [ + + + - ]: 4211 : return (lc != NULL && !list_member(root->tlist_vars, var));
3359 : : }
3360 : :
3361 : : /*
3362 : : * is_var_needed_by_join
3363 : : * Check if the given Var is needed by joins above the current rel.
3364 : : */
3365 : : static bool
3366 : 4585 : is_var_needed_by_join(PlannerInfo *root, Var *var, RelOptInfo *rel)
3367 : : {
3368 : : Relids relids;
3369 : : int attno;
3370 : : RelOptInfo *baserel;
3371 : :
3372 : : /*
3373 : : * Note that when checking if the Var is needed by joins above, we want to
3374 : : * exclude cases where the Var is only needed in the final targetlist. So
3375 : : * include "relation 0" in the check.
3376 : : */
3377 : 4585 : relids = bms_copy(rel->relids);
3378 : 4585 : relids = bms_add_member(relids, 0);
3379 : :
3380 : 4585 : baserel = find_base_rel(root, var->varno);
3381 : 4585 : attno = var->varattno - baserel->min_attr;
3382 : :
3383 : 4585 : return bms_nonempty_difference(baserel->attr_needed[attno], relids);
3384 : : }
3385 : :
3386 : : /*
3387 : : * get_expression_sortgroupref
3388 : : * Return the sortgroupref of the given "expr" if it is found among the
3389 : : * original grouping expressions, or is known equal to any of the original
3390 : : * grouping expressions due to equivalence relationships. Return 0 if no
3391 : : * match is found.
3392 : : */
3393 : : static Index
3394 : 8472 : get_expression_sortgroupref(PlannerInfo *root, Expr *expr)
3395 : : {
3396 : : ListCell *lc;
3397 : :
3398 : : Assert(IsA(expr, Var));
3399 : :
3400 [ + - + + : 13213 : foreach(lc, root->group_expr_list)
+ + ]
3401 : : {
3402 : 8628 : GroupingExprInfo *ge_info = lfirst_node(GroupingExprInfo, lc);
3403 : : ListCell *lc1;
3404 : :
3405 : : Assert(IsA(ge_info->expr, Var));
3406 : : Assert(ge_info->sortgroupref > 0);
3407 : :
3408 [ + + ]: 8628 : if (equal(expr, ge_info->expr))
3409 : 3887 : return ge_info->sortgroupref;
3410 : :
3411 [ + - ]: 4858 : if (ge_info->ec == NULL ||
3412 [ + + ]: 4858 : !bms_is_member(((Var *) expr)->varno, ge_info->ec->ec_relids))
3413 : 2295 : continue;
3414 : :
3415 : : /* The grouping operators can't be applied to a cross-type member */
3416 [ + + ]: 2563 : if (exprType((Node *) expr) != exprType((Node *) ge_info->expr))
3417 : 147 : continue;
3418 : :
3419 : : /*
3420 : : * Scan the EquivalenceClass, looking for a match to the given
3421 : : * expression. We ignore child members here.
3422 : : */
3423 [ + - + + : 7156 : foreach(lc1, ge_info->ec->ec_members)
+ + ]
3424 : : {
3425 : 4857 : EquivalenceMember *em = (EquivalenceMember *) lfirst(lc1);
3426 : :
3427 : : /* Child members should not exist in ec_members */
3428 : : Assert(!em->em_is_child);
3429 : :
3430 [ + + ]: 4857 : if (equal(expr, em->em_expr))
3431 : 117 : return ge_info->sortgroupref;
3432 : : }
3433 : : }
3434 : :
3435 : : /* no match is found */
3436 : 4585 : return 0;
3437 : : }
|