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