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