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