Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * initsplan.c
4 : : * Target list, group by, qualification, joininfo initialization 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/plan/initsplan.c
12 : : *
13 : : *-------------------------------------------------------------------------
14 : : */
15 : : #include "postgres.h"
16 : :
17 : : #include "access/nbtree.h"
18 : : #include "access/sysattr.h"
19 : : #include "catalog/pg_constraint.h"
20 : : #include "catalog/pg_type.h"
21 : : #include "nodes/makefuncs.h"
22 : : #include "nodes/nodeFuncs.h"
23 : : #include "optimizer/clauses.h"
24 : : #include "optimizer/cost.h"
25 : : #include "optimizer/inherit.h"
26 : : #include "optimizer/joininfo.h"
27 : : #include "optimizer/optimizer.h"
28 : : #include "optimizer/pathnode.h"
29 : : #include "optimizer/paths.h"
30 : : #include "optimizer/placeholder.h"
31 : : #include "optimizer/planmain.h"
32 : : #include "optimizer/restrictinfo.h"
33 : : #include "parser/analyze.h"
34 : : #include "rewrite/rewriteManip.h"
35 : : #include "utils/lsyscache.h"
36 : : #include "utils/rel.h"
37 : : #include "utils/typcache.h"
38 : :
39 : : /* These parameters are set by GUC */
40 : : int from_collapse_limit;
41 : : int join_collapse_limit;
42 : :
43 : :
44 : : /*
45 : : * deconstruct_jointree requires multiple passes over the join tree, because we
46 : : * need to finish computing JoinDomains before we start distributing quals.
47 : : * As long as we have to do that, other information such as the relevant
48 : : * qualscopes might as well be computed in the first pass too.
49 : : *
50 : : * deconstruct_recurse recursively examines the join tree and builds a List
51 : : * (in depth-first traversal order) of JoinTreeItem structs, which are then
52 : : * processed iteratively by deconstruct_distribute. If there are outer
53 : : * joins, non-degenerate outer join clauses are processed in a third pass
54 : : * deconstruct_distribute_oj_quals.
55 : : *
56 : : * The JoinTreeItem structs themselves can be freed at the end of
57 : : * deconstruct_jointree, but do not modify or free their substructure,
58 : : * as the relid sets may also be pointed to by RestrictInfo and
59 : : * SpecialJoinInfo nodes.
60 : : */
61 : : typedef struct JoinTreeItem
62 : : {
63 : : /* Fields filled during deconstruct_recurse: */
64 : : Node *jtnode; /* jointree node to examine */
65 : : JoinDomain *jdomain; /* join domain for its ON/WHERE clauses */
66 : : struct JoinTreeItem *jti_parent; /* JoinTreeItem for this node's
67 : : * parent, or NULL if it's the top */
68 : : Relids qualscope; /* base+OJ Relids syntactically included in
69 : : * this jointree node */
70 : : Relids inner_join_rels; /* base+OJ Relids syntactically included
71 : : * in inner joins appearing at or below
72 : : * this jointree node */
73 : : Relids left_rels; /* if join node, Relids of the left side */
74 : : Relids right_rels; /* if join node, Relids of the right side */
75 : : Relids nonnullable_rels; /* if outer join, Relids of the
76 : : * non-nullable side */
77 : : /* Fields filled during deconstruct_distribute: */
78 : : SpecialJoinInfo *sjinfo; /* if outer join, its SpecialJoinInfo */
79 : : List *oj_joinclauses; /* outer join quals not yet distributed */
80 : : List *lateral_clauses; /* quals postponed from children due to
81 : : * lateral references */
82 : : } JoinTreeItem;
83 : :
84 : : /*
85 : : * Compatibility info for one GROUP BY item, precomputed for use by
86 : : * remove_useless_groupby_columns() when matching unique-index columns against
87 : : * GROUP BY items.
88 : : */
89 : : typedef struct GroupByColInfo
90 : : {
91 : : AttrNumber attno; /* var->varattno */
92 : : List *eq_opfamilies; /* mergejoin opfamilies of sgc->eqop */
93 : : Oid coll; /* var->varcollid */
94 : : } GroupByColInfo;
95 : :
96 : :
97 : : static bool is_partial_agg_memory_risky(PlannerInfo *root);
98 : : static void create_agg_clause_infos(PlannerInfo *root);
99 : : static void create_grouping_expr_infos(PlannerInfo *root);
100 : : static EquivalenceClass *get_eclass_for_sortgroupclause(PlannerInfo *root,
101 : : SortGroupClause *sgc,
102 : : Expr *expr);
103 : : static void extract_lateral_references(PlannerInfo *root, RelOptInfo *brel,
104 : : Index rtindex);
105 : : static List *deconstruct_recurse(PlannerInfo *root, Node *jtnode,
106 : : JoinDomain *parent_domain,
107 : : JoinTreeItem *parent_jtitem,
108 : : List **item_list);
109 : : static void deconstruct_distribute(PlannerInfo *root, JoinTreeItem *jtitem);
110 : : static void process_security_barrier_quals(PlannerInfo *root,
111 : : int rti, JoinTreeItem *jtitem);
112 : : static void mark_rels_nulled_by_join(PlannerInfo *root, Index ojrelid,
113 : : Relids lower_rels);
114 : : static SpecialJoinInfo *make_outerjoininfo(PlannerInfo *root,
115 : : Relids left_rels, Relids right_rels,
116 : : Relids inner_join_rels,
117 : : JoinType jointype, Index ojrelid,
118 : : List *clause);
119 : : static void compute_semijoin_info(PlannerInfo *root, SpecialJoinInfo *sjinfo,
120 : : List *clause);
121 : : static void deconstruct_distribute_oj_quals(PlannerInfo *root,
122 : : List *jtitems,
123 : : JoinTreeItem *jtitem);
124 : : static void distribute_quals_to_rels(PlannerInfo *root, List *clauses,
125 : : JoinTreeItem *jtitem,
126 : : SpecialJoinInfo *sjinfo,
127 : : Index security_level,
128 : : Relids qualscope,
129 : : Relids ojscope,
130 : : Relids outerjoin_nonnullable,
131 : : Relids incompatible_relids,
132 : : bool allow_equivalence,
133 : : bool has_clone,
134 : : bool is_clone,
135 : : List **postponed_oj_qual_list);
136 : : static void distribute_qual_to_rels(PlannerInfo *root, Node *clause,
137 : : JoinTreeItem *jtitem,
138 : : SpecialJoinInfo *sjinfo,
139 : : Index security_level,
140 : : Relids qualscope,
141 : : Relids ojscope,
142 : : Relids outerjoin_nonnullable,
143 : : Relids incompatible_relids,
144 : : bool allow_equivalence,
145 : : bool has_clone,
146 : : bool is_clone,
147 : : List **postponed_oj_qual_list);
148 : : static Relids get_join_domain_min_rels(PlannerInfo *root, Relids domain_relids);
149 : : static void check_mergejoinable(RestrictInfo *restrictinfo);
150 : : static void check_hashjoinable(RestrictInfo *restrictinfo);
151 : : static void check_memoizable(RestrictInfo *restrictinfo);
152 : :
153 : :
154 : : /*****************************************************************************
155 : : *
156 : : * JOIN TREES
157 : : *
158 : : *****************************************************************************/
159 : :
160 : : /*
161 : : * add_base_rels_to_query
162 : : *
163 : : * Scan the query's jointree and create baserel RelOptInfos for all
164 : : * the base relations (e.g., table, subquery, and function RTEs)
165 : : * appearing in the jointree.
166 : : *
167 : : * The initial invocation must pass root->parse->jointree as the value of
168 : : * jtnode. Internally, the function recurses through the jointree.
169 : : *
170 : : * At the end of this process, there should be one baserel RelOptInfo for
171 : : * every non-join RTE that is used in the query. Some of the baserels
172 : : * may be appendrel parents, which will require additional "otherrel"
173 : : * RelOptInfos for their member rels, but those are added later.
174 : : */
175 : : void
176 : 759200 : add_base_rels_to_query(PlannerInfo *root, Node *jtnode)
177 : : {
178 [ - + ]: 759200 : if (jtnode == NULL)
179 : 0 : return;
180 [ + + ]: 759200 : if (IsA(jtnode, RangeTblRef))
181 : : {
182 : 390273 : int varno = ((RangeTblRef *) jtnode)->rtindex;
183 : :
184 : 390273 : (void) build_simple_rel(root, varno, NULL);
185 : : }
186 [ + + ]: 368927 : else if (IsA(jtnode, FromExpr))
187 : : {
188 : 276509 : FromExpr *f = (FromExpr *) jtnode;
189 : : ListCell *l;
190 : :
191 [ + - + + : 589168 : foreach(l, f->fromlist)
+ + ]
192 : 312671 : add_base_rels_to_query(root, lfirst(l));
193 : : }
194 [ + - ]: 92418 : else if (IsA(jtnode, JoinExpr))
195 : : {
196 : 92418 : JoinExpr *j = (JoinExpr *) jtnode;
197 : :
198 : 92418 : add_base_rels_to_query(root, j->larg);
199 : 92418 : add_base_rels_to_query(root, j->rarg);
200 : : }
201 : : else
202 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
203 : : (int) nodeTag(jtnode));
204 : : }
205 : :
206 : : /*
207 : : * add_other_rels_to_query
208 : : * create "otherrel" RelOptInfos for the children of appendrel baserels
209 : : *
210 : : * At the end of this process, there should be RelOptInfos for all relations
211 : : * that will be scanned by the query.
212 : : */
213 : : void
214 : 252932 : add_other_rels_to_query(PlannerInfo *root)
215 : : {
216 : : int rti;
217 : :
218 [ + + ]: 804627 : for (rti = 1; rti < root->simple_rel_array_size; rti++)
219 : : {
220 : 551696 : RelOptInfo *rel = root->simple_rel_array[rti];
221 : 551696 : RangeTblEntry *rte = root->simple_rte_array[rti];
222 : :
223 : : /* there may be empty slots corresponding to non-baserel RTEs */
224 [ + + ]: 551696 : if (rel == NULL)
225 : 138627 : continue;
226 : :
227 : : /* Ignore any "otherrels" that were already added. */
228 [ + + ]: 413069 : if (rel->reloptkind != RELOPT_BASEREL)
229 : 47993 : continue;
230 : :
231 : : /* If it's marked as inheritable, look for children. */
232 [ + + ]: 365076 : if (rte->inh)
233 : 17714 : expand_inherited_rtentry(root, rel, rte, rti);
234 : : }
235 : 252931 : }
236 : :
237 : :
238 : : /*****************************************************************************
239 : : *
240 : : * TARGET LISTS
241 : : *
242 : : *****************************************************************************/
243 : :
244 : : /*
245 : : * build_base_rel_tlists
246 : : * Add targetlist entries for each var needed in the query's final tlist
247 : : * (and HAVING clause, if any) to the appropriate base relations.
248 : : *
249 : : * We mark such vars as needed by "relation 0" to ensure that they will
250 : : * propagate up through all join plan steps.
251 : : */
252 : : void
253 : 261709 : build_base_rel_tlists(PlannerInfo *root, List *final_tlist)
254 : : {
255 : 261709 : List *tlist_vars = pull_var_clause((Node *) final_tlist,
256 : : PVC_RECURSE_AGGREGATES |
257 : : PVC_RECURSE_WINDOWFUNCS |
258 : : PVC_INCLUDE_PLACEHOLDERS);
259 : :
260 [ + + ]: 261709 : if (tlist_vars != NIL)
261 : : {
262 : 243763 : add_vars_to_targetlist(root, tlist_vars, bms_make_singleton(0));
263 : 243763 : list_free(tlist_vars);
264 : : }
265 : :
266 : : /*
267 : : * If there's a HAVING clause, we'll need the Vars it uses, too. Note
268 : : * that HAVING can contain Aggrefs but not WindowFuncs.
269 : : */
270 [ + + ]: 261709 : if (root->parse->havingQual)
271 : : {
272 : 865 : List *having_vars = pull_var_clause(root->parse->havingQual,
273 : : PVC_RECURSE_AGGREGATES |
274 : : PVC_INCLUDE_PLACEHOLDERS);
275 : :
276 [ + + ]: 865 : if (having_vars != NIL)
277 : : {
278 : 765 : add_vars_to_targetlist(root, having_vars,
279 : : bms_make_singleton(0));
280 : 765 : list_free(having_vars);
281 : : }
282 : : }
283 : 261709 : }
284 : :
285 : : /*
286 : : * add_vars_to_targetlist
287 : : * For each variable appearing in the list, add it to the owning
288 : : * relation's targetlist if not already present, and mark the variable
289 : : * as being needed for the indicated join (or for final output if
290 : : * where_needed includes "relation 0").
291 : : *
292 : : * The list may also contain PlaceHolderVars. These don't necessarily
293 : : * have a single owning relation; we keep their attr_needed info in
294 : : * root->placeholder_list instead. Find or create the associated
295 : : * PlaceHolderInfo entry, and update its ph_needed.
296 : : */
297 : : void
298 : 528769 : add_vars_to_targetlist(PlannerInfo *root, List *vars,
299 : : Relids where_needed)
300 : : {
301 : : ListCell *temp;
302 : :
303 : : Assert(!bms_is_empty(where_needed));
304 : :
305 [ + + + + : 1882331 : foreach(temp, vars)
+ + ]
306 : : {
307 : 1353562 : Node *node = (Node *) lfirst(temp);
308 : :
309 [ + + ]: 1353562 : if (IsA(node, Var))
310 : : {
311 : 1349476 : Var *var = (Var *) node;
312 : 1349476 : RelOptInfo *rel = find_base_rel(root, var->varno);
313 : 1349476 : int attno = var->varattno;
314 : :
315 [ + + ]: 1349476 : if (bms_is_subset(where_needed, rel->relids))
316 : 1633 : continue;
317 : : Assert(attno >= rel->min_attr && attno <= rel->max_attr);
318 : 1347843 : attno -= rel->min_attr;
319 [ + + ]: 1347843 : if (rel->attr_needed[attno] == NULL)
320 : : {
321 : : /*
322 : : * Variable not yet requested, so add to rel's targetlist.
323 : : *
324 : : * The value available at the rel's scan level has not been
325 : : * nulled by any outer join, so drop its varnullingrels.
326 : : * (We'll put those back as we climb up the join tree.)
327 : : */
328 : 976373 : var = copyObject(var);
329 : 976373 : var->varnullingrels = NULL;
330 : 976373 : rel->reltarget->exprs = lappend(rel->reltarget->exprs, var);
331 : : /* reltarget cost and width will be computed later */
332 : : }
333 : 1347843 : rel->attr_needed[attno] = bms_add_members(rel->attr_needed[attno],
334 : : where_needed);
335 : : }
336 [ + - ]: 4086 : else if (IsA(node, PlaceHolderVar))
337 : : {
338 : 4086 : PlaceHolderVar *phv = (PlaceHolderVar *) node;
339 : 4086 : PlaceHolderInfo *phinfo = find_placeholder_info(root, phv);
340 : :
341 : 4086 : phinfo->ph_needed = bms_add_members(phinfo->ph_needed,
342 : : where_needed);
343 : : }
344 : : else
345 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d", (int) nodeTag(node));
346 : : }
347 : 528769 : }
348 : :
349 : : /*****************************************************************************
350 : : *
351 : : * GROUP BY
352 : : *
353 : : *****************************************************************************/
354 : :
355 : : /*
356 : : * remove_useless_groupby_columns
357 : : * Remove any columns in the GROUP BY clause that are redundant due to
358 : : * being functionally dependent on other GROUP BY columns.
359 : : *
360 : : * Since some other DBMSes do not allow references to ungrouped columns, it's
361 : : * not unusual to find all columns listed in GROUP BY even though listing the
362 : : * primary-key columns, or columns of a unique constraint would be sufficient.
363 : : * Deleting such excess columns avoids redundant sorting or hashing work, so
364 : : * it's worth doing.
365 : : *
366 : : * Relcache invalidations will ensure that cached plans become invalidated
367 : : * when the underlying supporting indexes are dropped or if a column's NOT
368 : : * NULL attribute is removed.
369 : : */
370 : : void
371 : 261681 : remove_useless_groupby_columns(PlannerInfo *root)
372 : : {
373 : 261681 : Query *parse = root->parse;
374 : : Bitmapset **groupbyattnos;
375 : : List **groupbycols;
376 : : Bitmapset **surplusvars;
377 : 261681 : Relids nullable_relids = NULL;
378 : 261681 : bool tryremove = false;
379 : : ListCell *lc;
380 : : int relid;
381 : :
382 : : /* No chance to do anything if there are less than two GROUP BY items */
383 [ + + ]: 261681 : if (list_length(root->processed_groupClause) < 2)
384 : 259758 : return;
385 : :
386 : : /* Don't fiddle with the GROUP BY clause if the query has grouping sets */
387 [ + + ]: 1923 : if (parse->groupingSets)
388 : 678 : return;
389 : :
390 : : /*
391 : : * Scan the GROUP BY clause to find GROUP BY items that are simple Vars.
392 : : * Fill groupbyattnos[k] with a bitmapset of the column attnos of RTE k
393 : : * that are GROUP BY items, and groupbycols[k] with a parallel list of
394 : : * GroupByColInfo records. We need the latter so that, when checking a
395 : : * unique index against this rel's GROUP BY items, we can verify that the
396 : : * index's notion of equality agrees with at least one GROUP BY item per
397 : : * index column.
398 : : */
399 : 1245 : groupbyattnos = palloc0_array(Bitmapset *, list_length(parse->rtable) + 1);
400 : 1245 : groupbycols = palloc0_array(List *, list_length(parse->rtable) + 1);
401 [ + - + + : 4489 : foreach(lc, root->processed_groupClause)
+ + ]
402 : : {
403 : 3244 : SortGroupClause *sgc = lfirst_node(SortGroupClause, lc);
404 : 3244 : TargetEntry *tle = get_sortgroupclause_tle(sgc, parse->targetList);
405 : 3244 : Var *var = (Var *) tle->expr;
406 : : GroupByColInfo *info;
407 : :
408 : : /*
409 : : * Ignore non-Vars and Vars from other query levels.
410 : : *
411 : : * XXX in principle, stable expressions containing Vars could also be
412 : : * removed, if all the Vars are functionally dependent on other GROUP
413 : : * BY items. But it's not clear that such cases occur often enough to
414 : : * be worth troubling over.
415 : : */
416 [ + + ]: 3244 : if (!IsA(var, Var) ||
417 [ - + ]: 2561 : var->varlevelsup > 0)
418 : 683 : continue;
419 : :
420 : : /* OK, remember we have this Var */
421 : 2561 : relid = var->varno;
422 : : Assert(relid <= list_length(parse->rtable));
423 : :
424 : : /* Remember rels whose GROUP BY Vars can be nulled by an outer join */
425 [ + + ]: 2561 : if (!bms_is_empty(var->varnullingrels))
426 : 224 : nullable_relids = bms_add_member(nullable_relids, relid);
427 : :
428 : : /*
429 : : * If this isn't the first column for this relation then we now have
430 : : * multiple columns. That means there might be some that can be
431 : : * removed.
432 : : */
433 : 2561 : tryremove |= !bms_is_empty(groupbyattnos[relid]);
434 : 5122 : groupbyattnos[relid] = bms_add_member(groupbyattnos[relid],
435 : 2561 : var->varattno - FirstLowInvalidHeapAttributeNumber);
436 : :
437 : 2561 : info = palloc_object(GroupByColInfo);
438 : 2561 : info->attno = var->varattno;
439 : 2561 : info->eq_opfamilies = get_mergejoin_opfamilies(sgc->eqop);
440 : 2561 : info->coll = var->varcollid;
441 : 2561 : groupbycols[relid] = lappend(groupbycols[relid], info);
442 : : }
443 : :
444 : : /*
445 : : * No Vars or didn't find multiple Vars for any relation in the GROUP BY?
446 : : * If so, nothing can be removed, so don't waste more effort trying.
447 : : */
448 [ + + ]: 1245 : if (!tryremove)
449 : 377 : return;
450 : :
451 : : /*
452 : : * Consider each relation and see if it is possible to remove some of its
453 : : * Vars from GROUP BY. For simplicity and speed, we do the actual removal
454 : : * in a separate pass. Here, we just fill surplusvars[k] with a bitmapset
455 : : * of the column attnos of RTE k that are removable GROUP BY items.
456 : : */
457 : 868 : surplusvars = NULL; /* don't allocate array unless required */
458 : 868 : relid = 0;
459 [ + - + + : 3689 : foreach(lc, parse->rtable)
+ + ]
460 : : {
461 : 2821 : RangeTblEntry *rte = lfirst_node(RangeTblEntry, lc);
462 : : RelOptInfo *rel;
463 : : Bitmapset *relattnos;
464 : 2821 : Bitmapset *best_keycolumns = NULL;
465 : 2821 : int32 best_nkeycolumns = PG_INT32_MAX;
466 : :
467 : 2821 : relid++;
468 : :
469 : : /* Only plain relations could have primary-key constraints */
470 [ + + ]: 2821 : if (rte->rtekind != RTE_RELATION)
471 : 1433 : continue;
472 : :
473 : : /*
474 : : * We must skip inheritance parent tables as some of the child rels
475 : : * may cause duplicate rows. This cannot happen with partitioned
476 : : * tables, however.
477 : : */
478 [ + + + + ]: 1388 : if (rte->inh && rte->relkind != RELKIND_PARTITIONED_TABLE)
479 : 20 : continue;
480 : :
481 : : /* Nothing to do unless this rel has multiple Vars in GROUP BY */
482 : 1368 : relattnos = groupbyattnos[relid];
483 [ + + ]: 1368 : if (bms_membership(relattnos) != BMS_MULTIPLE)
484 : 528 : continue;
485 : :
486 : 840 : rel = root->simple_rel_array[relid];
487 : :
488 : : /*
489 : : * Now check each index for this relation to see if there are any with
490 : : * columns which are a proper subset of the grouping columns for this
491 : : * relation.
492 : : */
493 [ + + + + : 2696 : foreach_node(IndexOptInfo, index, rel->indexlist)
+ + ]
494 : : {
495 : : Bitmapset *ind_attnos;
496 : : bool index_check_ok;
497 : :
498 : : /*
499 : : * Skip any non-unique and deferrable indexes. Predicate indexes
500 : : * have not been checked yet, so we must skip those too as the
501 : : * predOK check that's done later might fail.
502 : : */
503 [ + + + + : 1016 : if (!index->unique || !index->immediate || index->indpred != NIL)
- + ]
504 : 420 : continue;
505 : :
506 : : /* For simplicity, we currently don't support expression indexes */
507 [ - + ]: 596 : if (index->indexprs != NIL)
508 : 0 : continue;
509 : :
510 : 596 : ind_attnos = NULL;
511 : 596 : index_check_ok = true;
512 [ + + ]: 1182 : for (int i = 0; i < index->nkeycolumns; i++)
513 : : {
514 : 876 : AttrNumber indkey_attno = index->indexkeys[i];
515 : 876 : Oid indkey_opfamily = index->opfamily[i];
516 : 876 : Oid indkey_coll = index->indexcollations[i];
517 : : ListCell *lc2;
518 : :
519 : : /*
520 : : * We must insist that the index columns are all defined NOT
521 : : * NULL otherwise duplicate NULLs could exist. However, we
522 : : * can relax this check when the index is defined with NULLS
523 : : * NOT DISTINCT as there can only be 1 NULL row, therefore
524 : : * functional dependency on the unique columns is maintained,
525 : : * despite the NULL. That doesn't hold if the rel is nullable
526 : : * by an outer join, though, as null-extended rows would be
527 : : * conflated with that NULL row.
528 : : */
529 [ + + + + ]: 886 : if ((!index->nullsnotdistinct ||
530 : 10 : bms_is_member(relid, nullable_relids)) &&
531 [ + + ]: 871 : !bms_is_member(indkey_attno, rel->notnullattnums))
532 : : {
533 : 10 : index_check_ok = false;
534 : 10 : break;
535 : : }
536 : :
537 : : /*
538 : : * The index proves uniqueness only under its own opfamily and
539 : : * collation. Require some GROUP BY item on this column to
540 : : * use a compatible eqop and collation, the same check
541 : : * relation_has_unique_index_for() applies to join clauses.
542 : : */
543 [ + - + + : 1736 : foreach(lc2, groupbycols[relid])
+ + ]
544 : : {
545 : 1456 : GroupByColInfo *info = (GroupByColInfo *) lfirst(lc2);
546 : :
547 [ + + ]: 1456 : if (info->attno != indkey_attno)
548 : 850 : continue;
549 [ + + + + ]: 1202 : if (list_member_oid(info->eq_opfamilies, indkey_opfamily) &&
550 : 596 : collations_agree_on_equality(indkey_coll, info->coll))
551 : 586 : break;
552 : : }
553 [ + + ]: 866 : if (lc2 == NULL)
554 : : {
555 : 280 : index_check_ok = false;
556 : 280 : break;
557 : : }
558 : :
559 : : ind_attnos =
560 : 586 : bms_add_member(ind_attnos,
561 : : indkey_attno -
562 : : FirstLowInvalidHeapAttributeNumber);
563 : : }
564 : :
565 [ + + ]: 596 : if (!index_check_ok)
566 : 290 : continue;
567 : :
568 : : /*
569 : : * Skip any indexes where the indexed columns aren't a proper
570 : : * subset of the GROUP BY.
571 : : */
572 [ + + ]: 306 : if (bms_subset_compare(ind_attnos, relattnos) != BMS_SUBSET1)
573 : 5 : continue;
574 : :
575 : : /*
576 : : * Record the attribute numbers from the index with the fewest
577 : : * columns. This allows the largest number of columns to be
578 : : * removed from the GROUP BY clause. In the future, we may wish
579 : : * to consider using the narrowest set of columns and looking at
580 : : * pg_statistic.stawidth as it might be better to use an index
581 : : * with, say two INT4s, rather than, say, one long varlena column.
582 : : */
583 [ + + ]: 301 : if (index->nkeycolumns < best_nkeycolumns)
584 : : {
585 : 286 : best_keycolumns = ind_attnos;
586 : 286 : best_nkeycolumns = index->nkeycolumns;
587 : : }
588 : : }
589 : :
590 : : /* Did we find a suitable index? */
591 [ + + ]: 840 : if (!bms_is_empty(best_keycolumns))
592 : : {
593 : : /*
594 : : * To easily remember whether we've found anything to do, we don't
595 : : * allocate the surplusvars[] array until we find something.
596 : : */
597 [ + + ]: 286 : if (surplusvars == NULL)
598 : 281 : surplusvars = palloc0_array(Bitmapset *, list_length(parse->rtable) + 1);
599 : :
600 : : /* Remember the attnos of the removable columns */
601 : 286 : surplusvars[relid] = bms_difference(relattnos, best_keycolumns);
602 : : }
603 : : }
604 : :
605 : : /*
606 : : * If we found any surplus Vars, build a new GROUP BY clause without them.
607 : : * (Note: this may leave some TLEs with unreferenced ressortgroupref
608 : : * markings, but that's harmless.)
609 : : */
610 [ + + ]: 868 : if (surplusvars != NULL)
611 : : {
612 : 281 : List *new_groupby = NIL;
613 : :
614 [ + - + + : 1153 : foreach(lc, root->processed_groupClause)
+ + ]
615 : : {
616 : 872 : SortGroupClause *sgc = lfirst_node(SortGroupClause, lc);
617 : 872 : TargetEntry *tle = get_sortgroupclause_tle(sgc, parse->targetList);
618 : 872 : Var *var = (Var *) tle->expr;
619 : :
620 : : /*
621 : : * New list must include non-Vars, outer Vars, and anything not
622 : : * marked as surplus.
623 : : */
624 [ + - ]: 872 : if (!IsA(var, Var) ||
625 [ + - ]: 872 : var->varlevelsup > 0 ||
626 [ + + ]: 872 : !bms_is_member(var->varattno - FirstLowInvalidHeapAttributeNumber,
627 : 872 : surplusvars[var->varno]))
628 : 551 : new_groupby = lappend(new_groupby, sgc);
629 : : }
630 : :
631 : 281 : root->processed_groupClause = new_groupby;
632 : : }
633 : : }
634 : :
635 : : /*
636 : : * setup_eager_aggregation
637 : : * Check if eager aggregation is applicable, and if so collect suitable
638 : : * aggregate expressions and grouping expressions in the query.
639 : : */
640 : : void
641 : 252932 : setup_eager_aggregation(PlannerInfo *root)
642 : : {
643 : : /*
644 : : * Don't apply eager aggregation if disabled by user.
645 : : */
646 [ + + ]: 252932 : if (!enable_eager_aggregate)
647 : 400 : return;
648 : :
649 : : /*
650 : : * Don't apply eager aggregation if there are no available GROUP BY
651 : : * clauses.
652 : : */
653 [ + + ]: 252532 : if (!root->processed_groupClause)
654 : 248542 : return;
655 : :
656 : : /*
657 : : * For now we don't try to support grouping sets.
658 : : */
659 [ + + ]: 3990 : if (root->parse->groupingSets)
660 : 787 : return;
661 : :
662 : : /*
663 : : * For now we don't try to support DISTINCT or ORDER BY aggregates.
664 : : */
665 [ + + ]: 3203 : if (root->numOrderedAggs > 0)
666 : 162 : return;
667 : :
668 : : /*
669 : : * If there are any aggregates that do not support partial mode, or any
670 : : * partial aggregates that are non-serializable, do not apply eager
671 : : * aggregation.
672 : : */
673 [ + + - + ]: 3041 : if (root->hasNonPartialAggs || root->hasNonSerialAggs)
674 : 130 : return;
675 : :
676 : : /*
677 : : * We don't try to apply eager aggregation if there are set-returning
678 : : * functions in targetlist.
679 : : */
680 [ + + ]: 2911 : if (root->parse->hasTargetSRFs)
681 : 65 : return;
682 : :
683 : : /*
684 : : * Eager aggregation only makes sense if there are multiple base rels in
685 : : * the query.
686 : : */
687 [ + + ]: 2846 : if (bms_membership(root->all_baserels) != BMS_MULTIPLE)
688 : 1874 : return;
689 : :
690 : : /*
691 : : * Don't apply eager aggregation if any aggregate poses a risk of
692 : : * excessive memory usage during partial aggregation.
693 : : */
694 [ + + ]: 972 : if (is_partial_agg_memory_risky(root))
695 : 1 : return;
696 : :
697 : : /*
698 : : * Collect aggregate expressions and plain Vars that appear in the
699 : : * targetlist and havingQual.
700 : : */
701 : 971 : create_agg_clause_infos(root);
702 : :
703 : : /*
704 : : * If there are no suitable aggregate expressions, we cannot apply eager
705 : : * aggregation.
706 : : */
707 [ + + ]: 971 : if (root->agg_clause_list == NIL)
708 : 308 : return;
709 : :
710 : : /*
711 : : * Collect grouping expressions that appear in grouping clauses.
712 : : */
713 : 663 : create_grouping_expr_infos(root);
714 : : }
715 : :
716 : : /*
717 : : * is_partial_agg_memory_risky
718 : : * Check if any aggregate poses a risk of excessive memory usage during
719 : : * partial aggregation.
720 : : *
721 : : * We check if any aggregate has a negative aggtransspace value, which
722 : : * indicates that its transition state data can grow unboundedly in size.
723 : : * Applying eager aggregation in such cases risks high memory usage since
724 : : * partial aggregation results might be stored in join hash tables or
725 : : * materialized nodes.
726 : : */
727 : : static bool
728 : 972 : is_partial_agg_memory_risky(PlannerInfo *root)
729 : : {
730 : : ListCell *lc;
731 : :
732 [ + + + + : 1856 : foreach(lc, root->aggtransinfos)
+ + ]
733 : : {
734 : 885 : AggTransInfo *transinfo = lfirst_node(AggTransInfo, lc);
735 : :
736 [ + + ]: 885 : if (transinfo->aggtransspace < 0)
737 : 1 : return true;
738 : : }
739 : :
740 : 971 : return false;
741 : : }
742 : :
743 : : /*
744 : : * create_agg_clause_infos
745 : : * Search the targetlist and havingQual for Aggrefs and plain Vars, and
746 : : * create an AggClauseInfo for each Aggref node.
747 : : */
748 : : static void
749 : 971 : create_agg_clause_infos(PlannerInfo *root)
750 : : {
751 : : List *tlist_exprs;
752 : 971 : List *agg_clause_list = NIL;
753 : 971 : List *tlist_vars = NIL;
754 : 971 : Relids aggregate_relids = NULL;
755 : 971 : bool eager_agg_applicable = true;
756 : : ListCell *lc;
757 : :
758 : : Assert(root->agg_clause_list == NIL);
759 : : Assert(root->tlist_vars == NIL);
760 : :
761 : 971 : tlist_exprs = pull_var_clause((Node *) root->processed_tlist,
762 : : PVC_INCLUDE_AGGREGATES |
763 : : PVC_RECURSE_WINDOWFUNCS |
764 : : PVC_RECURSE_PLACEHOLDERS);
765 : :
766 : : /*
767 : : * Aggregates within the HAVING clause need to be processed in the same
768 : : * way as those in the targetlist. Note that HAVING can contain Aggrefs
769 : : * but not WindowFuncs.
770 : : */
771 [ + + ]: 971 : if (root->parse->havingQual != NULL)
772 : : {
773 : : List *having_exprs;
774 : :
775 : 35 : having_exprs = pull_var_clause((Node *) root->parse->havingQual,
776 : : PVC_INCLUDE_AGGREGATES |
777 : : PVC_RECURSE_PLACEHOLDERS);
778 [ + - ]: 35 : if (having_exprs != NIL)
779 : : {
780 : 35 : tlist_exprs = list_concat(tlist_exprs, having_exprs);
781 : 35 : list_free(having_exprs);
782 : : }
783 : : }
784 : :
785 [ + - + + : 4147 : foreach(lc, tlist_exprs)
+ + ]
786 : : {
787 : 3224 : Expr *expr = (Expr *) lfirst(lc);
788 : : Aggref *aggref;
789 : : Relids agg_eval_at;
790 : : AggClauseInfo *ac_info;
791 : :
792 : : /* For now we don't try to support GROUPING() expressions */
793 [ - + ]: 3224 : if (IsA(expr, GroupingFunc))
794 : : {
795 : 0 : eager_agg_applicable = false;
796 : 0 : break;
797 : : }
798 : :
799 : : /* Collect plain Vars for future reference */
800 [ + + ]: 3224 : if (IsA(expr, Var))
801 : : {
802 : 2335 : tlist_vars = list_append_unique(tlist_vars, expr);
803 : 2335 : continue;
804 : : }
805 : :
806 : 889 : aggref = castNode(Aggref, expr);
807 : :
808 : : Assert(aggref->aggorder == NIL);
809 : : Assert(aggref->aggdistinct == NIL);
810 : :
811 : : /*
812 : : * We cannot push down aggregates that contain volatile functions.
813 : : * Doing so would change the number of times the function is
814 : : * evaluated.
815 : : */
816 [ + + ]: 889 : if (contain_volatile_functions((Node *) aggref))
817 : : {
818 : 10 : eager_agg_applicable = false;
819 : 10 : break;
820 : : }
821 : :
822 : : /*
823 : : * If there are any securityQuals, do not try to apply eager
824 : : * aggregation if any non-leakproof aggregate functions are present.
825 : : * This is overly strict, but for now...
826 : : */
827 [ - + ]: 879 : if (root->qual_security_level > 0 &&
828 [ # # ]: 0 : !get_func_leakproof(aggref->aggfnoid))
829 : : {
830 : 0 : eager_agg_applicable = false;
831 : 0 : break;
832 : : }
833 : :
834 : 879 : agg_eval_at = pull_varnos(root, (Node *) aggref);
835 : :
836 : : /*
837 : : * If all base relations in the query are referenced by aggregate
838 : : * functions, then eager aggregation is not applicable.
839 : : */
840 : 879 : aggregate_relids = bms_add_members(aggregate_relids, agg_eval_at);
841 [ + + ]: 879 : if (bms_is_subset(root->all_baserels, aggregate_relids))
842 : : {
843 : 38 : eager_agg_applicable = false;
844 : 38 : break;
845 : : }
846 : :
847 : : /* OK, create the AggClauseInfo node */
848 : 841 : ac_info = makeNode(AggClauseInfo);
849 : 841 : ac_info->aggref = aggref;
850 : 841 : ac_info->agg_eval_at = agg_eval_at;
851 : :
852 : : /* ... and add it to the list */
853 : 841 : agg_clause_list = list_append_unique(agg_clause_list, ac_info);
854 : : }
855 : :
856 : 971 : list_free(tlist_exprs);
857 : :
858 [ + + ]: 971 : if (eager_agg_applicable)
859 : : {
860 : 923 : root->agg_clause_list = agg_clause_list;
861 : 923 : root->tlist_vars = tlist_vars;
862 : : }
863 : : else
864 : : {
865 : 48 : list_free_deep(agg_clause_list);
866 : 48 : list_free(tlist_vars);
867 : : }
868 : 971 : }
869 : :
870 : : /*
871 : : * create_grouping_expr_infos
872 : : * Create a GroupingExprInfo for each expression usable as grouping key.
873 : : *
874 : : * If any grouping expression is not suitable, we will just return with
875 : : * root->group_expr_list being NIL.
876 : : */
877 : : static void
878 : 663 : create_grouping_expr_infos(PlannerInfo *root)
879 : : {
880 : 663 : List *exprs = NIL;
881 : 663 : List *sortgrouprefs = NIL;
882 : 663 : List *ecs = NIL;
883 : : ListCell *lc,
884 : : *lc1,
885 : : *lc2,
886 : : *lc3;
887 : :
888 : : Assert(root->group_expr_list == NIL);
889 : :
890 [ + - + + : 1246 : foreach(lc, root->processed_groupClause)
+ + ]
891 : : {
892 : 719 : SortGroupClause *sgc = lfirst_node(SortGroupClause, lc);
893 : 719 : TargetEntry *tle = get_sortgroupclause_tle(sgc, root->processed_tlist);
894 : : TypeCacheEntry *tce;
895 : : Oid equalimageproc;
896 : :
897 : : Assert(tle->ressortgroupref > 0);
898 : :
899 : : /*
900 : : * For now we only support plain Vars as grouping expressions.
901 : : */
902 [ + + ]: 719 : if (!IsA(tle->expr, Var))
903 : 136 : return;
904 : :
905 : : /*
906 : : * Eager aggregation is only possible if equality implies image
907 : : * equality for each grouping key. Otherwise, placing keys with
908 : : * different byte images into the same group may result in the loss of
909 : : * information that could be necessary to evaluate upper qual clauses.
910 : : *
911 : : * For instance, the NUMERIC data type is not supported, as values
912 : : * that are considered equal by the equality operator (e.g., 0 and
913 : : * 0.0) can have different scales.
914 : : */
915 : 648 : tce = lookup_type_cache(exprType((Node *) tle->expr),
916 : : TYPECACHE_BTREE_OPFAMILY);
917 [ + - ]: 648 : if (!OidIsValid(tce->btree_opf) ||
918 [ - + ]: 648 : !OidIsValid(tce->btree_opintype))
919 : 0 : return;
920 : :
921 : 648 : equalimageproc = get_opfamily_proc(tce->btree_opf,
922 : : tce->btree_opintype,
923 : : tce->btree_opintype,
924 : : BTEQUALIMAGE_PROC);
925 : :
926 : : /*
927 : : * If there is no BTEQUALIMAGE_PROC, eager aggregation is assumed to
928 : : * be unsafe. Otherwise, we call the procedure to check. We must be
929 : : * careful to pass the expression's actual collation, rather than the
930 : : * data type's default collation, to ensure that non-deterministic
931 : : * collations are correctly handled.
932 : : */
933 [ + + ]: 648 : if (!OidIsValid(equalimageproc) ||
934 [ + + ]: 1286 : !DatumGetBool(OidFunctionCall1Coll(equalimageproc,
935 : 643 : exprCollation((Node *) tle->expr),
936 : : ObjectIdGetDatum(tce->btree_opintype))))
937 : 65 : return;
938 : :
939 : 583 : exprs = lappend(exprs, tle->expr);
940 : 583 : sortgrouprefs = lappend_int(sortgrouprefs, tle->ressortgroupref);
941 : 583 : ecs = lappend(ecs, get_eclass_for_sortgroupclause(root, sgc, tle->expr));
942 : : }
943 : :
944 : : /*
945 : : * Construct a GroupingExprInfo for each expression.
946 : : */
947 [ + - + + : 1090 : forthree(lc1, exprs, lc2, sortgrouprefs, lc3, ecs)
+ - + + +
- + + + +
+ - + - +
+ ]
948 : : {
949 : 563 : Expr *expr = (Expr *) lfirst(lc1);
950 : 563 : int sortgroupref = lfirst_int(lc2);
951 : 563 : EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc3);
952 : : GroupingExprInfo *ge_info;
953 : :
954 : 563 : ge_info = makeNode(GroupingExprInfo);
955 : 563 : ge_info->expr = (Expr *) copyObject(expr);
956 : 563 : ge_info->sortgroupref = sortgroupref;
957 : 563 : ge_info->ec = ec;
958 : :
959 : 563 : root->group_expr_list = lappend(root->group_expr_list, ge_info);
960 : : }
961 : : }
962 : :
963 : : /*
964 : : * get_eclass_for_sortgroupclause
965 : : * Given a group clause and an expression, find an existing equivalence
966 : : * class that the expression is a member of; return NULL if none.
967 : : */
968 : : static EquivalenceClass *
969 : 583 : get_eclass_for_sortgroupclause(PlannerInfo *root, SortGroupClause *sgc,
970 : : Expr *expr)
971 : : {
972 : : Oid opfamily,
973 : : opcintype,
974 : : collation;
975 : : CompareType cmptype;
976 : : Oid equality_op;
977 : : List *opfamilies;
978 : :
979 : : /* Punt if the group clause is not sortable */
980 [ - + ]: 583 : if (!OidIsValid(sgc->sortop))
981 : 0 : return NULL;
982 : :
983 : : /* Find the operator in pg_amop --- failure shouldn't happen */
984 [ - + ]: 583 : if (!get_ordering_op_properties(sgc->sortop,
985 : : &opfamily, &opcintype, &cmptype))
986 [ # # ]: 0 : elog(ERROR, "operator %u is not a valid ordering operator",
987 : : sgc->sortop);
988 : :
989 : : /* Because SortGroupClause doesn't carry collation, consult the expr */
990 : 583 : collation = exprCollation((Node *) expr);
991 : :
992 : : /*
993 : : * EquivalenceClasses need to contain opfamily lists based on the family
994 : : * membership of mergejoinable equality operators, which could belong to
995 : : * more than one opfamily. So we have to look up the opfamily's equality
996 : : * operator and get its membership.
997 : : */
998 : 583 : equality_op = get_opfamily_member_for_cmptype(opfamily,
999 : : opcintype,
1000 : : opcintype,
1001 : : COMPARE_EQ);
1002 [ - + ]: 583 : if (!OidIsValid(equality_op)) /* shouldn't happen */
1003 [ # # ]: 0 : elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
1004 : : COMPARE_EQ, opcintype, opcintype, opfamily);
1005 : 583 : opfamilies = get_mergejoin_opfamilies(equality_op);
1006 [ - + ]: 583 : if (!opfamilies) /* certainly should find some */
1007 [ # # ]: 0 : elog(ERROR, "could not find opfamilies for equality operator %u",
1008 : : equality_op);
1009 : :
1010 : : /* Now find a matching EquivalenceClass */
1011 : 583 : return get_eclass_for_sort_expr(root, expr, opfamilies, opcintype,
1012 : : collation, sgc->tleSortGroupRef,
1013 : : NULL, false);
1014 : : }
1015 : :
1016 : : /*****************************************************************************
1017 : : *
1018 : : * LATERAL REFERENCES
1019 : : *
1020 : : *****************************************************************************/
1021 : :
1022 : : /*
1023 : : * find_lateral_references
1024 : : * For each LATERAL subquery, extract all its references to Vars and
1025 : : * PlaceHolderVars of the current query level, and make sure those values
1026 : : * will be available for evaluation of the subquery.
1027 : : *
1028 : : * While later planning steps ensure that the Var/PHV source rels are on the
1029 : : * outside of nestloops relative to the LATERAL subquery, we also need to
1030 : : * ensure that the Vars/PHVs propagate up to the nestloop join level; this
1031 : : * means setting suitable where_needed values for them.
1032 : : *
1033 : : * Note that this only deals with lateral references in unflattened LATERAL
1034 : : * subqueries. When we flatten a LATERAL subquery, its lateral references
1035 : : * become plain Vars in the parent query, but they may have to be wrapped in
1036 : : * PlaceHolderVars if they need to be forced NULL by outer joins that don't
1037 : : * also null the LATERAL subquery. That's all handled elsewhere.
1038 : : *
1039 : : * This has to run before deconstruct_jointree, since it might result in
1040 : : * creation of PlaceHolderInfos.
1041 : : */
1042 : : void
1043 : 261681 : find_lateral_references(PlannerInfo *root)
1044 : : {
1045 : : Index rti;
1046 : :
1047 : : /* We need do nothing if the query contains no LATERAL RTEs */
1048 [ + + ]: 261681 : if (!root->hasLateralRTEs)
1049 : 253879 : return;
1050 : :
1051 : : /*
1052 : : * Examine all baserels (the rel array has been set up by now).
1053 : : */
1054 [ + + ]: 43774 : for (rti = 1; rti < root->simple_rel_array_size; rti++)
1055 : : {
1056 : 35972 : RelOptInfo *brel = root->simple_rel_array[rti];
1057 : :
1058 : : /* there may be empty slots corresponding to non-baserel RTEs */
1059 [ + + ]: 35972 : if (brel == NULL)
1060 : 14542 : continue;
1061 : :
1062 : : Assert(brel->relid == rti); /* sanity check on array */
1063 : :
1064 : : /*
1065 : : * This bit is less obvious than it might look. We ignore appendrel
1066 : : * otherrels and consider only their parent baserels. In a case where
1067 : : * a LATERAL-containing UNION ALL subquery was pulled up, it is the
1068 : : * otherrel that is actually going to be in the plan. However, we
1069 : : * want to mark all its lateral references as needed by the parent,
1070 : : * because it is the parent's relid that will be used for join
1071 : : * planning purposes. And the parent's RTE will contain all the
1072 : : * lateral references we need to know, since the pulled-up member is
1073 : : * nothing but a copy of parts of the original RTE's subquery. We
1074 : : * could visit the parent's children instead and transform their
1075 : : * references back to the parent's relid, but it would be much more
1076 : : * complicated for no real gain. (Important here is that the child
1077 : : * members have not yet received any processing beyond being pulled
1078 : : * up.) Similarly, in appendrels created by inheritance expansion,
1079 : : * it's sufficient to look at the parent relation.
1080 : : */
1081 : :
1082 : : /* ignore RTEs that are "other rels" */
1083 [ - + ]: 21430 : if (brel->reloptkind != RELOPT_BASEREL)
1084 : 0 : continue;
1085 : :
1086 : 21430 : extract_lateral_references(root, brel, rti);
1087 : : }
1088 : : }
1089 : :
1090 : : static void
1091 : 21430 : extract_lateral_references(PlannerInfo *root, RelOptInfo *brel, Index rtindex)
1092 : : {
1093 : 21430 : RangeTblEntry *rte = root->simple_rte_array[rtindex];
1094 : : List *vars;
1095 : : List *newvars;
1096 : : Relids where_needed;
1097 : : ListCell *lc;
1098 : :
1099 : : /* No cross-references are possible if it's not LATERAL */
1100 [ + + ]: 21430 : if (!rte->lateral)
1101 : 14447 : return;
1102 : :
1103 : : /* Fetch the appropriate variables */
1104 [ + + ]: 6983 : if (rte->rtekind == RTE_RELATION)
1105 : 41 : vars = pull_vars_of_level((Node *) rte->tablesample, 0);
1106 [ + + ]: 6942 : else if (rte->rtekind == RTE_SUBQUERY)
1107 : 1881 : vars = pull_vars_of_level((Node *) rte->subquery, 1);
1108 [ + + ]: 5061 : else if (rte->rtekind == RTE_FUNCTION)
1109 : 4698 : vars = pull_vars_of_level((Node *) rte->functions, 0);
1110 [ + + ]: 363 : else if (rte->rtekind == RTE_TABLEFUNC)
1111 : 303 : vars = pull_vars_of_level((Node *) rte->tablefunc, 0);
1112 [ + - ]: 60 : else if (rte->rtekind == RTE_VALUES)
1113 : 60 : vars = pull_vars_of_level((Node *) rte->values_lists, 0);
1114 : : else
1115 : : {
1116 : : Assert(false);
1117 : 0 : return; /* keep compiler quiet */
1118 : : }
1119 : :
1120 [ + + ]: 6983 : if (vars == NIL)
1121 : 99 : return; /* nothing to do */
1122 : :
1123 : : /* Copy each Var (or PlaceHolderVar) and adjust it to match our level */
1124 : 6884 : newvars = NIL;
1125 [ + - + + : 17146 : foreach(lc, vars)
+ + ]
1126 : : {
1127 : 10262 : Node *node = (Node *) lfirst(lc);
1128 : :
1129 : 10262 : node = copyObject(node);
1130 [ + + ]: 10262 : if (IsA(node, Var))
1131 : : {
1132 : 9962 : Var *var = (Var *) node;
1133 : :
1134 : : /* Adjustment is easy since it's just one node */
1135 : 9962 : var->varlevelsup = 0;
1136 : : }
1137 [ + - ]: 300 : else if (IsA(node, PlaceHolderVar))
1138 : : {
1139 : 300 : PlaceHolderVar *phv = (PlaceHolderVar *) node;
1140 : 300 : int levelsup = phv->phlevelsup;
1141 : :
1142 : : /*
1143 : : * Have to work harder to adjust the contained expression too.
1144 : : * (Its expression has already been preprocessed by
1145 : : * subquery_planner(), so we must not do that again here.)
1146 : : */
1147 [ + + ]: 300 : if (levelsup != 0)
1148 : 195 : IncrementVarSublevelsUp(node, -levelsup, 0);
1149 : : }
1150 : : else
1151 : : Assert(false);
1152 : 10262 : newvars = lappend(newvars, node);
1153 : : }
1154 : :
1155 : 6884 : list_free(vars);
1156 : :
1157 : : /*
1158 : : * We mark the Vars as being "needed" at the LATERAL RTE. This is a bit
1159 : : * of a cheat: a more formal approach would be to mark each one as needed
1160 : : * at the join of the LATERAL RTE with its source RTE. But it will work,
1161 : : * and it's much less tedious than computing a separate where_needed for
1162 : : * each Var.
1163 : : */
1164 : 6884 : where_needed = bms_make_singleton(rtindex);
1165 : :
1166 : : /*
1167 : : * Push Vars into their source relations' targetlists, and PHVs into
1168 : : * root->placeholder_list.
1169 : : */
1170 : 6884 : add_vars_to_targetlist(root, newvars, where_needed);
1171 : :
1172 : : /* Remember the lateral references for create_lateral_join_info */
1173 : 6884 : brel->lateral_vars = newvars;
1174 : : }
1175 : :
1176 : : /*
1177 : : * create_lateral_join_info
1178 : : * Fill in the per-base-relation direct_lateral_relids, lateral_relids
1179 : : * and lateral_referencers sets.
1180 : : */
1181 : : void
1182 : 252932 : create_lateral_join_info(PlannerInfo *root)
1183 : : {
1184 : 252932 : bool found_laterals = false;
1185 : : Index rti;
1186 : : ListCell *lc;
1187 : :
1188 : : /* We need do nothing if the query contains no LATERAL RTEs */
1189 [ + + ]: 252932 : if (!root->hasLateralRTEs)
1190 : 245951 : return;
1191 : :
1192 : : /* We'll need to have the ph_eval_at values for PlaceHolderVars */
1193 : : Assert(root->placeholdersFrozen);
1194 : :
1195 : : /*
1196 : : * Examine all baserels (the rel array has been set up by now).
1197 : : */
1198 [ + + ]: 34671 : for (rti = 1; rti < root->simple_rel_array_size; rti++)
1199 : : {
1200 : 27690 : RelOptInfo *brel = root->simple_rel_array[rti];
1201 : : Relids lateral_relids;
1202 : :
1203 : : /* there may be empty slots corresponding to non-baserel RTEs */
1204 [ + + ]: 27690 : if (brel == NULL)
1205 : 10395 : continue;
1206 : :
1207 : : Assert(brel->relid == rti); /* sanity check on array */
1208 : :
1209 : : /* ignore RTEs that are "other rels" */
1210 [ - + ]: 17295 : if (brel->reloptkind != RELOPT_BASEREL)
1211 : 0 : continue;
1212 : :
1213 : 17295 : lateral_relids = NULL;
1214 : :
1215 : : /* consider each laterally-referenced Var or PHV */
1216 [ + + + + : 26606 : foreach(lc, brel->lateral_vars)
+ + ]
1217 : : {
1218 : 9311 : Node *node = (Node *) lfirst(lc);
1219 : :
1220 [ + + ]: 9311 : if (IsA(node, Var))
1221 : : {
1222 : 9041 : Var *var = (Var *) node;
1223 : :
1224 : 9041 : found_laterals = true;
1225 : 9041 : lateral_relids = bms_add_member(lateral_relids,
1226 : : var->varno);
1227 : : }
1228 [ + - ]: 270 : else if (IsA(node, PlaceHolderVar))
1229 : : {
1230 : 270 : PlaceHolderVar *phv = (PlaceHolderVar *) node;
1231 : 270 : PlaceHolderInfo *phinfo = find_placeholder_info(root, phv);
1232 : :
1233 : 270 : found_laterals = true;
1234 : :
1235 : : /*
1236 : : * A subquery needs the PHV as a whole, so any outer joins in
1237 : : * its ph_eval_at must be formed first. Other rels can
1238 : : * compute the PHV's expression themselves, so they need only
1239 : : * the baserels.
1240 : : */
1241 [ + + ]: 270 : if (brel->rtekind == RTE_SUBQUERY)
1242 : 165 : lateral_relids = bms_add_members(lateral_relids,
1243 : 165 : phinfo->ph_eval_at);
1244 : : else
1245 : 105 : lateral_relids = bms_add_members(lateral_relids,
1246 : 105 : bms_intersect(phinfo->ph_eval_at,
1247 : 105 : root->all_baserels));
1248 : : }
1249 : : else
1250 : : Assert(false);
1251 : : }
1252 : :
1253 : : /* We now have all the simple lateral refs from this rel */
1254 : 17295 : brel->direct_lateral_relids = lateral_relids;
1255 : 17295 : brel->lateral_relids = bms_copy(lateral_relids);
1256 : : }
1257 : :
1258 : : /*
1259 : : * Now check for lateral references within PlaceHolderVars, and mark their
1260 : : * eval_at rels as having lateral references to the source rels.
1261 : : *
1262 : : * For a PHV that is due to be evaluated at a baserel, mark its source(s)
1263 : : * as direct lateral dependencies of the baserel (adding onto the ones
1264 : : * recorded above). If it's due to be evaluated at a join, mark its
1265 : : * source(s) as indirect lateral dependencies of each baserel in the join,
1266 : : * ie put them into lateral_relids but not direct_lateral_relids. This is
1267 : : * appropriate because we can't put any such baserel on the outside of a
1268 : : * join to one of the PHV's lateral dependencies, but on the other hand we
1269 : : * also can't yet join it directly to the dependency.
1270 : : */
1271 [ + + + + : 7761 : foreach(lc, root->placeholder_list)
+ + ]
1272 : : {
1273 : 780 : PlaceHolderInfo *phinfo = (PlaceHolderInfo *) lfirst(lc);
1274 : 780 : Relids eval_at = phinfo->ph_eval_at;
1275 : : Relids lateral_refs;
1276 : : int varno;
1277 : :
1278 [ + + ]: 780 : if (phinfo->ph_lateral == NULL)
1279 : 463 : continue; /* PHV is uninteresting if no lateral refs */
1280 : :
1281 : 317 : found_laterals = true;
1282 : :
1283 : : /*
1284 : : * Include only baserels not outer joins in the evaluation sites'
1285 : : * lateral relids. This avoids problems when outer join order gets
1286 : : * rearranged, and it should still ensure that the lateral values are
1287 : : * available when needed.
1288 : : */
1289 : 317 : lateral_refs = bms_intersect(phinfo->ph_lateral, root->all_baserels);
1290 : : Assert(!bms_is_empty(lateral_refs));
1291 : :
1292 [ + + ]: 317 : if (bms_get_singleton_member(eval_at, &varno))
1293 : : {
1294 : : /* Evaluation site is a baserel */
1295 : 252 : RelOptInfo *brel = find_base_rel(root, varno);
1296 : :
1297 : 252 : brel->direct_lateral_relids =
1298 : 252 : bms_add_members(brel->direct_lateral_relids,
1299 : : lateral_refs);
1300 : 252 : brel->lateral_relids =
1301 : 252 : bms_add_members(brel->lateral_relids,
1302 : : lateral_refs);
1303 : : }
1304 : : else
1305 : : {
1306 : : /* Evaluation site is a join */
1307 : 65 : varno = -1;
1308 [ + + ]: 195 : while ((varno = bms_next_member(eval_at, varno)) >= 0)
1309 : : {
1310 : 130 : RelOptInfo *brel = find_base_rel_ignore_join(root, varno);
1311 : :
1312 [ - + ]: 130 : if (brel == NULL)
1313 : 0 : continue; /* ignore outer joins in eval_at */
1314 : 130 : brel->lateral_relids = bms_add_members(brel->lateral_relids,
1315 : : lateral_refs);
1316 : : }
1317 : : }
1318 : : }
1319 : :
1320 : : /*
1321 : : * If we found no actual lateral references, we're done; but reset the
1322 : : * hasLateralRTEs flag to avoid useless work later.
1323 : : */
1324 [ + + ]: 6981 : if (!found_laterals)
1325 : : {
1326 : 604 : root->hasLateralRTEs = false;
1327 : 604 : return;
1328 : : }
1329 : :
1330 : : /*
1331 : : * Calculate the transitive closure of the lateral_relids sets, so that
1332 : : * they describe both direct and indirect lateral references. If relation
1333 : : * X references Y laterally, and Y references Z laterally, then we will
1334 : : * have to scan X on the inside of a nestloop with Z, so for all intents
1335 : : * and purposes X is laterally dependent on Z too.
1336 : : *
1337 : : * This code is essentially Warshall's algorithm for transitive closure.
1338 : : * The outer loop considers each baserel, and propagates its lateral
1339 : : * dependencies to those baserels that have a lateral dependency on it.
1340 : : */
1341 [ + + ]: 30094 : for (rti = 1; rti < root->simple_rel_array_size; rti++)
1342 : : {
1343 : 23717 : RelOptInfo *brel = root->simple_rel_array[rti];
1344 : : Relids outer_lateral_relids;
1345 : : Index rti2;
1346 : :
1347 [ + + - + ]: 23717 : if (brel == NULL || brel->reloptkind != RELOPT_BASEREL)
1348 : 7750 : continue;
1349 : :
1350 : : /* need not consider baserel further if it has no lateral refs */
1351 : 15967 : outer_lateral_relids = brel->lateral_relids;
1352 [ + + ]: 15967 : if (outer_lateral_relids == NULL)
1353 : 9392 : continue;
1354 : :
1355 : : /* else scan all baserels */
1356 [ + + ]: 31661 : for (rti2 = 1; rti2 < root->simple_rel_array_size; rti2++)
1357 : : {
1358 : 25086 : RelOptInfo *brel2 = root->simple_rel_array[rti2];
1359 : :
1360 [ + + - + ]: 25086 : if (brel2 == NULL || brel2->reloptkind != RELOPT_BASEREL)
1361 : 8350 : continue;
1362 : :
1363 : : /* if brel2 has lateral ref to brel, propagate brel's refs */
1364 [ + + ]: 16736 : if (bms_is_member(rti, brel2->lateral_relids))
1365 : 88 : brel2->lateral_relids = bms_add_members(brel2->lateral_relids,
1366 : : outer_lateral_relids);
1367 : : }
1368 : : }
1369 : :
1370 : : /*
1371 : : * Now that we've identified all lateral references, mark each baserel
1372 : : * with the set of relids of rels that reference it laterally (possibly
1373 : : * indirectly) --- that is, the inverse mapping of lateral_relids.
1374 : : */
1375 [ + + ]: 30094 : for (rti = 1; rti < root->simple_rel_array_size; rti++)
1376 : : {
1377 : 23717 : RelOptInfo *brel = root->simple_rel_array[rti];
1378 : : Relids lateral_relids;
1379 : : int rti2;
1380 : :
1381 [ + + - + ]: 23717 : if (brel == NULL || brel->reloptkind != RELOPT_BASEREL)
1382 : 7750 : continue;
1383 : :
1384 : : /* Nothing to do at rels with no lateral refs */
1385 : 15967 : lateral_relids = brel->lateral_relids;
1386 [ + + ]: 15967 : if (bms_is_empty(lateral_relids))
1387 : 9392 : continue;
1388 : :
1389 : : /* No rel should have a lateral dependency on itself */
1390 : : Assert(!bms_is_member(rti, lateral_relids));
1391 : :
1392 : : /* Mark this rel's referencees */
1393 : 6575 : rti2 = -1;
1394 [ + + ]: 13850 : while ((rti2 = bms_next_member(lateral_relids, rti2)) >= 0)
1395 : : {
1396 : 7275 : RelOptInfo *brel2 = root->simple_rel_array[rti2];
1397 : :
1398 [ + + ]: 7275 : if (brel2 == NULL)
1399 : 45 : continue; /* must be an OJ */
1400 : :
1401 : : Assert(brel2->reloptkind == RELOPT_BASEREL);
1402 : 7230 : brel2->lateral_referencers =
1403 : 7230 : bms_add_member(brel2->lateral_referencers, rti);
1404 : : }
1405 : : }
1406 : : }
1407 : :
1408 : :
1409 : : /*****************************************************************************
1410 : : *
1411 : : * JOIN TREE PROCESSING
1412 : : *
1413 : : *****************************************************************************/
1414 : :
1415 : : /*
1416 : : * deconstruct_jointree
1417 : : * Recursively scan the query's join tree for WHERE and JOIN/ON qual
1418 : : * clauses, and add these to the appropriate restrictinfo and joininfo
1419 : : * lists belonging to base RelOptInfos. Also, add SpecialJoinInfo nodes
1420 : : * to root->join_info_list for any outer joins appearing in the query tree.
1421 : : * Return a "joinlist" data structure showing the join order decisions
1422 : : * that need to be made by make_one_rel().
1423 : : *
1424 : : * The "joinlist" result is a list of items that are either RangeTblRef
1425 : : * jointree nodes or sub-joinlists. All the items at the same level of
1426 : : * joinlist must be joined in an order to be determined by make_one_rel()
1427 : : * (note that legal orders may be constrained by SpecialJoinInfo nodes).
1428 : : * A sub-joinlist represents a subproblem to be planned separately. Currently
1429 : : * sub-joinlists arise only from FULL OUTER JOIN or when collapsing of
1430 : : * subproblems is stopped by join_collapse_limit or from_collapse_limit.
1431 : : */
1432 : : List *
1433 : 261681 : deconstruct_jointree(PlannerInfo *root)
1434 : : {
1435 : : List *result;
1436 : : JoinDomain *top_jdomain;
1437 : 261681 : List *item_list = NIL;
1438 : : ListCell *lc;
1439 : :
1440 : : /*
1441 : : * After this point, no more PlaceHolderInfos may be made, because
1442 : : * make_outerjoininfo requires all active placeholders to be present in
1443 : : * root->placeholder_list while we crawl up the join tree.
1444 : : */
1445 : 261681 : root->placeholdersFrozen = true;
1446 : :
1447 : : /* Fetch the already-created top-level join domain for the query */
1448 : 261681 : top_jdomain = linitial_node(JoinDomain, root->join_domains);
1449 : 261681 : top_jdomain->jd_relids = NULL; /* filled during deconstruct_recurse */
1450 : :
1451 : : /* Start recursion at top of jointree */
1452 : : Assert(root->parse->jointree != NULL &&
1453 : : IsA(root->parse->jointree, FromExpr));
1454 : :
1455 : : /* These are filled as we scan the jointree */
1456 : 261681 : root->all_baserels = NULL;
1457 : 261681 : root->outer_join_rels = NULL;
1458 : :
1459 : : /* Perform the initial scan of the jointree */
1460 : 261681 : result = deconstruct_recurse(root, (Node *) root->parse->jointree,
1461 : : top_jdomain, NULL,
1462 : : &item_list);
1463 : :
1464 : : /* Now we can form the value of all_query_rels, too */
1465 : 261681 : root->all_query_rels = bms_union(root->all_baserels, root->outer_join_rels);
1466 : :
1467 : : /* ... which should match what we computed for the top join domain */
1468 : : Assert(bms_equal(root->all_query_rels, top_jdomain->jd_relids));
1469 : :
1470 : : /* Now scan all the jointree nodes again, and distribute quals */
1471 [ + - + + : 1020857 : foreach(lc, item_list)
+ + ]
1472 : : {
1473 : 759176 : JoinTreeItem *jtitem = (JoinTreeItem *) lfirst(lc);
1474 : :
1475 : 759176 : deconstruct_distribute(root, jtitem);
1476 : : }
1477 : :
1478 : : /*
1479 : : * If there were any special joins then we may have some postponed LEFT
1480 : : * JOIN clauses to deal with.
1481 : : */
1482 [ + + ]: 261681 : if (root->join_info_list)
1483 : : {
1484 [ + - + + : 262328 : foreach(lc, item_list)
+ + ]
1485 : : {
1486 : 223315 : JoinTreeItem *jtitem = (JoinTreeItem *) lfirst(lc);
1487 : :
1488 [ + + ]: 223315 : if (jtitem->oj_joinclauses != NIL)
1489 : 34486 : deconstruct_distribute_oj_quals(root, item_list, jtitem);
1490 : : }
1491 : : }
1492 : :
1493 : : /* Don't need the JoinTreeItems any more */
1494 : 261681 : list_free_deep(item_list);
1495 : :
1496 : 261681 : return result;
1497 : : }
1498 : :
1499 : : /*
1500 : : * deconstruct_recurse
1501 : : * One recursion level of deconstruct_jointree's initial jointree scan.
1502 : : *
1503 : : * jtnode is the jointree node to examine, and parent_domain is the
1504 : : * enclosing join domain. (We must add all base+OJ relids appearing
1505 : : * here or below to parent_domain.) parent_jtitem is the JoinTreeItem
1506 : : * for the parent jointree node, or NULL at the top of the recursion.
1507 : : *
1508 : : * item_list is an in/out parameter: we add a JoinTreeItem struct to
1509 : : * that list for each jointree node, in depth-first traversal order.
1510 : : * (Hence, after each call, the last list item corresponds to its jtnode.)
1511 : : *
1512 : : * Return value is the appropriate joinlist for this jointree node.
1513 : : */
1514 : : static List *
1515 : 759176 : deconstruct_recurse(PlannerInfo *root, Node *jtnode,
1516 : : JoinDomain *parent_domain,
1517 : : JoinTreeItem *parent_jtitem,
1518 : : List **item_list)
1519 : : {
1520 : : List *joinlist;
1521 : : JoinTreeItem *jtitem;
1522 : :
1523 : : Assert(jtnode != NULL);
1524 : :
1525 : : /* Make the new JoinTreeItem, but don't add it to item_list yet */
1526 : 759176 : jtitem = palloc0_object(JoinTreeItem);
1527 : 759176 : jtitem->jtnode = jtnode;
1528 : 759176 : jtitem->jti_parent = parent_jtitem;
1529 : :
1530 [ + + ]: 759176 : if (IsA(jtnode, RangeTblRef))
1531 : : {
1532 : 390261 : int varno = ((RangeTblRef *) jtnode)->rtindex;
1533 : :
1534 : : /* Fill all_baserels as we encounter baserel jointree nodes */
1535 : 390261 : root->all_baserels = bms_add_member(root->all_baserels, varno);
1536 : : /* This node belongs to parent_domain */
1537 : 390261 : jtitem->jdomain = parent_domain;
1538 : 390261 : parent_domain->jd_relids = bms_add_member(parent_domain->jd_relids,
1539 : : varno);
1540 : : /* qualscope is just the one RTE */
1541 : 390261 : jtitem->qualscope = bms_make_singleton(varno);
1542 : : /* A single baserel does not create an inner join */
1543 : 390261 : jtitem->inner_join_rels = NULL;
1544 : 390261 : joinlist = list_make1(jtnode);
1545 : : }
1546 [ + + ]: 368915 : else if (IsA(jtnode, FromExpr))
1547 : : {
1548 : 276497 : FromExpr *f = (FromExpr *) jtnode;
1549 : : int remaining;
1550 : : ListCell *l;
1551 : :
1552 : : /* This node belongs to parent_domain, as do its children */
1553 : 276497 : jtitem->jdomain = parent_domain;
1554 : :
1555 : : /*
1556 : : * Recurse to handle child nodes, and compute output joinlist. We
1557 : : * collapse subproblems into a single joinlist whenever the resulting
1558 : : * joinlist wouldn't exceed from_collapse_limit members. Also, always
1559 : : * collapse one-element subproblems, since that won't lengthen the
1560 : : * joinlist anyway.
1561 : : */
1562 : 276497 : jtitem->qualscope = NULL;
1563 : 276497 : jtitem->inner_join_rels = NULL;
1564 : 276497 : joinlist = NIL;
1565 : 276497 : remaining = list_length(f->fromlist);
1566 [ + - + + : 589156 : foreach(l, f->fromlist)
+ + ]
1567 : : {
1568 : : JoinTreeItem *sub_item;
1569 : : List *sub_joinlist;
1570 : : int sub_members;
1571 : :
1572 : 312659 : sub_joinlist = deconstruct_recurse(root, lfirst(l),
1573 : : parent_domain,
1574 : : jtitem,
1575 : : item_list);
1576 : 312659 : sub_item = (JoinTreeItem *) llast(*item_list);
1577 : 625318 : jtitem->qualscope = bms_add_members(jtitem->qualscope,
1578 : 312659 : sub_item->qualscope);
1579 : 312659 : jtitem->inner_join_rels = sub_item->inner_join_rels;
1580 : 312659 : sub_members = list_length(sub_joinlist);
1581 : 312659 : remaining--;
1582 [ + + ]: 312659 : if (sub_members <= 1 ||
1583 [ + + ]: 62217 : list_length(joinlist) + sub_members + remaining <= from_collapse_limit)
1584 : 312619 : joinlist = list_concat(joinlist, sub_joinlist);
1585 : : else
1586 : 40 : joinlist = lappend(joinlist, sub_joinlist);
1587 : : }
1588 : :
1589 : : /*
1590 : : * A FROM with more than one list element is an inner join subsuming
1591 : : * all below it, so we should report inner_join_rels = qualscope. If
1592 : : * there was exactly one element, we should (and already did) report
1593 : : * whatever its inner_join_rels were. If there were no elements (is
1594 : : * that still possible?) the initialization before the loop fixed it.
1595 : : */
1596 [ + + ]: 276497 : if (list_length(f->fromlist) > 1)
1597 : 32280 : jtitem->inner_join_rels = jtitem->qualscope;
1598 : : }
1599 [ + - ]: 92418 : else if (IsA(jtnode, JoinExpr))
1600 : : {
1601 : 92418 : JoinExpr *j = (JoinExpr *) jtnode;
1602 : : JoinDomain *child_domain,
1603 : : *fj_domain;
1604 : : JoinTreeItem *left_item,
1605 : : *right_item;
1606 : : List *leftjoinlist,
1607 : : *rightjoinlist;
1608 : :
1609 [ + + + + : 92418 : switch (j->jointype)
- ]
1610 : : {
1611 : 42255 : case JOIN_INNER:
1612 : : /* This node belongs to parent_domain, as do its children */
1613 : 42255 : jtitem->jdomain = parent_domain;
1614 : : /* Recurse */
1615 : 42255 : leftjoinlist = deconstruct_recurse(root, j->larg,
1616 : : parent_domain,
1617 : : jtitem,
1618 : : item_list);
1619 : 42255 : left_item = (JoinTreeItem *) llast(*item_list);
1620 : 42255 : rightjoinlist = deconstruct_recurse(root, j->rarg,
1621 : : parent_domain,
1622 : : jtitem,
1623 : : item_list);
1624 : 42255 : right_item = (JoinTreeItem *) llast(*item_list);
1625 : : /* Compute qualscope etc */
1626 : 84510 : jtitem->qualscope = bms_union(left_item->qualscope,
1627 : 42255 : right_item->qualscope);
1628 : 42255 : jtitem->inner_join_rels = jtitem->qualscope;
1629 : 42255 : jtitem->left_rels = left_item->qualscope;
1630 : 42255 : jtitem->right_rels = right_item->qualscope;
1631 : : /* Inner join adds no restrictions for quals */
1632 : 42255 : jtitem->nonnullable_rels = NULL;
1633 : 42255 : break;
1634 : 44959 : case JOIN_LEFT:
1635 : : case JOIN_ANTI:
1636 : : /* Make new join domain for my quals and the RHS */
1637 : 44959 : child_domain = makeNode(JoinDomain);
1638 : 44959 : child_domain->jd_relids = NULL; /* filled by recursion */
1639 : 44959 : root->join_domains = lappend(root->join_domains, child_domain);
1640 : 44959 : jtitem->jdomain = child_domain;
1641 : : /* Recurse */
1642 : 44959 : leftjoinlist = deconstruct_recurse(root, j->larg,
1643 : : parent_domain,
1644 : : jtitem,
1645 : : item_list);
1646 : 44959 : left_item = (JoinTreeItem *) llast(*item_list);
1647 : 44959 : rightjoinlist = deconstruct_recurse(root, j->rarg,
1648 : : child_domain,
1649 : : jtitem,
1650 : : item_list);
1651 : 44959 : right_item = (JoinTreeItem *) llast(*item_list);
1652 : : /* Compute join domain contents, qualscope etc */
1653 : 44959 : parent_domain->jd_relids =
1654 : 44959 : bms_add_members(parent_domain->jd_relids,
1655 : 44959 : child_domain->jd_relids);
1656 : 89918 : jtitem->qualscope = bms_union(left_item->qualscope,
1657 : 44959 : right_item->qualscope);
1658 : : Assert(j->rtindex != 0);
1659 : 44959 : parent_domain->jd_relids =
1660 : 44959 : bms_add_member(parent_domain->jd_relids,
1661 : : j->rtindex);
1662 : 44959 : jtitem->qualscope = bms_add_member(jtitem->qualscope,
1663 : : j->rtindex);
1664 : 44959 : root->outer_join_rels = bms_add_member(root->outer_join_rels,
1665 : : j->rtindex);
1666 : 44959 : mark_rels_nulled_by_join(root, j->rtindex,
1667 : : right_item->qualscope);
1668 : 89918 : jtitem->inner_join_rels = bms_union(left_item->inner_join_rels,
1669 : 44959 : right_item->inner_join_rels);
1670 : 44959 : jtitem->left_rels = left_item->qualscope;
1671 : 44959 : jtitem->right_rels = right_item->qualscope;
1672 : 44959 : jtitem->nonnullable_rels = left_item->qualscope;
1673 : 44959 : break;
1674 : 4148 : case JOIN_SEMI:
1675 : : /* This node belongs to parent_domain, as do its children */
1676 : 4148 : jtitem->jdomain = parent_domain;
1677 : : /* Recurse */
1678 : 4148 : leftjoinlist = deconstruct_recurse(root, j->larg,
1679 : : parent_domain,
1680 : : jtitem,
1681 : : item_list);
1682 : 4148 : left_item = (JoinTreeItem *) llast(*item_list);
1683 : 4148 : rightjoinlist = deconstruct_recurse(root, j->rarg,
1684 : : parent_domain,
1685 : : jtitem,
1686 : : item_list);
1687 : 4148 : right_item = (JoinTreeItem *) llast(*item_list);
1688 : : /* Compute qualscope etc */
1689 : 8296 : jtitem->qualscope = bms_union(left_item->qualscope,
1690 : 4148 : right_item->qualscope);
1691 : : /* SEMI join never has rtindex, so don't add to anything */
1692 : : Assert(j->rtindex == 0);
1693 : 8296 : jtitem->inner_join_rels = bms_union(left_item->inner_join_rels,
1694 : 4148 : right_item->inner_join_rels);
1695 : 4148 : jtitem->left_rels = left_item->qualscope;
1696 : 4148 : jtitem->right_rels = right_item->qualscope;
1697 : : /* Semi join adds no restrictions for quals */
1698 : 4148 : jtitem->nonnullable_rels = NULL;
1699 : 4148 : break;
1700 : 1056 : case JOIN_FULL:
1701 : : /* The FULL JOIN's quals need their very own domain */
1702 : 1056 : fj_domain = makeNode(JoinDomain);
1703 : 1056 : root->join_domains = lappend(root->join_domains, fj_domain);
1704 : 1056 : jtitem->jdomain = fj_domain;
1705 : : /* Recurse, giving each side its own join domain */
1706 : 1056 : child_domain = makeNode(JoinDomain);
1707 : 1056 : child_domain->jd_relids = NULL; /* filled by recursion */
1708 : 1056 : root->join_domains = lappend(root->join_domains, child_domain);
1709 : 1056 : leftjoinlist = deconstruct_recurse(root, j->larg,
1710 : : child_domain,
1711 : : jtitem,
1712 : : item_list);
1713 : 1056 : left_item = (JoinTreeItem *) llast(*item_list);
1714 : 1056 : fj_domain->jd_relids = bms_copy(child_domain->jd_relids);
1715 : 1056 : child_domain = makeNode(JoinDomain);
1716 : 1056 : child_domain->jd_relids = NULL; /* filled by recursion */
1717 : 1056 : root->join_domains = lappend(root->join_domains, child_domain);
1718 : 1056 : rightjoinlist = deconstruct_recurse(root, j->rarg,
1719 : : child_domain,
1720 : : jtitem,
1721 : : item_list);
1722 : 1056 : right_item = (JoinTreeItem *) llast(*item_list);
1723 : : /* Compute qualscope etc */
1724 : 2112 : fj_domain->jd_relids = bms_add_members(fj_domain->jd_relids,
1725 : 1056 : child_domain->jd_relids);
1726 : 2112 : parent_domain->jd_relids = bms_add_members(parent_domain->jd_relids,
1727 : 1056 : fj_domain->jd_relids);
1728 : 2112 : jtitem->qualscope = bms_union(left_item->qualscope,
1729 : 1056 : right_item->qualscope);
1730 : : Assert(j->rtindex != 0);
1731 : 1056 : parent_domain->jd_relids = bms_add_member(parent_domain->jd_relids,
1732 : : j->rtindex);
1733 : 1056 : jtitem->qualscope = bms_add_member(jtitem->qualscope,
1734 : : j->rtindex);
1735 : 1056 : root->outer_join_rels = bms_add_member(root->outer_join_rels,
1736 : : j->rtindex);
1737 : 1056 : mark_rels_nulled_by_join(root, j->rtindex,
1738 : : left_item->qualscope);
1739 : 1056 : mark_rels_nulled_by_join(root, j->rtindex,
1740 : : right_item->qualscope);
1741 : 2112 : jtitem->inner_join_rels = bms_union(left_item->inner_join_rels,
1742 : 1056 : right_item->inner_join_rels);
1743 : 1056 : jtitem->left_rels = left_item->qualscope;
1744 : 1056 : jtitem->right_rels = right_item->qualscope;
1745 : : /* each side is both outer and inner */
1746 : 1056 : jtitem->nonnullable_rels = jtitem->qualscope;
1747 : 1056 : break;
1748 : 0 : default:
1749 : : /* JOIN_RIGHT was eliminated during reduce_outer_joins() */
1750 [ # # ]: 0 : elog(ERROR, "unrecognized join type: %d",
1751 : : (int) j->jointype);
1752 : : leftjoinlist = rightjoinlist = NIL; /* keep compiler quiet */
1753 : : break;
1754 : : }
1755 : :
1756 : : /*
1757 : : * Compute the output joinlist. We fold subproblems together except
1758 : : * at a FULL JOIN or where join_collapse_limit would be exceeded.
1759 : : */
1760 [ + + ]: 92418 : if (j->jointype == JOIN_FULL)
1761 : : {
1762 : : /* force the join order exactly at this node */
1763 : 1056 : joinlist = list_make1(list_make2(leftjoinlist, rightjoinlist));
1764 : : }
1765 [ + + ]: 91362 : else if (list_length(leftjoinlist) + list_length(rightjoinlist) <=
1766 : : join_collapse_limit)
1767 : : {
1768 : : /* OK to combine subproblems */
1769 : 91097 : joinlist = list_concat(leftjoinlist, rightjoinlist);
1770 : : }
1771 : : else
1772 : : {
1773 : : /* can't combine, but needn't force join order above here */
1774 : : Node *leftpart,
1775 : : *rightpart;
1776 : :
1777 : : /* avoid creating useless 1-element sublists */
1778 [ + + ]: 265 : if (list_length(leftjoinlist) == 1)
1779 : 55 : leftpart = (Node *) linitial(leftjoinlist);
1780 : : else
1781 : 210 : leftpart = (Node *) leftjoinlist;
1782 [ + + ]: 265 : if (list_length(rightjoinlist) == 1)
1783 : 50 : rightpart = (Node *) linitial(rightjoinlist);
1784 : : else
1785 : 215 : rightpart = (Node *) rightjoinlist;
1786 : 265 : joinlist = list_make2(leftpart, rightpart);
1787 : : }
1788 : : }
1789 : : else
1790 : : {
1791 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
1792 : : (int) nodeTag(jtnode));
1793 : : joinlist = NIL; /* keep compiler quiet */
1794 : : }
1795 : :
1796 : : /* Finally, we can add the new JoinTreeItem to item_list */
1797 : 759176 : *item_list = lappend(*item_list, jtitem);
1798 : :
1799 : 759176 : return joinlist;
1800 : : }
1801 : :
1802 : : /*
1803 : : * deconstruct_distribute
1804 : : * Process one jointree node in phase 2 of deconstruct_jointree processing.
1805 : : *
1806 : : * Distribute quals of the node to appropriate restriction and join lists.
1807 : : * In addition, entries will be added to root->join_info_list for outer joins.
1808 : : */
1809 : : static void
1810 : 759176 : deconstruct_distribute(PlannerInfo *root, JoinTreeItem *jtitem)
1811 : : {
1812 : 759176 : Node *jtnode = jtitem->jtnode;
1813 : :
1814 [ + + ]: 759176 : if (IsA(jtnode, RangeTblRef))
1815 : : {
1816 : 390261 : int varno = ((RangeTblRef *) jtnode)->rtindex;
1817 : :
1818 : : /* Deal with any securityQuals attached to the RTE */
1819 [ + + ]: 390261 : if (root->qual_security_level > 0)
1820 : 2752 : process_security_barrier_quals(root,
1821 : : varno,
1822 : : jtitem);
1823 : : }
1824 [ + + ]: 368915 : else if (IsA(jtnode, FromExpr))
1825 : : {
1826 : 276497 : FromExpr *f = (FromExpr *) jtnode;
1827 : :
1828 : : /*
1829 : : * Process any lateral-referencing quals that were postponed to this
1830 : : * level by children.
1831 : : */
1832 : 276497 : distribute_quals_to_rels(root, jtitem->lateral_clauses,
1833 : : jtitem,
1834 : : NULL,
1835 : : root->qual_security_level,
1836 : : jtitem->qualscope,
1837 : : NULL, NULL, NULL,
1838 : : true, false, false,
1839 : : NULL);
1840 : :
1841 : : /*
1842 : : * Now process the top-level quals.
1843 : : */
1844 : 276497 : distribute_quals_to_rels(root, (List *) f->quals,
1845 : : jtitem,
1846 : : NULL,
1847 : : root->qual_security_level,
1848 : : jtitem->qualscope,
1849 : : NULL, NULL, NULL,
1850 : : true, false, false,
1851 : : NULL);
1852 : : }
1853 [ + - ]: 92418 : else if (IsA(jtnode, JoinExpr))
1854 : : {
1855 : 92418 : JoinExpr *j = (JoinExpr *) jtnode;
1856 : : Relids ojscope;
1857 : : List *my_quals;
1858 : : SpecialJoinInfo *sjinfo;
1859 : : List **postponed_oj_qual_list;
1860 : :
1861 : : /*
1862 : : * Include lateral-referencing quals postponed from children in
1863 : : * my_quals, so that they'll be handled properly in
1864 : : * make_outerjoininfo. (This is destructive to
1865 : : * jtitem->lateral_clauses, but we won't use that again.)
1866 : : */
1867 : 92418 : my_quals = list_concat(jtitem->lateral_clauses,
1868 : 92418 : (List *) j->quals);
1869 : :
1870 : : /*
1871 : : * For an OJ, form the SpecialJoinInfo now, so that we can pass it to
1872 : : * distribute_qual_to_rels. We must compute its ojscope too.
1873 : : *
1874 : : * Semijoins are a bit of a hybrid: we build a SpecialJoinInfo, but we
1875 : : * want ojscope = NULL for distribute_qual_to_rels.
1876 : : */
1877 [ + + ]: 92418 : if (j->jointype != JOIN_INNER)
1878 : : {
1879 : 50163 : sjinfo = make_outerjoininfo(root,
1880 : : jtitem->left_rels,
1881 : : jtitem->right_rels,
1882 : : jtitem->inner_join_rels,
1883 : : j->jointype,
1884 : 50163 : j->rtindex,
1885 : : my_quals);
1886 : 50163 : jtitem->sjinfo = sjinfo;
1887 [ + + ]: 50163 : if (j->jointype == JOIN_SEMI)
1888 : 4148 : ojscope = NULL;
1889 : : else
1890 : 46015 : ojscope = bms_union(sjinfo->min_lefthand,
1891 : 46015 : sjinfo->min_righthand);
1892 : : }
1893 : : else
1894 : : {
1895 : 42255 : sjinfo = NULL;
1896 : 42255 : ojscope = NULL;
1897 : : }
1898 : :
1899 : : /*
1900 : : * If it's a left join with a join clause that is strict for the LHS,
1901 : : * then we need to postpone handling of any non-degenerate join
1902 : : * clauses, in case the join is able to commute with another left join
1903 : : * per identity 3. (Degenerate clauses need not be postponed, since
1904 : : * they will drop down below this join anyway.)
1905 : : */
1906 [ + + + + ]: 92418 : if (j->jointype == JOIN_LEFT && sjinfo->lhs_strict)
1907 : : {
1908 : 34486 : postponed_oj_qual_list = &jtitem->oj_joinclauses;
1909 : :
1910 : : /*
1911 : : * Add back any commutable lower OJ relids that were removed from
1912 : : * min_lefthand or min_righthand, else the ojscope cross-check in
1913 : : * distribute_qual_to_rels will complain. Since we are postponing
1914 : : * processing of non-degenerate clauses, this addition doesn't
1915 : : * affect anything except that cross-check. Real clause
1916 : : * positioning decisions will be made later, when we revisit the
1917 : : * postponed clauses.
1918 : : */
1919 : 34486 : ojscope = bms_add_members(ojscope, sjinfo->commute_below_l);
1920 : 34486 : ojscope = bms_add_members(ojscope, sjinfo->commute_below_r);
1921 : : }
1922 : : else
1923 : 57932 : postponed_oj_qual_list = NULL;
1924 : :
1925 : : /* Process the JOIN's qual clauses */
1926 : 92418 : distribute_quals_to_rels(root, my_quals,
1927 : : jtitem,
1928 : : sjinfo,
1929 : : root->qual_security_level,
1930 : : jtitem->qualscope,
1931 : : ojscope, jtitem->nonnullable_rels,
1932 : : NULL, /* incompatible_relids */
1933 : : true, /* allow_equivalence */
1934 : : false, false, /* not clones */
1935 : : postponed_oj_qual_list);
1936 : :
1937 : : /* And add the SpecialJoinInfo to join_info_list */
1938 [ + + ]: 92418 : if (sjinfo)
1939 : 50163 : root->join_info_list = lappend(root->join_info_list, sjinfo);
1940 : : }
1941 : : else
1942 : : {
1943 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
1944 : : (int) nodeTag(jtnode));
1945 : : }
1946 : 759176 : }
1947 : :
1948 : : /*
1949 : : * process_security_barrier_quals
1950 : : * Transfer security-barrier quals into relation's baserestrictinfo list.
1951 : : *
1952 : : * The rewriter put any relevant security-barrier conditions into the RTE's
1953 : : * securityQuals field, but it's now time to copy them into the rel's
1954 : : * baserestrictinfo.
1955 : : *
1956 : : * In inheritance cases, we only consider quals attached to the parent rel
1957 : : * here; they will be valid for all children too, so it's okay to consider
1958 : : * them for purposes like equivalence class creation. Quals attached to
1959 : : * individual child rels will be dealt with during path creation.
1960 : : */
1961 : : static void
1962 : 2752 : process_security_barrier_quals(PlannerInfo *root,
1963 : : int rti, JoinTreeItem *jtitem)
1964 : : {
1965 : 2752 : RangeTblEntry *rte = root->simple_rte_array[rti];
1966 : 2752 : Index security_level = 0;
1967 : : ListCell *lc;
1968 : :
1969 : : /*
1970 : : * Each element of the securityQuals list has been preprocessed into an
1971 : : * implicitly-ANDed list of clauses. All the clauses in a given sublist
1972 : : * should get the same security level, but successive sublists get higher
1973 : : * levels.
1974 : : */
1975 [ + + + + : 5597 : foreach(lc, rte->securityQuals)
+ + ]
1976 : : {
1977 : 2845 : List *qualset = (List *) lfirst(lc);
1978 : :
1979 : : /*
1980 : : * We cheat to the extent of passing ojscope = qualscope rather than
1981 : : * its more logical value of NULL. The only effect this has is to
1982 : : * force a Var-free qual to be evaluated at the rel rather than being
1983 : : * pushed up to top of tree, which we don't want.
1984 : : */
1985 : 2845 : distribute_quals_to_rels(root, qualset,
1986 : : jtitem,
1987 : : NULL,
1988 : : security_level,
1989 : : jtitem->qualscope,
1990 : : jtitem->qualscope,
1991 : : NULL,
1992 : : NULL,
1993 : : true,
1994 : : false, false, /* not clones */
1995 : : NULL);
1996 : 2845 : security_level++;
1997 : : }
1998 : :
1999 : : /* Assert that qual_security_level is higher than anything we just used */
2000 : : Assert(security_level <= root->qual_security_level);
2001 : 2752 : }
2002 : :
2003 : : /*
2004 : : * mark_rels_nulled_by_join
2005 : : * Fill RelOptInfo.nulling_relids of baserels nulled by this outer join
2006 : : *
2007 : : * Inputs:
2008 : : * ojrelid: RT index of the join RTE (must not be 0)
2009 : : * lower_rels: the base+OJ Relids syntactically below nullable side of join
2010 : : */
2011 : : static void
2012 : 47071 : mark_rels_nulled_by_join(PlannerInfo *root, Index ojrelid,
2013 : : Relids lower_rels)
2014 : : {
2015 : 47071 : int relid = -1;
2016 : :
2017 [ + + ]: 97464 : while ((relid = bms_next_member(lower_rels, relid)) > 0)
2018 : : {
2019 : 50393 : RelOptInfo *rel = root->simple_rel_array[relid];
2020 : :
2021 : : /* ignore the RTE_GROUP RTE */
2022 [ - + ]: 50393 : if (relid == root->group_rtindex)
2023 : 0 : continue;
2024 : :
2025 [ + + ]: 50393 : if (rel == NULL) /* must be an outer join */
2026 : : {
2027 : : Assert(bms_is_member(relid, root->outer_join_rels));
2028 : 906 : continue;
2029 : : }
2030 : 49487 : rel->nulling_relids = bms_add_member(rel->nulling_relids, ojrelid);
2031 : : }
2032 : 47071 : }
2033 : :
2034 : : /*
2035 : : * make_outerjoininfo
2036 : : * Build a SpecialJoinInfo for the current outer join
2037 : : *
2038 : : * Inputs:
2039 : : * left_rels: the base+OJ Relids syntactically on outer side of join
2040 : : * right_rels: the base+OJ Relids syntactically on inner side of join
2041 : : * inner_join_rels: base+OJ Relids participating in inner joins below this one
2042 : : * jointype: what it says (must always be LEFT, FULL, SEMI, or ANTI)
2043 : : * ojrelid: RT index of the join RTE (0 for SEMI, which isn't in the RT list)
2044 : : * clause: the outer join's join condition (in implicit-AND format)
2045 : : *
2046 : : * The node should eventually be appended to root->join_info_list, but we
2047 : : * do not do that here.
2048 : : *
2049 : : * Note: we assume that this function is invoked bottom-up, so that
2050 : : * root->join_info_list already contains entries for all outer joins that are
2051 : : * syntactically below this one.
2052 : : */
2053 : : static SpecialJoinInfo *
2054 : 50163 : make_outerjoininfo(PlannerInfo *root,
2055 : : Relids left_rels, Relids right_rels,
2056 : : Relids inner_join_rels,
2057 : : JoinType jointype, Index ojrelid,
2058 : : List *clause)
2059 : : {
2060 : 50163 : SpecialJoinInfo *sjinfo = makeNode(SpecialJoinInfo);
2061 : : Relids clause_relids;
2062 : : Relids strict_relids;
2063 : : Relids min_lefthand;
2064 : : Relids min_righthand;
2065 : : Relids commute_below_l;
2066 : : Relids commute_below_r;
2067 : : ListCell *l;
2068 : :
2069 : : /*
2070 : : * We should not see RIGHT JOIN here because left/right were switched
2071 : : * earlier
2072 : : */
2073 : : Assert(jointype != JOIN_INNER);
2074 : : Assert(jointype != JOIN_RIGHT);
2075 : :
2076 : : /*
2077 : : * Presently the executor cannot support FOR [KEY] UPDATE/SHARE marking of
2078 : : * rels appearing on the nullable side of an outer join. (It's somewhat
2079 : : * unclear what that would mean, anyway: what should we mark when a result
2080 : : * row is generated from no element of the nullable relation?) So,
2081 : : * complain if any nullable rel is FOR [KEY] UPDATE/SHARE.
2082 : : *
2083 : : * You might be wondering why this test isn't made far upstream in the
2084 : : * parser. It's because the parser hasn't got enough info --- consider
2085 : : * FOR UPDATE applied to a view. Only after rewriting and flattening do
2086 : : * we know whether the view contains an outer join.
2087 : : *
2088 : : * We use the original RowMarkClause list here; the PlanRowMark list would
2089 : : * list everything.
2090 : : */
2091 [ + + + + : 50185 : foreach(l, root->parse->rowMarks)
+ + ]
2092 : : {
2093 : 22 : RowMarkClause *rc = (RowMarkClause *) lfirst(l);
2094 : :
2095 [ + - + + ]: 22 : if (bms_is_member(rc->rti, right_rels) ||
2096 [ - + ]: 4 : (jointype == JOIN_FULL && bms_is_member(rc->rti, left_rels)))
2097 [ # # ]: 0 : ereport(ERROR,
2098 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2099 : : /*------
2100 : : translator: %s is a SQL row locking clause such as FOR UPDATE */
2101 : : errmsg("%s cannot be applied to the nullable side of an outer join",
2102 : : LCS_asString(rc->strength))));
2103 : : }
2104 : :
2105 : 50163 : sjinfo->syn_lefthand = left_rels;
2106 : 50163 : sjinfo->syn_righthand = right_rels;
2107 : 50163 : sjinfo->jointype = jointype;
2108 : 50163 : sjinfo->ojrelid = ojrelid;
2109 : : /* these fields may get added to later: */
2110 : 50163 : sjinfo->commute_above_l = NULL;
2111 : 50163 : sjinfo->commute_above_r = NULL;
2112 : 50163 : sjinfo->commute_below_l = NULL;
2113 : 50163 : sjinfo->commute_below_r = NULL;
2114 : :
2115 : 50163 : compute_semijoin_info(root, sjinfo, clause);
2116 : :
2117 : : /* If it's a full join, no need to be very smart */
2118 [ + + ]: 50163 : if (jointype == JOIN_FULL)
2119 : : {
2120 : 1056 : sjinfo->min_lefthand = bms_copy(left_rels);
2121 : 1056 : sjinfo->min_righthand = bms_copy(right_rels);
2122 : 1056 : sjinfo->lhs_strict = false; /* don't care about this */
2123 : 1056 : return sjinfo;
2124 : : }
2125 : :
2126 : : /*
2127 : : * Retrieve all relids mentioned within the join clause.
2128 : : */
2129 : 49107 : clause_relids = pull_varnos(root, (Node *) clause);
2130 : :
2131 : : /*
2132 : : * For which relids is the clause strict, ie, it cannot succeed if the
2133 : : * rel's columns are all NULL?
2134 : : */
2135 : 49107 : strict_relids = find_nonnullable_rels((Node *) clause);
2136 : :
2137 : : /*
2138 : : * find_nonnullable_rels looks inside PlaceHolderVars, so it can report
2139 : : * rels that the clause references only laterally. Ignore those, since
2140 : : * like clause_relids we treat a PHV as computed at its ph_eval_at.
2141 : : */
2142 : 49107 : strict_relids = bms_int_members(strict_relids, clause_relids);
2143 : :
2144 : : /* Remember whether the clause is strict for any LHS relations */
2145 : 49107 : sjinfo->lhs_strict = bms_overlap(strict_relids, left_rels);
2146 : :
2147 : : /*
2148 : : * Required LHS always includes the LHS rels mentioned in the clause. We
2149 : : * may have to add more rels based on lower outer joins; see below.
2150 : : */
2151 : 49107 : min_lefthand = bms_intersect(clause_relids, left_rels);
2152 : :
2153 : : /*
2154 : : * Similarly for required RHS. But here, we must also include any lower
2155 : : * inner joins, to ensure we don't try to commute with any of them.
2156 : : */
2157 : 49107 : min_righthand = bms_int_members(bms_union(clause_relids, inner_join_rels),
2158 : : right_rels);
2159 : :
2160 : : /*
2161 : : * Now check previous outer joins for ordering restrictions.
2162 : : *
2163 : : * commute_below_l and commute_below_r accumulate the relids of lower
2164 : : * outer joins that we think this one can commute with. These decisions
2165 : : * are just tentative within this loop, since we might find an
2166 : : * intermediate outer join that prevents commutation. Surviving relids
2167 : : * will get merged into the SpecialJoinInfo structs afterwards.
2168 : : */
2169 : 49107 : commute_below_l = commute_below_r = NULL;
2170 [ + + + + : 62371 : foreach(l, root->join_info_list)
+ + ]
2171 : : {
2172 : 13264 : SpecialJoinInfo *otherinfo = (SpecialJoinInfo *) lfirst(l);
2173 : : bool have_unsafe_phvs;
2174 : :
2175 : : /*
2176 : : * A full join is an optimization barrier: we can't associate into or
2177 : : * out of it. Hence, if it overlaps either LHS or RHS of the current
2178 : : * rel, expand that side's min relset to cover the whole full join.
2179 : : */
2180 [ + + ]: 13264 : if (otherinfo->jointype == JOIN_FULL)
2181 : : {
2182 : : Assert(otherinfo->ojrelid != 0);
2183 [ + + - + ]: 95 : if (bms_overlap(left_rels, otherinfo->syn_lefthand) ||
2184 : 35 : bms_overlap(left_rels, otherinfo->syn_righthand))
2185 : : {
2186 : 25 : min_lefthand = bms_add_members(min_lefthand,
2187 : 25 : otherinfo->syn_lefthand);
2188 : 25 : min_lefthand = bms_add_members(min_lefthand,
2189 : 25 : otherinfo->syn_righthand);
2190 : 25 : min_lefthand = bms_add_member(min_lefthand,
2191 : 25 : otherinfo->ojrelid);
2192 : : }
2193 [ + + - + ]: 85 : if (bms_overlap(right_rels, otherinfo->syn_lefthand) ||
2194 : 25 : bms_overlap(right_rels, otherinfo->syn_righthand))
2195 : : {
2196 : 35 : min_righthand = bms_add_members(min_righthand,
2197 : 35 : otherinfo->syn_lefthand);
2198 : 35 : min_righthand = bms_add_members(min_righthand,
2199 : 35 : otherinfo->syn_righthand);
2200 : 35 : min_righthand = bms_add_member(min_righthand,
2201 : 35 : otherinfo->ojrelid);
2202 : : }
2203 : : /* Needn't do anything else with the full join */
2204 : 60 : continue;
2205 : : }
2206 : :
2207 : : /*
2208 : : * If our join condition contains any PlaceHolderVars that need to be
2209 : : * evaluated above the lower OJ, then we can't commute with it.
2210 : : */
2211 [ + + ]: 13204 : if (otherinfo->ojrelid != 0)
2212 : : have_unsafe_phvs =
2213 : 13058 : contain_placeholder_references_to(root,
2214 : : (Node *) clause,
2215 : 13058 : otherinfo->ojrelid);
2216 : : else
2217 : 146 : have_unsafe_phvs = false;
2218 : :
2219 : : /*
2220 : : * For a lower OJ in our LHS, if our join condition uses the lower
2221 : : * join's RHS and is not strict for that rel, we must preserve the
2222 : : * ordering of the two OJs, so add lower OJ's full syntactic relset to
2223 : : * min_lefthand. (We must use its full syntactic relset, not just its
2224 : : * min_lefthand + min_righthand. This is because there might be other
2225 : : * OJs below this one that this one can commute with, but we cannot
2226 : : * commute with them if we don't with this one.) Also, if we have
2227 : : * unsafe PHVs or the current join is a semijoin or antijoin, we must
2228 : : * preserve ordering regardless of strictness.
2229 : : *
2230 : : * Note: I believe we have to insist on being strict for at least one
2231 : : * rel in the lower OJ's min_righthand, not its whole syn_righthand.
2232 : : *
2233 : : * When we don't need to preserve ordering, check to see if outer join
2234 : : * identity 3 applies, and if so, remove the lower OJ's ojrelid from
2235 : : * our min_lefthand so that commutation is allowed.
2236 : : */
2237 [ + + ]: 13204 : if (bms_overlap(left_rels, otherinfo->syn_righthand))
2238 : : {
2239 [ + + + + ]: 12278 : if (bms_overlap(clause_relids, otherinfo->syn_righthand) &&
2240 [ + - ]: 2870 : (have_unsafe_phvs ||
2241 [ + - ]: 2870 : jointype == JOIN_SEMI || jointype == JOIN_ANTI ||
2242 [ + + ]: 2870 : !bms_overlap(strict_relids, otherinfo->min_righthand)))
2243 : : {
2244 : : /* Preserve ordering */
2245 : 40 : min_lefthand = bms_add_members(min_lefthand,
2246 : 40 : otherinfo->syn_lefthand);
2247 : 40 : min_lefthand = bms_add_members(min_lefthand,
2248 : 40 : otherinfo->syn_righthand);
2249 [ + - ]: 40 : if (otherinfo->ojrelid != 0)
2250 : 40 : min_lefthand = bms_add_member(min_lefthand,
2251 : 40 : otherinfo->ojrelid);
2252 : : }
2253 [ + + ]: 12238 : else if (jointype == JOIN_LEFT &&
2254 [ + + + + ]: 23633 : otherinfo->jointype == JOIN_LEFT &&
2255 : 11813 : bms_overlap(strict_relids, otherinfo->min_righthand) &&
2256 [ + + ]: 2835 : !bms_overlap(clause_relids, otherinfo->syn_lefthand))
2257 : : {
2258 : : /* Identity 3 applies, so remove the ordering restriction */
2259 : 2786 : min_lefthand = bms_del_member(min_lefthand, otherinfo->ojrelid);
2260 : : /* Record the (still tentative) commutability relationship */
2261 : : commute_below_l =
2262 : 2786 : bms_add_member(commute_below_l, otherinfo->ojrelid);
2263 : : }
2264 : : }
2265 : :
2266 : : /*
2267 : : * For a lower OJ in our RHS, if our join condition does not use the
2268 : : * lower join's RHS and the lower OJ's join condition is strict, we
2269 : : * can interchange the ordering of the two OJs; otherwise we must add
2270 : : * the lower OJ's full syntactic relset to min_righthand.
2271 : : *
2272 : : * Also, if our join condition does not use the lower join's LHS
2273 : : * either, force the ordering to be preserved. Otherwise we can end
2274 : : * up with SpecialJoinInfos with identical min_righthands, which can
2275 : : * confuse join_is_legal (see discussion in backend/optimizer/README).
2276 : : *
2277 : : * Also, we must preserve ordering anyway if we have unsafe PHVs, or
2278 : : * if either this join or the lower OJ is a semijoin or antijoin.
2279 : : *
2280 : : * When we don't need to preserve ordering, check to see if outer join
2281 : : * identity 3 applies, and if so, remove the lower OJ's ojrelid from
2282 : : * our min_righthand so that commutation is allowed.
2283 : : */
2284 [ + + ]: 13204 : if (bms_overlap(right_rels, otherinfo->syn_righthand))
2285 : : {
2286 [ + + ]: 836 : if (bms_overlap(clause_relids, otherinfo->syn_righthand) ||
2287 [ + + + - ]: 796 : !bms_overlap(clause_relids, otherinfo->min_lefthand) ||
2288 [ + + ]: 400 : have_unsafe_phvs ||
2289 [ + + ]: 327 : jointype == JOIN_SEMI ||
2290 : 287 : jointype == JOIN_ANTI ||
2291 [ + + ]: 287 : otherinfo->jointype == JOIN_SEMI ||
2292 [ + - ]: 253 : otherinfo->jointype == JOIN_ANTI ||
2293 [ + + ]: 253 : !otherinfo->lhs_strict)
2294 : : {
2295 : : /* Preserve ordering */
2296 : 613 : min_righthand = bms_add_members(min_righthand,
2297 : 613 : otherinfo->syn_lefthand);
2298 : 613 : min_righthand = bms_add_members(min_righthand,
2299 : 613 : otherinfo->syn_righthand);
2300 [ + + ]: 613 : if (otherinfo->ojrelid != 0)
2301 : 511 : min_righthand = bms_add_member(min_righthand,
2302 : 511 : otherinfo->ojrelid);
2303 : : }
2304 [ + - ]: 223 : else if (jointype == JOIN_LEFT &&
2305 [ + - ]: 223 : otherinfo->jointype == JOIN_LEFT &&
2306 [ + - ]: 223 : otherinfo->lhs_strict)
2307 : : {
2308 : : /* Identity 3 applies, so remove the ordering restriction */
2309 : 223 : min_righthand = bms_del_member(min_righthand,
2310 : 223 : otherinfo->ojrelid);
2311 : : /* Record the (still tentative) commutability relationship */
2312 : : commute_below_r =
2313 : 223 : bms_add_member(commute_below_r, otherinfo->ojrelid);
2314 : : }
2315 : : }
2316 : : }
2317 : :
2318 : : /*
2319 : : * Examine PlaceHolderVars. If a PHV is supposed to be evaluated within
2320 : : * this join's nullable side, then ensure that min_righthand contains the
2321 : : * full eval_at set of the PHV. This ensures that the PHV actually can be
2322 : : * evaluated within the RHS. Note that this works only because we should
2323 : : * already have determined the final eval_at level for any PHV
2324 : : * syntactically within this join.
2325 : : */
2326 [ + + + + : 50891 : foreach(l, root->placeholder_list)
+ + ]
2327 : : {
2328 : 1784 : PlaceHolderInfo *phinfo = (PlaceHolderInfo *) lfirst(l);
2329 : 1784 : Relids ph_syn_level = phinfo->ph_var->phrels;
2330 : :
2331 : : /* Ignore placeholder if it didn't syntactically come from RHS */
2332 [ + + ]: 1784 : if (!bms_is_subset(ph_syn_level, right_rels))
2333 : 678 : continue;
2334 : :
2335 : : /* Else, prevent join from being formed before we eval the PHV */
2336 : 1106 : min_righthand = bms_add_members(min_righthand, phinfo->ph_eval_at);
2337 : : }
2338 : :
2339 : : /*
2340 : : * If we found nothing to put in min_lefthand, punt and make it the full
2341 : : * LHS, to avoid having an empty min_lefthand which will confuse later
2342 : : * processing. (We don't try to be smart about such cases, just correct.)
2343 : : * Likewise for min_righthand.
2344 : : */
2345 [ + + ]: 49107 : if (bms_is_empty(min_lefthand))
2346 : 1777 : min_lefthand = bms_copy(left_rels);
2347 [ + + ]: 49107 : if (bms_is_empty(min_righthand))
2348 : 1225 : min_righthand = bms_copy(right_rels);
2349 : :
2350 : : /* Now they'd better be nonempty */
2351 : : Assert(!bms_is_empty(min_lefthand));
2352 : : Assert(!bms_is_empty(min_righthand));
2353 : : /* Shouldn't overlap either */
2354 : : Assert(!bms_overlap(min_lefthand, min_righthand));
2355 : :
2356 : 49107 : sjinfo->min_lefthand = min_lefthand;
2357 : 49107 : sjinfo->min_righthand = min_righthand;
2358 : :
2359 : : /*
2360 : : * Now that we've identified the correct min_lefthand and min_righthand,
2361 : : * any commute_below_l or commute_below_r relids that have not gotten
2362 : : * added back into those sets (due to intervening outer joins) are indeed
2363 : : * commutable with this one.
2364 : : *
2365 : : * First, delete any subsequently-added-back relids (this is easier than
2366 : : * maintaining commute_below_l/r precisely through all the above).
2367 : : */
2368 : 49107 : commute_below_l = bms_del_members(commute_below_l, min_lefthand);
2369 : 49107 : commute_below_r = bms_del_members(commute_below_r, min_righthand);
2370 : :
2371 : : /* Anything left? */
2372 [ + + + + ]: 49107 : if (commute_below_l || commute_below_r)
2373 : : {
2374 : : /* Yup, so we must update the derived data in the SpecialJoinInfos */
2375 : 2899 : sjinfo->commute_below_l = commute_below_l;
2376 : 2899 : sjinfo->commute_below_r = commute_below_r;
2377 [ + - + + : 6477 : foreach(l, root->join_info_list)
+ + ]
2378 : : {
2379 : 3578 : SpecialJoinInfo *otherinfo = (SpecialJoinInfo *) lfirst(l);
2380 : :
2381 [ + + ]: 3578 : if (bms_is_member(otherinfo->ojrelid, commute_below_l))
2382 : 2786 : otherinfo->commute_above_l =
2383 : 2786 : bms_add_member(otherinfo->commute_above_l, ojrelid);
2384 [ + + ]: 792 : else if (bms_is_member(otherinfo->ojrelid, commute_below_r))
2385 : 198 : otherinfo->commute_above_r =
2386 : 198 : bms_add_member(otherinfo->commute_above_r, ojrelid);
2387 : : }
2388 : : }
2389 : :
2390 : 49107 : return sjinfo;
2391 : : }
2392 : :
2393 : : /*
2394 : : * compute_semijoin_info
2395 : : * Fill semijoin-related fields of a new SpecialJoinInfo
2396 : : *
2397 : : * Note: this relies on only the jointype and syn_righthand fields of the
2398 : : * SpecialJoinInfo; the rest may not be set yet.
2399 : : */
2400 : : static void
2401 : 50163 : compute_semijoin_info(PlannerInfo *root, SpecialJoinInfo *sjinfo, List *clause)
2402 : : {
2403 : : List *semi_operators;
2404 : : List *semi_rhs_exprs;
2405 : : bool all_btree;
2406 : : bool all_hash;
2407 : : ListCell *lc;
2408 : :
2409 : : /* Initialize semijoin-related fields in case we can't unique-ify */
2410 : 50163 : sjinfo->semi_can_btree = false;
2411 : 50163 : sjinfo->semi_can_hash = false;
2412 : 50163 : sjinfo->semi_operators = NIL;
2413 : 50163 : sjinfo->semi_rhs_exprs = NIL;
2414 : :
2415 : : /* Nothing more to do if it's not a semijoin */
2416 [ + + ]: 50163 : if (sjinfo->jointype != JOIN_SEMI)
2417 : 46015 : return;
2418 : :
2419 : : /*
2420 : : * Look to see whether the semijoin's join quals consist of AND'ed
2421 : : * equality operators, with (only) RHS variables on only one side of each
2422 : : * one. If so, we can figure out how to enforce uniqueness for the RHS.
2423 : : *
2424 : : * Note that the input clause list is the list of quals that are
2425 : : * *syntactically* associated with the semijoin, which in practice means
2426 : : * the synthesized comparison list for an IN or the WHERE of an EXISTS.
2427 : : * Particularly in the latter case, it might contain clauses that aren't
2428 : : * *semantically* associated with the join, but refer to just one side or
2429 : : * the other. We can ignore such clauses here, as they will just drop
2430 : : * down to be processed within one side or the other. (It is okay to
2431 : : * consider only the syntactically-associated clauses here because for a
2432 : : * semijoin, no higher-level quals could refer to the RHS, and so there
2433 : : * can be no other quals that are semantically associated with this join.
2434 : : * We do things this way because it is useful to have the set of potential
2435 : : * unique-ification expressions before we can extract the list of quals
2436 : : * that are actually semantically associated with the particular join.)
2437 : : *
2438 : : * Note that the semi_operators list consists of the joinqual operators
2439 : : * themselves (but commuted if needed to put the RHS value on the right).
2440 : : * These could be cross-type operators, in which case the operator
2441 : : * actually needed for uniqueness is a related single-type operator. We
2442 : : * assume here that that operator will be available from the btree or hash
2443 : : * opclass when the time comes ... if not, create_unique_plan() will fail.
2444 : : */
2445 : 4148 : semi_operators = NIL;
2446 : 4148 : semi_rhs_exprs = NIL;
2447 : 4148 : all_btree = true;
2448 : 4148 : all_hash = enable_hashagg; /* don't consider hash if not enabled */
2449 [ + - + + : 8619 : foreach(lc, clause)
+ + ]
2450 : : {
2451 : 4560 : OpExpr *op = (OpExpr *) lfirst(lc);
2452 : : Oid opno;
2453 : : Node *left_expr;
2454 : : Node *right_expr;
2455 : : Relids left_varnos;
2456 : : Relids right_varnos;
2457 : : Relids all_varnos;
2458 : : Oid opinputtype;
2459 : :
2460 : : /* Is it a binary opclause? */
2461 [ + + - + ]: 9026 : if (!IsA(op, OpExpr) ||
2462 : 4466 : list_length(op->args) != 2)
2463 : : {
2464 : : /* No, but does it reference both sides? */
2465 : 94 : all_varnos = pull_varnos(root, (Node *) op);
2466 [ + + + + ]: 178 : if (!bms_overlap(all_varnos, sjinfo->syn_righthand) ||
2467 : 84 : bms_is_subset(all_varnos, sjinfo->syn_righthand))
2468 : : {
2469 : : /*
2470 : : * Clause refers to only one rel, so ignore it --- unless it
2471 : : * contains volatile functions, in which case we'd better
2472 : : * punt.
2473 : : */
2474 [ - + ]: 84 : if (contain_volatile_functions((Node *) op))
2475 : 89 : return;
2476 : 84 : continue;
2477 : : }
2478 : : /* Non-operator clause referencing both sides, must punt */
2479 : 10 : return;
2480 : : }
2481 : :
2482 : : /* Extract data from binary opclause */
2483 : 4466 : opno = op->opno;
2484 : 4466 : left_expr = linitial(op->args);
2485 : 4466 : right_expr = lsecond(op->args);
2486 : 4466 : left_varnos = pull_varnos(root, left_expr);
2487 : 4466 : right_varnos = pull_varnos(root, right_expr);
2488 : 4466 : all_varnos = bms_union(left_varnos, right_varnos);
2489 : 4466 : opinputtype = exprType(left_expr);
2490 : :
2491 : : /* Does it reference both sides? */
2492 [ + + + + ]: 8918 : if (!bms_overlap(all_varnos, sjinfo->syn_righthand) ||
2493 : 4452 : bms_is_subset(all_varnos, sjinfo->syn_righthand))
2494 : : {
2495 : : /*
2496 : : * Clause refers to only one rel, so ignore it --- unless it
2497 : : * contains volatile functions, in which case we'd better punt.
2498 : : */
2499 [ - + ]: 103 : if (contain_volatile_functions((Node *) op))
2500 : 0 : return;
2501 : 103 : continue;
2502 : : }
2503 : :
2504 : : /* check rel membership of arguments */
2505 [ + - + + ]: 8726 : if (!bms_is_empty(right_varnos) &&
2506 : 4363 : bms_is_subset(right_varnos, sjinfo->syn_righthand) &&
2507 [ + - ]: 4000 : !bms_overlap(left_varnos, sjinfo->syn_righthand))
2508 : : {
2509 : : /* typical case, right_expr is RHS variable */
2510 : : }
2511 [ + - + + ]: 726 : else if (!bms_is_empty(left_varnos) &&
2512 : 363 : bms_is_subset(left_varnos, sjinfo->syn_righthand) &&
2513 [ + - ]: 358 : !bms_overlap(right_varnos, sjinfo->syn_righthand))
2514 : : {
2515 : : /* flipped case, left_expr is RHS variable */
2516 : 358 : opno = get_commutator(opno);
2517 [ - + ]: 358 : if (!OidIsValid(opno))
2518 : 0 : return;
2519 : 358 : right_expr = left_expr;
2520 : : }
2521 : : else
2522 : : {
2523 : : /* mixed membership of args, punt */
2524 : 5 : return;
2525 : : }
2526 : :
2527 : : /* all operators must be btree equality or hash equality */
2528 [ + - ]: 4358 : if (all_btree)
2529 : : {
2530 : : /* oprcanmerge is considered a hint... */
2531 [ + + - + ]: 8642 : if (!op_mergejoinable(opno, opinputtype) ||
2532 : 4284 : get_mergejoin_opfamilies(opno) == NIL)
2533 : 74 : all_btree = false;
2534 : : }
2535 [ + + ]: 4358 : if (all_hash)
2536 : : {
2537 : : /* ... but oprcanhash had better be correct */
2538 [ + + ]: 4294 : if (!op_hashjoinable(opno, opinputtype))
2539 : 74 : all_hash = false;
2540 : : }
2541 [ + + + - ]: 4358 : if (!(all_btree || all_hash))
2542 : 74 : return;
2543 : :
2544 : : /*
2545 : : * Ensure the RHS expression exposes the join's input collation (its
2546 : : * type should be OK already); see comments for
2547 : : * canonicalize_ec_expression.
2548 : : */
2549 : 4284 : right_expr = (Node *) canonicalize_ec_expression((Expr *) copyObject(right_expr),
2550 : : exprType(right_expr),
2551 : : op->inputcollid);
2552 : :
2553 : : /* so far so good, keep building lists */
2554 : 4284 : semi_operators = lappend_oid(semi_operators, opno);
2555 : 4284 : semi_rhs_exprs = lappend(semi_rhs_exprs, right_expr);
2556 : : }
2557 : :
2558 : : /* Punt if we didn't find at least one column to unique-ify */
2559 [ + + ]: 4059 : if (semi_rhs_exprs == NIL)
2560 : 10 : return;
2561 : :
2562 : : /*
2563 : : * The expressions we'd need to unique-ify mustn't be volatile.
2564 : : */
2565 [ - + ]: 4049 : if (contain_volatile_functions((Node *) semi_rhs_exprs))
2566 : 0 : return;
2567 : :
2568 : : /*
2569 : : * If we get here, we can unique-ify the semijoin's RHS using at least one
2570 : : * of sorting and hashing. Save the information about how to do that.
2571 : : */
2572 : 4049 : sjinfo->semi_can_btree = all_btree;
2573 : 4049 : sjinfo->semi_can_hash = all_hash;
2574 : 4049 : sjinfo->semi_operators = semi_operators;
2575 : 4049 : sjinfo->semi_rhs_exprs = semi_rhs_exprs;
2576 : : }
2577 : :
2578 : : /*
2579 : : * deconstruct_distribute_oj_quals
2580 : : * Adjust LEFT JOIN quals to be suitable for commuted-left-join cases,
2581 : : * then push them into the joinqual lists and EquivalenceClass structures.
2582 : : *
2583 : : * This runs immediately after we've completed the deconstruct_distribute scan.
2584 : : * jtitems contains all the JoinTreeItems (in depth-first order), and jtitem
2585 : : * is one that has postponed oj_joinclauses to deal with.
2586 : : */
2587 : : static void
2588 : 34486 : deconstruct_distribute_oj_quals(PlannerInfo *root,
2589 : : List *jtitems,
2590 : : JoinTreeItem *jtitem)
2591 : : {
2592 : 34486 : SpecialJoinInfo *sjinfo = jtitem->sjinfo;
2593 : : Relids qualscope,
2594 : : ojscope,
2595 : : nonnullable_rels;
2596 : :
2597 : : /* Recompute syntactic and semantic scopes of this left join */
2598 : 34486 : qualscope = bms_union(sjinfo->syn_lefthand, sjinfo->syn_righthand);
2599 : 34486 : qualscope = bms_add_member(qualscope, sjinfo->ojrelid);
2600 : 34486 : ojscope = bms_union(sjinfo->min_lefthand, sjinfo->min_righthand);
2601 : 34486 : nonnullable_rels = sjinfo->syn_lefthand;
2602 : :
2603 : : /*
2604 : : * If this join can commute with any other ones per outer-join identity 3,
2605 : : * and it is the one providing the join clause with flexible semantics,
2606 : : * then we have to generate variants of the join clause with different
2607 : : * nullingrels labeling. Otherwise, just push out the postponed clause
2608 : : * as-is.
2609 : : */
2610 : : Assert(sjinfo->lhs_strict); /* else we shouldn't be here */
2611 [ + + + + ]: 34486 : if (sjinfo->commute_above_r || sjinfo->commute_below_l)
2612 : 2924 : {
2613 : : Relids joins_above;
2614 : : Relids joins_below;
2615 : : Relids incompatible_joins;
2616 : : Relids joins_so_far;
2617 : : List *quals;
2618 : : int save_last_rinfo_serial;
2619 : : ListCell *lc;
2620 : :
2621 : : /* Identify the outer joins this one commutes with */
2622 : 2924 : joins_above = sjinfo->commute_above_r;
2623 : 2924 : joins_below = sjinfo->commute_below_l;
2624 : :
2625 : : /*
2626 : : * Generate qual variants with different sets of nullingrels bits.
2627 : : *
2628 : : * We only need bit-sets that correspond to the successively less
2629 : : * deeply syntactically-nested subsets of this join and its
2630 : : * commutators. That's true first because obviously only those forms
2631 : : * of the Vars and PHVs could appear elsewhere in the query, and
2632 : : * second because the outer join identities do not provide a way to
2633 : : * re-order such joins in a way that would require different marking.
2634 : : * (That is, while the current join may commute with several others,
2635 : : * none of those others can commute with each other.) To visit the
2636 : : * interesting joins in syntactic nesting order, we rely on the
2637 : : * jtitems list to be ordered that way.
2638 : : *
2639 : : * We first strip out all the nullingrels bits corresponding to
2640 : : * commuting joins below this one, and then successively put them back
2641 : : * as we crawl up the join stack.
2642 : : */
2643 : 2924 : quals = jtitem->oj_joinclauses;
2644 [ + + ]: 2924 : if (!bms_is_empty(joins_below))
2645 : 2726 : quals = (List *) remove_nulling_relids((Node *) quals,
2646 : : joins_below,
2647 : : NULL);
2648 : :
2649 : : /*
2650 : : * We'll need to mark the lower versions of the quals as not safe to
2651 : : * apply above not-yet-processed joins of the stack. This prevents
2652 : : * possibly applying a cloned qual at the wrong join level.
2653 : : */
2654 : 2924 : incompatible_joins = bms_union(joins_below, joins_above);
2655 : 2924 : incompatible_joins = bms_add_member(incompatible_joins,
2656 : 2924 : sjinfo->ojrelid);
2657 : :
2658 : : /*
2659 : : * Each time we produce RestrictInfo(s) from these quals, reset the
2660 : : * last_rinfo_serial counter, so that the RestrictInfos for the "same"
2661 : : * qual condition get identical serial numbers. (This relies on the
2662 : : * fact that we're not changing the qual list in any way that'd affect
2663 : : * the number of RestrictInfos built from it.) This'll allow us to
2664 : : * detect duplicative qual usage later.
2665 : : */
2666 : 2924 : save_last_rinfo_serial = root->last_rinfo_serial;
2667 : :
2668 : 2924 : joins_so_far = NULL;
2669 [ + - + + : 25783 : foreach(lc, jtitems)
+ + ]
2670 : : {
2671 : 22859 : JoinTreeItem *otherjtitem = (JoinTreeItem *) lfirst(lc);
2672 : 22859 : SpecialJoinInfo *othersj = otherjtitem->sjinfo;
2673 : 22859 : bool below_sjinfo = false;
2674 : 22859 : bool above_sjinfo = false;
2675 : : Relids this_qualscope;
2676 : : Relids this_ojscope;
2677 : : bool allow_equivalence,
2678 : : has_clone,
2679 : : is_clone;
2680 : :
2681 [ + + ]: 22859 : if (othersj == NULL)
2682 : 16084 : continue; /* not an outer-join item, ignore */
2683 : :
2684 [ + + ]: 6775 : if (bms_is_member(othersj->ojrelid, joins_below))
2685 : : {
2686 : : /* othersj commutes with sjinfo from below left */
2687 : 2786 : below_sjinfo = true;
2688 : : }
2689 [ + + ]: 3989 : else if (othersj == sjinfo)
2690 : : {
2691 : : /* found our join in syntactic order */
2692 : : Assert(bms_equal(joins_so_far, joins_below));
2693 : : }
2694 [ + + ]: 1065 : else if (bms_is_member(othersj->ojrelid, joins_above))
2695 : : {
2696 : : /* othersj commutes with sjinfo from above */
2697 : 198 : above_sjinfo = true;
2698 : : }
2699 : : else
2700 : : {
2701 : : /* othersj is not relevant, ignore */
2702 : 867 : continue;
2703 : : }
2704 : :
2705 : : /* Reset serial counter for this version of the quals */
2706 : 5908 : root->last_rinfo_serial = save_last_rinfo_serial;
2707 : :
2708 : : /*
2709 : : * When we are looking at joins above sjinfo, we are envisioning
2710 : : * pushing sjinfo to above othersj, so add othersj's nulling bit
2711 : : * before distributing the quals. We should add it to Vars coming
2712 : : * from the current join's LHS: we want to transform the second
2713 : : * form of OJ identity 3 to the first form, in which Vars of
2714 : : * relation B will appear nulled by the syntactically-upper OJ
2715 : : * within the Pbc clause, but those of relation C will not. (In
2716 : : * the notation used by optimizer/README, we're converting a qual
2717 : : * of the form Pbc to Pb*c.) Of course, we must also remove that
2718 : : * bit from the incompatible_joins value, else we'll make a qual
2719 : : * that can't be placed anywhere.
2720 : : */
2721 [ + + ]: 5908 : if (above_sjinfo)
2722 : : {
2723 : : quals = (List *)
2724 : 198 : add_nulling_relids((Node *) quals,
2725 : 198 : sjinfo->syn_lefthand,
2726 : 198 : bms_make_singleton(othersj->ojrelid));
2727 : 198 : incompatible_joins = bms_del_member(incompatible_joins,
2728 : 198 : othersj->ojrelid);
2729 : : }
2730 : :
2731 : : /* Compute qualscope and ojscope for this join level */
2732 : 5908 : this_qualscope = bms_union(qualscope, joins_so_far);
2733 : 5908 : this_ojscope = bms_union(ojscope, joins_so_far);
2734 [ + + ]: 5908 : if (above_sjinfo)
2735 : : {
2736 : : /* othersj is not yet in joins_so_far, but we need it */
2737 : 198 : this_qualscope = bms_add_member(this_qualscope,
2738 : 198 : othersj->ojrelid);
2739 : 198 : this_ojscope = bms_add_member(this_ojscope,
2740 : 198 : othersj->ojrelid);
2741 : : /* sjinfo is in joins_so_far, and we don't want it */
2742 : 198 : this_ojscope = bms_del_member(this_ojscope,
2743 : 198 : sjinfo->ojrelid);
2744 : : }
2745 : :
2746 : : /*
2747 : : * We generate EquivalenceClasses only from the first form of the
2748 : : * quals, with the fewest nullingrels bits set. An EC made from
2749 : : * this version of the quals can be useful below the outer-join
2750 : : * nest, whereas versions with some nullingrels bits set would not
2751 : : * be. We cannot generate ECs from more than one version, or
2752 : : * we'll make nonsensical conclusions that Vars with nullingrels
2753 : : * bits set are equal to their versions without. Fortunately,
2754 : : * such ECs wouldn't be very useful anyway, because they'd equate
2755 : : * values not observable outside the join nest. (See
2756 : : * optimizer/README.)
2757 : : *
2758 : : * The first form of the quals is also the only one marked as
2759 : : * has_clone rather than is_clone.
2760 : : */
2761 : 5908 : allow_equivalence = (joins_so_far == NULL);
2762 : 5908 : has_clone = allow_equivalence;
2763 : 5908 : is_clone = !has_clone;
2764 : :
2765 : 5908 : distribute_quals_to_rels(root, quals,
2766 : : otherjtitem,
2767 : : sjinfo,
2768 : : root->qual_security_level,
2769 : : this_qualscope,
2770 : : this_ojscope, nonnullable_rels,
2771 : : bms_copy(incompatible_joins),
2772 : : allow_equivalence,
2773 : : has_clone,
2774 : : is_clone,
2775 : : NULL); /* no more postponement */
2776 : :
2777 : : /*
2778 : : * Adjust qual nulling bits for next level up, if needed. We
2779 : : * don't want to put sjinfo's own bit in at all, and if we're
2780 : : * above sjinfo then we did it already. Here, we should mark all
2781 : : * Vars coming from the lower join's RHS. (Again, we are
2782 : : * converting a qual of the form Pbc to Pb*c, but now we are
2783 : : * putting back bits that were there in the parser output and were
2784 : : * temporarily stripped above.) Update incompatible_joins too.
2785 : : */
2786 [ + + ]: 5908 : if (below_sjinfo)
2787 : : {
2788 : : quals = (List *)
2789 : 2786 : add_nulling_relids((Node *) quals,
2790 : 2786 : othersj->syn_righthand,
2791 : 2786 : bms_make_singleton(othersj->ojrelid));
2792 : 2786 : incompatible_joins = bms_del_member(incompatible_joins,
2793 : 2786 : othersj->ojrelid);
2794 : : }
2795 : :
2796 : : /* ... and track joins processed so far */
2797 : 5908 : joins_so_far = bms_add_member(joins_so_far, othersj->ojrelid);
2798 : : }
2799 : : }
2800 : : else
2801 : : {
2802 : : /* No commutation possible, just process the postponed clauses */
2803 : 31562 : distribute_quals_to_rels(root, jtitem->oj_joinclauses,
2804 : : jtitem,
2805 : : sjinfo,
2806 : : root->qual_security_level,
2807 : : qualscope,
2808 : : ojscope, nonnullable_rels,
2809 : : NULL, /* incompatible_relids */
2810 : : true, /* allow_equivalence */
2811 : : false, false, /* not clones */
2812 : : NULL); /* no more postponement */
2813 : : }
2814 : 34486 : }
2815 : :
2816 : :
2817 : : /*****************************************************************************
2818 : : *
2819 : : * QUALIFICATIONS
2820 : : *
2821 : : *****************************************************************************/
2822 : :
2823 : : /*
2824 : : * distribute_quals_to_rels
2825 : : * Convenience routine to apply distribute_qual_to_rels to each element
2826 : : * of an AND'ed list of clauses.
2827 : : */
2828 : : static void
2829 : 685727 : distribute_quals_to_rels(PlannerInfo *root, List *clauses,
2830 : : JoinTreeItem *jtitem,
2831 : : SpecialJoinInfo *sjinfo,
2832 : : Index security_level,
2833 : : Relids qualscope,
2834 : : Relids ojscope,
2835 : : Relids outerjoin_nonnullable,
2836 : : Relids incompatible_relids,
2837 : : bool allow_equivalence,
2838 : : bool has_clone,
2839 : : bool is_clone,
2840 : : List **postponed_oj_qual_list)
2841 : : {
2842 : : ListCell *lc;
2843 : :
2844 [ + + + + : 1167883 : foreach(lc, clauses)
+ + ]
2845 : : {
2846 : 482156 : Node *clause = (Node *) lfirst(lc);
2847 : :
2848 : 482156 : distribute_qual_to_rels(root, clause,
2849 : : jtitem,
2850 : : sjinfo,
2851 : : security_level,
2852 : : qualscope,
2853 : : ojscope,
2854 : : outerjoin_nonnullable,
2855 : : incompatible_relids,
2856 : : allow_equivalence,
2857 : : has_clone,
2858 : : is_clone,
2859 : : postponed_oj_qual_list);
2860 : : }
2861 : 685727 : }
2862 : :
2863 : : /*
2864 : : * distribute_qual_to_rels
2865 : : * Add clause information to either the baserestrictinfo or joininfo list
2866 : : * (depending on whether the clause is a join) of each base relation
2867 : : * mentioned in the clause. A RestrictInfo node is created and added to
2868 : : * the appropriate list for each rel. Alternatively, if the clause uses a
2869 : : * mergejoinable operator, enter its left- and right-side expressions into
2870 : : * the query's EquivalenceClasses.
2871 : : *
2872 : : * In some cases, quals will be added to parent jtitems' lateral_clauses
2873 : : * or to postponed_oj_qual_list instead of being processed right away.
2874 : : * These will be dealt with in later calls of deconstruct_distribute.
2875 : : *
2876 : : * 'clause': the qual clause to be distributed
2877 : : * 'jtitem': the JoinTreeItem for the containing jointree node
2878 : : * 'sjinfo': join's SpecialJoinInfo (NULL for an inner join or WHERE clause)
2879 : : * 'security_level': security_level to assign to the qual
2880 : : * 'qualscope': set of base+OJ rels the qual's syntactic scope covers
2881 : : * 'ojscope': NULL if not an outer-join qual, else the minimum set of base+OJ
2882 : : * rels needed to form this join
2883 : : * 'outerjoin_nonnullable': NULL if not an outer-join qual, else the set of
2884 : : * base+OJ rels appearing on the outer (nonnullable) side of the join
2885 : : * (for FULL JOIN this includes both sides of the join, and must in fact
2886 : : * equal qualscope)
2887 : : * 'incompatible_relids': the set of outer-join relid(s) that must not be
2888 : : * computed below this qual. We only bother to compute this for
2889 : : * "clone" quals, otherwise it can be left NULL.
2890 : : * 'allow_equivalence': true if it's okay to convert clause into an
2891 : : * EquivalenceClass
2892 : : * 'has_clone': has_clone property to assign to the qual
2893 : : * 'is_clone': is_clone property to assign to the qual
2894 : : * 'postponed_oj_qual_list': if not NULL, non-degenerate outer join clauses
2895 : : * should be added to this list instead of being processed (list entries
2896 : : * are just the bare clauses)
2897 : : *
2898 : : * 'qualscope' identifies what level of JOIN the qual came from syntactically.
2899 : : * 'ojscope' is needed if we decide to force the qual up to the outer-join
2900 : : * level, which will be ojscope not necessarily qualscope.
2901 : : */
2902 : : static void
2903 : 482156 : distribute_qual_to_rels(PlannerInfo *root, Node *clause,
2904 : : JoinTreeItem *jtitem,
2905 : : SpecialJoinInfo *sjinfo,
2906 : : Index security_level,
2907 : : Relids qualscope,
2908 : : Relids ojscope,
2909 : : Relids outerjoin_nonnullable,
2910 : : Relids incompatible_relids,
2911 : : bool allow_equivalence,
2912 : : bool has_clone,
2913 : : bool is_clone,
2914 : : List **postponed_oj_qual_list)
2915 : : {
2916 : : Relids relids;
2917 : : bool is_pushed_down;
2918 : 482156 : bool pseudoconstant = false;
2919 : : bool maybe_equivalence;
2920 : : bool maybe_outer_join;
2921 : : RestrictInfo *restrictinfo;
2922 : :
2923 : : /*
2924 : : * Retrieve all relids mentioned within the clause.
2925 : : */
2926 : 482156 : relids = pull_varnos(root, clause);
2927 : :
2928 : : /*
2929 : : * In ordinary SQL, a WHERE or JOIN/ON clause can't reference any rels
2930 : : * that aren't within its syntactic scope; however, if we pulled up a
2931 : : * LATERAL subquery then we might find such references in quals that have
2932 : : * been pulled up. We need to treat such quals as belonging to the join
2933 : : * level that includes every rel they reference. Although we could make
2934 : : * pull_up_subqueries() place such quals correctly to begin with, it's
2935 : : * easier to handle it here. When we find a clause that contains Vars
2936 : : * outside its syntactic scope, locate the nearest parent join level that
2937 : : * includes all the required rels and add the clause to that level's
2938 : : * lateral_clauses list. We'll process it when we reach that join level.
2939 : : */
2940 [ + + ]: 482156 : if (!bms_is_subset(relids, qualscope))
2941 : : {
2942 : : JoinTreeItem *pitem;
2943 : :
2944 : : Assert(root->hasLateralRTEs); /* shouldn't happen otherwise */
2945 : : Assert(sjinfo == NULL); /* mustn't postpone past outer join */
2946 [ + - ]: 119 : for (pitem = jtitem->jti_parent; pitem; pitem = pitem->jti_parent)
2947 : : {
2948 [ + + ]: 119 : if (bms_is_subset(relids, pitem->qualscope))
2949 : : {
2950 : 104 : pitem->lateral_clauses = lappend(pitem->lateral_clauses,
2951 : : clause);
2952 : 335890 : return;
2953 : : }
2954 : :
2955 : : /*
2956 : : * We should not be postponing any quals past an outer join. If
2957 : : * this Assert fires, pull_up_subqueries() messed up.
2958 : : */
2959 : : Assert(pitem->sjinfo == NULL);
2960 : : }
2961 [ # # ]: 0 : elog(ERROR, "failed to postpone qual containing lateral reference");
2962 : : }
2963 : :
2964 : : /*
2965 : : * If it's an outer-join clause, also check that relids is a subset of
2966 : : * ojscope. (This should not fail if the syntactic scope check passed.)
2967 : : */
2968 [ + + - + ]: 482052 : if (ojscope && !bms_is_subset(relids, ojscope))
2969 [ # # ]: 0 : elog(ERROR, "JOIN qualification cannot refer to other relations");
2970 : :
2971 : : /*
2972 : : * If the clause is variable-free, our normal heuristic for pushing it
2973 : : * down to just the mentioned rels doesn't work, because there are none.
2974 : : *
2975 : : * If the clause is an outer-join clause, we must force it to the OJ's
2976 : : * semantic level to preserve semantics.
2977 : : *
2978 : : * Otherwise, when the clause contains volatile functions, we force it to
2979 : : * be evaluated at its original syntactic level. This preserves the
2980 : : * expected semantics.
2981 : : *
2982 : : * When the clause contains no volatile functions either, it is actually a
2983 : : * pseudoconstant clause that will not change value during any one
2984 : : * execution of the plan, and hence can be used as a one-time qual in a
2985 : : * gating Result plan node. We put such a clause into the regular
2986 : : * RestrictInfo lists for the moment, but eventually createplan.c will
2987 : : * pull it out and make a gating Result node immediately above whatever
2988 : : * plan node the pseudoconstant clause is assigned to. It's usually best
2989 : : * to put a gating node as high in the plan tree as possible.
2990 : : */
2991 [ + + ]: 482052 : if (bms_is_empty(relids))
2992 : : {
2993 [ + + ]: 9596 : if (ojscope)
2994 : : {
2995 : : /* clause is attached to outer join, eval it there */
2996 : 421 : relids = bms_copy(ojscope);
2997 : : /* mustn't use as gating qual, so don't mark pseudoconstant */
2998 : : }
2999 [ + + ]: 9175 : else if (contain_volatile_functions(clause))
3000 : : {
3001 : : /* eval at original syntactic level */
3002 : 108 : relids = bms_copy(qualscope);
3003 : : /* again, can't mark pseudoconstant */
3004 : : }
3005 : : else
3006 : : {
3007 : : /*
3008 : : * If we are in the top-level join domain, we can push the qual to
3009 : : * the top of the plan tree. Otherwise, be conservative and eval
3010 : : * it at original syntactic level. (Ideally we'd push it to the
3011 : : * top of the current join domain in all cases, but that causes
3012 : : * problems if we later rearrange outer-join evaluation order.
3013 : : * Pseudoconstant quals below the top level are a pretty odd case,
3014 : : * so it's not clear that it's worth working hard on.)
3015 : : */
3016 [ + + ]: 9067 : if (jtitem->jdomain == (JoinDomain *) linitial(root->join_domains))
3017 : 9007 : relids = bms_copy(jtitem->jdomain->jd_relids);
3018 : : else
3019 : 60 : relids = bms_copy(qualscope);
3020 : : /* mark as gating qual */
3021 : 9067 : pseudoconstant = true;
3022 : : /* tell createplan.c to check for gating quals */
3023 : 9067 : root->hasPseudoConstantQuals = true;
3024 : : }
3025 : : }
3026 : :
3027 : : /*----------
3028 : : * Check to see if clause application must be delayed by outer-join
3029 : : * considerations.
3030 : : *
3031 : : * A word about is_pushed_down: we mark the qual as "pushed down" if
3032 : : * it is (potentially) applicable at a level different from its original
3033 : : * syntactic level. This flag is used to distinguish OUTER JOIN ON quals
3034 : : * from other quals pushed down to the same joinrel. The rules are:
3035 : : * WHERE quals and INNER JOIN quals: is_pushed_down = true.
3036 : : * Non-degenerate OUTER JOIN quals: is_pushed_down = false.
3037 : : * Degenerate OUTER JOIN quals: is_pushed_down = true.
3038 : : * A "degenerate" OUTER JOIN qual is one that doesn't mention the
3039 : : * non-nullable side, and hence can be pushed down into the nullable side
3040 : : * without changing the join result. It is correct to treat it as a
3041 : : * regular filter condition at the level where it is evaluated.
3042 : : *
3043 : : * Note: it is not immediately obvious that a simple boolean is enough
3044 : : * for this: if for some reason we were to attach a degenerate qual to
3045 : : * its original join level, it would need to be treated as an outer join
3046 : : * qual there. However, this cannot happen, because all the rels the
3047 : : * clause mentions must be in the outer join's min_righthand, therefore
3048 : : * the join it needs must be formed before the outer join; and we always
3049 : : * attach quals to the lowest level where they can be evaluated. But
3050 : : * if we were ever to re-introduce a mechanism for delaying evaluation
3051 : : * of "expensive" quals, this area would need work.
3052 : : *
3053 : : * Note: generally, use of is_pushed_down has to go through the macro
3054 : : * RINFO_IS_PUSHED_DOWN, because that flag alone is not always sufficient
3055 : : * to tell whether a clause must be treated as pushed-down in context.
3056 : : * This seems like another reason why it should perhaps be rethought.
3057 : : *----------
3058 : : */
3059 [ + + ]: 482052 : if (bms_overlap(relids, outerjoin_nonnullable))
3060 : : {
3061 : : /*
3062 : : * The qual is attached to an outer join and mentions (some of the)
3063 : : * rels on the nonnullable side, so it's not degenerate. If the
3064 : : * caller wants to postpone handling such clauses, just add it to
3065 : : * postponed_oj_qual_list and return. (The work we've done up to here
3066 : : * will have to be redone later, but there's not much of it.)
3067 : : */
3068 [ + + ]: 92961 : if (postponed_oj_qual_list != NULL)
3069 : : {
3070 : 37912 : *postponed_oj_qual_list = lappend(*postponed_oj_qual_list, clause);
3071 : 37912 : return;
3072 : : }
3073 : :
3074 : : /*
3075 : : * We can't use such a clause to deduce equivalence (the left and
3076 : : * right sides might be unequal above the join because one of them has
3077 : : * gone to NULL) ... but we might be able to use it for more limited
3078 : : * deductions, if it is mergejoinable. So consider adding it to the
3079 : : * lists of set-aside outer-join clauses.
3080 : : */
3081 : 55049 : is_pushed_down = false;
3082 : 55049 : maybe_equivalence = false;
3083 : 55049 : maybe_outer_join = true;
3084 : :
3085 : : /*
3086 : : * Now force the qual to be evaluated exactly at the level of joining
3087 : : * corresponding to the outer join. We cannot let it get pushed down
3088 : : * into the nonnullable side, since then we'd produce no output rows,
3089 : : * rather than the intended single null-extended row, for any
3090 : : * nonnullable-side rows failing the qual.
3091 : : */
3092 : : Assert(ojscope);
3093 : 55049 : relids = ojscope;
3094 : : Assert(!pseudoconstant);
3095 : : }
3096 : : else
3097 : : {
3098 : : /*
3099 : : * Normal qual clause or degenerate outer-join clause. Either way, we
3100 : : * can mark it as pushed-down.
3101 : : */
3102 : 389091 : is_pushed_down = true;
3103 : :
3104 : : /* Feed qual to the equivalence machinery, if allowed by caller */
3105 : 389091 : maybe_equivalence = allow_equivalence;
3106 : :
3107 : : /*
3108 : : * Since it doesn't mention the LHS, it's certainly not useful as a
3109 : : * set-aside OJ clause, even if it's in an OJ.
3110 : : */
3111 : 389091 : maybe_outer_join = false;
3112 : : }
3113 : :
3114 : : /*
3115 : : * Build the RestrictInfo node itself.
3116 : : */
3117 : 444140 : restrictinfo = make_restrictinfo(root,
3118 : : (Expr *) clause,
3119 : : is_pushed_down,
3120 : : has_clone,
3121 : : is_clone,
3122 : : pseudoconstant,
3123 : : security_level,
3124 : : relids,
3125 : : incompatible_relids,
3126 : : outerjoin_nonnullable);
3127 : :
3128 : : /*
3129 : : * If it's a join clause, add vars used in the clause to targetlists of
3130 : : * their relations, so that they will be emitted by the plan nodes that
3131 : : * scan those relations (else they won't be available at the join node!).
3132 : : *
3133 : : * Normally we mark the vars as needed at the join identified by "relids".
3134 : : * However, if this is a clone clause then ignore the outer-join relids in
3135 : : * that set. Otherwise, vars appearing in a cloned clause would end up
3136 : : * marked as having to propagate to the highest one of the commuting
3137 : : * joins, which would often be an overestimate. For such clauses, correct
3138 : : * var propagation is ensured by making ojscope include input rels from
3139 : : * both sides of the join.
3140 : : *
3141 : : * Note: if the clause gets absorbed into an EquivalenceClass then this
3142 : : * may be unnecessary, but for now we have to do it to cover the case
3143 : : * where the EC becomes ec_broken and we end up reinserting the original
3144 : : * clauses into the plan.
3145 : : */
3146 [ + + ]: 444140 : if (bms_membership(relids) == BMS_MULTIPLE)
3147 : : {
3148 : 142383 : List *vars = pull_var_clause(clause,
3149 : : PVC_RECURSE_AGGREGATES |
3150 : : PVC_RECURSE_WINDOWFUNCS |
3151 : : PVC_INCLUDE_PLACEHOLDERS);
3152 : : Relids where_needed;
3153 : :
3154 [ + + ]: 142383 : if (is_clone)
3155 : 3259 : where_needed = bms_intersect(relids, root->all_baserels);
3156 : : else
3157 : 139124 : where_needed = relids;
3158 : 142383 : add_vars_to_targetlist(root, vars, where_needed);
3159 : 142383 : list_free(vars);
3160 : : }
3161 : :
3162 : : /*
3163 : : * We check "mergejoinability" of every clause, not only join clauses,
3164 : : * because we want to know about equivalences between vars of the same
3165 : : * relation, or between vars and consts.
3166 : : */
3167 : 444140 : check_mergejoinable(restrictinfo);
3168 : :
3169 : : /*
3170 : : * If it is a true equivalence clause, send it to the EquivalenceClass
3171 : : * machinery. We do *not* attach it directly to any restriction or join
3172 : : * lists. The EC code will propagate it to the appropriate places later.
3173 : : *
3174 : : * If the clause has a mergejoinable operator, yet isn't an equivalence
3175 : : * because it is an outer-join clause, the EC code may still be able to do
3176 : : * something with it. We add it to appropriate lists for further
3177 : : * consideration later. Specifically:
3178 : : *
3179 : : * If it is a left or right outer-join qualification that relates the two
3180 : : * sides of the outer join (no funny business like leftvar1 = leftvar2 +
3181 : : * rightvar), we add it to root->left_join_clauses or
3182 : : * root->right_join_clauses according to which side the nonnullable
3183 : : * variable appears on.
3184 : : *
3185 : : * If it is a full outer-join qualification, we add it to
3186 : : * root->full_join_clauses. (Ideally we'd discard cases that aren't
3187 : : * leftvar = rightvar, as we do for left/right joins, but we leave that to
3188 : : * reconsider_full_join_clause(), which has to work out which side of the
3189 : : * join each operand comes from anyway.)
3190 : : *
3191 : : * If none of the above hold, pass it off to
3192 : : * distribute_restrictinfo_to_rels().
3193 : : *
3194 : : * In all cases, it's important to initialize the left_ec and right_ec
3195 : : * fields of a mergejoinable clause, so that all possibly mergejoinable
3196 : : * expressions have representations in EquivalenceClasses. If
3197 : : * process_equivalence is successful, it will take care of that;
3198 : : * otherwise, we have to call initialize_mergeclause_eclasses to do it.
3199 : : */
3200 [ + + ]: 444140 : if (restrictinfo->mergeopfamilies)
3201 : : {
3202 [ + + ]: 298956 : if (maybe_equivalence)
3203 : : {
3204 [ + + ]: 245560 : if (process_equivalence(root, &restrictinfo, jtitem->jdomain))
3205 : 245343 : return;
3206 : : /* EC rejected it, so set left_ec/right_ec the hard way ... */
3207 [ + + ]: 217 : if (restrictinfo->mergeopfamilies) /* EC might have changed this */
3208 : 172 : initialize_mergeclause_eclasses(root, restrictinfo);
3209 : : /* ... and fall through to distribute_restrictinfo_to_rels */
3210 : : }
3211 [ + - + + ]: 53396 : else if (maybe_outer_join && restrictinfo->can_join)
3212 : : {
3213 : : /* we need to set up left_ec/right_ec the hard way */
3214 : 52734 : initialize_mergeclause_eclasses(root, restrictinfo);
3215 : : /* now see if it should go to any outer-join lists */
3216 : : Assert(sjinfo != NULL);
3217 [ + + ]: 52734 : if (bms_is_subset(restrictinfo->left_relids,
3218 : 24328 : outerjoin_nonnullable) &&
3219 [ + + ]: 24328 : !bms_overlap(restrictinfo->right_relids,
3220 : : outerjoin_nonnullable))
3221 : : {
3222 : : /* we have outervar = innervar */
3223 : 23046 : OuterJoinClauseInfo *ojcinfo = makeNode(OuterJoinClauseInfo);
3224 : :
3225 : 23046 : ojcinfo->rinfo = restrictinfo;
3226 : 23046 : ojcinfo->sjinfo = sjinfo;
3227 : 23046 : root->left_join_clauses = lappend(root->left_join_clauses,
3228 : : ojcinfo);
3229 : 23046 : return;
3230 : : }
3231 [ + + ]: 29688 : if (bms_is_subset(restrictinfo->right_relids,
3232 : 29515 : outerjoin_nonnullable) &&
3233 [ + + ]: 29515 : !bms_overlap(restrictinfo->left_relids,
3234 : : outerjoin_nonnullable))
3235 : : {
3236 : : /* we have innervar = outervar */
3237 : 28233 : OuterJoinClauseInfo *ojcinfo = makeNode(OuterJoinClauseInfo);
3238 : :
3239 : 28233 : ojcinfo->rinfo = restrictinfo;
3240 : 28233 : ojcinfo->sjinfo = sjinfo;
3241 : 28233 : root->right_join_clauses = lappend(root->right_join_clauses,
3242 : : ojcinfo);
3243 : 28233 : return;
3244 : : }
3245 [ + + ]: 1455 : if (sjinfo->jointype == JOIN_FULL)
3246 : : {
3247 : : /* FULL JOIN (above tests cannot match in this case) */
3248 : 1252 : OuterJoinClauseInfo *ojcinfo = makeNode(OuterJoinClauseInfo);
3249 : :
3250 : 1252 : ojcinfo->rinfo = restrictinfo;
3251 : 1252 : ojcinfo->sjinfo = sjinfo;
3252 : 1252 : root->full_join_clauses = lappend(root->full_join_clauses,
3253 : : ojcinfo);
3254 : 1252 : return;
3255 : : }
3256 : : /* nope, so fall through to distribute_restrictinfo_to_rels */
3257 : : }
3258 : : else
3259 : : {
3260 : : /* we still need to set up left_ec/right_ec */
3261 : 662 : initialize_mergeclause_eclasses(root, restrictinfo);
3262 : : }
3263 : : }
3264 : :
3265 : : /* No EC special case applies, so push it into the clause lists */
3266 : 146266 : distribute_restrictinfo_to_rels(root, restrictinfo);
3267 : : }
3268 : :
3269 : : /*
3270 : : * add_base_clause_to_rel
3271 : : * Add 'restrictinfo' as a baserestrictinfo to the base relation denoted
3272 : : * by 'relid'. We offer some simple prechecks to try to determine if the
3273 : : * qual is always true, in which case we ignore it rather than add it.
3274 : : * If we detect the qual is always false, we replace it with
3275 : : * constant-FALSE.
3276 : : */
3277 : : static void
3278 : 313789 : add_base_clause_to_rel(PlannerInfo *root, Index relid,
3279 : : RestrictInfo *restrictinfo)
3280 : : {
3281 : 313789 : RelOptInfo *rel = find_base_rel(root, relid);
3282 : 313789 : RangeTblEntry *rte = root->simple_rte_array[relid];
3283 : :
3284 : : Assert(bms_membership(restrictinfo->required_relids) == BMS_SINGLETON);
3285 : :
3286 : : /*
3287 : : * For inheritance parent tables, we must always record the RestrictInfo
3288 : : * in baserestrictinfo as is. If we were to transform or skip adding it,
3289 : : * then the original wouldn't be available in apply_child_basequals. Since
3290 : : * there are two RangeTblEntries for inheritance parents, one with
3291 : : * inh==true and the other with inh==false, we're still able to apply this
3292 : : * optimization to the inh==false one. The inh==true one is what
3293 : : * apply_child_basequals() sees, whereas the inh==false one is what's used
3294 : : * for the scan node in the final plan.
3295 : : *
3296 : : * We make an exception to this for partitioned tables. For these, we
3297 : : * always apply the constant-TRUE and constant-FALSE transformations. A
3298 : : * qual which is either of these for a partitioned table must also be that
3299 : : * for all of its child partitions.
3300 : : */
3301 [ + + + + ]: 313789 : if (!rte->inh || rte->relkind == RELKIND_PARTITIONED_TABLE)
3302 : : {
3303 : : /* Don't add the clause if it is always true */
3304 [ + + ]: 312063 : if (restriction_is_always_true(root, restrictinfo))
3305 : 347 : return;
3306 : :
3307 : : /*
3308 : : * Substitute the origin qual with constant-FALSE if it is provably
3309 : : * always false.
3310 : : *
3311 : : * Note that we need to keep the same rinfo_serial, since it is in
3312 : : * practice the same condition. We also need to reset the
3313 : : * last_rinfo_serial counter, which is essential to ensure that the
3314 : : * RestrictInfos for the "same" qual condition get identical serial
3315 : : * numbers (see deconstruct_distribute_oj_quals).
3316 : : */
3317 [ - + ]: 311716 : if (restriction_is_always_false(root, restrictinfo))
3318 : : {
3319 : 0 : int save_rinfo_serial = restrictinfo->rinfo_serial;
3320 : 0 : int save_last_rinfo_serial = root->last_rinfo_serial;
3321 : :
3322 : 0 : restrictinfo = make_restrictinfo(root,
3323 : 0 : (Expr *) makeBoolConst(false, false),
3324 : 0 : restrictinfo->is_pushed_down,
3325 : 0 : restrictinfo->has_clone,
3326 : 0 : restrictinfo->is_clone,
3327 : 0 : restrictinfo->pseudoconstant,
3328 : : 0, /* security_level */
3329 : : restrictinfo->required_relids,
3330 : : restrictinfo->incompatible_relids,
3331 : : restrictinfo->outer_relids);
3332 : 0 : restrictinfo->rinfo_serial = save_rinfo_serial;
3333 : 0 : root->last_rinfo_serial = save_last_rinfo_serial;
3334 : : }
3335 : : }
3336 : :
3337 : : /* Add clause to rel's restriction list */
3338 : 313442 : rel->baserestrictinfo = lappend(rel->baserestrictinfo, restrictinfo);
3339 : :
3340 : : /* Update security level info */
3341 : 313442 : rel->baserestrict_min_security = Min(rel->baserestrict_min_security,
3342 : : restrictinfo->security_level);
3343 : : }
3344 : :
3345 : : /*
3346 : : * restriction_is_always_true
3347 : : * Check to see if the RestrictInfo is always true.
3348 : : *
3349 : : * Currently we only check for NullTest quals and OR clauses that include
3350 : : * NullTest quals. We may extend it in the future.
3351 : : */
3352 : : bool
3353 : 395123 : restriction_is_always_true(PlannerInfo *root,
3354 : : RestrictInfo *restrictinfo)
3355 : : {
3356 : : /*
3357 : : * For a clone clause, we don't have a reliable way to determine if the
3358 : : * input expression of a NullTest is non-nullable: nullingrel bits in
3359 : : * clone clauses may not reflect reality, so we dare not draw conclusions
3360 : : * from clones about whether Vars are guaranteed not-null.
3361 : : */
3362 [ + + + + ]: 395123 : if (restrictinfo->has_clone || restrictinfo->is_clone)
3363 : 6458 : return false;
3364 : :
3365 : : /* Check for NullTest qual */
3366 [ + + ]: 388665 : if (IsA(restrictinfo->clause, NullTest))
3367 : : {
3368 : 8419 : NullTest *nulltest = (NullTest *) restrictinfo->clause;
3369 : :
3370 : : /* is this NullTest an IS_NOT_NULL qual? */
3371 [ + + ]: 8419 : if (nulltest->nulltesttype != IS_NOT_NULL)
3372 : 1924 : return false;
3373 : :
3374 : : /*
3375 : : * Empty rows can appear NULL in some contexts and NOT NULL in others,
3376 : : * so avoid this optimization for row expressions.
3377 : : */
3378 [ + + ]: 6495 : if (nulltest->argisrow)
3379 : 148 : return false;
3380 : :
3381 : 6347 : return expr_is_nonnullable(root, nulltest->arg, NOTNULL_SOURCE_RELOPT);
3382 : : }
3383 : :
3384 : : /* If it's an OR, check its sub-clauses */
3385 [ + + ]: 380246 : if (restriction_is_or_clause(restrictinfo))
3386 : : {
3387 : : ListCell *lc;
3388 : :
3389 : : Assert(is_orclause(restrictinfo->orclause));
3390 : :
3391 : : /*
3392 : : * if any of the given OR branches is provably always true then the
3393 : : * entire condition is true.
3394 : : */
3395 [ + - + + : 26475 : foreach(lc, ((BoolExpr *) restrictinfo->orclause)->args)
+ + ]
3396 : : {
3397 : 18424 : Node *orarg = (Node *) lfirst(lc);
3398 : :
3399 [ + + ]: 18424 : if (!IsA(orarg, RestrictInfo))
3400 : 1518 : continue;
3401 : :
3402 [ - + ]: 16906 : if (restriction_is_always_true(root, (RestrictInfo *) orarg))
3403 : 0 : return true;
3404 : : }
3405 : : }
3406 : :
3407 : 380246 : return false;
3408 : : }
3409 : :
3410 : : /*
3411 : : * restriction_is_always_false
3412 : : * Check to see if the RestrictInfo is always false.
3413 : : *
3414 : : * Currently we only check for NullTest quals and OR clauses that include
3415 : : * NullTest quals. We may extend it in the future.
3416 : : */
3417 : : bool
3418 : 385239 : restriction_is_always_false(PlannerInfo *root,
3419 : : RestrictInfo *restrictinfo)
3420 : : {
3421 : : /*
3422 : : * For a clone clause, we don't have a reliable way to determine if the
3423 : : * input expression of a NullTest is non-nullable: nullingrel bits in
3424 : : * clone clauses may not reflect reality, so we dare not draw conclusions
3425 : : * from clones about whether Vars are guaranteed not-null.
3426 : : */
3427 [ + + + + ]: 385239 : if (restrictinfo->has_clone || restrictinfo->is_clone)
3428 : 6458 : return false;
3429 : :
3430 : : /* Check for NullTest qual */
3431 [ + + ]: 378781 : if (IsA(restrictinfo->clause, NullTest))
3432 : : {
3433 : 7426 : NullTest *nulltest = (NullTest *) restrictinfo->clause;
3434 : :
3435 : : /* is this NullTest an IS_NULL qual? */
3436 [ + + ]: 7426 : if (nulltest->nulltesttype != IS_NULL)
3437 : 5716 : return false;
3438 : :
3439 : : /*
3440 : : * Empty rows can appear NULL in some contexts and NOT NULL in others,
3441 : : * so avoid this optimization for row expressions.
3442 : : */
3443 [ + + ]: 1710 : if (nulltest->argisrow)
3444 : 123 : return false;
3445 : :
3446 : 1587 : return expr_is_nonnullable(root, nulltest->arg, NOTNULL_SOURCE_RELOPT);
3447 : : }
3448 : :
3449 : : /* If it's an OR, check its sub-clauses */
3450 [ + + ]: 371355 : if (restriction_is_or_clause(restrictinfo))
3451 : : {
3452 : : ListCell *lc;
3453 : :
3454 : : Assert(is_orclause(restrictinfo->orclause));
3455 : :
3456 : : /*
3457 : : * Currently, when processing OR expressions, we only return true when
3458 : : * all of the OR branches are always false. This could perhaps be
3459 : : * expanded to remove OR branches that are provably false. This may
3460 : : * be a useful thing to do as it could result in the OR being left
3461 : : * with a single arg. That's useful as it would allow the OR
3462 : : * condition to be replaced with its single argument which may allow
3463 : : * use of an index for faster filtering on the remaining condition.
3464 : : */
3465 [ + - + - : 8051 : foreach(lc, ((BoolExpr *) restrictinfo->orclause)->args)
+ - ]
3466 : : {
3467 : 8051 : Node *orarg = (Node *) lfirst(lc);
3468 : :
3469 [ + + ]: 8051 : if (!IsA(orarg, RestrictInfo) ||
3470 [ + - ]: 7369 : !restriction_is_always_false(root, (RestrictInfo *) orarg))
3471 : 8051 : return false;
3472 : : }
3473 : 0 : return true;
3474 : : }
3475 : :
3476 : 363304 : return false;
3477 : : }
3478 : :
3479 : : /*
3480 : : * distribute_restrictinfo_to_rels
3481 : : * Push a completed RestrictInfo into the proper restriction or join
3482 : : * clause list(s).
3483 : : *
3484 : : * This is the last step of distribute_qual_to_rels() for ordinary qual
3485 : : * clauses. Clauses that are interesting for equivalence-class processing
3486 : : * are diverted to the EC machinery, but may ultimately get fed back here.
3487 : : */
3488 : : void
3489 : 379943 : distribute_restrictinfo_to_rels(PlannerInfo *root,
3490 : : RestrictInfo *restrictinfo)
3491 : : {
3492 : 379943 : Relids relids = restrictinfo->required_relids;
3493 : :
3494 [ + - ]: 379943 : if (!bms_is_empty(relids))
3495 : : {
3496 : : int relid;
3497 : :
3498 [ + + ]: 379943 : if (bms_get_singleton_member(relids, &relid))
3499 : : {
3500 : : /*
3501 : : * There is only one relation participating in the clause, so it
3502 : : * is a restriction clause for that relation.
3503 : : */
3504 : 313789 : add_base_clause_to_rel(root, relid, restrictinfo);
3505 : : }
3506 : : else
3507 : : {
3508 : : /*
3509 : : * The clause is a join clause, since there is more than one rel
3510 : : * in its relid set.
3511 : : */
3512 : :
3513 : : /*
3514 : : * Check for hashjoinable operators. (We don't bother setting the
3515 : : * hashjoin info except in true join clauses.)
3516 : : */
3517 : 66154 : check_hashjoinable(restrictinfo);
3518 : :
3519 : : /*
3520 : : * Likewise, check if the clause is suitable to be used with a
3521 : : * Memoize node to cache inner tuples during a parameterized
3522 : : * nested loop.
3523 : : */
3524 : 66154 : check_memoizable(restrictinfo);
3525 : :
3526 : : /*
3527 : : * Add clause to the join lists of all the relevant relations.
3528 : : */
3529 : 66154 : add_join_clause_to_rels(root, restrictinfo, relids);
3530 : : }
3531 : : }
3532 : : else
3533 : : {
3534 : : /*
3535 : : * clause references no rels, and therefore we have no place to attach
3536 : : * it. Shouldn't get here if callers are working properly.
3537 : : */
3538 [ # # ]: 0 : elog(ERROR, "cannot cope with variable-free clause");
3539 : : }
3540 : 379943 : }
3541 : :
3542 : : /*
3543 : : * process_implied_equality
3544 : : * Create a restrictinfo item that says "item1 op item2", and push it
3545 : : * into the appropriate lists. (In practice opno is always a btree
3546 : : * equality operator.)
3547 : : *
3548 : : * "qualscope" is the nominal syntactic level to impute to the restrictinfo.
3549 : : * This must contain at least all the rels used in the expressions, but it
3550 : : * is used only to set the qual application level when both exprs are
3551 : : * variable-free. (Hence, it should usually match the join domain in which
3552 : : * the clause applies.) Otherwise the qual is applied at the lowest join
3553 : : * level that provides all its variables.
3554 : : *
3555 : : * "security_level" is the security level to assign to the new restrictinfo.
3556 : : *
3557 : : * "both_const" indicates whether both items are known pseudo-constant;
3558 : : * in this case it is worth applying eval_const_expressions() in case we
3559 : : * can produce constant TRUE or constant FALSE. (Otherwise it's not,
3560 : : * because the expressions went through eval_const_expressions already.)
3561 : : *
3562 : : * Returns the generated RestrictInfo, if any. The result will be NULL
3563 : : * if both_const is true and we successfully reduced the clause to
3564 : : * constant TRUE.
3565 : : *
3566 : : * Note: this function will copy item1 and item2, but it is caller's
3567 : : * responsibility to make sure that the Relids parameters are fresh copies
3568 : : * not shared with other uses.
3569 : : *
3570 : : * Note: we do not do initialize_mergeclause_eclasses() here. It is
3571 : : * caller's responsibility that left_ec/right_ec be set as necessary.
3572 : : */
3573 : : RestrictInfo *
3574 : 25200 : process_implied_equality(PlannerInfo *root,
3575 : : Oid opno,
3576 : : Oid collation,
3577 : : Expr *item1,
3578 : : Expr *item2,
3579 : : Relids qualscope,
3580 : : Index security_level,
3581 : : bool both_const)
3582 : : {
3583 : : RestrictInfo *restrictinfo;
3584 : : Node *clause;
3585 : : Relids relids;
3586 : 25200 : bool pseudoconstant = false;
3587 : :
3588 : : /*
3589 : : * Build the new clause. Copy to ensure it shares no substructure with
3590 : : * original (this is necessary in case there are subselects in there...)
3591 : : */
3592 : 25200 : clause = (Node *) make_opclause(opno,
3593 : : BOOLOID, /* opresulttype */
3594 : : false, /* opretset */
3595 : 25200 : copyObject(item1),
3596 : 25200 : copyObject(item2),
3597 : : InvalidOid,
3598 : : collation);
3599 : :
3600 : : /* If both constant, try to reduce to a boolean constant. */
3601 [ + + ]: 25200 : if (both_const)
3602 : : {
3603 : 145 : clause = eval_const_expressions(root, clause);
3604 : :
3605 : : /* If we produced const TRUE, just drop the clause */
3606 [ + - + + ]: 145 : if (clause && IsA(clause, Const))
3607 : : {
3608 : 130 : Const *cclause = (Const *) clause;
3609 : :
3610 : : Assert(cclause->consttype == BOOLOID);
3611 [ + - - + ]: 130 : if (!cclause->constisnull && DatumGetBool(cclause->constvalue))
3612 : 0 : return NULL;
3613 : : }
3614 : : }
3615 : :
3616 : : /*
3617 : : * The rest of this is a very cut-down version of distribute_qual_to_rels.
3618 : : * We can skip most of the work therein, but there are a couple of special
3619 : : * cases we still have to handle.
3620 : : *
3621 : : * Retrieve all relids mentioned within the possibly-simplified clause.
3622 : : */
3623 : 25200 : relids = pull_varnos(root, clause);
3624 : : Assert(bms_is_subset(relids, qualscope));
3625 : :
3626 : : /*
3627 : : * If the clause is variable-free, our normal heuristic for pushing it
3628 : : * down to just the mentioned rels doesn't work, because there are none.
3629 : : * Apply it as a gating qual at the appropriate level (see comments for
3630 : : * get_join_domain_min_rels).
3631 : : */
3632 [ + + ]: 25200 : if (bms_is_empty(relids))
3633 : : {
3634 : : /* eval at join domain's safe level */
3635 : 145 : relids = get_join_domain_min_rels(root, qualscope);
3636 : : /* mark as gating qual */
3637 : 145 : pseudoconstant = true;
3638 : : /* tell createplan.c to check for gating quals */
3639 : 145 : root->hasPseudoConstantQuals = true;
3640 : : }
3641 : :
3642 : : /*
3643 : : * Build the RestrictInfo node itself.
3644 : : */
3645 : 25200 : restrictinfo = make_restrictinfo(root,
3646 : : (Expr *) clause,
3647 : : true, /* is_pushed_down */
3648 : : false, /* !has_clone */
3649 : : false, /* !is_clone */
3650 : : pseudoconstant,
3651 : : security_level,
3652 : : relids,
3653 : : NULL, /* incompatible_relids */
3654 : : NULL); /* outer_relids */
3655 : :
3656 : : /*
3657 : : * If it's a join clause, add vars used in the clause to targetlists of
3658 : : * their relations, so that they will be emitted by the plan nodes that
3659 : : * scan those relations (else they won't be available at the join node!).
3660 : : *
3661 : : * Typically, we'd have already done this when the component expressions
3662 : : * were first seen by distribute_qual_to_rels; but it is possible that
3663 : : * some of the Vars could have missed having that done because they only
3664 : : * appeared in single-relation clauses originally. So do it here for
3665 : : * safety.
3666 : : */
3667 [ + + ]: 25200 : if (bms_membership(relids) == BMS_MULTIPLE)
3668 : : {
3669 : 70 : List *vars = pull_var_clause(clause,
3670 : : PVC_RECURSE_AGGREGATES |
3671 : : PVC_RECURSE_WINDOWFUNCS |
3672 : : PVC_INCLUDE_PLACEHOLDERS);
3673 : :
3674 : 70 : add_vars_to_targetlist(root, vars, relids);
3675 : 70 : list_free(vars);
3676 : : }
3677 : :
3678 : : /*
3679 : : * Check mergejoinability. This will usually succeed, since the op came
3680 : : * from an EquivalenceClass; but we could have reduced the original clause
3681 : : * to a constant.
3682 : : */
3683 : 25200 : check_mergejoinable(restrictinfo);
3684 : :
3685 : : /*
3686 : : * Note we don't do initialize_mergeclause_eclasses(); the caller can
3687 : : * handle that much more cheaply than we can. It's okay to call
3688 : : * distribute_restrictinfo_to_rels() before that happens.
3689 : : */
3690 : :
3691 : : /*
3692 : : * Push the new clause into all the appropriate restrictinfo lists.
3693 : : */
3694 : 25200 : distribute_restrictinfo_to_rels(root, restrictinfo);
3695 : :
3696 : 25200 : return restrictinfo;
3697 : : }
3698 : :
3699 : : /*
3700 : : * build_implied_join_equality --- build a RestrictInfo for a derived equality
3701 : : *
3702 : : * This overlaps the functionality of process_implied_equality(), but we
3703 : : * must not push the RestrictInfo into the joininfo tree.
3704 : : *
3705 : : * Note: this function will copy item1 and item2, but it is caller's
3706 : : * responsibility to make sure that the Relids parameters are fresh copies
3707 : : * not shared with other uses.
3708 : : *
3709 : : * Note: we do not do initialize_mergeclause_eclasses() here. It is
3710 : : * caller's responsibility that left_ec/right_ec be set as necessary.
3711 : : */
3712 : : RestrictInfo *
3713 : 70905 : build_implied_join_equality(PlannerInfo *root,
3714 : : Oid opno,
3715 : : Oid collation,
3716 : : Expr *item1,
3717 : : Expr *item2,
3718 : : Relids qualscope,
3719 : : Index security_level)
3720 : : {
3721 : : RestrictInfo *restrictinfo;
3722 : : Expr *clause;
3723 : :
3724 : : /*
3725 : : * Build the new clause. Copy to ensure it shares no substructure with
3726 : : * original (this is necessary in case there are subselects in there...)
3727 : : */
3728 : 70905 : clause = make_opclause(opno,
3729 : : BOOLOID, /* opresulttype */
3730 : : false, /* opretset */
3731 : 70905 : copyObject(item1),
3732 : 70905 : copyObject(item2),
3733 : : InvalidOid,
3734 : : collation);
3735 : :
3736 : : /*
3737 : : * Build the RestrictInfo node itself.
3738 : : */
3739 : 70905 : restrictinfo = make_restrictinfo(root,
3740 : : clause,
3741 : : true, /* is_pushed_down */
3742 : : false, /* !has_clone */
3743 : : false, /* !is_clone */
3744 : : false, /* pseudoconstant */
3745 : : security_level, /* security_level */
3746 : : qualscope, /* required_relids */
3747 : : NULL, /* incompatible_relids */
3748 : : NULL); /* outer_relids */
3749 : :
3750 : : /* Set mergejoinability/hashjoinability flags */
3751 : 70905 : check_mergejoinable(restrictinfo);
3752 : 70905 : check_hashjoinable(restrictinfo);
3753 : 70905 : check_memoizable(restrictinfo);
3754 : :
3755 : 70905 : return restrictinfo;
3756 : : }
3757 : :
3758 : : /*
3759 : : * get_join_domain_min_rels
3760 : : * Identify the appropriate join level for derived quals belonging
3761 : : * to the join domain with the given relids.
3762 : : *
3763 : : * When we derive a pseudoconstant (Var-free) clause from an EquivalenceClass,
3764 : : * we'd ideally apply the clause at the top level of the EC's join domain.
3765 : : * However, if there are any outer joins inside that domain that get commuted
3766 : : * with joins outside it, that leads to not finding a correct place to apply
3767 : : * the clause. Instead, remove any lower outer joins from the relid set,
3768 : : * and apply the clause to just the remaining rels. This still results in a
3769 : : * correct answer, since if the clause produces FALSE then the LHS of these
3770 : : * joins will be empty leading to an empty join result.
3771 : : *
3772 : : * However, there's no need to remove outer joins if this is the top-level
3773 : : * join domain of the query, since then there's nothing else to commute with.
3774 : : *
3775 : : * Note: it's tempting to use this in distribute_qual_to_rels where it's
3776 : : * dealing with pseudoconstant quals; but we can't because the necessary
3777 : : * SpecialJoinInfos aren't all formed at that point.
3778 : : *
3779 : : * The result is always freshly palloc'd; we do not modify domain_relids.
3780 : : */
3781 : : static Relids
3782 : 145 : get_join_domain_min_rels(PlannerInfo *root, Relids domain_relids)
3783 : : {
3784 : 145 : Relids result = bms_copy(domain_relids);
3785 : : ListCell *lc;
3786 : :
3787 : : /* Top-level join domain? */
3788 [ + + ]: 145 : if (bms_equal(result, root->all_query_rels))
3789 : 80 : return result;
3790 : :
3791 : : /* Nope, look for lower outer joins that could potentially commute out */
3792 [ + - + + : 135 : foreach(lc, root->join_info_list)
+ + ]
3793 : : {
3794 : 70 : SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(lc);
3795 : :
3796 [ + + + + ]: 130 : if (sjinfo->jointype == JOIN_LEFT &&
3797 : 60 : bms_is_member(sjinfo->ojrelid, result))
3798 : : {
3799 : 5 : result = bms_del_member(result, sjinfo->ojrelid);
3800 : 5 : result = bms_del_members(result, sjinfo->syn_righthand);
3801 : : }
3802 : : }
3803 : 65 : return result;
3804 : : }
3805 : :
3806 : :
3807 : : /*
3808 : : * match_foreign_keys_to_quals
3809 : : * Match foreign-key constraints to equivalence classes and join quals
3810 : : *
3811 : : * The idea here is to see which query join conditions match equality
3812 : : * constraints of a foreign-key relationship. For such join conditions,
3813 : : * we can use the FK semantics to make selectivity estimates that are more
3814 : : * reliable than estimating from statistics, especially for multiple-column
3815 : : * FKs, where the normal assumption of independent conditions tends to fail.
3816 : : *
3817 : : * In this function we annotate the ForeignKeyOptInfos in root->fkey_list
3818 : : * with info about which eclasses and join qual clauses they match, and
3819 : : * discard any ForeignKeyOptInfos that are irrelevant for the query.
3820 : : */
3821 : : void
3822 : 252932 : match_foreign_keys_to_quals(PlannerInfo *root)
3823 : : {
3824 : 252932 : List *newlist = NIL;
3825 : : ListCell *lc;
3826 : :
3827 [ + + + + : 254445 : foreach(lc, root->fkey_list)
+ + ]
3828 : : {
3829 : 1513 : ForeignKeyOptInfo *fkinfo = (ForeignKeyOptInfo *) lfirst(lc);
3830 : : RelOptInfo *con_rel;
3831 : : RelOptInfo *ref_rel;
3832 : : int colno;
3833 : :
3834 : : /*
3835 : : * Either relid might identify a rel that is in the query's rtable but
3836 : : * isn't referenced by the jointree (typically because it's been
3837 : : * removed by join removal), so that it won't have a RelOptInfo. Hence
3838 : : * don't use find_base_rel() here. We can ignore such FKs.
3839 : : */
3840 [ + - ]: 1513 : if (fkinfo->con_relid >= root->simple_rel_array_size ||
3841 [ - + ]: 1513 : fkinfo->ref_relid >= root->simple_rel_array_size)
3842 : 0 : continue; /* just paranoia */
3843 : 1513 : con_rel = root->simple_rel_array[fkinfo->con_relid];
3844 [ - + ]: 1513 : if (con_rel == NULL)
3845 : 0 : continue;
3846 : 1513 : ref_rel = root->simple_rel_array[fkinfo->ref_relid];
3847 [ + + ]: 1513 : if (ref_rel == NULL)
3848 : 20 : continue;
3849 : :
3850 : : /*
3851 : : * Ignore FK unless both rels are baserels. This gets rid of FKs that
3852 : : * link to inheritance child rels (otherrels).
3853 : : */
3854 [ + - ]: 1493 : if (con_rel->reloptkind != RELOPT_BASEREL ||
3855 [ - + ]: 1493 : ref_rel->reloptkind != RELOPT_BASEREL)
3856 : 0 : continue;
3857 : :
3858 : : /*
3859 : : * Scan the columns and try to match them to eclasses and quals.
3860 : : *
3861 : : * Note: for simple inner joins, any match should be in an eclass.
3862 : : * "Loose" quals that syntactically match an FK equality must have
3863 : : * been rejected for EC status because they are outer-join quals or
3864 : : * similar. We can still consider them to match the FK.
3865 : : */
3866 [ + + ]: 3436 : for (colno = 0; colno < fkinfo->nkeys; colno++)
3867 : : {
3868 : : EquivalenceClass *ec;
3869 : : AttrNumber con_attno,
3870 : : ref_attno;
3871 : : Oid fpeqop;
3872 : : ListCell *lc2;
3873 : :
3874 : 1943 : ec = match_eclasses_to_foreign_key_col(root, fkinfo, colno);
3875 : : /* Don't bother looking for loose quals if we got an EC match */
3876 [ + + ]: 1943 : if (ec != NULL)
3877 : : {
3878 : 345 : fkinfo->nmatched_ec++;
3879 [ + + ]: 345 : if (ec->ec_has_const)
3880 : 45 : fkinfo->nconst_ec++;
3881 : 345 : continue;
3882 : : }
3883 : :
3884 : : /*
3885 : : * Scan joininfo list for relevant clauses. Either rel's joininfo
3886 : : * list would do equally well; we use con_rel's.
3887 : : */
3888 : 1598 : con_attno = fkinfo->conkey[colno];
3889 : 1598 : ref_attno = fkinfo->confkey[colno];
3890 : 1598 : fpeqop = InvalidOid; /* we'll look this up only if needed */
3891 : :
3892 [ + + + + : 4168 : foreach(lc2, con_rel->joininfo)
+ + ]
3893 : : {
3894 : 2570 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc2);
3895 : 2570 : OpExpr *clause = (OpExpr *) rinfo->clause;
3896 : : Var *leftvar;
3897 : : Var *rightvar;
3898 : :
3899 : : /* Only binary OpExprs are useful for consideration */
3900 [ + + - + ]: 5128 : if (!IsA(clause, OpExpr) ||
3901 : 2558 : list_length(clause->args) != 2)
3902 : 12 : continue;
3903 : 2558 : leftvar = (Var *) get_leftop((Expr *) clause);
3904 : 2558 : rightvar = (Var *) get_rightop((Expr *) clause);
3905 : :
3906 : : /* Operands must be Vars, possibly with RelabelType */
3907 [ + - + + ]: 2763 : while (leftvar && IsA(leftvar, RelabelType))
3908 : 205 : leftvar = (Var *) ((RelabelType *) leftvar)->arg;
3909 [ + - + + ]: 2558 : if (!(leftvar && IsA(leftvar, Var)))
3910 : 12 : continue;
3911 [ + - + + ]: 2736 : while (rightvar && IsA(rightvar, RelabelType))
3912 : 190 : rightvar = (Var *) ((RelabelType *) rightvar)->arg;
3913 [ + - + + ]: 2546 : if (!(rightvar && IsA(rightvar, Var)))
3914 : 25 : continue;
3915 : :
3916 : : /* Now try to match the vars to the current foreign key cols */
3917 [ + + ]: 2521 : if (fkinfo->ref_relid == leftvar->varno &&
3918 [ + + ]: 2416 : ref_attno == leftvar->varattno &&
3919 [ + - ]: 1371 : fkinfo->con_relid == rightvar->varno &&
3920 [ + + ]: 1371 : con_attno == rightvar->varattno)
3921 : : {
3922 : : /* Vars match, but is it the right operator? */
3923 [ + - ]: 1306 : if (clause->opno == fkinfo->conpfeqop[colno])
3924 : : {
3925 : 1306 : fkinfo->rinfos[colno] = lappend(fkinfo->rinfos[colno],
3926 : : rinfo);
3927 : 1306 : fkinfo->nmatched_ri++;
3928 : : }
3929 : : }
3930 [ + + ]: 1215 : else if (fkinfo->ref_relid == rightvar->varno &&
3931 [ + + ]: 75 : ref_attno == rightvar->varattno &&
3932 [ + - ]: 30 : fkinfo->con_relid == leftvar->varno &&
3933 [ + - ]: 30 : con_attno == leftvar->varattno)
3934 : : {
3935 : : /*
3936 : : * Reverse match, must check commutator operator. Look it
3937 : : * up if we didn't already. (In the worst case we might
3938 : : * do multiple lookups here, but that would require an FK
3939 : : * equality operator without commutator, which is
3940 : : * unlikely.)
3941 : : */
3942 [ + - ]: 30 : if (!OidIsValid(fpeqop))
3943 : 30 : fpeqop = get_commutator(fkinfo->conpfeqop[colno]);
3944 [ + - ]: 30 : if (clause->opno == fpeqop)
3945 : : {
3946 : 30 : fkinfo->rinfos[colno] = lappend(fkinfo->rinfos[colno],
3947 : : rinfo);
3948 : 30 : fkinfo->nmatched_ri++;
3949 : : }
3950 : : }
3951 : : }
3952 : : /* If we found any matching loose quals, count col as matched */
3953 [ + + ]: 1598 : if (fkinfo->rinfos[colno])
3954 : 1336 : fkinfo->nmatched_rcols++;
3955 : : }
3956 : :
3957 : : /*
3958 : : * Currently, we drop multicolumn FKs that aren't fully matched to the
3959 : : * query. Later we might figure out how to derive some sort of
3960 : : * estimate from them, in which case this test should be weakened to
3961 : : * "if ((fkinfo->nmatched_ec + fkinfo->nmatched_rcols) > 0)".
3962 : : */
3963 [ + + ]: 1493 : if ((fkinfo->nmatched_ec + fkinfo->nmatched_rcols) == fkinfo->nkeys)
3964 : 1251 : newlist = lappend(newlist, fkinfo);
3965 : : }
3966 : : /* Replace fkey_list, thereby discarding any useless entries */
3967 : 252932 : root->fkey_list = newlist;
3968 : 252932 : }
3969 : :
3970 : :
3971 : : /*****************************************************************************
3972 : : *
3973 : : * CHECKS FOR MERGEJOINABLE AND HASHJOINABLE CLAUSES
3974 : : *
3975 : : *****************************************************************************/
3976 : :
3977 : : /*
3978 : : * check_mergejoinable
3979 : : * If the restrictinfo's clause is mergejoinable, set the mergejoin
3980 : : * info fields in the restrictinfo.
3981 : : *
3982 : : * Currently, we support mergejoin for binary opclauses where
3983 : : * the operator is a mergejoinable operator. The arguments can be
3984 : : * anything --- as long as there are no volatile functions in them.
3985 : : */
3986 : : static void
3987 : 540245 : check_mergejoinable(RestrictInfo *restrictinfo)
3988 : : {
3989 : 540245 : Expr *clause = restrictinfo->clause;
3990 : : Oid opno;
3991 : : Node *leftarg;
3992 : :
3993 [ + + ]: 540245 : if (restrictinfo->pseudoconstant)
3994 : 9212 : return;
3995 [ + + ]: 531033 : if (!is_opclause(clause))
3996 : 73421 : return;
3997 [ + + ]: 457612 : if (list_length(((OpExpr *) clause)->args) != 2)
3998 : 20 : return;
3999 : :
4000 : 457592 : opno = ((OpExpr *) clause)->opno;
4001 : 457592 : leftarg = linitial(((OpExpr *) clause)->args);
4002 : :
4003 [ + + ]: 457592 : if (op_mergejoinable(opno, exprType(leftarg)) &&
4004 [ + + ]: 395087 : !contain_volatile_functions((Node *) restrictinfo))
4005 : 394916 : restrictinfo->mergeopfamilies = get_mergejoin_opfamilies(opno);
4006 : :
4007 : : /*
4008 : : * Note: op_mergejoinable is just a hint; if we fail to find the operator
4009 : : * in any btree opfamilies, mergeopfamilies remains NIL and so the clause
4010 : : * is not treated as mergejoinable.
4011 : : */
4012 : : }
4013 : :
4014 : : /*
4015 : : * check_hashjoinable
4016 : : * If the restrictinfo's clause is hashjoinable, set the hashjoin
4017 : : * info fields in the restrictinfo.
4018 : : *
4019 : : * Currently, we support hashjoin for binary opclauses where
4020 : : * the operator is a hashjoinable operator. The arguments can be
4021 : : * anything --- as long as there are no volatile functions in them.
4022 : : */
4023 : : static void
4024 : 137059 : check_hashjoinable(RestrictInfo *restrictinfo)
4025 : : {
4026 : 137059 : Expr *clause = restrictinfo->clause;
4027 : : Oid opno;
4028 : : Node *leftarg;
4029 : :
4030 [ + + ]: 137059 : if (restrictinfo->pseudoconstant)
4031 : 5470 : return;
4032 [ + + ]: 131589 : if (!is_opclause(clause))
4033 : 6501 : return;
4034 [ - + ]: 125088 : if (list_length(((OpExpr *) clause)->args) != 2)
4035 : 0 : return;
4036 : :
4037 : 125088 : opno = ((OpExpr *) clause)->opno;
4038 : 125088 : leftarg = linitial(((OpExpr *) clause)->args);
4039 : :
4040 [ + + ]: 125088 : if (op_hashjoinable(opno, exprType(leftarg)) &&
4041 [ + + ]: 122494 : !contain_volatile_functions((Node *) restrictinfo))
4042 : 122488 : restrictinfo->hashjoinoperator = opno;
4043 : : }
4044 : :
4045 : : /*
4046 : : * check_memoizable
4047 : : * If the restrictinfo's clause is suitable to be used for a Memoize node,
4048 : : * set the left_hasheqoperator and right_hasheqoperator to the hash equality
4049 : : * operator that will be needed during caching.
4050 : : *
4051 : : * When the clause is hashjoinable, the cache must use the same notion of
4052 : : * equality as the join operator, as the type's default equality operator
4053 : : * could consider values equal that the join operator does not. If both
4054 : : * inputs are of the same type, we can just use the join operator itself;
4055 : : * otherwise we look up the same-type equality operators in the join
4056 : : * operator's hash opfamily, and if there are none, Memoize won't be used.
4057 : : * When the clause is not hashjoinable, we use the type's default equality
4058 : : * operator and Memoize uses binary mode.
4059 : : *
4060 : : * Note: check_hashjoinable() must be called on the given RestrictInfo before
4061 : : * calling this function.
4062 : : */
4063 : : static void
4064 : 137059 : check_memoizable(RestrictInfo *restrictinfo)
4065 : : {
4066 : : TypeCacheEntry *typentry;
4067 : 137059 : Expr *clause = restrictinfo->clause;
4068 : 137059 : Oid hashop = restrictinfo->hashjoinoperator;
4069 : : Oid lefttype;
4070 : : Oid righttype;
4071 : :
4072 [ + + ]: 137059 : if (restrictinfo->pseudoconstant)
4073 : 5470 : return;
4074 [ + + ]: 131589 : if (!is_opclause(clause))
4075 : 6501 : return;
4076 [ - + ]: 125088 : if (list_length(((OpExpr *) clause)->args) != 2)
4077 : 0 : return;
4078 : :
4079 : 125088 : lefttype = exprType(linitial(((OpExpr *) clause)->args));
4080 : 125088 : righttype = exprType(lsecond(((OpExpr *) clause)->args));
4081 : :
4082 [ + + ]: 125088 : if (OidIsValid(hashop))
4083 : : {
4084 [ + + ]: 122488 : if (lefttype == righttype)
4085 : 120848 : restrictinfo->left_hasheqoperator =
4086 : 120848 : restrictinfo->right_hasheqoperator = hashop;
4087 : : else
4088 : 1640 : (void) get_compatible_hash_operators(restrictinfo->hashjoinoperator,
4089 : : &restrictinfo->left_hasheqoperator,
4090 : : &restrictinfo->right_hasheqoperator);
4091 : : }
4092 : : else
4093 : : {
4094 : : /* No hashjoinoperator. Memoize will use binary mode. */
4095 : 2600 : typentry = lookup_type_cache(lefttype, TYPECACHE_HASH_PROC |
4096 : : TYPECACHE_EQ_OPR);
4097 : :
4098 [ + + + - ]: 2600 : if (OidIsValid(typentry->hash_proc) && OidIsValid(typentry->eq_opr))
4099 : 2260 : restrictinfo->left_hasheqoperator = typentry->eq_opr;
4100 : :
4101 : : /*
4102 : : * Lookup the right type, unless it's the same as the left type, in
4103 : : * which case typentry is already pointing to the required
4104 : : * TypeCacheEntry.
4105 : : */
4106 [ + + ]: 2600 : if (lefttype != righttype)
4107 : 365 : typentry = lookup_type_cache(righttype, TYPECACHE_HASH_PROC |
4108 : : TYPECACHE_EQ_OPR);
4109 : :
4110 [ + + + - ]: 2600 : if (OidIsValid(typentry->hash_proc) && OidIsValid(typentry->eq_opr))
4111 : 2095 : restrictinfo->right_hasheqoperator = typentry->eq_opr;
4112 : : }
4113 : : }
|