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