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