Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * subselect.c
4 : : * Planning routines for subselects.
5 : : *
6 : : * This module deals with SubLinks and CTEs, but not subquery RTEs (i.e.,
7 : : * not sub-SELECT-in-FROM cases).
8 : : *
9 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
10 : : * Portions Copyright (c) 1994, Regents of the University of California
11 : : *
12 : : * IDENTIFICATION
13 : : * src/backend/optimizer/plan/subselect.c
14 : : *
15 : : *-------------------------------------------------------------------------
16 : : */
17 : : #include "postgres.h"
18 : :
19 : : #include "access/htup_details.h"
20 : : #include "catalog/pg_operator.h"
21 : : #include "catalog/pg_type.h"
22 : : #include "executor/executor.h"
23 : : #include "executor/nodeSubplan.h"
24 : : #include "miscadmin.h"
25 : : #include "nodes/makefuncs.h"
26 : : #include "nodes/nodeFuncs.h"
27 : : #include "optimizer/clauses.h"
28 : : #include "optimizer/cost.h"
29 : : #include "optimizer/optimizer.h"
30 : : #include "optimizer/paramassign.h"
31 : : #include "optimizer/pathnode.h"
32 : : #include "optimizer/planmain.h"
33 : : #include "optimizer/planner.h"
34 : : #include "optimizer/prep.h"
35 : : #include "optimizer/subselect.h"
36 : : #include "parser/parse_relation.h"
37 : : #include "rewrite/rewriteManip.h"
38 : : #include "utils/builtins.h"
39 : : #include "utils/lsyscache.h"
40 : : #include "utils/syscache.h"
41 : :
42 : :
43 : : typedef struct convert_testexpr_context
44 : : {
45 : : PlannerInfo *root;
46 : : List *subst_nodes; /* Nodes to substitute for Params */
47 : : } convert_testexpr_context;
48 : :
49 : : typedef struct process_sublinks_context
50 : : {
51 : : PlannerInfo *root;
52 : : bool isTopQual;
53 : : bool skipPHVs; /* don't descend into PlaceHolderVars? */
54 : : } process_sublinks_context;
55 : :
56 : : typedef struct finalize_primnode_context
57 : : {
58 : : PlannerInfo *root;
59 : : Bitmapset *paramids; /* Non-local PARAM_EXEC paramids found */
60 : : } finalize_primnode_context;
61 : :
62 : : typedef struct inline_cte_walker_context
63 : : {
64 : : const char *ctename; /* name and relative level of target CTE */
65 : : int levelsup;
66 : : Query *ctequery; /* query to substitute */
67 : : } inline_cte_walker_context;
68 : :
69 : :
70 : : static Node *build_subplan(PlannerInfo *root, Plan *plan, Path *path,
71 : : PlannerInfo *subroot, List *plan_params,
72 : : SubLinkType subLinkType, int subLinkId,
73 : : Node *testexpr, List *testexpr_paramids,
74 : : bool unknownEqFalse);
75 : : static List *generate_subquery_params(PlannerInfo *root, List *tlist,
76 : : List **paramIds);
77 : : static List *generate_subquery_vars(PlannerInfo *root, List *tlist,
78 : : Index varno);
79 : : static Node *convert_testexpr(PlannerInfo *root,
80 : : Node *testexpr,
81 : : List *subst_nodes);
82 : : static Node *convert_testexpr_mutator(Node *node,
83 : : convert_testexpr_context *context);
84 : : static bool subplan_is_hashable(Plan *plan, bool unknownEqFalse);
85 : : static bool subpath_is_hashable(Path *path, bool unknownEqFalse);
86 : : static bool testexpr_is_hashable(Node *testexpr, List *param_ids);
87 : : static bool test_opexpr_is_hashable(OpExpr *testexpr, List *param_ids);
88 : : static bool hash_ok_operator(OpExpr *expr);
89 : : static bool contain_dml(Node *node);
90 : : static bool contain_dml_walker(Node *node, void *context);
91 : : static bool contain_outer_selfref(Node *node);
92 : : static bool contain_outer_selfref_walker(Node *node, Index *depth);
93 : : static void inline_cte(PlannerInfo *root, CommonTableExpr *cte);
94 : : static bool inline_cte_walker(Node *node, inline_cte_walker_context *context);
95 : : static bool sublink_testexpr_is_not_nullable(PlannerInfo *root, SubLink *sublink);
96 : : static int add_antijoin_rte(Query *parse);
97 : : static bool simplify_EXISTS_query(PlannerInfo *root, Query *query);
98 : : static Query *convert_EXISTS_to_ANY(PlannerInfo *root, Query *subselect,
99 : : Node **testexpr, List **paramIds);
100 : : static Node *replace_correlation_vars_mutator(Node *node, PlannerInfo *root);
101 : : static Node *process_sublinks_mutator(Node *node,
102 : : process_sublinks_context *context);
103 : : static Bitmapset *finalize_plan(PlannerInfo *root,
104 : : Plan *plan,
105 : : int gather_param,
106 : : Bitmapset *valid_params,
107 : : Bitmapset *scan_params);
108 : : static bool finalize_primnode(Node *node, finalize_primnode_context *context);
109 : : static bool finalize_agg_primnode(Node *node, finalize_primnode_context *context);
110 : : static const char *sublinktype_to_string(SubLinkType subLinkType);
111 : :
112 : :
113 : : /*
114 : : * Get the datatype/typmod/collation of the first column of the plan's output.
115 : : *
116 : : * This information is stored for ARRAY_SUBLINK execution and for
117 : : * exprType()/exprTypmod()/exprCollation(), which have no way to get at the
118 : : * plan associated with a SubPlan node. We really only need the info for
119 : : * EXPR_SUBLINK and ARRAY_SUBLINK subplans, but for consistency we save it
120 : : * always.
121 : : */
122 : : static void
123 : 32812 : get_first_col_type(Plan *plan, Oid *coltype, int32 *coltypmod,
124 : : Oid *colcollation)
125 : : {
126 : : /* In cases such as EXISTS, tlist might be empty; arbitrarily use VOID */
127 [ + + ]: 32812 : if (plan->targetlist)
128 : : {
129 : 30719 : TargetEntry *tent = linitial_node(TargetEntry, plan->targetlist);
130 : :
131 [ + - ]: 30719 : if (!tent->resjunk)
132 : : {
133 : 30719 : *coltype = exprType((Node *) tent->expr);
134 : 30719 : *coltypmod = exprTypmod((Node *) tent->expr);
135 : 30719 : *colcollation = exprCollation((Node *) tent->expr);
136 : 30719 : return;
137 : : }
138 : : }
139 : 2093 : *coltype = VOIDOID;
140 : 2093 : *coltypmod = -1;
141 : 2093 : *colcollation = InvalidOid;
142 : : }
143 : :
144 : : /*
145 : : * Convert a SubLink (as created by the parser) into a SubPlan.
146 : : *
147 : : * We are given the SubLink's contained query, type, ID, and testexpr. We are
148 : : * also told if this expression appears at top level of a WHERE/HAVING qual.
149 : : *
150 : : * Note: we assume that the testexpr has been AND/OR flattened (actually,
151 : : * it's been through eval_const_expressions), but not converted to
152 : : * implicit-AND form; and any SubLinks in it should already have been
153 : : * converted to SubPlans. The subquery is as yet untouched, however.
154 : : *
155 : : * The result is whatever we need to substitute in place of the SubLink node
156 : : * in the executable expression. If we're going to do the subplan as a
157 : : * regular subplan, this will be the constructed SubPlan node. If we're going
158 : : * to do the subplan as an InitPlan, the SubPlan node instead goes into
159 : : * root->init_plans, and what we return here is an expression tree
160 : : * representing the InitPlan's result: usually just a Param node representing
161 : : * a single scalar result, but possibly a row comparison tree containing
162 : : * multiple Param nodes, or for a MULTIEXPR subquery a simple NULL constant
163 : : * (since the real output Params are elsewhere in the tree, and the MULTIEXPR
164 : : * subquery itself is in a resjunk tlist entry whose value is uninteresting).
165 : : */
166 : : static Node *
167 : 29196 : make_subplan(PlannerInfo *root, Query *orig_subquery,
168 : : SubLinkType subLinkType, int subLinkId,
169 : : Node *testexpr, bool isTopQual)
170 : : {
171 : : Query *subquery;
172 : 29196 : bool simple_exists = false;
173 : : double tuple_fraction;
174 : : PlannerInfo *subroot;
175 : : RelOptInfo *final_rel;
176 : : Path *best_path;
177 : : Plan *plan;
178 : : List *plan_params;
179 : : Node *result;
180 : 29196 : const char *sublinkstr = sublinktype_to_string(subLinkType);
181 : :
182 : : /*
183 : : * Copy the source Query node. This is a quick and dirty kluge to resolve
184 : : * the fact that the parser can generate trees with multiple links to the
185 : : * same sub-Query node, but the planner wants to scribble on the Query.
186 : : * Try to clean this up when we do querytree redesign...
187 : : */
188 : 29196 : subquery = copyObject(orig_subquery);
189 : :
190 : : /*
191 : : * If it's an EXISTS subplan, we might be able to simplify it.
192 : : */
193 [ + + ]: 29196 : if (subLinkType == EXISTS_SUBLINK)
194 : 1854 : simple_exists = simplify_EXISTS_query(root, subquery);
195 : :
196 : : /*
197 : : * For an EXISTS subplan, tell lower-level planner to expect that only the
198 : : * first tuple will be retrieved. For ALL and ANY subplans, we will be
199 : : * able to stop evaluating if the test condition fails or matches, so very
200 : : * often not all the tuples will be retrieved; for lack of a better idea,
201 : : * specify 50% retrieval. For EXPR, MULTIEXPR, and ROWCOMPARE subplans,
202 : : * use default behavior (we're only expecting one row out, anyway).
203 : : *
204 : : * NOTE: if you change these numbers, also change cost_subplan() in
205 : : * path/costsize.c.
206 : : *
207 : : * XXX If an ANY subplan is uncorrelated, build_subplan may decide to hash
208 : : * its output. In that case it would've been better to specify full
209 : : * retrieval. At present, however, we can only check hashability after
210 : : * we've made the subplan :-(. (Determining whether it'll fit in hash_mem
211 : : * is the really hard part.) Therefore, we don't want to be too
212 : : * optimistic about the percentage of tuples retrieved, for fear of
213 : : * selecting a plan that's bad for the materialization case.
214 : : */
215 [ + + ]: 29196 : if (subLinkType == EXISTS_SUBLINK)
216 : 1854 : tuple_fraction = 1.0; /* just like a LIMIT 1 */
217 [ + + + + ]: 27342 : else if (subLinkType == ALL_SUBLINK ||
218 : : subLinkType == ANY_SUBLINK)
219 : 601 : tuple_fraction = 0.5; /* 50% */
220 : : else
221 : 26741 : tuple_fraction = 0.0; /* default behavior */
222 : :
223 : : /* plan_params should not be in use in current query level */
224 : : Assert(root->plan_params == NIL);
225 : :
226 : : /* Generate Paths for the subquery */
227 : 29196 : subroot = subquery_planner(root->glob, subquery,
228 : : choose_plan_name(root->glob, sublinkstr, true),
229 : : root, NULL, false, tuple_fraction, NULL);
230 : :
231 : : /* Isolate the params needed by this specific subplan */
232 : 29196 : plan_params = root->plan_params;
233 : 29196 : root->plan_params = NIL;
234 : :
235 : : /*
236 : : * Select best Path and turn it into a Plan. At least for now, there
237 : : * seems no reason to postpone doing that.
238 : : */
239 : 29196 : final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
240 : 29196 : best_path = get_cheapest_fractional_path(final_rel, tuple_fraction);
241 : :
242 : 29196 : plan = create_plan(subroot, best_path);
243 : :
244 : : /* And convert to SubPlan or InitPlan format. */
245 : 29196 : result = build_subplan(root, plan, best_path,
246 : : subroot, plan_params,
247 : : subLinkType, subLinkId,
248 : : testexpr, NIL, isTopQual);
249 : :
250 : : /*
251 : : * If it's a correlated EXISTS with an unimportant targetlist, we might be
252 : : * able to transform it to the equivalent of an IN and then implement it
253 : : * by hashing. We don't have enough information yet to tell which way is
254 : : * likely to be better (it depends on the expected number of executions of
255 : : * the EXISTS qual, and we are much too early in planning the outer query
256 : : * to be able to guess that). So we generate both plans, if possible, and
257 : : * leave it to setrefs.c to decide which to use.
258 : : */
259 [ + + + + ]: 29196 : if (simple_exists && IsA(result, SubPlan))
260 : : {
261 : : Node *newtestexpr;
262 : : List *paramIds;
263 : :
264 : : /* Make a second copy of the original subquery */
265 : 1569 : subquery = copyObject(orig_subquery);
266 : : /* and re-simplify */
267 : 1569 : simple_exists = simplify_EXISTS_query(root, subquery);
268 : : Assert(simple_exists);
269 : : /* See if it can be converted to an ANY query */
270 : 1569 : subquery = convert_EXISTS_to_ANY(root, subquery,
271 : : &newtestexpr, ¶mIds);
272 [ + + ]: 1569 : if (subquery)
273 : : {
274 : : char *plan_name;
275 : :
276 : : /*
277 : : * Generate Paths for the ANY subquery; we'll need all rows. Use a
278 : : * distinct prefix for this user-visible name, since this is an
279 : : * ANY implementation of the original EXISTS subplan.
280 : : */
281 : 1279 : plan_name = choose_plan_name(root->glob, "exists_to_any", true);
282 : 1279 : subroot = subquery_planner(root->glob, subquery, plan_name,
283 : : root, subroot, false, 0.0, NULL);
284 : :
285 : : /* Isolate the params needed by this specific subplan */
286 : 1279 : plan_params = root->plan_params;
287 : 1279 : root->plan_params = NIL;
288 : :
289 : : /* Select best Path */
290 : 1279 : final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
291 : 1279 : best_path = final_rel->cheapest_total_path;
292 : :
293 : : /* Now we can check if it'll fit in hash_mem */
294 [ + + ]: 1279 : if (subpath_is_hashable(best_path, true))
295 : : {
296 : : SubPlan *hashplan;
297 : : AlternativeSubPlan *asplan;
298 : :
299 : : /* OK, finish planning the ANY subquery */
300 : 1274 : plan = create_plan(subroot, best_path);
301 : :
302 : : /* ... and convert to SubPlan format */
303 : 1274 : hashplan = castNode(SubPlan,
304 : : build_subplan(root, plan, best_path,
305 : : subroot, plan_params,
306 : : ANY_SUBLINK, 0,
307 : : newtestexpr,
308 : : paramIds,
309 : : true));
310 : : /* Check we got what we expected */
311 : : Assert(hashplan->parParam == NIL);
312 : : Assert(hashplan->useHashTable);
313 : :
314 : : /* Leave it to setrefs.c to decide which plan to use */
315 : 1274 : asplan = makeNode(AlternativeSubPlan);
316 : 1274 : asplan->subplans = list_make2(result, hashplan);
317 : 1274 : result = (Node *) asplan;
318 : 1274 : root->hasAlternativeSubPlans = true;
319 : : }
320 : : }
321 : : }
322 : :
323 : 29196 : return result;
324 : : }
325 : :
326 : : /*
327 : : * Build a SubPlan node given the raw inputs --- subroutine for make_subplan
328 : : *
329 : : * Returns either the SubPlan, or a replacement expression if we decide to
330 : : * make it an InitPlan, as explained in the comments for make_subplan.
331 : : */
332 : : static Node *
333 : 30470 : build_subplan(PlannerInfo *root, Plan *plan, Path *path,
334 : : PlannerInfo *subroot, List *plan_params,
335 : : SubLinkType subLinkType, int subLinkId,
336 : : Node *testexpr, List *testexpr_paramids,
337 : : bool unknownEqFalse)
338 : : {
339 : : Node *result;
340 : : SubPlan *splan;
341 : : ListCell *lc;
342 : :
343 : : /*
344 : : * Initialize the SubPlan node.
345 : : *
346 : : * Note: plan_id and cost fields are set further down.
347 : : */
348 : 30470 : splan = makeNode(SubPlan);
349 : 30470 : splan->subLinkType = subLinkType;
350 : 30470 : splan->plan_name = subroot->plan_name;
351 : 30470 : splan->testexpr = NULL;
352 : 30470 : splan->paramIds = NIL;
353 : 30470 : get_first_col_type(plan, &splan->firstColType, &splan->firstColTypmod,
354 : : &splan->firstColCollation);
355 : 30470 : splan->useHashTable = false;
356 : 30470 : splan->unknownEqFalse = unknownEqFalse;
357 : 30470 : splan->parallel_safe = plan->parallel_safe;
358 : 30470 : splan->setParam = NIL;
359 : 30470 : splan->parParam = NIL;
360 : 30470 : splan->args = NIL;
361 : :
362 : : /*
363 : : * Make parParam and args lists of param IDs and expressions that current
364 : : * query level will pass to this child plan.
365 : : */
366 [ + + + + : 65374 : foreach(lc, plan_params)
+ + ]
367 : : {
368 : 34904 : PlannerParamItem *pitem = (PlannerParamItem *) lfirst(lc);
369 : 34904 : Node *arg = pitem->item;
370 : :
371 : : /*
372 : : * The Var, PlaceHolderVar, Aggref, GroupingFunc, or ReturningExpr has
373 : : * already been adjusted to have the correct varlevelsup, phlevelsup,
374 : : * agglevelsup, or retlevelsup.
375 : : *
376 : : * If it's an Aggref, GroupingFunc, or ReturningExpr, its arguments
377 : : * might contain SubLinks, which have not yet been processed (see the
378 : : * comments for SS_replace_correlation_vars). Do that now. A
379 : : * PlaceHolderVar needs no such treatment: subquery_planner already
380 : : * preprocessed the PHVs of its owning level, so its expression is
381 : : * fully processed and may already contain SubPlans. The same goes
382 : : * for any PlaceHolderVars within the arguments, so skip those.
383 : : */
384 [ + + ]: 34904 : if (IsA(arg, Aggref) ||
385 [ + + ]: 34842 : IsA(arg, GroupingFunc) ||
386 [ + + ]: 34785 : IsA(arg, ReturningExpr))
387 : : {
388 : : process_sublinks_context context;
389 : :
390 : 134 : context.root = root;
391 : 134 : context.isTopQual = false;
392 : 134 : context.skipPHVs = true;
393 : 134 : arg = process_sublinks_mutator(arg, &context);
394 : : }
395 : :
396 : 34904 : splan->parParam = lappend_int(splan->parParam, pitem->paramId);
397 : 34904 : splan->args = lappend(splan->args, arg);
398 : : }
399 : :
400 : : /*
401 : : * Un-correlated or undirect correlated plans of EXISTS, EXPR, ARRAY,
402 : : * ROWCOMPARE, or MULTIEXPR types can be used as initPlans. For EXISTS,
403 : : * EXPR, or ARRAY, we return a Param referring to the result of evaluating
404 : : * the initPlan. For ROWCOMPARE, we must modify the testexpr tree to
405 : : * contain PARAM_EXEC Params instead of the PARAM_SUBLINK Params emitted
406 : : * by the parser, and then return that tree. For MULTIEXPR, we return a
407 : : * null constant: the resjunk targetlist item containing the SubLink does
408 : : * not need to return anything useful, since the referencing Params are
409 : : * elsewhere.
410 : : */
411 [ + + + + ]: 30470 : if (splan->parParam == NIL && subLinkType == EXISTS_SUBLINK)
412 : 263 : {
413 : : Param *prm;
414 : :
415 : : Assert(testexpr == NULL);
416 : 263 : prm = generate_new_exec_param(root, BOOLOID, -1, InvalidOid);
417 : 263 : splan->setParam = list_make1_int(prm->paramid);
418 : 263 : splan->isInitPlan = true;
419 : 263 : result = (Node *) prm;
420 : : }
421 [ + + + + ]: 30207 : else if (splan->parParam == NIL && subLinkType == EXPR_SUBLINK)
422 : 6881 : {
423 : 6881 : TargetEntry *te = linitial(plan->targetlist);
424 : : Param *prm;
425 : :
426 : : Assert(!te->resjunk);
427 : : Assert(testexpr == NULL);
428 : 6881 : prm = generate_new_exec_param(root,
429 : 6881 : exprType((Node *) te->expr),
430 : 6881 : exprTypmod((Node *) te->expr),
431 : 6881 : exprCollation((Node *) te->expr));
432 : 6881 : splan->setParam = list_make1_int(prm->paramid);
433 : 6881 : splan->isInitPlan = true;
434 : 6881 : result = (Node *) prm;
435 : : }
436 [ + + + + ]: 23326 : else if (splan->parParam == NIL && subLinkType == ARRAY_SUBLINK)
437 : 92 : {
438 : 92 : TargetEntry *te = linitial(plan->targetlist);
439 : : Oid arraytype;
440 : : Param *prm;
441 : :
442 : : Assert(!te->resjunk);
443 : : Assert(testexpr == NULL);
444 : 92 : arraytype = get_promoted_array_type(exprType((Node *) te->expr));
445 [ - + ]: 92 : if (!OidIsValid(arraytype))
446 [ # # ]: 0 : elog(ERROR, "could not find array type for datatype %s",
447 : : format_type_be(exprType((Node *) te->expr)));
448 : 92 : prm = generate_new_exec_param(root,
449 : : arraytype,
450 : 92 : exprTypmod((Node *) te->expr),
451 : 92 : exprCollation((Node *) te->expr));
452 : 92 : splan->setParam = list_make1_int(prm->paramid);
453 : 92 : splan->isInitPlan = true;
454 : 92 : result = (Node *) prm;
455 : : }
456 [ + + + + ]: 23234 : else if (splan->parParam == NIL && subLinkType == ROWCOMPARE_SUBLINK)
457 : 15 : {
458 : : /* Adjust the Params */
459 : : List *params;
460 : :
461 : : Assert(testexpr != NULL);
462 : 15 : params = generate_subquery_params(root,
463 : : plan->targetlist,
464 : : &splan->paramIds);
465 : 15 : result = convert_testexpr(root,
466 : : testexpr,
467 : : params);
468 : 15 : splan->setParam = list_copy(splan->paramIds);
469 : 15 : splan->isInitPlan = true;
470 : :
471 : : /*
472 : : * The executable expression is returned to become part of the outer
473 : : * plan's expression tree; it is not kept in the initplan node.
474 : : */
475 : : }
476 [ + + ]: 23219 : else if (subLinkType == MULTIEXPR_SUBLINK)
477 : : {
478 : : /*
479 : : * Whether it's an initplan or not, it needs to set a PARAM_EXEC Param
480 : : * for each output column.
481 : : */
482 : : List *params;
483 : :
484 : : Assert(testexpr == NULL);
485 : 108 : params = generate_subquery_params(root,
486 : : plan->targetlist,
487 : : &splan->setParam);
488 : :
489 : : /*
490 : : * Save the list of replacement Params in the n'th cell of
491 : : * root->multiexpr_params; setrefs.c will use it to replace
492 : : * PARAM_MULTIEXPR Params.
493 : : */
494 [ + + ]: 216 : while (list_length(root->multiexpr_params) < subLinkId)
495 : 108 : root->multiexpr_params = lappend(root->multiexpr_params, NIL);
496 : 108 : lc = list_nth_cell(root->multiexpr_params, subLinkId - 1);
497 : : Assert(lfirst(lc) == NIL);
498 : 108 : lfirst(lc) = params;
499 : :
500 : : /* It can be an initplan if there are no parParams. */
501 [ + + ]: 108 : if (splan->parParam == NIL)
502 : : {
503 : 25 : splan->isInitPlan = true;
504 : 25 : result = (Node *) makeNullConst(RECORDOID, -1, InvalidOid);
505 : : }
506 : : else
507 : : {
508 : 83 : splan->isInitPlan = false;
509 : 83 : result = (Node *) splan;
510 : : }
511 : : }
512 : : else
513 : : {
514 : : /*
515 : : * Adjust the Params in the testexpr, unless caller already took care
516 : : * of it (as indicated by passing a list of Param IDs).
517 : : */
518 [ + + + + ]: 23111 : if (testexpr && testexpr_paramids == NIL)
519 : 611 : {
520 : : List *params;
521 : :
522 : 611 : params = generate_subquery_params(root,
523 : : plan->targetlist,
524 : : &splan->paramIds);
525 : 611 : splan->testexpr = convert_testexpr(root,
526 : : testexpr,
527 : : params);
528 : : }
529 : : else
530 : : {
531 : 22500 : splan->testexpr = testexpr;
532 : 22500 : splan->paramIds = testexpr_paramids;
533 : : }
534 : :
535 : : /*
536 : : * We can't convert subplans of ALL_SUBLINK or ANY_SUBLINK types to
537 : : * initPlans, even when they are uncorrelated or undirect correlated,
538 : : * because we need to scan the output of the subplan for each outer
539 : : * tuple. But if it's a not-direct-correlated IN (= ANY) test, we
540 : : * might be able to use a hashtable to avoid comparing all the tuples.
541 : : */
542 [ + + ]: 23111 : if (subLinkType == ANY_SUBLINK &&
543 [ + + + + ]: 3606 : splan->parParam == NIL &&
544 [ + + ]: 3507 : subplan_is_hashable(plan, unknownEqFalse) &&
545 : 1751 : testexpr_is_hashable(splan->testexpr, splan->paramIds))
546 : 1721 : splan->useHashTable = true;
547 : :
548 : : /*
549 : : * Otherwise, we have the option to tack a Material node onto the top
550 : : * of the subplan, to reduce the cost of reading it repeatedly. This
551 : : * is pointless for a direct-correlated subplan, since we'd have to
552 : : * recompute its results each time anyway. For uncorrelated/undirect
553 : : * correlated subplans, we add Material unless the subplan's top plan
554 : : * node would materialize its output anyway. Also, if enable_material
555 : : * is false, then the user does not want us to materialize anything
556 : : * unnecessarily, so we don't.
557 : : */
558 [ + + + + ]: 21390 : else if (splan->parParam == NIL && enable_material &&
559 [ + - ]: 50 : !ExecMaterializesOutput(nodeTag(plan)))
560 : 50 : plan = materialize_finished_plan(plan);
561 : :
562 : 23111 : result = (Node *) splan;
563 : 23111 : splan->isInitPlan = false;
564 : : }
565 : :
566 : : /*
567 : : * Add the subplan, its path, and its PlannerInfo to the global lists.
568 : : */
569 : 30470 : root->glob->subplans = lappend(root->glob->subplans, plan);
570 : 30470 : root->glob->subpaths = lappend(root->glob->subpaths, path);
571 : 30470 : root->glob->subroots = lappend(root->glob->subroots, subroot);
572 : 30470 : splan->plan_id = list_length(root->glob->subplans);
573 : :
574 [ + + ]: 30470 : if (splan->isInitPlan)
575 : 7276 : root->init_plans = lappend(root->init_plans, splan);
576 : :
577 : : /*
578 : : * A parameterless subplan (not initplan) should be prepared to handle
579 : : * REWIND efficiently. If it has direct parameters then there's no point
580 : : * since it'll be reset on each scan anyway; and if it's an initplan then
581 : : * there's no point since it won't get re-run without parameter changes
582 : : * anyway. The input of a hashed subplan doesn't need REWIND either.
583 : : */
584 [ + + + + : 30470 : if (splan->parParam == NIL && !splan->isInitPlan && !splan->useHashTable)
+ + ]
585 : 60 : root->glob->rewindPlanIDs = bms_add_member(root->glob->rewindPlanIDs,
586 : : splan->plan_id);
587 : :
588 : : /* Lastly, fill in the cost estimates for use later */
589 : 30470 : cost_subplan(root, splan, plan);
590 : :
591 : 30470 : return result;
592 : : }
593 : :
594 : : /*
595 : : * generate_subquery_params: build a list of Params representing the output
596 : : * columns of a sublink's sub-select, given the sub-select's targetlist.
597 : : *
598 : : * We also return an integer list of the paramids of the Params.
599 : : */
600 : : static List *
601 : 734 : generate_subquery_params(PlannerInfo *root, List *tlist, List **paramIds)
602 : : {
603 : : List *result;
604 : : List *ids;
605 : : ListCell *lc;
606 : :
607 : 734 : result = ids = NIL;
608 [ + - + + : 1692 : foreach(lc, tlist)
+ + ]
609 : : {
610 : 958 : TargetEntry *tent = (TargetEntry *) lfirst(lc);
611 : : Param *param;
612 : :
613 [ + + ]: 958 : if (tent->resjunk)
614 : 10 : continue;
615 : :
616 : 948 : param = generate_new_exec_param(root,
617 : 948 : exprType((Node *) tent->expr),
618 : 948 : exprTypmod((Node *) tent->expr),
619 : 948 : exprCollation((Node *) tent->expr));
620 : 948 : result = lappend(result, param);
621 : 948 : ids = lappend_int(ids, param->paramid);
622 : : }
623 : :
624 : 734 : *paramIds = ids;
625 : 734 : return result;
626 : : }
627 : :
628 : : /*
629 : : * generate_subquery_vars: build a list of Vars representing the output
630 : : * columns of a sublink's sub-select, given the sub-select's targetlist.
631 : : * The Vars have the specified varno (RTE index).
632 : : */
633 : : static List *
634 : 3788 : generate_subquery_vars(PlannerInfo *root, List *tlist, Index varno)
635 : : {
636 : : List *result;
637 : : ListCell *lc;
638 : :
639 : 3788 : result = NIL;
640 [ + - + + : 7657 : foreach(lc, tlist)
+ + ]
641 : : {
642 : 3869 : TargetEntry *tent = (TargetEntry *) lfirst(lc);
643 : : Var *var;
644 : :
645 [ - + ]: 3869 : if (tent->resjunk)
646 : 0 : continue;
647 : :
648 : 3869 : var = makeVarFromTargetEntry(varno, tent);
649 : 3869 : result = lappend(result, var);
650 : : }
651 : :
652 : 3788 : return result;
653 : : }
654 : :
655 : : /*
656 : : * convert_testexpr: convert the testexpr given by the parser into
657 : : * actually executable form. This entails replacing PARAM_SUBLINK Params
658 : : * with Params or Vars representing the results of the sub-select. The
659 : : * nodes to be substituted are passed in as the List result from
660 : : * generate_subquery_params or generate_subquery_vars.
661 : : */
662 : : static Node *
663 : 4644 : convert_testexpr(PlannerInfo *root,
664 : : Node *testexpr,
665 : : List *subst_nodes)
666 : : {
667 : : convert_testexpr_context context;
668 : :
669 : 4644 : context.root = root;
670 : 4644 : context.subst_nodes = subst_nodes;
671 : 4644 : return convert_testexpr_mutator(testexpr, &context);
672 : : }
673 : :
674 : : static Node *
675 : 22321 : convert_testexpr_mutator(Node *node,
676 : : convert_testexpr_context *context)
677 : : {
678 [ + + ]: 22321 : if (node == NULL)
679 : 77 : return NULL;
680 [ + + ]: 22244 : if (IsA(node, Param))
681 : : {
682 : 4842 : Param *param = (Param *) node;
683 : :
684 [ + + ]: 4842 : if (param->paramkind == PARAM_SUBLINK)
685 : : {
686 [ + - - + ]: 9674 : if (param->paramid <= 0 ||
687 : 4837 : param->paramid > list_length(context->subst_nodes))
688 [ # # ]: 0 : elog(ERROR, "unexpected PARAM_SUBLINK ID: %d", param->paramid);
689 : :
690 : : /*
691 : : * We copy the list item to avoid having doubly-linked
692 : : * substructure in the modified parse tree. This is probably
693 : : * unnecessary when it's a Param, but be safe.
694 : : */
695 : 4837 : return (Node *) copyObject(list_nth(context->subst_nodes,
696 : : param->paramid - 1));
697 : : }
698 : : }
699 [ + + ]: 17407 : if (IsA(node, SubLink))
700 : : {
701 : : /*
702 : : * If we come across a nested SubLink, it is neither necessary nor
703 : : * correct to recurse into it: any PARAM_SUBLINKs we might find inside
704 : : * belong to the inner SubLink not the outer. So just return it as-is.
705 : : *
706 : : * This reasoning depends on the assumption that nothing will pull
707 : : * subexpressions into or out of the testexpr field of a SubLink, at
708 : : * least not without replacing PARAM_SUBLINKs first. If we did want
709 : : * to do that we'd need to rethink the parser-output representation
710 : : * altogether, since currently PARAM_SUBLINKs are only unique per
711 : : * SubLink not globally across the query. The whole point of
712 : : * replacing them with Vars or PARAM_EXEC nodes is to make them
713 : : * globally unique before they escape from the SubLink's testexpr.
714 : : *
715 : : * Note: this can't happen when called during SS_process_sublinks,
716 : : * because that recursively processes inner SubLinks first. It can
717 : : * happen when called from convert_ANY_sublink_to_join, though.
718 : : */
719 : 10 : return node;
720 : : }
721 : 17397 : return expression_tree_mutator(node, convert_testexpr_mutator, context);
722 : : }
723 : :
724 : : /*
725 : : * subplan_is_hashable: can we implement an ANY subplan by hashing?
726 : : *
727 : : * This is not responsible for checking whether the combining testexpr
728 : : * is suitable for hashing. We only look at the subquery itself.
729 : : */
730 : : static bool
731 : 1756 : subplan_is_hashable(Plan *plan, bool unknownEqFalse)
732 : : {
733 : : Size hashtablesize;
734 : :
735 : : /*
736 : : * The estimated size of the hashtable holding the subquery result must
737 : : * fit in hash_mem. (Note: reject on equality, to ensure that an estimate
738 : : * of SIZE_MAX disables hashing regardless of the hash_mem limit.)
739 : : */
740 : 1756 : hashtablesize = EstimateSubplanHashTableSpace(plan->plan_rows,
741 : 1756 : plan->plan_width,
742 : : unknownEqFalse);
743 [ + + ]: 1756 : if (hashtablesize >= get_hash_memory_limit())
744 : 5 : return false;
745 : :
746 : 1751 : return true;
747 : : }
748 : :
749 : : /*
750 : : * subpath_is_hashable: can we implement an ANY subplan by hashing?
751 : : *
752 : : * Identical to subplan_is_hashable, but work from a Path for the subplan.
753 : : */
754 : : static bool
755 : 1279 : subpath_is_hashable(Path *path, bool unknownEqFalse)
756 : : {
757 : : Size hashtablesize;
758 : :
759 : : /*
760 : : * The estimated size of the hashtable holding the subquery result must
761 : : * fit in hash_mem. (Note: reject on equality, to ensure that an estimate
762 : : * of SIZE_MAX disables hashing regardless of the hash_mem limit.)
763 : : */
764 : 1279 : hashtablesize = EstimateSubplanHashTableSpace(path->rows,
765 : 1279 : path->pathtarget->width,
766 : : unknownEqFalse);
767 [ + + ]: 1279 : if (hashtablesize >= get_hash_memory_limit())
768 : 5 : return false;
769 : :
770 : 1274 : return true;
771 : : }
772 : :
773 : : /*
774 : : * testexpr_is_hashable: is an ANY SubLink's test expression hashable?
775 : : *
776 : : * To identify LHS vs RHS of the hash expression, we must be given the
777 : : * list of output Param IDs of the SubLink's subquery.
778 : : */
779 : : static bool
780 : 1751 : testexpr_is_hashable(Node *testexpr, List *param_ids)
781 : : {
782 : : /*
783 : : * The testexpr must be a single OpExpr, or an AND-clause containing only
784 : : * OpExprs, each of which satisfy test_opexpr_is_hashable().
785 : : */
786 [ + - + + ]: 1751 : if (testexpr && IsA(testexpr, OpExpr))
787 : : {
788 [ + + ]: 1012 : if (test_opexpr_is_hashable((OpExpr *) testexpr, param_ids))
789 : 987 : return true;
790 : : }
791 [ + + ]: 739 : else if (is_andclause(testexpr))
792 : : {
793 : : ListCell *l;
794 : :
795 [ + - + + : 2202 : foreach(l, ((BoolExpr *) testexpr)->args)
+ + ]
796 : : {
797 : 1468 : Node *andarg = (Node *) lfirst(l);
798 : :
799 [ - + ]: 1468 : if (!IsA(andarg, OpExpr))
800 : 0 : return false;
801 [ - + ]: 1468 : if (!test_opexpr_is_hashable((OpExpr *) andarg, param_ids))
802 : 0 : return false;
803 : : }
804 : 734 : return true;
805 : : }
806 : :
807 : 30 : return false;
808 : : }
809 : :
810 : : static bool
811 : 2480 : test_opexpr_is_hashable(OpExpr *testexpr, List *param_ids)
812 : : {
813 : : /*
814 : : * The combining operator must be hashable and strict. The need for
815 : : * hashability is obvious, since we want to use hashing. Without
816 : : * strictness, behavior in the presence of nulls is too unpredictable. We
817 : : * actually must assume even more than plain strictness: it can't yield
818 : : * NULL for non-null inputs, either (see nodeSubplan.c). However, hash
819 : : * indexes and hash joins assume that too.
820 : : */
821 [ + + ]: 2480 : if (!hash_ok_operator(testexpr))
822 : 15 : return false;
823 : :
824 : : /*
825 : : * The left and right inputs must belong to the outer and inner queries
826 : : * respectively; hence Params that will be supplied by the subquery must
827 : : * not appear in the LHS, and Vars of the outer query must not appear in
828 : : * the RHS. (Ordinarily, this must be true because of the way that the
829 : : * parser builds an ANY SubLink's testexpr ... but inlining of functions
830 : : * could have changed the expression's structure, so we have to check.
831 : : * Such cases do not occur often enough to be worth trying to optimize, so
832 : : * we don't worry about trying to commute the clause or anything like
833 : : * that; we just need to be sure not to build an invalid plan.)
834 : : */
835 [ - + ]: 2465 : if (list_length(testexpr->args) != 2)
836 : 0 : return false;
837 [ + + ]: 2465 : if (contain_exec_param((Node *) linitial(testexpr->args), param_ids))
838 : 10 : return false;
839 [ - + ]: 2455 : if (contain_var_clause((Node *) lsecond(testexpr->args)))
840 : 0 : return false;
841 : 2455 : return true;
842 : : }
843 : :
844 : : /*
845 : : * Check expression is hashable + strict
846 : : *
847 : : * We could use op_hashjoinable() and op_strict(), but do it like this to
848 : : * avoid a redundant cache lookup.
849 : : */
850 : : static bool
851 : 7152 : hash_ok_operator(OpExpr *expr)
852 : : {
853 : 7152 : Oid opid = expr->opno;
854 : :
855 : : /* quick out if not a binary operator */
856 [ - + ]: 7152 : if (list_length(expr->args) != 2)
857 : 0 : return false;
858 [ + - + + ]: 7152 : if (opid == ARRAY_EQ_OP ||
859 [ + - ]: 7142 : opid == RECORD_EQ_OP ||
860 [ - + ]: 7142 : opid == RANGE_EQ_OP ||
861 : : opid == MULTIRANGE_EQ_OP)
862 : : {
863 : : /* these are strict, but must check input type to ensure hashable */
864 : 10 : Node *leftarg = linitial(expr->args);
865 : :
866 : 10 : return op_hashjoinable(opid, exprType(leftarg));
867 : : }
868 : : else
869 : : {
870 : : /* else must look up the operator properties */
871 : : HeapTuple tup;
872 : : Form_pg_operator optup;
873 : :
874 : 7142 : tup = SearchSysCache1(OPEROID, ObjectIdGetDatum(opid));
875 [ - + ]: 7142 : if (!HeapTupleIsValid(tup))
876 [ # # ]: 0 : elog(ERROR, "cache lookup failed for operator %u", opid);
877 : 7142 : optup = (Form_pg_operator) GETSTRUCT(tup);
878 [ + + - + ]: 7142 : if (!optup->oprcanhash || !func_strict(optup->oprcode))
879 : : {
880 : 481 : ReleaseSysCache(tup);
881 : 481 : return false;
882 : : }
883 : 6661 : ReleaseSysCache(tup);
884 : 6661 : return true;
885 : : }
886 : : }
887 : :
888 : :
889 : : /*
890 : : * SS_process_ctes: process a query's WITH list
891 : : *
892 : : * Consider each CTE in the WITH list and either ignore it (if it's an
893 : : * unreferenced SELECT), "inline" it to create a regular sub-SELECT-in-FROM,
894 : : * or convert it to an initplan.
895 : : *
896 : : * A side effect is to fill in root->cte_plan_ids with a list that
897 : : * parallels root->parse->cteList and provides the subplan ID for
898 : : * each CTE's initplan, or a dummy ID (-1) if we didn't make an initplan.
899 : : */
900 : : void
901 : 2371 : SS_process_ctes(PlannerInfo *root)
902 : : {
903 : : ListCell *lc;
904 : :
905 : : Assert(root->cte_plan_ids == NIL);
906 : :
907 [ + - + + : 5530 : foreach(lc, root->parse->cteList)
+ + ]
908 : : {
909 : 3163 : CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
910 : 3163 : CmdType cmdType = ((Query *) cte->ctequery)->commandType;
911 : : Query *subquery;
912 : : PlannerInfo *subroot;
913 : : RelOptInfo *final_rel;
914 : : Path *best_path;
915 : : Plan *plan;
916 : : SubPlan *splan;
917 : : int paramid;
918 : :
919 : : /*
920 : : * Ignore SELECT CTEs that are not actually referenced anywhere.
921 : : */
922 [ + + + + ]: 3163 : if (cte->cterefcount == 0 && cmdType == CMD_SELECT)
923 : : {
924 : : /* Make a dummy entry in cte_plan_ids */
925 : 34 : root->cte_plan_ids = lappend_int(root->cte_plan_ids, -1);
926 : 34 : continue;
927 : : }
928 : :
929 : : /*
930 : : * Consider inlining the CTE (creating RTE_SUBQUERY RTE(s)) instead of
931 : : * implementing it as a separately-planned CTE.
932 : : *
933 : : * We cannot inline if any of these conditions hold:
934 : : *
935 : : * 1. The user said not to (the CTEMaterializeAlways option).
936 : : *
937 : : * 2. The CTE is recursive.
938 : : *
939 : : * 3. The CTE has side-effects; this includes either not being a plain
940 : : * SELECT, or containing volatile functions. Inlining might change
941 : : * the side-effects, which would be bad.
942 : : *
943 : : * 4. The CTE is multiply-referenced and contains a self-reference to
944 : : * a recursive CTE outside itself. Inlining would result in multiple
945 : : * recursive self-references, which we don't support.
946 : : *
947 : : * Otherwise, we have an option whether to inline or not. That should
948 : : * always be a win if there's just a single reference, but if the CTE
949 : : * is multiply-referenced then it's unclear: inlining adds duplicate
950 : : * computations, but the ability to absorb restrictions from the outer
951 : : * query level could outweigh that. We do not have nearly enough
952 : : * information at this point to tell whether that's true, so we let
953 : : * the user express a preference. Our default behavior is to inline
954 : : * only singly-referenced CTEs, but a CTE marked CTEMaterializeNever
955 : : * will be inlined even if multiply referenced.
956 : : *
957 : : * Note: we check for volatile functions last, because that's more
958 : : * expensive than the other tests needed.
959 : : */
960 [ + + ]: 3129 : if ((cte->ctematerialized == CTEMaterializeNever ||
961 [ + + ]: 3089 : (cte->ctematerialized == CTEMaterializeDefault &&
962 [ + + ]: 2921 : cte->cterefcount == 1)) &&
963 [ + + + + ]: 2110 : !cte->cterecursive &&
964 : 1244 : cmdType == CMD_SELECT &&
965 [ + + ]: 1244 : !contain_dml(cte->ctequery) &&
966 [ + + ]: 1237 : (cte->cterefcount <= 1 ||
967 [ + + ]: 30 : !contain_outer_selfref(cte->ctequery)) &&
968 [ + + ]: 1227 : !contain_volatile_functions(cte->ctequery))
969 : : {
970 : 1113 : inline_cte(root, cte);
971 : : /* Make a dummy entry in cte_plan_ids */
972 : 1113 : root->cte_plan_ids = lappend_int(root->cte_plan_ids, -1);
973 : 1113 : continue;
974 : : }
975 : :
976 : : /*
977 : : * Copy the source Query node. Probably not necessary, but let's keep
978 : : * this similar to make_subplan.
979 : : */
980 : 2016 : subquery = (Query *) copyObject(cte->ctequery);
981 : :
982 : : /* plan_params should not be in use in current query level */
983 : : Assert(root->plan_params == NIL);
984 : :
985 : : /*
986 : : * Generate Paths for the CTE query. Always plan for full retrieval
987 : : * --- we don't have enough info to predict otherwise.
988 : : */
989 : 2016 : subroot = subquery_planner(root->glob, subquery,
990 : 2016 : choose_plan_name(root->glob, cte->ctename, false),
991 : 2016 : root, NULL, cte->cterecursive, 0.0, NULL);
992 : :
993 : : /*
994 : : * Since the current query level doesn't yet contain any RTEs, it
995 : : * should not be possible for the CTE to have requested parameters of
996 : : * this level.
997 : : */
998 [ - + ]: 2012 : if (root->plan_params)
999 [ # # ]: 0 : elog(ERROR, "unexpected outer reference in CTE query");
1000 : :
1001 : : /*
1002 : : * Select best Path and turn it into a Plan. At least for now, there
1003 : : * seems no reason to postpone doing that.
1004 : : */
1005 : 2012 : final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
1006 : 2012 : best_path = final_rel->cheapest_total_path;
1007 : :
1008 : 2012 : plan = create_plan(subroot, best_path);
1009 : :
1010 : : /*
1011 : : * Make a SubPlan node for it. This is just enough unlike
1012 : : * build_subplan that we can't share code.
1013 : : *
1014 : : * Note: plan_id and cost fields are set further down.
1015 : : */
1016 : 2012 : splan = makeNode(SubPlan);
1017 : 2012 : splan->subLinkType = CTE_SUBLINK;
1018 : 2012 : splan->plan_name = subroot->plan_name;
1019 : 2012 : splan->testexpr = NULL;
1020 : 2012 : splan->paramIds = NIL;
1021 : 2012 : get_first_col_type(plan, &splan->firstColType, &splan->firstColTypmod,
1022 : : &splan->firstColCollation);
1023 : 2012 : splan->useHashTable = false;
1024 : 2012 : splan->unknownEqFalse = false;
1025 : :
1026 : : /*
1027 : : * CTE scans are not considered for parallelism (cf
1028 : : * set_rel_consider_parallel).
1029 : : */
1030 : 2012 : splan->parallel_safe = false;
1031 : 2012 : splan->setParam = NIL;
1032 : 2012 : splan->parParam = NIL;
1033 : 2012 : splan->args = NIL;
1034 : :
1035 : : /*
1036 : : * The node can't have any inputs (since it's an initplan), so the
1037 : : * parParam and args lists remain empty. (It could contain references
1038 : : * to earlier CTEs' output param IDs, but CTE outputs are not
1039 : : * propagated via the args list.)
1040 : : */
1041 : :
1042 : : /*
1043 : : * Assign a param ID to represent the CTE's output. No ordinary
1044 : : * "evaluation" of this param slot ever happens, but we use the param
1045 : : * ID for setParam/chgParam signaling just as if the CTE plan were
1046 : : * returning a simple scalar output. (Also, the executor abuses the
1047 : : * ParamExecData slot for this param ID for communication among
1048 : : * multiple CteScan nodes that might be scanning this CTE.)
1049 : : */
1050 : 2012 : paramid = assign_special_exec_param(root);
1051 : 2012 : splan->setParam = list_make1_int(paramid);
1052 : :
1053 : : /*
1054 : : * Add the subplan, its path, and its PlannerInfo to the global lists.
1055 : : */
1056 : 2012 : root->glob->subplans = lappend(root->glob->subplans, plan);
1057 : 2012 : root->glob->subpaths = lappend(root->glob->subpaths, best_path);
1058 : 2012 : root->glob->subroots = lappend(root->glob->subroots, subroot);
1059 : 2012 : splan->plan_id = list_length(root->glob->subplans);
1060 : :
1061 : 2012 : root->init_plans = lappend(root->init_plans, splan);
1062 : :
1063 : 2012 : root->cte_plan_ids = lappend_int(root->cte_plan_ids, splan->plan_id);
1064 : :
1065 : : /* Lastly, fill in the cost estimates for use later */
1066 : 2012 : cost_subplan(root, splan, plan);
1067 : : }
1068 : 2367 : }
1069 : :
1070 : : /*
1071 : : * contain_dml: is any subquery not a plain SELECT?
1072 : : *
1073 : : * We reject SELECT FOR UPDATE/SHARE as well as INSERT etc.
1074 : : */
1075 : : static bool
1076 : 1244 : contain_dml(Node *node)
1077 : : {
1078 : 1244 : return contain_dml_walker(node, NULL);
1079 : : }
1080 : :
1081 : : static bool
1082 : 83072 : contain_dml_walker(Node *node, void *context)
1083 : : {
1084 [ + + ]: 83072 : if (node == NULL)
1085 : 29359 : return false;
1086 [ + + ]: 53713 : if (IsA(node, Query))
1087 : : {
1088 : 2314 : Query *query = (Query *) node;
1089 : :
1090 [ + - ]: 2314 : if (query->commandType != CMD_SELECT ||
1091 [ + + ]: 2314 : query->rowMarks != NIL)
1092 : 7 : return true;
1093 : :
1094 : 2307 : return query_tree_walker(query, contain_dml_walker, context, 0);
1095 : : }
1096 : 51399 : return expression_tree_walker(node, contain_dml_walker, context);
1097 : : }
1098 : :
1099 : : /*
1100 : : * contain_outer_selfref: is there an external recursive self-reference?
1101 : : */
1102 : : static bool
1103 : 30 : contain_outer_selfref(Node *node)
1104 : : {
1105 : 30 : Index depth = 0;
1106 : :
1107 : : /*
1108 : : * We should be starting with a Query, so that depth will be 1 while
1109 : : * examining its immediate contents.
1110 : : */
1111 : : Assert(IsA(node, Query));
1112 : :
1113 : 30 : return contain_outer_selfref_walker(node, &depth);
1114 : : }
1115 : :
1116 : : static bool
1117 : 675 : contain_outer_selfref_walker(Node *node, Index *depth)
1118 : : {
1119 [ + + ]: 675 : if (node == NULL)
1120 : 405 : return false;
1121 [ + + ]: 270 : if (IsA(node, RangeTblEntry))
1122 : : {
1123 : 25 : RangeTblEntry *rte = (RangeTblEntry *) node;
1124 : :
1125 : : /*
1126 : : * Check for a self-reference to a CTE that's above the Query that our
1127 : : * search started at.
1128 : : */
1129 [ + + ]: 25 : if (rte->rtekind == RTE_CTE &&
1130 [ + - ]: 10 : rte->self_reference &&
1131 [ + - ]: 10 : rte->ctelevelsup >= *depth)
1132 : 10 : return true;
1133 : 15 : return false; /* allow range_table_walker to continue */
1134 : : }
1135 [ + + ]: 245 : if (IsA(node, Query))
1136 : : {
1137 : : /* Recurse into subquery, tracking nesting depth properly */
1138 : 35 : Query *query = (Query *) node;
1139 : : bool result;
1140 : :
1141 : 35 : (*depth)++;
1142 : :
1143 : 35 : result = query_tree_walker(query, contain_outer_selfref_walker,
1144 : : depth, QTW_EXAMINE_RTES_BEFORE);
1145 : :
1146 : 35 : (*depth)--;
1147 : :
1148 : 35 : return result;
1149 : : }
1150 : 210 : return expression_tree_walker(node, contain_outer_selfref_walker, depth);
1151 : : }
1152 : :
1153 : : /*
1154 : : * inline_cte: convert RTE_CTE references to given CTE into RTE_SUBQUERYs
1155 : : */
1156 : : static void
1157 : 1113 : inline_cte(PlannerInfo *root, CommonTableExpr *cte)
1158 : : {
1159 : : struct inline_cte_walker_context context;
1160 : :
1161 : 1113 : context.ctename = cte->ctename;
1162 : : /* Start at levelsup = -1 because we'll immediately increment it */
1163 : 1113 : context.levelsup = -1;
1164 : 1113 : context.ctequery = castNode(Query, cte->ctequery);
1165 : :
1166 : 1113 : (void) inline_cte_walker((Node *) root->parse, &context);
1167 : 1113 : }
1168 : :
1169 : : static bool
1170 : 336700 : inline_cte_walker(Node *node, inline_cte_walker_context *context)
1171 : : {
1172 [ + + ]: 336700 : if (node == NULL)
1173 : 95738 : return false;
1174 [ + + ]: 240962 : if (IsA(node, Query))
1175 : : {
1176 : 7058 : Query *query = (Query *) node;
1177 : :
1178 : 7058 : context->levelsup++;
1179 : :
1180 : : /*
1181 : : * Visit the query's RTE nodes after their contents; otherwise
1182 : : * query_tree_walker would descend into the newly inlined CTE query,
1183 : : * which we don't want.
1184 : : */
1185 : 7058 : (void) query_tree_walker(query, inline_cte_walker, context,
1186 : : QTW_EXAMINE_RTES_AFTER);
1187 : :
1188 : 7058 : context->levelsup--;
1189 : :
1190 : 7058 : return false;
1191 : : }
1192 [ + + ]: 233904 : else if (IsA(node, RangeTblEntry))
1193 : : {
1194 : 12506 : RangeTblEntry *rte = (RangeTblEntry *) node;
1195 : :
1196 [ + + ]: 12506 : if (rte->rtekind == RTE_CTE &&
1197 [ + + ]: 3828 : strcmp(rte->ctename, context->ctename) == 0 &&
1198 [ + + ]: 1138 : rte->ctelevelsup == context->levelsup)
1199 : : {
1200 : : /*
1201 : : * Found a reference to replace. Generate a copy of the CTE query
1202 : : * with appropriate level adjustment for outer references (e.g.,
1203 : : * to other CTEs).
1204 : : */
1205 : 1133 : Query *newquery = copyObject(context->ctequery);
1206 : :
1207 [ + + ]: 1133 : if (context->levelsup > 0)
1208 : 619 : IncrementVarSublevelsUp((Node *) newquery, context->levelsup, 1);
1209 : :
1210 : : /*
1211 : : * Convert the RTE_CTE RTE into a RTE_SUBQUERY.
1212 : : *
1213 : : * Historically, a FOR UPDATE clause has been treated as extending
1214 : : * into views and subqueries, but not into CTEs. We preserve this
1215 : : * distinction by not trying to push rowmarks into the new
1216 : : * subquery.
1217 : : */
1218 : 1133 : rte->rtekind = RTE_SUBQUERY;
1219 : 1133 : rte->subquery = newquery;
1220 : 1133 : rte->security_barrier = false;
1221 : :
1222 : : /* Zero out CTE-specific fields */
1223 : 1133 : rte->ctename = NULL;
1224 : 1133 : rte->ctelevelsup = 0;
1225 : 1133 : rte->self_reference = false;
1226 : 1133 : rte->coltypes = NIL;
1227 : 1133 : rte->coltypmods = NIL;
1228 : 1133 : rte->colcollations = NIL;
1229 : : }
1230 : :
1231 : 12506 : return false;
1232 : : }
1233 : :
1234 : 221398 : return expression_tree_walker(node, inline_cte_walker, context);
1235 : : }
1236 : :
1237 : : /*
1238 : : * Attempt to transform 'testexpr' over the VALUES subquery into
1239 : : * a ScalarArrayOpExpr. We currently support the transformation only when
1240 : : * it ends up with a constant array. Otherwise, the evaluation of non-hashed
1241 : : * SAOP might be slower than the corresponding Hash Join with VALUES.
1242 : : *
1243 : : * Return transformed ScalarArrayOpExpr or NULL if transformation isn't
1244 : : * allowed.
1245 : : */
1246 : : ScalarArrayOpExpr *
1247 : 3865 : convert_VALUES_to_ANY(PlannerInfo *root, Node *testexpr, Query *values)
1248 : : {
1249 : : RangeTblEntry *rte;
1250 : : Node *leftop;
1251 : : Node *rightop;
1252 : : Oid opno;
1253 : : ListCell *lc;
1254 : : Oid inputcollid;
1255 : 3865 : List *exprs = NIL;
1256 : :
1257 : : /*
1258 : : * Check we have a binary operator over a single-column subquery with no
1259 : : * joins and no LIMIT/OFFSET/ORDER BY clauses.
1260 : : */
1261 [ + + + - ]: 7632 : if (!IsA(testexpr, OpExpr) ||
1262 [ + - ]: 7534 : list_length(((OpExpr *) testexpr)->args) != 2 ||
1263 : 3767 : list_length(values->targetList) > 1 ||
1264 [ + + ]: 3767 : values->limitCount != NULL ||
1265 [ + + ]: 3757 : values->limitOffset != NULL ||
1266 [ + + + + ]: 7469 : values->sortClause != NIL ||
1267 : 3732 : list_length(values->rtable) != 1)
1268 : 3075 : return NULL;
1269 : :
1270 : 790 : rte = linitial_node(RangeTblEntry, values->rtable);
1271 : 790 : leftop = linitial(((OpExpr *) testexpr)->args);
1272 : 790 : rightop = lsecond(((OpExpr *) testexpr)->args);
1273 : 790 : opno = ((OpExpr *) testexpr)->opno;
1274 : 790 : inputcollid = ((OpExpr *) testexpr)->inputcollid;
1275 : :
1276 : : /*
1277 : : * Also, check that only RTE corresponds to VALUES; the list of values has
1278 : : * at least two items and no volatile functions.
1279 : : */
1280 [ + + + + ]: 900 : if (rte->rtekind != RTE_VALUES ||
1281 [ - + ]: 210 : list_length(rte->values_lists) < 2 ||
1282 : 100 : contain_volatile_functions((Node *) rte->values_lists))
1283 : 690 : return NULL;
1284 : :
1285 [ + - + + : 300 : foreach(lc, rte->values_lists)
+ + ]
1286 : : {
1287 : 230 : List *elem = lfirst(lc);
1288 : 230 : Node *value = linitial(elem);
1289 : :
1290 : : /*
1291 : : * Prepare an evaluation of the right side of the operator with
1292 : : * substitution of the given value.
1293 : : */
1294 : 230 : value = convert_testexpr(root, rightop, list_make1(value));
1295 : :
1296 : : /*
1297 : : * Try to evaluate constant expressions. We could get Const as a
1298 : : * result.
1299 : : */
1300 : 230 : value = eval_const_expressions(root, value);
1301 : :
1302 : : /*
1303 : : * As we only support constant output arrays, all the items must also
1304 : : * be constant.
1305 : : */
1306 [ + + ]: 230 : if (!IsA(value, Const))
1307 : 30 : return NULL;
1308 : :
1309 : 200 : exprs = lappend(exprs, value);
1310 : : }
1311 : :
1312 : : /* Finally, build ScalarArrayOpExpr at the top of the 'exprs' list. */
1313 : 70 : return make_SAOP_expr(opno, leftop, exprType(rightop),
1314 : 70 : linitial_oid(rte->colcollations), inputcollid,
1315 : : exprs, false);
1316 : : }
1317 : :
1318 : : /*
1319 : : * convert_ANY_sublink_to_join: try to convert an ANY SubLink to a join
1320 : : *
1321 : : * The caller has found an ANY SubLink at the top level of one of the query's
1322 : : * qual clauses, but has not checked the properties of the SubLink further.
1323 : : * Decide whether it is appropriate to process this SubLink in join style.
1324 : : * If so, form a JoinExpr and return it. Return NULL if the SubLink cannot
1325 : : * be converted to a join.
1326 : : *
1327 : : * If under_not is true, the caller actually found NOT (ANY SubLink), so
1328 : : * that what we must try to build is an ANTI not SEMI join.
1329 : : *
1330 : : * available_rels is the set of query rels that can safely be referenced
1331 : : * in the sublink expression. (We must restrict this to avoid changing
1332 : : * the semantics when a sublink is present in an outer join's ON qual.)
1333 : : * The conversion must fail if the converted qual would reference any but
1334 : : * these parent-query relids.
1335 : : *
1336 : : * On success, the returned JoinExpr has larg = NULL and rarg = the jointree
1337 : : * item representing the pulled-up subquery. The caller must set larg to
1338 : : * represent the relation(s) on the lefthand side of the new join, and insert
1339 : : * the JoinExpr into the upper query's jointree at an appropriate place
1340 : : * (typically, where the lefthand relation(s) had been). Note that the
1341 : : * passed-in SubLink must also be removed from its original position in the
1342 : : * query quals, since the quals of the returned JoinExpr replace it.
1343 : : * (Notionally, we replace the SubLink with a constant TRUE, then elide the
1344 : : * redundant constant from the qual.)
1345 : : *
1346 : : * On success, the caller is also responsible for recursively applying
1347 : : * pull_up_sublinks processing to the rarg and quals of the returned JoinExpr.
1348 : : * (On failure, there is no need to do anything, since pull_up_sublinks will
1349 : : * be applied when we recursively plan the sub-select.)
1350 : : *
1351 : : * Side effects of a successful conversion include adding the SubLink's
1352 : : * subselect to the query's rangetable, so that it can be referenced in
1353 : : * the JoinExpr's rarg.
1354 : : */
1355 : : JoinExpr *
1356 : 4045 : convert_ANY_sublink_to_join(PlannerInfo *root, SubLink *sublink,
1357 : : bool under_not, Relids available_rels)
1358 : : {
1359 : : JoinExpr *result;
1360 : 4045 : Query *parse = root->parse;
1361 : 4045 : Query *subselect = (Query *) sublink->subselect;
1362 : : Relids upper_varnos;
1363 : : int rtindex;
1364 : : ParseNamespaceItem *nsitem;
1365 : : RangeTblEntry *rte;
1366 : : RangeTblRef *rtr;
1367 : : List *subquery_vars;
1368 : : Node *quals;
1369 : : ParseState *pstate;
1370 : : Relids sub_ref_outer_relids;
1371 : : bool use_lateral;
1372 : :
1373 : : Assert(sublink->subLinkType == ANY_SUBLINK);
1374 : :
1375 : : /*
1376 : : * Per SQL spec, NOT IN is not ordinarily equivalent to an anti-join, so
1377 : : * that by default we have to fail when under_not. However, if we can
1378 : : * prove that neither the outer query's expressions nor the sub-select's
1379 : : * output columns can be NULL, and further that the operator itself cannot
1380 : : * return NULL for non-null inputs, then the logic is identical and it's
1381 : : * safe to convert NOT IN to an anti-join.
1382 : : */
1383 [ + + ]: 4045 : if (under_not &&
1384 [ + + ]: 245 : (!sublink_testexpr_is_not_nullable(root, sublink) ||
1385 [ + + ]: 150 : !query_outputs_are_not_nullable(subselect)))
1386 : 150 : return NULL;
1387 : :
1388 : : /*
1389 : : * If the sub-select contains any Vars of the parent query, we treat it as
1390 : : * LATERAL. (Vars from higher levels don't matter here.)
1391 : : */
1392 : 3895 : sub_ref_outer_relids = pull_varnos_of_level(NULL, (Node *) subselect, 1);
1393 : 3895 : use_lateral = !bms_is_empty(sub_ref_outer_relids);
1394 : :
1395 : : /*
1396 : : * Can't convert if the sub-select contains parent-level Vars of relations
1397 : : * not in available_rels.
1398 : : */
1399 [ + + ]: 3895 : if (!bms_is_subset(sub_ref_outer_relids, available_rels))
1400 : 10 : return NULL;
1401 : :
1402 : : /*
1403 : : * The test expression must contain some Vars of the parent query, else
1404 : : * it's not gonna be a join. (Note that it won't have Vars referring to
1405 : : * the subquery, rather Params.)
1406 : : */
1407 : 3885 : upper_varnos = pull_varnos(root, sublink->testexpr);
1408 [ + + ]: 3885 : if (bms_is_empty(upper_varnos))
1409 : 20 : return NULL;
1410 : :
1411 : : /*
1412 : : * However, it can't refer to anything outside available_rels.
1413 : : */
1414 [ + + ]: 3865 : if (!bms_is_subset(upper_varnos, available_rels))
1415 : 25 : return NULL;
1416 : :
1417 : : /*
1418 : : * The combining operators and left-hand expressions mustn't be volatile.
1419 : : */
1420 [ + + ]: 3840 : if (contain_volatile_functions(sublink->testexpr))
1421 : 52 : return NULL;
1422 : :
1423 : : /* Create a dummy ParseState for addRangeTableEntryForSubquery */
1424 : 3788 : pstate = make_parsestate(NULL);
1425 : :
1426 : : /*
1427 : : * Okay, pull up the sub-select into upper range table.
1428 : : *
1429 : : * We rely here on the assumption that the outer query has no references
1430 : : * to the inner (necessarily true, other than the Vars that we build
1431 : : * below). Therefore this is a lot easier than what pull_up_subqueries has
1432 : : * to go through.
1433 : : */
1434 : 3788 : nsitem = addRangeTableEntryForSubquery(pstate,
1435 : : subselect,
1436 : : NULL,
1437 : : use_lateral,
1438 : : false);
1439 : 3788 : rte = nsitem->p_rte;
1440 : 3788 : parse->rtable = lappend(parse->rtable, rte);
1441 : 3788 : rtindex = list_length(parse->rtable);
1442 : :
1443 : : /*
1444 : : * Form a RangeTblRef for the pulled-up sub-select.
1445 : : */
1446 : 3788 : rtr = makeNode(RangeTblRef);
1447 : 3788 : rtr->rtindex = rtindex;
1448 : :
1449 : : /*
1450 : : * Build a list of Vars representing the subselect outputs.
1451 : : */
1452 : 3788 : subquery_vars = generate_subquery_vars(root,
1453 : : subselect->targetList,
1454 : : rtindex);
1455 : :
1456 : : /*
1457 : : * Build the new join's qual expression, replacing Params with these Vars.
1458 : : */
1459 : 3788 : quals = convert_testexpr(root, sublink->testexpr, subquery_vars);
1460 : :
1461 : : /*
1462 : : * And finally, build the JoinExpr node.
1463 : : */
1464 : 3788 : result = makeNode(JoinExpr);
1465 [ + + ]: 3788 : result->jointype = under_not ? JOIN_ANTI : JOIN_SEMI;
1466 : 3788 : result->isNatural = false;
1467 : 3788 : result->larg = NULL; /* caller must fill this in */
1468 : 3788 : result->rarg = (Node *) rtr;
1469 : 3788 : result->usingClause = NIL;
1470 : 3788 : result->join_using_alias = NULL;
1471 : 3788 : result->quals = quals;
1472 : 3788 : result->alias = NULL;
1473 : : /* a semijoin doesn't need an RTE, but see add_antijoin_rte() */
1474 [ + + ]: 3788 : result->rtindex = under_not ? add_antijoin_rte(parse) : 0;
1475 : :
1476 : 3788 : return result;
1477 : : }
1478 : :
1479 : : /*
1480 : : * sublink_testexpr_is_not_nullable: verify that testexpr of an ANY_SUBLINK
1481 : : * guarantees a non-null result, assuming the sub-select's outputs are also
1482 : : * non-null.
1483 : : *
1484 : : * To ensure the expression never returns NULL, we require both that the outer
1485 : : * expressions are provably non-nullable and that the operator itself is safe.
1486 : : * We validate operator safety by checking for membership in a standard index
1487 : : * operator family (B-tree or Hash); this acts as a proxy for standard boolean
1488 : : * behavior, ensuring the operator does not produce NULL results from non-null
1489 : : * inputs.
1490 : : *
1491 : : * We handle the three standard parser representations for ANY sublinks: a
1492 : : * single OpExpr for single-column comparisons, a BoolExpr containing a list of
1493 : : * OpExprs for multi-column equality or inequality checks (where equality
1494 : : * becomes an AND and inequality becomes an OR), and a RowCompareExpr for
1495 : : * multi-column ordering checks. In all cases, we validate the operators and
1496 : : * the outer expressions.
1497 : : *
1498 : : * We also require each inner operand to be a bare (or relabeled) sublink
1499 : : * Param, since a cast function on it could return NULL for a non-null input.
1500 : : *
1501 : : * It is acceptable for this check not to be exhaustive. We can err on the
1502 : : * side of conservatism: if we're not sure, it's okay to return FALSE.
1503 : : */
1504 : : static bool
1505 : 245 : sublink_testexpr_is_not_nullable(PlannerInfo *root, SubLink *sublink)
1506 : : {
1507 : 245 : Node *testexpr = sublink->testexpr;
1508 : 245 : List *outer_exprs = NIL;
1509 : 245 : List *inner_exprs = NIL;
1510 : :
1511 : : /* Punt if sublink is not in the expected format */
1512 [ + - - + ]: 245 : if (sublink->subLinkType != ANY_SUBLINK || testexpr == NULL)
1513 : 0 : return false;
1514 : :
1515 [ + + ]: 245 : if (IsA(testexpr, OpExpr))
1516 : : {
1517 : : /* single-column comparison */
1518 : 180 : OpExpr *opexpr = (OpExpr *) testexpr;
1519 : :
1520 : : /* standard ANY structure should be op(outer_var, param) */
1521 [ - + ]: 180 : if (list_length(opexpr->args) != 2)
1522 : 0 : return false;
1523 : :
1524 : : /*
1525 : : * We rely on membership in a B-tree or Hash operator family as a
1526 : : * guarantee that the operator acts as a proper boolean comparison and
1527 : : * does not yield NULL for valid non-null inputs.
1528 : : */
1529 [ + + ]: 180 : if (!op_is_safe_index_member(opexpr->opno))
1530 : 5 : return false;
1531 : :
1532 : 175 : outer_exprs = lappend(outer_exprs, linitial(opexpr->args));
1533 : 175 : inner_exprs = lappend(inner_exprs, lsecond(opexpr->args));
1534 : : }
1535 [ + + - + ]: 65 : else if (is_andclause(testexpr) || is_orclause(testexpr))
1536 : 60 : {
1537 : : /* multi-column equality or inequality checks */
1538 : 60 : BoolExpr *bexpr = (BoolExpr *) testexpr;
1539 : :
1540 [ + - + + : 240 : foreach_ptr(OpExpr, opexpr, bexpr->args)
+ + ]
1541 : : {
1542 [ - + ]: 120 : if (!IsA(opexpr, OpExpr))
1543 : 0 : return false;
1544 : :
1545 : : /* standard ANY structure should be op(outer_var, param) */
1546 [ - + ]: 120 : if (list_length(opexpr->args) != 2)
1547 : 0 : return false;
1548 : :
1549 : : /* verify operator safety; see comment above */
1550 [ - + ]: 120 : if (!op_is_safe_index_member(opexpr->opno))
1551 : 0 : return false;
1552 : :
1553 : 120 : outer_exprs = lappend(outer_exprs, linitial(opexpr->args));
1554 : 120 : inner_exprs = lappend(inner_exprs, lsecond(opexpr->args));
1555 : : }
1556 : : }
1557 [ + - ]: 5 : else if (IsA(testexpr, RowCompareExpr))
1558 : : {
1559 : : /* multi-column ordering checks */
1560 : 5 : RowCompareExpr *rcexpr = (RowCompareExpr *) testexpr;
1561 : :
1562 [ + - + + : 20 : foreach_oid(opno, rcexpr->opnos)
+ + ]
1563 : : {
1564 : : /* verify operator safety; see comment above */
1565 [ - + ]: 10 : if (!op_is_safe_index_member(opno))
1566 : 0 : return false;
1567 : : }
1568 : :
1569 : 5 : outer_exprs = list_concat(outer_exprs, rcexpr->largs);
1570 : 5 : inner_exprs = list_concat(inner_exprs, rcexpr->rargs);
1571 : : }
1572 : : else
1573 : : {
1574 : : /* Punt if other node types */
1575 : 0 : return false;
1576 : : }
1577 : :
1578 : : /* Check that every inner operand is a possibly-relabeled sublink Param */
1579 [ + - + + : 775 : foreach_ptr(Expr, expr, inner_exprs)
+ + ]
1580 : : {
1581 [ - + ]: 305 : while (IsA(expr, RelabelType))
1582 : 0 : expr = ((RelabelType *) expr)->arg;
1583 : :
1584 [ + + ]: 305 : if (!IsA(expr, Param) ||
1585 [ - + ]: 300 : ((Param *) expr)->paramkind != PARAM_SUBLINK)
1586 : 5 : return false;
1587 : : }
1588 : :
1589 : : /*
1590 : : * Since the query hasn't yet been through expression preprocessing, we
1591 : : * must apply flatten_join_alias_vars to the outer expressions to avoid
1592 : : * being fooled by join aliases.
1593 : : *
1594 : : * We do not need to apply flatten_group_exprs though, since grouping Vars
1595 : : * cannot appear in jointree quals.
1596 : : */
1597 : : outer_exprs = (List *)
1598 : 235 : flatten_join_alias_vars(root, root->parse, (Node *) outer_exprs);
1599 : :
1600 : : /* Check that every outer expression is non-nullable */
1601 [ + - + + : 555 : foreach_ptr(Expr, expr, outer_exprs)
+ + ]
1602 : : {
1603 : : /*
1604 : : * We have already collected relation-level not-null constraints for
1605 : : * the outer query, so we can consult the global hash table for
1606 : : * nullability information.
1607 : : */
1608 [ + + ]: 255 : if (!expr_is_nonnullable(root, expr, NOTNULL_SOURCE_HASHTABLE))
1609 : 85 : return false;
1610 : :
1611 : : /*
1612 : : * Note: It is possible to further prove non-nullability by examining
1613 : : * the qual clauses available at or below the jointree node where this
1614 : : * NOT IN clause is evaluated, but for the moment it doesn't seem
1615 : : * worth the extra complication.
1616 : : */
1617 : : }
1618 : :
1619 : 150 : return true;
1620 : : }
1621 : :
1622 : : /*
1623 : : * convert_EXISTS_sublink_to_join: try to convert an EXISTS SubLink to a join
1624 : : *
1625 : : * The API of this function is identical to convert_ANY_sublink_to_join's.
1626 : : */
1627 : : JoinExpr *
1628 : 8126 : convert_EXISTS_sublink_to_join(PlannerInfo *root, SubLink *sublink,
1629 : : bool under_not, Relids available_rels)
1630 : : {
1631 : : JoinExpr *result;
1632 : 8126 : Query *parse = root->parse;
1633 : 8126 : Query *subselect = (Query *) sublink->subselect;
1634 : : Node *whereClause;
1635 : : PlannerInfo subroot;
1636 : : int rtoffset;
1637 : : int varno;
1638 : : Relids clause_varnos;
1639 : : Relids upper_varnos;
1640 : :
1641 : : Assert(sublink->subLinkType == EXISTS_SUBLINK);
1642 : :
1643 : : /*
1644 : : * Can't flatten if it contains WITH. (We could arrange to pull up the
1645 : : * WITH into the parent query's cteList, but that risks changing the
1646 : : * semantics, since a WITH ought to be executed once per associated query
1647 : : * call.) Note that convert_ANY_sublink_to_join doesn't have to reject
1648 : : * this case, since it just produces a subquery RTE that doesn't have to
1649 : : * get flattened into the parent query.
1650 : : */
1651 [ - + ]: 8126 : if (subselect->cteList)
1652 : 0 : return NULL;
1653 : :
1654 : : /*
1655 : : * Copy the subquery so we can modify it safely (see comments in
1656 : : * make_subplan).
1657 : : */
1658 : 8126 : subselect = copyObject(subselect);
1659 : :
1660 : : /*
1661 : : * See if the subquery can be simplified based on the knowledge that it's
1662 : : * being used in EXISTS(). If we aren't able to get rid of its
1663 : : * targetlist, we have to fail, because the pullup operation leaves us
1664 : : * with noplace to evaluate the targetlist.
1665 : : */
1666 [ + + ]: 8126 : if (!simplify_EXISTS_query(root, subselect))
1667 : 22 : return NULL;
1668 : :
1669 : : /*
1670 : : * Separate out the WHERE clause. (We could theoretically also remove
1671 : : * top-level plain JOIN/ON clauses, but it's probably not worth the
1672 : : * trouble.)
1673 : : */
1674 : 8104 : whereClause = subselect->jointree->quals;
1675 : 8104 : subselect->jointree->quals = NULL;
1676 : :
1677 : : /*
1678 : : * The rest of the sub-select must not refer to any Vars of the parent
1679 : : * query. (Vars of higher levels should be okay, though.)
1680 : : */
1681 [ + + ]: 8104 : if (contain_vars_of_level((Node *) subselect, 1))
1682 : 7 : return NULL;
1683 : :
1684 : : /*
1685 : : * On the other hand, the WHERE clause must contain some Vars of the
1686 : : * parent query, else it's not gonna be a join.
1687 : : */
1688 [ + + ]: 8097 : if (!contain_vars_of_level(whereClause, 1))
1689 : 71 : return NULL;
1690 : :
1691 : : /*
1692 : : * We don't risk optimizing if the WHERE clause is volatile, either.
1693 : : */
1694 [ - + ]: 8026 : if (contain_volatile_functions(whereClause))
1695 : 0 : return NULL;
1696 : :
1697 : : /*
1698 : : * Scan the rangetable for relation RTEs and retrieve the necessary
1699 : : * catalog information for each relation. Using this information, clear
1700 : : * the inh flag for any relation that has no children, collect not-null
1701 : : * attribute numbers for any relation that has column not-null
1702 : : * constraints, and expand virtual generated columns for any relation that
1703 : : * contains them.
1704 : : *
1705 : : * Note: we construct up an entirely dummy PlannerInfo for use here. This
1706 : : * is fine because only the "glob" and "parse" links will be used in this
1707 : : * case.
1708 : : *
1709 : : * Note: we temporarily assign back the WHERE clause so that any virtual
1710 : : * generated column references within it can be expanded. It should be
1711 : : * separated out again afterward.
1712 : : */
1713 [ + - + - : 754444 : MemSet(&subroot, 0, sizeof(subroot));
+ - + - +
+ ]
1714 : 8026 : subroot.type = T_PlannerInfo;
1715 : 8026 : subroot.glob = root->glob;
1716 : 8026 : subroot.parse = subselect;
1717 : 8026 : subselect->jointree->quals = whereClause;
1718 : 8026 : subselect = preprocess_relation_rtes(&subroot);
1719 : :
1720 : : /*
1721 : : * Now separate out the WHERE clause again.
1722 : : */
1723 : 8026 : whereClause = subselect->jointree->quals;
1724 : 8026 : subselect->jointree->quals = NULL;
1725 : :
1726 : : /*
1727 : : * The subquery must have a nonempty jointree, but we can make it so.
1728 : : */
1729 : 8026 : replace_empty_jointree(subselect);
1730 : :
1731 : : /*
1732 : : * Prepare to pull up the sub-select into top range table.
1733 : : *
1734 : : * We rely here on the assumption that the outer query has no references
1735 : : * to the inner (necessarily true). Therefore this is a lot easier than
1736 : : * what pull_up_subqueries has to go through.
1737 : : *
1738 : : * In fact, it's even easier than what convert_ANY_sublink_to_join has to
1739 : : * do. The machinations of simplify_EXISTS_query ensured that there is
1740 : : * nothing interesting in the subquery except an rtable and jointree, and
1741 : : * even the jointree FromExpr no longer has quals. So we can just append
1742 : : * the rtable to our own and use the FromExpr in our jointree. But first,
1743 : : * adjust all level-zero varnos in the subquery to account for the rtable
1744 : : * merger.
1745 : : */
1746 : 8026 : rtoffset = list_length(parse->rtable);
1747 : 8026 : OffsetVarNodes((Node *) subselect, rtoffset, 0);
1748 : 8026 : OffsetVarNodes(whereClause, rtoffset, 0);
1749 : :
1750 : : /*
1751 : : * Upper-level vars in subquery will now be one level closer to their
1752 : : * parent than before; in particular, anything that had been level 1
1753 : : * becomes level zero.
1754 : : */
1755 : 8026 : IncrementVarSublevelsUp((Node *) subselect, -1, 1);
1756 : 8026 : IncrementVarSublevelsUp(whereClause, -1, 1);
1757 : :
1758 : : /*
1759 : : * Now that the WHERE clause is adjusted to match the parent query
1760 : : * environment, we can easily identify all the level-zero rels it uses.
1761 : : * The ones <= rtoffset belong to the upper query; the ones > rtoffset do
1762 : : * not.
1763 : : */
1764 : 8026 : clause_varnos = pull_varnos(root, whereClause);
1765 : 8026 : upper_varnos = NULL;
1766 : 8026 : varno = -1;
1767 [ + + ]: 26965 : while ((varno = bms_next_member(clause_varnos, varno)) >= 0)
1768 : : {
1769 [ + + ]: 18939 : if (varno <= rtoffset)
1770 : 10893 : upper_varnos = bms_add_member(upper_varnos, varno);
1771 : : }
1772 : 8026 : bms_free(clause_varnos);
1773 : : Assert(!bms_is_empty(upper_varnos));
1774 : :
1775 : : /*
1776 : : * Now that we've got the set of upper-level varnos, we can make the last
1777 : : * check: only available_rels can be referenced.
1778 : : */
1779 [ + + ]: 8026 : if (!bms_is_subset(upper_varnos, available_rels))
1780 : 26 : return NULL;
1781 : :
1782 : : /*
1783 : : * Now we can attach the modified subquery rtable to the parent. This also
1784 : : * adds subquery's RTEPermissionInfos into the upper query.
1785 : : */
1786 : 8000 : CombineRangeTables(&parse->rtable, &parse->rteperminfos,
1787 : : subselect->rtable, subselect->rteperminfos);
1788 : :
1789 : : /*
1790 : : * And finally, build the JoinExpr node.
1791 : : */
1792 : 8000 : result = makeNode(JoinExpr);
1793 [ + + ]: 8000 : result->jointype = under_not ? JOIN_ANTI : JOIN_SEMI;
1794 : 8000 : result->isNatural = false;
1795 : 8000 : result->larg = NULL; /* caller must fill this in */
1796 : : /* flatten out the FromExpr node if it's useless */
1797 [ + + ]: 8000 : if (list_length(subselect->jointree->fromlist) == 1)
1798 : 7984 : result->rarg = (Node *) linitial(subselect->jointree->fromlist);
1799 : : else
1800 : 16 : result->rarg = (Node *) subselect->jointree;
1801 : 8000 : result->usingClause = NIL;
1802 : 8000 : result->join_using_alias = NULL;
1803 : 8000 : result->quals = whereClause;
1804 : 8000 : result->alias = NULL;
1805 : : /* a semijoin doesn't need an RTE, but see add_antijoin_rte() */
1806 [ + + ]: 8000 : result->rtindex = under_not ? add_antijoin_rte(parse) : 0;
1807 : :
1808 : 8000 : return result;
1809 : : }
1810 : :
1811 : : /*
1812 : : * add_antijoin_rte: make a join RTE for an antijoin built from a sublink
1813 : : *
1814 : : * Giving the antijoin a relid, like an antijoin made by reducing a left join
1815 : : * has, is what tells the rest of the planner that anything coming from above
1816 : : * the join must not be evaluated within its RHS. Normally nothing above can
1817 : : * reference the RHS at all, but a PlaceHolderVar whose phrels cover the whole
1818 : : * join can make a qual appear to; the join's relid in phrels then keeps such
1819 : : * a qual from being pushed down into the RHS, where it would have the
1820 : : * opposite of the intended effect. (For a semijoin that would be harmless,
1821 : : * so those are left without a relid.)
1822 : : *
1823 : : * Returns the new RTE's index.
1824 : : */
1825 : : static int
1826 : 7518 : add_antijoin_rte(Query *parse)
1827 : : {
1828 : : RangeTblEntry *rte;
1829 : :
1830 : : /* Manufacture a join RTE to use. */
1831 : 7518 : rte = makeNode(RangeTblEntry);
1832 : 7518 : rte->rtekind = RTE_JOIN;
1833 : 7518 : rte->jointype = JOIN_ANTI;
1834 : 7518 : rte->joinmergedcols = 0;
1835 : 7518 : rte->joinaliasvars = NIL; /* nothing can reference the join's output */
1836 : 7518 : rte->joinleftcols = NIL; /* so it has no columns */
1837 : 7518 : rte->joinrightcols = NIL; /* ditto */
1838 : 7518 : rte->join_using_alias = NULL;
1839 : :
1840 : 7518 : rte->alias = NULL;
1841 : 7518 : rte->eref = makeAlias("*ANTI*", NIL);
1842 : 7518 : rte->lateral = false;
1843 : 7518 : rte->inh = false;
1844 : 7518 : rte->inFromCl = false; /* not something the user wrote in FROM */
1845 : :
1846 : : /*
1847 : : * Add completed RTE to the query's range table list, so that we know its
1848 : : * index.
1849 : : */
1850 : 7518 : parse->rtable = lappend(parse->rtable, rte);
1851 : :
1852 : 7518 : return list_length(parse->rtable);
1853 : : }
1854 : :
1855 : : /*
1856 : : * simplify_EXISTS_query: remove any useless stuff in an EXISTS's subquery
1857 : : *
1858 : : * The only thing that matters about an EXISTS query is whether it returns
1859 : : * zero or more than zero rows. Therefore, we can remove certain SQL features
1860 : : * that won't affect that. The only part that is really likely to matter in
1861 : : * typical usage is simplifying the targetlist: it's a common habit to write
1862 : : * "SELECT * FROM" even though there is no need to evaluate any columns.
1863 : : *
1864 : : * Note: by suppressing the targetlist we could cause an observable behavioral
1865 : : * change, namely that any errors that might occur in evaluating the tlist
1866 : : * won't occur, nor will other side-effects of volatile functions. This seems
1867 : : * unlikely to bother anyone in practice. Note that any column privileges are
1868 : : * still checked even if the reference is removed here.
1869 : : *
1870 : : * The SQL standard specifies that a SELECT * immediately inside EXISTS
1871 : : * expands to not all columns but an arbitrary literal. That is kind of the
1872 : : * same idea, but our optimization goes further in that it throws away the
1873 : : * entire targetlist, and not only if it was written as *.
1874 : : *
1875 : : * Returns true if was able to discard the targetlist, else false.
1876 : : */
1877 : : static bool
1878 : 11549 : simplify_EXISTS_query(PlannerInfo *root, Query *query)
1879 : : {
1880 : : /*
1881 : : * We don't try to simplify at all if the query uses set operations,
1882 : : * aggregates, grouping sets, SRFs, modifying CTEs, HAVING, OFFSET, or FOR
1883 : : * UPDATE/SHARE; none of these seem likely in normal usage and their
1884 : : * possible effects are complex. (Note: we could ignore an "OFFSET 0"
1885 : : * clause, but that traditionally is used as an optimization fence, so we
1886 : : * don't.)
1887 : : */
1888 [ + - ]: 11549 : if (query->commandType != CMD_SELECT ||
1889 [ + - ]: 11549 : query->setOperations ||
1890 [ + - ]: 11549 : query->hasAggs ||
1891 [ + - ]: 11549 : query->groupingSets ||
1892 [ + - ]: 11549 : query->hasWindowFuncs ||
1893 [ + - ]: 11549 : query->hasTargetSRFs ||
1894 [ + - ]: 11549 : query->hasModifyingCTE ||
1895 [ + - ]: 11549 : query->havingQual ||
1896 [ + + ]: 11549 : query->limitOffset ||
1897 [ + + ]: 11529 : query->rowMarks)
1898 : 34 : return false;
1899 : :
1900 : : /*
1901 : : * LIMIT with a constant positive (or NULL) value doesn't affect the
1902 : : * semantics of EXISTS, so let's ignore such clauses. This is worth doing
1903 : : * because people accustomed to certain other DBMSes may be in the habit
1904 : : * of writing EXISTS(SELECT ... LIMIT 1) as an optimization. If there's a
1905 : : * LIMIT with anything else as argument, though, we can't simplify.
1906 : : */
1907 [ + + ]: 11515 : if (query->limitCount)
1908 : : {
1909 : : /*
1910 : : * The LIMIT clause has not yet been through eval_const_expressions,
1911 : : * so we have to apply that here. It might seem like this is a waste
1912 : : * of cycles, since the only case plausibly worth worrying about is
1913 : : * "LIMIT 1" ... but what we'll actually see is "LIMIT int8(1::int4)",
1914 : : * so we have to fold constants or we're not going to recognize it.
1915 : : */
1916 : 20 : Node *node = eval_const_expressions(root, query->limitCount);
1917 : : Const *limit;
1918 : :
1919 : : /* Might as well update the query if we simplified the clause. */
1920 : 20 : query->limitCount = node;
1921 : :
1922 [ - + ]: 20 : if (!IsA(node, Const))
1923 : 0 : return false;
1924 : :
1925 : 20 : limit = (Const *) node;
1926 : : Assert(limit->consttype == INT8OID);
1927 [ + + + + ]: 20 : if (!limit->constisnull && DatumGetInt64(limit->constvalue) <= 0)
1928 : 10 : return false;
1929 : :
1930 : : /* Whether or not the targetlist is safe, we can drop the LIMIT. */
1931 : 10 : query->limitCount = NULL;
1932 : : }
1933 : :
1934 : : /*
1935 : : * Otherwise, we can throw away the targetlist, as well as any GROUP,
1936 : : * WINDOW, DISTINCT, and ORDER BY clauses; none of those clauses will
1937 : : * change a nonzero-rows result to zero rows or vice versa. (Furthermore,
1938 : : * since our parsetree representation of these clauses depends on the
1939 : : * targetlist, we'd better throw them away if we drop the targetlist.)
1940 : : */
1941 : 11505 : query->targetList = NIL;
1942 : 11505 : query->groupClause = NIL;
1943 : 11505 : query->windowClause = NIL;
1944 : 11505 : query->distinctClause = NIL;
1945 : 11505 : query->sortClause = NIL;
1946 : 11505 : query->hasDistinctOn = false;
1947 : :
1948 : : /*
1949 : : * Since we have thrown away the GROUP BY clauses, we'd better get rid of
1950 : : * the RTE_GROUP RTE and clear the hasGroupRTE flag. To safely get rid of
1951 : : * the RTE_GROUP RTE without shifting the index of any subsequent RTE in
1952 : : * the rtable, we convert the RTE to be RTE_RESULT type in-place, and zero
1953 : : * out RTE_GROUP-specific fields.
1954 : : */
1955 [ + + ]: 11505 : if (query->hasGroupRTE)
1956 : : {
1957 [ + - + - : 15 : foreach_node(RangeTblEntry, rte, query->rtable)
+ + ]
1958 : : {
1959 [ + + ]: 10 : if (rte->rtekind == RTE_GROUP)
1960 : : {
1961 : 5 : rte->rtekind = RTE_RESULT;
1962 : 5 : rte->groupexprs = NIL;
1963 : :
1964 : : /* A query should only have one RTE_GROUP, so we can stop. */
1965 : 5 : break;
1966 : : }
1967 : : }
1968 : :
1969 : 5 : query->hasGroupRTE = false;
1970 : : }
1971 : :
1972 : 11505 : return true;
1973 : : }
1974 : :
1975 : : /*
1976 : : * convert_EXISTS_to_ANY: try to convert EXISTS to a hashable ANY sublink
1977 : : *
1978 : : * The subselect is expected to be a fresh copy that we can munge up,
1979 : : * and to have been successfully passed through simplify_EXISTS_query.
1980 : : *
1981 : : * On success, the modified subselect is returned, and we store a suitable
1982 : : * upper-level test expression at *testexpr, plus a list of the subselect's
1983 : : * output Params at *paramIds. (The test expression is already Param-ified
1984 : : * and hence need not go through convert_testexpr, which is why we have to
1985 : : * deal with the Param IDs specially.)
1986 : : *
1987 : : * On failure, returns NULL.
1988 : : */
1989 : : static Query *
1990 : 1569 : convert_EXISTS_to_ANY(PlannerInfo *root, Query *subselect,
1991 : : Node **testexpr, List **paramIds)
1992 : : {
1993 : : Node *whereClause;
1994 : : PlannerInfo subroot;
1995 : : List *leftargs,
1996 : : *rightargs,
1997 : : *opids,
1998 : : *opcollations,
1999 : : *newWhere,
2000 : : *tlist,
2001 : : *testlist,
2002 : : *paramids;
2003 : : ListCell *lc,
2004 : : *rc,
2005 : : *oc,
2006 : : *cc;
2007 : : AttrNumber resno;
2008 : :
2009 : : /*
2010 : : * Query must not require a targetlist, since we have to insert a new one.
2011 : : * Caller should have dealt with the case already.
2012 : : */
2013 : : Assert(subselect->targetList == NIL);
2014 : :
2015 : : /*
2016 : : * Separate out the WHERE clause. (We could theoretically also remove
2017 : : * top-level plain JOIN/ON clauses, but it's probably not worth the
2018 : : * trouble.)
2019 : : */
2020 : 1569 : whereClause = subselect->jointree->quals;
2021 : 1569 : subselect->jointree->quals = NULL;
2022 : :
2023 : : /*
2024 : : * The rest of the sub-select must not refer to any Vars of the parent
2025 : : * query. (Vars of higher levels should be okay, though.)
2026 : : *
2027 : : * Note: we need not check for Aggrefs separately because we know the
2028 : : * sub-select is as yet unoptimized; any uplevel Aggref must therefore
2029 : : * contain an uplevel Var reference. This is not the case below ...
2030 : : */
2031 [ + + ]: 1569 : if (contain_vars_of_level((Node *) subselect, 1))
2032 : 12 : return NULL;
2033 : :
2034 : : /*
2035 : : * We don't risk optimizing if the WHERE clause is volatile, either.
2036 : : */
2037 [ - + ]: 1557 : if (contain_volatile_functions(whereClause))
2038 : 0 : return NULL;
2039 : :
2040 : : /*
2041 : : * Clean up the WHERE clause by doing const-simplification etc on it.
2042 : : * Aside from simplifying the processing we're about to do, this is
2043 : : * important for being able to pull chunks of the WHERE clause up into the
2044 : : * parent query. Since we are invoked partway through the parent's
2045 : : * preprocess_expression() work, earlier steps of preprocess_expression()
2046 : : * wouldn't get applied to the pulled-up stuff unless we do them here. For
2047 : : * the parts of the WHERE clause that get put back into the child query,
2048 : : * this work is partially duplicative, but it shouldn't hurt.
2049 : : *
2050 : : * Note: we do not run flatten_join_alias_vars. This is OK because any
2051 : : * parent aliases were flattened already, and we're not going to pull any
2052 : : * child Vars (of any description) into the parent.
2053 : : *
2054 : : * Note: we construct up an entirely dummy PlannerInfo to pass to
2055 : : * eval_const_expressions. This is fine because only the "glob" and
2056 : : * "parse" links are used by eval_const_expressions.
2057 : : */
2058 [ + - + - : 146358 : MemSet(&subroot, 0, sizeof(subroot));
+ - + - +
+ ]
2059 : 1557 : subroot.type = T_PlannerInfo;
2060 : 1557 : subroot.glob = root->glob;
2061 : 1557 : subroot.parse = subselect;
2062 : 1557 : whereClause = eval_const_expressions(&subroot, whereClause);
2063 : 1557 : whereClause = (Node *) canonicalize_qual((Expr *) whereClause, false);
2064 : 1557 : whereClause = (Node *) make_ands_implicit((Expr *) whereClause);
2065 : :
2066 : : /*
2067 : : * We now have a flattened implicit-AND list of clauses, which we try to
2068 : : * break apart into "outervar = innervar" hash clauses. Anything that
2069 : : * can't be broken apart just goes back into the newWhere list. Note that
2070 : : * we aren't trying hard yet to ensure that we have only outer or only
2071 : : * inner on each side; we'll check that if we get to the end.
2072 : : */
2073 : 1557 : leftargs = rightargs = opids = opcollations = newWhere = NIL;
2074 [ + - + + : 6215 : foreach(lc, (List *) whereClause)
+ + ]
2075 : : {
2076 : 4658 : OpExpr *expr = (OpExpr *) lfirst(lc);
2077 : :
2078 [ + + + + ]: 7550 : if (IsA(expr, OpExpr) &&
2079 : 2892 : hash_ok_operator(expr))
2080 : : {
2081 : 2416 : Node *leftarg = (Node *) linitial(expr->args);
2082 : 2416 : Node *rightarg = (Node *) lsecond(expr->args);
2083 : :
2084 [ + + ]: 2416 : if (contain_vars_of_level(leftarg, 1))
2085 : : {
2086 : 228 : leftargs = lappend(leftargs, leftarg);
2087 : 228 : rightargs = lappend(rightargs, rightarg);
2088 : 228 : opids = lappend_oid(opids, expr->opno);
2089 : 228 : opcollations = lappend_oid(opcollations, expr->inputcollid);
2090 : 228 : continue;
2091 : : }
2092 [ + + ]: 2188 : if (contain_vars_of_level(rightarg, 1))
2093 : : {
2094 : : /*
2095 : : * We must commute the clause to put the outer var on the
2096 : : * left, because the hashing code in nodeSubplan.c expects
2097 : : * that. This probably shouldn't ever fail, since hashable
2098 : : * operators ought to have commutators, but be paranoid.
2099 : : */
2100 : 1780 : expr->opno = get_commutator(expr->opno);
2101 [ + - + - ]: 1780 : if (OidIsValid(expr->opno) && hash_ok_operator(expr))
2102 : : {
2103 : 1780 : leftargs = lappend(leftargs, rightarg);
2104 : 1780 : rightargs = lappend(rightargs, leftarg);
2105 : 1780 : opids = lappend_oid(opids, expr->opno);
2106 : 1780 : opcollations = lappend_oid(opcollations, expr->inputcollid);
2107 : 1780 : continue;
2108 : : }
2109 : : /* If no commutator, no chance to optimize the WHERE clause */
2110 : 0 : return NULL;
2111 : : }
2112 : : }
2113 : : /* Couldn't handle it as a hash clause */
2114 : 2650 : newWhere = lappend(newWhere, expr);
2115 : : }
2116 : :
2117 : : /*
2118 : : * If we didn't find anything we could convert, fail.
2119 : : */
2120 [ + + ]: 1557 : if (leftargs == NIL)
2121 : 223 : return NULL;
2122 : :
2123 : : /*
2124 : : * There mustn't be any parent Vars or Aggs in the stuff that we intend to
2125 : : * put back into the child query. Note: you might think we don't need to
2126 : : * check for Aggs separately, because an uplevel Agg must contain an
2127 : : * uplevel Var in its argument. But it is possible that the uplevel Var
2128 : : * got optimized away by eval_const_expressions. Consider
2129 : : *
2130 : : * SUM(CASE WHEN false THEN uplevelvar ELSE 0 END)
2131 : : */
2132 [ + + - + ]: 2613 : if (contain_vars_of_level((Node *) newWhere, 1) ||
2133 : 1279 : contain_vars_of_level((Node *) rightargs, 1))
2134 : 55 : return NULL;
2135 [ + + + - ]: 1319 : if (root->parse->hasAggs &&
2136 [ - + ]: 80 : (contain_aggs_of_level((Node *) newWhere, 1) ||
2137 : 40 : contain_aggs_of_level((Node *) rightargs, 1)))
2138 : 0 : return NULL;
2139 : :
2140 : : /*
2141 : : * And there can't be any child Vars in the stuff we intend to pull up.
2142 : : * (Note: we'd need to check for child Aggs too, except we know the child
2143 : : * has no aggs at all because of simplify_EXISTS_query's check. The same
2144 : : * goes for window functions.)
2145 : : */
2146 [ - + ]: 1279 : if (contain_vars_of_level((Node *) leftargs, 0))
2147 : 0 : return NULL;
2148 : :
2149 : : /*
2150 : : * Also reject sublinks in the stuff we intend to pull up. (It might be
2151 : : * possible to support this, but doesn't seem worth the complication.)
2152 : : */
2153 [ - + ]: 1279 : if (contain_subplans((Node *) leftargs))
2154 : 0 : return NULL;
2155 : :
2156 : : /*
2157 : : * Okay, adjust the sublevelsup in the stuff we're pulling up.
2158 : : */
2159 : 1279 : IncrementVarSublevelsUp((Node *) leftargs, -1, 1);
2160 : :
2161 : : /*
2162 : : * Put back any child-level-only WHERE clauses.
2163 : : */
2164 [ + + ]: 1279 : if (newWhere)
2165 : 1101 : subselect->jointree->quals = (Node *) make_ands_explicit(newWhere);
2166 : :
2167 : : /*
2168 : : * Build a new targetlist for the child that emits the expressions we
2169 : : * need. Concurrently, build a testexpr for the parent using Params to
2170 : : * reference the child outputs. (Since we generate Params directly here,
2171 : : * there will be no need to convert the testexpr in build_subplan.)
2172 : : */
2173 : 1279 : tlist = testlist = paramids = NIL;
2174 : 1279 : resno = 1;
2175 [ + - + + : 3232 : forfour(lc, leftargs, rc, rightargs, oc, opids, cc, opcollations)
+ - + + +
- + + + -
+ + + + +
- + - + -
+ + ]
2176 : : {
2177 : 1953 : Node *leftarg = (Node *) lfirst(lc);
2178 : 1953 : Node *rightarg = (Node *) lfirst(rc);
2179 : 1953 : Oid opid = lfirst_oid(oc);
2180 : 1953 : Oid opcollation = lfirst_oid(cc);
2181 : : Param *param;
2182 : :
2183 : 1953 : param = generate_new_exec_param(root,
2184 : : exprType(rightarg),
2185 : : exprTypmod(rightarg),
2186 : : exprCollation(rightarg));
2187 : 1953 : tlist = lappend(tlist,
2188 : 1953 : makeTargetEntry((Expr *) rightarg,
2189 : 1953 : resno++,
2190 : : NULL,
2191 : : false));
2192 : 1953 : testlist = lappend(testlist,
2193 : 1953 : make_opclause(opid, BOOLOID, false,
2194 : : (Expr *) leftarg, (Expr *) param,
2195 : : InvalidOid, opcollation));
2196 : 1953 : paramids = lappend_int(paramids, param->paramid);
2197 : : }
2198 : :
2199 : : /* Put everything where it should go, and we're done */
2200 : 1279 : subselect->targetList = tlist;
2201 : 1279 : *testexpr = (Node *) make_ands_explicit(testlist);
2202 : 1279 : *paramIds = paramids;
2203 : :
2204 : 1279 : return subselect;
2205 : : }
2206 : :
2207 : :
2208 : : /*
2209 : : * Replace correlation vars (uplevel vars) with Params.
2210 : : *
2211 : : * Uplevel PlaceHolderVars, aggregates, GROUPING() expressions,
2212 : : * MergeSupportFuncs, and ReturningExprs are replaced, too.
2213 : : *
2214 : : * Note: it is critical that this runs immediately after SS_process_sublinks.
2215 : : * Since we do not recurse into the arguments of uplevel PHVs and aggregates,
2216 : : * they will get copied to the appropriate subplan args list in the parent
2217 : : * query with uplevel vars not replaced by Params, but only adjusted in level
2218 : : * (see replace_outer_placeholdervar and replace_outer_agg). That's exactly
2219 : : * what we want for the vars of the parent level --- but if a PHV's or
2220 : : * aggregate's argument contains any further-up variables, they have to be
2221 : : * replaced with Params in their turn. That will happen when the parent level
2222 : : * runs SS_replace_correlation_vars. Therefore it must do so after expanding
2223 : : * its sublinks to subplans. And we don't want any steps in between, else
2224 : : * those steps would never get applied to the argument expressions, either in
2225 : : * the parent or the child level.
2226 : : *
2227 : : * Another fairly tricky thing going on here is the handling of SubLinks in
2228 : : * the arguments of uplevel PHVs/aggregates. Those are not touched inside the
2229 : : * intermediate query level, either. Instead, SS_process_sublinks recurses on
2230 : : * them after copying the PHV or Aggref expression into the parent plan level
2231 : : * (this is actually taken care of in build_subplan).
2232 : : */
2233 : : Node *
2234 : 146631 : SS_replace_correlation_vars(PlannerInfo *root, Node *expr)
2235 : : {
2236 : : /* No setup needed for tree walk, so away we go */
2237 : 146631 : return replace_correlation_vars_mutator(expr, root);
2238 : : }
2239 : :
2240 : : static Node *
2241 : 1429026 : replace_correlation_vars_mutator(Node *node, PlannerInfo *root)
2242 : : {
2243 [ + + ]: 1429026 : if (node == NULL)
2244 : 58974 : return NULL;
2245 [ + + ]: 1370052 : if (IsA(node, Var))
2246 : : {
2247 [ + + ]: 367117 : if (((Var *) node)->varlevelsup > 0)
2248 : 42574 : return (Node *) replace_outer_var(root, (Var *) node);
2249 : : }
2250 [ + + ]: 1327478 : if (IsA(node, PlaceHolderVar))
2251 : : {
2252 [ + + ]: 186 : if (((PlaceHolderVar *) node)->phlevelsup > 0)
2253 : 145 : return (Node *) replace_outer_placeholdervar(root,
2254 : : (PlaceHolderVar *) node);
2255 : : }
2256 [ + + ]: 1327333 : if (IsA(node, Aggref))
2257 : : {
2258 [ + + ]: 7342 : if (((Aggref *) node)->agglevelsup > 0)
2259 : 62 : return (Node *) replace_outer_agg(root, (Aggref *) node);
2260 : : }
2261 [ + + ]: 1327271 : if (IsA(node, GroupingFunc))
2262 : : {
2263 [ + + ]: 78 : if (((GroupingFunc *) node)->agglevelsup > 0)
2264 : 57 : return (Node *) replace_outer_grouping(root, (GroupingFunc *) node);
2265 : : }
2266 [ + + ]: 1327214 : if (IsA(node, MergeSupportFunc))
2267 : : {
2268 [ + + ]: 30 : if (root->parse->commandType != CMD_MERGE)
2269 : 5 : return (Node *) replace_outer_merge_support(root,
2270 : : (MergeSupportFunc *) node);
2271 : : }
2272 [ + + ]: 1327209 : if (IsA(node, ReturningExpr))
2273 : : {
2274 [ + - ]: 15 : if (((ReturningExpr *) node)->retlevelsup > 0)
2275 : 15 : return (Node *) replace_outer_returning(root,
2276 : : (ReturningExpr *) node);
2277 : : }
2278 : 1327194 : return expression_tree_mutator(node, replace_correlation_vars_mutator, root);
2279 : : }
2280 : :
2281 : : /*
2282 : : * Expand SubLinks to SubPlans in the given expression.
2283 : : *
2284 : : * The isQual argument tells whether or not this expression is a WHERE/HAVING
2285 : : * qualifier expression. If it is, any sublinks appearing at top level need
2286 : : * not distinguish FALSE from UNKNOWN return values.
2287 : : */
2288 : : Node *
2289 : 91997 : SS_process_sublinks(PlannerInfo *root, Node *expr, bool isQual)
2290 : : {
2291 : : process_sublinks_context context;
2292 : :
2293 : 91997 : context.root = root;
2294 : 91997 : context.isTopQual = isQual;
2295 : 91997 : context.skipPHVs = false;
2296 : 91997 : return process_sublinks_mutator(expr, &context);
2297 : : }
2298 : :
2299 : : static Node *
2300 : 1136281 : process_sublinks_mutator(Node *node, process_sublinks_context *context)
2301 : : {
2302 : : process_sublinks_context locContext;
2303 : :
2304 : 1136281 : locContext.root = context->root;
2305 : 1136281 : locContext.skipPHVs = context->skipPHVs;
2306 : :
2307 [ + + ]: 1136281 : if (node == NULL)
2308 : 44958 : return NULL;
2309 [ + + ]: 1091323 : if (IsA(node, SubLink))
2310 : : {
2311 : 29196 : SubLink *sublink = (SubLink *) node;
2312 : : Node *testexpr;
2313 : :
2314 : : /*
2315 : : * First, recursively process the lefthand-side expressions, if any.
2316 : : * They're not top-level anymore.
2317 : : */
2318 : 29196 : locContext.isTopQual = false;
2319 : 29196 : testexpr = process_sublinks_mutator(sublink->testexpr, &locContext);
2320 : :
2321 : : /*
2322 : : * Now build the SubPlan node and make the expr to return.
2323 : : */
2324 : 29196 : return make_subplan(context->root,
2325 : 29196 : (Query *) sublink->subselect,
2326 : : sublink->subLinkType,
2327 : : sublink->subLinkId,
2328 : : testexpr,
2329 : 29196 : context->isTopQual);
2330 : : }
2331 : :
2332 : : /*
2333 : : * Don't recurse into the arguments of an outer PHV, Aggref, GroupingFunc,
2334 : : * or ReturningExpr here. Any SubLinks in the arguments have to be dealt
2335 : : * with at the outer query level; for an Aggref, GroupingFunc, or
2336 : : * ReturningExpr they'll be handled when build_subplan collects it into
2337 : : * the arguments to be passed down to the current subplan, while an outer
2338 : : * PHV's expression has already been preprocessed by its owning level.
2339 : : * That also holds for a PHV within such an argument (skipPHVs).
2340 : : */
2341 [ + + ]: 1062127 : if (IsA(node, PlaceHolderVar))
2342 : : {
2343 [ + + + + ]: 306 : if (((PlaceHolderVar *) node)->phlevelsup > 0 || context->skipPHVs)
2344 : 77 : return node;
2345 : : }
2346 [ + + ]: 1061821 : else if (IsA(node, Aggref))
2347 : : {
2348 [ + + ]: 663 : if (((Aggref *) node)->agglevelsup > 0)
2349 : 20 : return node;
2350 : : }
2351 [ + + ]: 1061158 : else if (IsA(node, GroupingFunc))
2352 : : {
2353 [ + + ]: 137 : if (((GroupingFunc *) node)->agglevelsup > 0)
2354 : 30 : return node;
2355 : : }
2356 [ + + ]: 1061021 : else if (IsA(node, ReturningExpr))
2357 : : {
2358 [ + + ]: 165 : if (((ReturningExpr *) node)->retlevelsup > 0)
2359 : 5 : return node;
2360 : : }
2361 : :
2362 : : /*
2363 : : * We should never see a SubPlan expression in the input (since this is
2364 : : * the very routine that creates 'em to begin with). We shouldn't find
2365 : : * ourselves invoked directly on a Query, either.
2366 : : */
2367 : : Assert(!IsA(node, SubPlan));
2368 : : Assert(!IsA(node, AlternativeSubPlan));
2369 : : Assert(!IsA(node, Query));
2370 : :
2371 : : /*
2372 : : * Because make_subplan() could return an AND or OR clause, we have to
2373 : : * take steps to preserve AND/OR flatness of a qual. We assume the input
2374 : : * has been AND/OR flattened and so we need no recursion here.
2375 : : *
2376 : : * (Due to the coding here, we will not get called on the List subnodes of
2377 : : * an AND; and the input is *not* yet in implicit-AND format. So no check
2378 : : * is needed for a bare List.)
2379 : : *
2380 : : * Anywhere within the top-level AND/OR clause structure, we can tell
2381 : : * make_subplan() that NULL and FALSE are interchangeable. So isTopQual
2382 : : * propagates down in both cases. (Note that this is unlike the meaning
2383 : : * of "top level qual" used in most other places in Postgres.)
2384 : : */
2385 [ + + ]: 1061995 : if (is_andclause(node))
2386 : : {
2387 : 25527 : List *newargs = NIL;
2388 : : ListCell *l;
2389 : :
2390 : : /* Still at qual top-level */
2391 : 25527 : locContext.isTopQual = context->isTopQual;
2392 : :
2393 [ + - + + : 86892 : foreach(l, ((BoolExpr *) node)->args)
+ + ]
2394 : : {
2395 : : Node *newarg;
2396 : :
2397 : 61365 : newarg = process_sublinks_mutator(lfirst(l), &locContext);
2398 [ - + ]: 61365 : if (is_andclause(newarg))
2399 : 0 : newargs = list_concat(newargs, ((BoolExpr *) newarg)->args);
2400 : : else
2401 : 61365 : newargs = lappend(newargs, newarg);
2402 : : }
2403 : 25527 : return (Node *) make_andclause(newargs);
2404 : : }
2405 : :
2406 [ + + ]: 1036468 : if (is_orclause(node))
2407 : : {
2408 : 2158 : List *newargs = NIL;
2409 : : ListCell *l;
2410 : :
2411 : : /* Still at qual top-level */
2412 : 2158 : locContext.isTopQual = context->isTopQual;
2413 : :
2414 [ + - + + : 7243 : foreach(l, ((BoolExpr *) node)->args)
+ + ]
2415 : : {
2416 : : Node *newarg;
2417 : :
2418 : 5085 : newarg = process_sublinks_mutator(lfirst(l), &locContext);
2419 [ - + ]: 5085 : if (is_orclause(newarg))
2420 : 0 : newargs = list_concat(newargs, ((BoolExpr *) newarg)->args);
2421 : : else
2422 : 5085 : newargs = lappend(newargs, newarg);
2423 : : }
2424 : 2158 : return (Node *) make_orclause(newargs);
2425 : : }
2426 : :
2427 : : /*
2428 : : * If we recurse down through anything other than an AND or OR node, we
2429 : : * are definitely not at top qual level anymore.
2430 : : */
2431 : 1034310 : locContext.isTopQual = false;
2432 : :
2433 : 1034310 : return expression_tree_mutator(node,
2434 : : process_sublinks_mutator,
2435 : : &locContext);
2436 : : }
2437 : :
2438 : : /*
2439 : : * SS_identify_outer_params - identify the Params available from outer levels
2440 : : *
2441 : : * This must be run after SS_replace_correlation_vars and SS_process_sublinks
2442 : : * processing is complete in a given query level as well as all of its
2443 : : * descendant levels (which means it's most practical to do it at the end of
2444 : : * processing the query level). We compute the set of paramIds that outer
2445 : : * levels will make available to this level+descendants, and record it in
2446 : : * root->outer_params for use while computing extParam/allParam sets in final
2447 : : * plan cleanup. (We can't just compute it then, because the upper levels'
2448 : : * plan_params lists are transient and will be gone by then.)
2449 : : */
2450 : : void
2451 : 394661 : SS_identify_outer_params(PlannerInfo *root)
2452 : : {
2453 : : Bitmapset *outer_params;
2454 : : PlannerInfo *proot;
2455 : : ListCell *l;
2456 : :
2457 : : /*
2458 : : * If no parameters have been assigned anywhere in the tree, we certainly
2459 : : * don't need to do anything here.
2460 : : */
2461 [ + + ]: 394661 : if (root->glob->paramExecTypes == NIL)
2462 : 262115 : return;
2463 : :
2464 : : /*
2465 : : * Scan all query levels above this one to see which parameters are due to
2466 : : * be available from them, either because lower query levels have
2467 : : * requested them (via plan_params) or because they will be available from
2468 : : * initPlans of those levels.
2469 : : */
2470 : 132546 : outer_params = NULL;
2471 [ + + ]: 182265 : for (proot = root->parent_root; proot != NULL; proot = proot->parent_root)
2472 : : {
2473 : : /*
2474 : : * Include ordinary Var/PHV/Aggref/GroupingFunc/ReturningExpr params.
2475 : : */
2476 [ + + + + : 86960 : foreach(l, proot->plan_params)
+ + ]
2477 : : {
2478 : 37241 : PlannerParamItem *pitem = (PlannerParamItem *) lfirst(l);
2479 : :
2480 : 37241 : outer_params = bms_add_member(outer_params, pitem->paramId);
2481 : : }
2482 : : /* Include any outputs of outer-level initPlans */
2483 [ + + + + : 54746 : foreach(l, proot->init_plans)
+ + ]
2484 : : {
2485 : 5027 : SubPlan *initsubplan = (SubPlan *) lfirst(l);
2486 : : ListCell *l2;
2487 : :
2488 [ + - + + : 10054 : foreach(l2, initsubplan->setParam)
+ + ]
2489 : : {
2490 : 5027 : outer_params = bms_add_member(outer_params, lfirst_int(l2));
2491 : : }
2492 : : }
2493 : : /* Include worktable ID, if a recursive query is being planned */
2494 [ + + ]: 49719 : if (proot->wt_param_id >= 0)
2495 : 2646 : outer_params = bms_add_member(outer_params, proot->wt_param_id);
2496 : : }
2497 : 132546 : root->outer_params = outer_params;
2498 : : }
2499 : :
2500 : : /*
2501 : : * SS_charge_for_initplans - account for initplans in Path costs & parallelism
2502 : : *
2503 : : * If any initPlans have been created in the current query level, they will
2504 : : * get attached to the Plan tree created from whichever Path we select from
2505 : : * the given rel. Increment all that rel's Paths' costs to account for them,
2506 : : * and if any of the initPlans are parallel-unsafe, mark all the rel's Paths
2507 : : * parallel-unsafe as well.
2508 : : *
2509 : : * This is separate from SS_attach_initplans because we might conditionally
2510 : : * create more initPlans during create_plan(), depending on which Path we
2511 : : * select. However, Paths that would generate such initPlans are expected
2512 : : * to have included their cost and parallel-safety effects already.
2513 : : */
2514 : : void
2515 : 394661 : SS_charge_for_initplans(PlannerInfo *root, RelOptInfo *final_rel)
2516 : : {
2517 : : Cost initplan_cost;
2518 : : bool unsafe_initplans;
2519 : : ListCell *lc;
2520 : :
2521 : : /* Nothing to do if no initPlans */
2522 [ + + ]: 394661 : if (root->init_plans == NIL)
2523 : 386462 : return;
2524 : :
2525 : : /*
2526 : : * Compute the cost increment just once, since it will be the same for all
2527 : : * Paths. Also check for parallel-unsafe initPlans.
2528 : : */
2529 : 8199 : SS_compute_initplan_cost(root->init_plans,
2530 : : &initplan_cost, &unsafe_initplans);
2531 : :
2532 : : /*
2533 : : * Now adjust the costs and parallel_safe flags.
2534 : : */
2535 [ + - + + : 16532 : foreach(lc, final_rel->pathlist)
+ + ]
2536 : : {
2537 : 8333 : Path *path = (Path *) lfirst(lc);
2538 : :
2539 : 8333 : path->startup_cost += initplan_cost;
2540 : 8333 : path->total_cost += initplan_cost;
2541 [ + + ]: 8333 : if (unsafe_initplans)
2542 : 4815 : path->parallel_safe = false;
2543 : : }
2544 : :
2545 : : /*
2546 : : * Adjust partial paths' costs too, or forget them entirely if we must
2547 : : * consider the rel parallel-unsafe.
2548 : : */
2549 [ + + ]: 8199 : if (unsafe_initplans)
2550 : : {
2551 : 4748 : final_rel->partial_pathlist = NIL;
2552 : 4748 : final_rel->consider_parallel = false;
2553 : : }
2554 : : else
2555 : : {
2556 [ + + + + : 3461 : foreach(lc, final_rel->partial_pathlist)
+ + ]
2557 : : {
2558 : 10 : Path *path = (Path *) lfirst(lc);
2559 : :
2560 : 10 : path->startup_cost += initplan_cost;
2561 : 10 : path->total_cost += initplan_cost;
2562 : : }
2563 : : }
2564 : :
2565 : : /* We needn't do set_cheapest() here, caller will do it */
2566 : : }
2567 : :
2568 : : /*
2569 : : * SS_compute_initplan_cost - count up the cost delta for some initplans
2570 : : *
2571 : : * The total cost returned in *initplan_cost_p should be added to both the
2572 : : * startup and total costs of the plan node the initplans get attached to.
2573 : : * We also report whether any of the initplans are not parallel-safe.
2574 : : *
2575 : : * The primary user of this is SS_charge_for_initplans, but it's also
2576 : : * used in adjusting costs when we move initplans to another plan node.
2577 : : */
2578 : : void
2579 : 8417 : SS_compute_initplan_cost(List *init_plans,
2580 : : Cost *initplan_cost_p,
2581 : : bool *unsafe_initplans_p)
2582 : : {
2583 : : Cost initplan_cost;
2584 : : bool unsafe_initplans;
2585 : : ListCell *lc;
2586 : :
2587 : : /*
2588 : : * We assume each initPlan gets run once during top plan startup. This is
2589 : : * a conservative overestimate, since in fact an initPlan might be
2590 : : * executed later than plan startup, or even not at all.
2591 : : */
2592 : 8417 : initplan_cost = 0;
2593 : 8417 : unsafe_initplans = false;
2594 [ + + + + : 17760 : foreach(lc, init_plans)
+ + ]
2595 : : {
2596 : 9343 : SubPlan *initsubplan = lfirst_node(SubPlan, lc);
2597 : :
2598 : 9343 : initplan_cost += initsubplan->startup_cost + initsubplan->per_call_cost;
2599 [ + + ]: 9343 : if (!initsubplan->parallel_safe)
2600 : 5604 : unsafe_initplans = true;
2601 : : }
2602 : 8417 : *initplan_cost_p = initplan_cost;
2603 : 8417 : *unsafe_initplans_p = unsafe_initplans;
2604 : 8417 : }
2605 : :
2606 : : /*
2607 : : * SS_attach_initplans - attach initplans to topmost plan node
2608 : : *
2609 : : * Attach any initplans created in the current query level to the specified
2610 : : * plan node, which should normally be the topmost node for the query level.
2611 : : * (In principle the initPlans could go in any node at or above where they're
2612 : : * referenced; but there seems no reason to put them any lower than the
2613 : : * topmost node, so we don't bother to track exactly where they came from.)
2614 : : *
2615 : : * We do not touch the plan node's cost or parallel_safe flag. The initplans
2616 : : * must have been accounted for in SS_charge_for_initplans, or by any later
2617 : : * code that adds initplans via SS_make_initplan_from_plan.
2618 : : */
2619 : : void
2620 : 393487 : SS_attach_initplans(PlannerInfo *root, Plan *plan)
2621 : : {
2622 : 393487 : plan->initPlan = root->init_plans;
2623 : 393487 : }
2624 : :
2625 : : /*
2626 : : * SS_finalize_plan - do final parameter processing for a completed Plan.
2627 : : *
2628 : : * This recursively computes the extParam and allParam sets for every Plan
2629 : : * node in the given plan tree. (Oh, and RangeTblFunction.funcparams too.)
2630 : : *
2631 : : * We assume that SS_finalize_plan has already been run on any initplans or
2632 : : * subplans the plan tree could reference.
2633 : : */
2634 : : void
2635 : 145791 : SS_finalize_plan(PlannerInfo *root, Plan *plan)
2636 : : {
2637 : : /* No setup needed, just recurse through plan tree. */
2638 : 145791 : (void) finalize_plan(root, plan, -1, root->outer_params, NULL);
2639 : 145791 : }
2640 : :
2641 : : /*
2642 : : * Recursive processing of all nodes in the plan tree
2643 : : *
2644 : : * gather_param is the rescan_param of an ancestral Gather/GatherMerge,
2645 : : * or -1 if there is none.
2646 : : *
2647 : : * valid_params is the set of param IDs supplied by outer plan levels
2648 : : * that are valid to reference in this plan node or its children.
2649 : : *
2650 : : * scan_params is a set of param IDs to force scan plan nodes to reference.
2651 : : * This is for EvalPlanQual support, and is always NULL at the top of the
2652 : : * recursion.
2653 : : *
2654 : : * The return value is the computed allParam set for the given Plan node.
2655 : : * This is just an internal notational convenience: we can add a child
2656 : : * plan's allParams to the set of param IDs of interest to this level
2657 : : * in the same statement that recurses to that child.
2658 : : *
2659 : : * Do not scribble on caller's values of valid_params or scan_params!
2660 : : *
2661 : : * Note: although we attempt to deal with initPlans anywhere in the tree, the
2662 : : * logic is not really right. The problem is that a plan node might return an
2663 : : * output Param of its initPlan as a targetlist item, in which case it's valid
2664 : : * for the parent plan level to reference that same Param; the parent's usage
2665 : : * will be converted into a Var referencing the child plan node by setrefs.c.
2666 : : * But this function would see the parent's reference as out of scope and
2667 : : * complain about it. For now, this does not matter because the planner only
2668 : : * attaches initPlans to the topmost plan node in a query level, so the case
2669 : : * doesn't arise. If we ever merge this processing into setrefs.c, maybe it
2670 : : * can be handled more cleanly.
2671 : : */
2672 : : static Bitmapset *
2673 : 1210136 : finalize_plan(PlannerInfo *root, Plan *plan,
2674 : : int gather_param,
2675 : : Bitmapset *valid_params,
2676 : : Bitmapset *scan_params)
2677 : : {
2678 : : finalize_primnode_context context;
2679 : : int locally_added_param;
2680 : : Bitmapset *nestloop_params;
2681 : : Bitmapset *initExtParam;
2682 : : Bitmapset *initSetParam;
2683 : : Bitmapset *child_params;
2684 : : ListCell *l;
2685 : :
2686 [ + + ]: 1210136 : if (plan == NULL)
2687 : 701675 : return NULL;
2688 : :
2689 : 508461 : context.root = root;
2690 : 508461 : context.paramids = NULL; /* initialize set to empty */
2691 : 508461 : locally_added_param = -1; /* there isn't one */
2692 : 508461 : nestloop_params = NULL; /* there aren't any */
2693 : :
2694 : : /*
2695 : : * Examine any initPlans to determine the set of external params they
2696 : : * reference and the set of output params they supply. (We assume
2697 : : * SS_finalize_plan was run on them already.)
2698 : : */
2699 : 508461 : initExtParam = initSetParam = NULL;
2700 [ + + + + : 518079 : foreach(l, plan->initPlan)
+ + ]
2701 : : {
2702 : 9618 : SubPlan *initsubplan = (SubPlan *) lfirst(l);
2703 : 9618 : Plan *initplan = planner_subplan_get_plan(root, initsubplan);
2704 : : ListCell *l2;
2705 : :
2706 : 9618 : initExtParam = bms_add_members(initExtParam, initplan->extParam);
2707 [ + - + + : 19276 : foreach(l2, initsubplan->setParam)
+ + ]
2708 : : {
2709 : 9658 : initSetParam = bms_add_member(initSetParam, lfirst_int(l2));
2710 : : }
2711 : : }
2712 : :
2713 : : /* Any setParams are validly referenceable in this node and children */
2714 [ + + ]: 508461 : if (initSetParam)
2715 : 8487 : valid_params = bms_union(valid_params, initSetParam);
2716 : :
2717 : : /*
2718 : : * When we call finalize_primnode, context.paramids sets are automatically
2719 : : * merged together. But when recursing to self, we have to do it the hard
2720 : : * way. We want the paramids set to include params in subplans as well as
2721 : : * at this level.
2722 : : */
2723 : :
2724 : : /* Find params in targetlist and qual */
2725 : 508461 : finalize_primnode((Node *) plan->targetlist, &context);
2726 : 508461 : finalize_primnode((Node *) plan->qual, &context);
2727 : :
2728 : : /*
2729 : : * If it's a parallel-aware scan node, mark it as dependent on the parent
2730 : : * Gather/GatherMerge's rescan Param.
2731 : : */
2732 [ + + ]: 508461 : if (plan->parallel_aware)
2733 : : {
2734 [ - + ]: 3020 : if (gather_param < 0)
2735 [ # # ]: 0 : elog(ERROR, "parallel-aware plan node is not below a Gather");
2736 : 3020 : context.paramids =
2737 : 3020 : bms_add_member(context.paramids, gather_param);
2738 : : }
2739 : :
2740 : : /* Check additional node-type-specific fields */
2741 [ + + + + : 508461 : switch (nodeTag(plan))
+ + + + +
+ + + + +
+ + + - +
+ + + + +
+ + + + +
+ + + + +
+ + - ]
2742 : : {
2743 : 55486 : case T_Result:
2744 : 55486 : finalize_primnode(((Result *) plan)->resconstantqual,
2745 : : &context);
2746 : 55486 : break;
2747 : :
2748 : 80243 : case T_SeqScan:
2749 : 80243 : context.paramids = bms_add_members(context.paramids, scan_params);
2750 : 80243 : break;
2751 : :
2752 : 99 : case T_SampleScan:
2753 : 99 : finalize_primnode((Node *) ((SampleScan *) plan)->tablesample,
2754 : : &context);
2755 : 99 : context.paramids = bms_add_members(context.paramids, scan_params);
2756 : 99 : break;
2757 : :
2758 : 72334 : case T_IndexScan:
2759 : 72334 : finalize_primnode((Node *) ((IndexScan *) plan)->indexqual,
2760 : : &context);
2761 : 72334 : finalize_primnode((Node *) ((IndexScan *) plan)->indexorderby,
2762 : : &context);
2763 : :
2764 : : /*
2765 : : * we need not look at indexqualorig, since it will have the same
2766 : : * param references as indexqual. Likewise, we can ignore
2767 : : * indexorderbyorig.
2768 : : */
2769 : 72334 : context.paramids = bms_add_members(context.paramids, scan_params);
2770 : 72334 : break;
2771 : :
2772 : 6767 : case T_IndexOnlyScan:
2773 : 6767 : finalize_primnode((Node *) ((IndexOnlyScan *) plan)->indexqual,
2774 : : &context);
2775 : 6767 : finalize_primnode((Node *) ((IndexOnlyScan *) plan)->recheckqual,
2776 : : &context);
2777 : 6767 : finalize_primnode((Node *) ((IndexOnlyScan *) plan)->indexorderby,
2778 : : &context);
2779 : :
2780 : : /*
2781 : : * we need not look at indextlist, since it cannot contain Params.
2782 : : */
2783 : 6767 : context.paramids = bms_add_members(context.paramids, scan_params);
2784 : 6767 : break;
2785 : :
2786 : 8464 : case T_BitmapIndexScan:
2787 : 8464 : finalize_primnode((Node *) ((BitmapIndexScan *) plan)->indexqual,
2788 : : &context);
2789 : :
2790 : : /*
2791 : : * we need not look at indexqualorig, since it will have the same
2792 : : * param references as indexqual.
2793 : : */
2794 : 8464 : break;
2795 : :
2796 : 8213 : case T_BitmapHeapScan:
2797 : 8213 : finalize_primnode((Node *) ((BitmapHeapScan *) plan)->bitmapqualorig,
2798 : : &context);
2799 : 8213 : context.paramids = bms_add_members(context.paramids, scan_params);
2800 : 8213 : break;
2801 : :
2802 : 466 : case T_TidScan:
2803 : 466 : finalize_primnode((Node *) ((TidScan *) plan)->tidquals,
2804 : : &context);
2805 : 466 : context.paramids = bms_add_members(context.paramids, scan_params);
2806 : 466 : break;
2807 : :
2808 : 89 : case T_TidRangeScan:
2809 : 89 : finalize_primnode((Node *) ((TidRangeScan *) plan)->tidrangequals,
2810 : : &context);
2811 : 89 : context.paramids = bms_add_members(context.paramids, scan_params);
2812 : 89 : break;
2813 : :
2814 : 22148 : case T_SubqueryScan:
2815 : : {
2816 : 22148 : SubqueryScan *sscan = (SubqueryScan *) plan;
2817 : : RelOptInfo *rel;
2818 : : Bitmapset *subquery_params;
2819 : :
2820 : : /* We must run finalize_plan on the subquery */
2821 : 22148 : rel = find_base_rel(root, sscan->scan.scanrelid);
2822 : 22148 : subquery_params = rel->subroot->outer_params;
2823 [ + + ]: 22148 : if (gather_param >= 0)
2824 : 31 : subquery_params = bms_add_member(bms_copy(subquery_params),
2825 : : gather_param);
2826 : 22148 : finalize_plan(rel->subroot, sscan->subplan, gather_param,
2827 : : subquery_params, NULL);
2828 : :
2829 : : /* Now we can add its extParams to the parent's params */
2830 : 44296 : context.paramids = bms_add_members(context.paramids,
2831 : 22148 : sscan->subplan->extParam);
2832 : : /* We need scan_params too, though */
2833 : 22148 : context.paramids = bms_add_members(context.paramids,
2834 : : scan_params);
2835 : : }
2836 : 22148 : break;
2837 : :
2838 : 16109 : case T_FunctionScan:
2839 : : {
2840 : 16109 : FunctionScan *fscan = (FunctionScan *) plan;
2841 : : ListCell *lc;
2842 : :
2843 : : /*
2844 : : * Call finalize_primnode independently on each function
2845 : : * expression, so that we can record which params are
2846 : : * referenced in each, in order to decide which need
2847 : : * re-evaluating during rescan.
2848 : : */
2849 [ + - + + : 32240 : foreach(lc, fscan->functions)
+ + ]
2850 : : {
2851 : 16131 : RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
2852 : : finalize_primnode_context funccontext;
2853 : :
2854 : 16131 : funccontext = context;
2855 : 16131 : funccontext.paramids = NULL;
2856 : :
2857 : 16131 : finalize_primnode(rtfunc->funcexpr, &funccontext);
2858 : :
2859 : : /* remember results for execution */
2860 : 16131 : rtfunc->funcparams = funccontext.paramids;
2861 : :
2862 : : /* add the function's params to the overall set */
2863 : 16131 : context.paramids = bms_add_members(context.paramids,
2864 : 16131 : funccontext.paramids);
2865 : : }
2866 : :
2867 : 16109 : context.paramids = bms_add_members(context.paramids,
2868 : : scan_params);
2869 : : }
2870 : 16109 : break;
2871 : :
2872 : 313 : case T_TableFuncScan:
2873 : 313 : finalize_primnode((Node *) ((TableFuncScan *) plan)->tablefunc,
2874 : : &context);
2875 : 313 : context.paramids = bms_add_members(context.paramids, scan_params);
2876 : 313 : break;
2877 : :
2878 : 4681 : case T_ValuesScan:
2879 : 4681 : finalize_primnode((Node *) ((ValuesScan *) plan)->values_lists,
2880 : : &context);
2881 : 4681 : context.paramids = bms_add_members(context.paramids, scan_params);
2882 : 4681 : break;
2883 : :
2884 : 3330 : case T_CteScan:
2885 : : {
2886 : : /*
2887 : : * You might think we should add the node's cteParam to
2888 : : * paramids, but we shouldn't because that param is just a
2889 : : * linkage mechanism for multiple CteScan nodes for the same
2890 : : * CTE; it is never used for changed-param signaling. What we
2891 : : * have to do instead is to find the referenced CTE plan and
2892 : : * incorporate its external paramids, so that the correct
2893 : : * things will happen if the CTE references outer-level
2894 : : * variables. See test cases for bug #4902. (We assume
2895 : : * SS_finalize_plan was run on the CTE plan already.)
2896 : : */
2897 : 3330 : int plan_id = ((CteScan *) plan)->ctePlanId;
2898 : : Plan *cteplan;
2899 : :
2900 : : /* so, do this ... */
2901 [ + - - + ]: 3330 : if (plan_id < 1 || plan_id > list_length(root->glob->subplans))
2902 [ # # ]: 0 : elog(ERROR, "could not find plan for CteScan referencing plan ID %d",
2903 : : plan_id);
2904 : 3330 : cteplan = (Plan *) list_nth(root->glob->subplans, plan_id - 1);
2905 : 3330 : context.paramids =
2906 : 3330 : bms_add_members(context.paramids, cteplan->extParam);
2907 : :
2908 : : #ifdef NOT_USED
2909 : : /* ... but not this */
2910 : : context.paramids =
2911 : : bms_add_member(context.paramids,
2912 : : ((CteScan *) plan)->cteParam);
2913 : : #endif
2914 : :
2915 : 3330 : context.paramids = bms_add_members(context.paramids,
2916 : : scan_params);
2917 : : }
2918 : 3330 : break;
2919 : :
2920 : 693 : case T_WorkTableScan:
2921 : 693 : context.paramids =
2922 : 693 : bms_add_member(context.paramids,
2923 : : ((WorkTableScan *) plan)->wtParam);
2924 : 693 : context.paramids = bms_add_members(context.paramids, scan_params);
2925 : 693 : break;
2926 : :
2927 : 341 : case T_NamedTuplestoreScan:
2928 : 341 : context.paramids = bms_add_members(context.paramids, scan_params);
2929 : 341 : break;
2930 : :
2931 : 445 : case T_ForeignScan:
2932 : : {
2933 : 445 : ForeignScan *fscan = (ForeignScan *) plan;
2934 : :
2935 : 445 : finalize_primnode((Node *) fscan->fdw_exprs,
2936 : : &context);
2937 : 445 : finalize_primnode((Node *) fscan->fdw_recheck_quals,
2938 : : &context);
2939 : :
2940 : : /* We assume fdw_scan_tlist cannot contain Params */
2941 : 445 : context.paramids = bms_add_members(context.paramids,
2942 : : scan_params);
2943 : : }
2944 : 445 : break;
2945 : :
2946 : 0 : case T_CustomScan:
2947 : : {
2948 : 0 : CustomScan *cscan = (CustomScan *) plan;
2949 : : ListCell *lc;
2950 : :
2951 : 0 : finalize_primnode((Node *) cscan->custom_exprs,
2952 : : &context);
2953 : : /* We assume custom_scan_tlist cannot contain Params */
2954 : 0 : context.paramids =
2955 : 0 : bms_add_members(context.paramids, scan_params);
2956 : :
2957 : : /* child nodes if any */
2958 [ # # # # : 0 : foreach(lc, cscan->custom_plans)
# # ]
2959 : : {
2960 : 0 : context.paramids =
2961 : 0 : bms_add_members(context.paramids,
2962 : 0 : finalize_plan(root,
2963 : 0 : (Plan *) lfirst(lc),
2964 : : gather_param,
2965 : : valid_params,
2966 : : scan_params));
2967 : : }
2968 : : }
2969 : 0 : break;
2970 : :
2971 : 64746 : case T_ModifyTable:
2972 : : {
2973 : 64746 : ModifyTable *mtplan = (ModifyTable *) plan;
2974 : :
2975 : : /* Force descendant scan nodes to reference epqParam */
2976 : 64746 : locally_added_param = mtplan->epqParam;
2977 : 64746 : valid_params = bms_add_member(bms_copy(valid_params),
2978 : : locally_added_param);
2979 : 64746 : scan_params = bms_add_member(bms_copy(scan_params),
2980 : : locally_added_param);
2981 : 64746 : finalize_primnode((Node *) mtplan->returningLists,
2982 : : &context);
2983 : 64746 : finalize_primnode((Node *) mtplan->onConflictSet,
2984 : : &context);
2985 : 64746 : finalize_primnode((Node *) mtplan->onConflictWhere,
2986 : : &context);
2987 : : /* exclRelTlist contains only Vars, doesn't need examination */
2988 : : }
2989 : 64746 : break;
2990 : :
2991 : 8751 : case T_Append:
2992 : : {
2993 [ + - + + : 33109 : foreach(l, ((Append *) plan)->appendplans)
+ + ]
2994 : : {
2995 : 24358 : context.paramids =
2996 : 24358 : bms_add_members(context.paramids,
2997 : 24358 : finalize_plan(root,
2998 : 24358 : (Plan *) lfirst(l),
2999 : : gather_param,
3000 : : valid_params,
3001 : : scan_params));
3002 : : }
3003 : : }
3004 : 8751 : break;
3005 : :
3006 : 135 : case T_MergeAppend:
3007 : : {
3008 [ + - + + : 550 : foreach(l, ((MergeAppend *) plan)->mergeplans)
+ + ]
3009 : : {
3010 : 415 : context.paramids =
3011 : 415 : bms_add_members(context.paramids,
3012 : 415 : finalize_plan(root,
3013 : 415 : (Plan *) lfirst(l),
3014 : : gather_param,
3015 : : valid_params,
3016 : : scan_params));
3017 : : }
3018 : : }
3019 : 135 : break;
3020 : :
3021 : 107 : case T_BitmapAnd:
3022 : : {
3023 [ + - + + : 321 : foreach(l, ((BitmapAnd *) plan)->bitmapplans)
+ + ]
3024 : : {
3025 : 214 : context.paramids =
3026 : 214 : bms_add_members(context.paramids,
3027 : 214 : finalize_plan(root,
3028 : 214 : (Plan *) lfirst(l),
3029 : : gather_param,
3030 : : valid_params,
3031 : : scan_params));
3032 : : }
3033 : : }
3034 : 107 : break;
3035 : :
3036 : 144 : case T_BitmapOr:
3037 : : {
3038 [ + - + + : 432 : foreach(l, ((BitmapOr *) plan)->bitmapplans)
+ + ]
3039 : : {
3040 : 288 : context.paramids =
3041 : 288 : bms_add_members(context.paramids,
3042 : 288 : finalize_plan(root,
3043 : 288 : (Plan *) lfirst(l),
3044 : : gather_param,
3045 : : valid_params,
3046 : : scan_params));
3047 : : }
3048 : : }
3049 : 144 : break;
3050 : :
3051 : 57019 : case T_NestLoop:
3052 : : {
3053 : 57019 : finalize_primnode((Node *) ((Join *) plan)->joinqual,
3054 : : &context);
3055 : : /* collect set of params that will be passed to right child */
3056 [ + + + + : 99898 : foreach(l, ((NestLoop *) plan)->nestParams)
+ + ]
3057 : : {
3058 : 42879 : NestLoopParam *nlp = (NestLoopParam *) lfirst(l);
3059 : :
3060 : 42879 : nestloop_params = bms_add_member(nestloop_params,
3061 : : nlp->paramno);
3062 : : }
3063 : : }
3064 : 57019 : break;
3065 : :
3066 : 2706 : case T_MergeJoin:
3067 : 2706 : finalize_primnode((Node *) ((Join *) plan)->joinqual,
3068 : : &context);
3069 : 2706 : finalize_primnode((Node *) ((MergeJoin *) plan)->mergeclauses,
3070 : : &context);
3071 : 2706 : break;
3072 : :
3073 : 18390 : case T_HashJoin:
3074 : 18390 : finalize_primnode((Node *) ((Join *) plan)->joinqual,
3075 : : &context);
3076 : 18390 : finalize_primnode((Node *) ((HashJoin *) plan)->hashclauses,
3077 : : &context);
3078 : 18390 : break;
3079 : :
3080 : 18390 : case T_Hash:
3081 : 18390 : finalize_primnode((Node *) ((Hash *) plan)->hashkeys,
3082 : : &context);
3083 : 18390 : break;
3084 : :
3085 : 1760 : case T_Limit:
3086 : 1760 : finalize_primnode(((Limit *) plan)->limitOffset,
3087 : : &context);
3088 : 1760 : finalize_primnode(((Limit *) plan)->limitCount,
3089 : : &context);
3090 : 1760 : break;
3091 : :
3092 : 693 : case T_RecursiveUnion:
3093 : : /* child nodes are allowed to reference wtParam */
3094 : 693 : locally_added_param = ((RecursiveUnion *) plan)->wtParam;
3095 : 693 : valid_params = bms_add_member(bms_copy(valid_params),
3096 : : locally_added_param);
3097 : : /* wtParam does *not* get added to scan_params */
3098 : 693 : break;
3099 : :
3100 : 6661 : case T_LockRows:
3101 : : /* Force descendant scan nodes to reference epqParam */
3102 : 6661 : locally_added_param = ((LockRows *) plan)->epqParam;
3103 : 6661 : valid_params = bms_add_member(bms_copy(valid_params),
3104 : : locally_added_param);
3105 : 6661 : scan_params = bms_add_member(bms_copy(scan_params),
3106 : : locally_added_param);
3107 : 6661 : break;
3108 : :
3109 : 12217 : case T_Agg:
3110 : : {
3111 : 12217 : Agg *agg = (Agg *) plan;
3112 : :
3113 : : /*
3114 : : * AGG_HASHED plans need to know which Params are referenced
3115 : : * in aggregate calls. Do a separate scan to identify them.
3116 : : */
3117 [ + + ]: 12217 : if (agg->aggstrategy == AGG_HASHED)
3118 : : {
3119 : : finalize_primnode_context aggcontext;
3120 : :
3121 : 1417 : aggcontext.root = root;
3122 : 1417 : aggcontext.paramids = NULL;
3123 : 1417 : finalize_agg_primnode((Node *) agg->plan.targetlist,
3124 : : &aggcontext);
3125 : 1417 : finalize_agg_primnode((Node *) agg->plan.qual,
3126 : : &aggcontext);
3127 : 1417 : agg->aggParams = aggcontext.paramids;
3128 : : }
3129 : : }
3130 : 12217 : break;
3131 : :
3132 : 160 : case T_WindowAgg:
3133 : 160 : finalize_primnode(((WindowAgg *) plan)->startOffset,
3134 : : &context);
3135 : 160 : finalize_primnode(((WindowAgg *) plan)->endOffset,
3136 : : &context);
3137 : 160 : break;
3138 : :
3139 : 881 : case T_Gather:
3140 : : /* child nodes are allowed to reference rescan_param, if any */
3141 : 881 : locally_added_param = ((Gather *) plan)->rescan_param;
3142 [ + + ]: 881 : if (locally_added_param >= 0)
3143 : : {
3144 : 876 : valid_params = bms_add_member(bms_copy(valid_params),
3145 : : locally_added_param);
3146 : :
3147 : : /*
3148 : : * We currently don't support nested Gathers. The issue so
3149 : : * far as this function is concerned would be how to identify
3150 : : * which child nodes depend on which Gather.
3151 : : */
3152 : : Assert(gather_param < 0);
3153 : : /* Pass down rescan_param to child parallel-aware nodes */
3154 : 876 : gather_param = locally_added_param;
3155 : : }
3156 : : /* rescan_param does *not* get added to scan_params */
3157 : 881 : break;
3158 : :
3159 : 308 : case T_GatherMerge:
3160 : : /* child nodes are allowed to reference rescan_param, if any */
3161 : 308 : locally_added_param = ((GatherMerge *) plan)->rescan_param;
3162 [ + - ]: 308 : if (locally_added_param >= 0)
3163 : : {
3164 : 308 : valid_params = bms_add_member(bms_copy(valid_params),
3165 : : locally_added_param);
3166 : :
3167 : : /*
3168 : : * We currently don't support nested Gathers. The issue so
3169 : : * far as this function is concerned would be how to identify
3170 : : * which child nodes depend on which Gather.
3171 : : */
3172 : : Assert(gather_param < 0);
3173 : : /* Pass down rescan_param to child parallel-aware nodes */
3174 : 308 : gather_param = locally_added_param;
3175 : : }
3176 : : /* rescan_param does *not* get added to scan_params */
3177 : 308 : break;
3178 : :
3179 : 1579 : case T_Memoize:
3180 : 1579 : finalize_primnode((Node *) ((Memoize *) plan)->param_exprs,
3181 : : &context);
3182 : 1579 : break;
3183 : :
3184 : 33593 : case T_ProjectSet:
3185 : : case T_Material:
3186 : : case T_Sort:
3187 : : case T_IncrementalSort:
3188 : : case T_Unique:
3189 : : case T_SetOp:
3190 : : case T_Group:
3191 : : /* no node-type-specific fields need fixing */
3192 : 33593 : break;
3193 : :
3194 : 0 : default:
3195 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
3196 : : (int) nodeTag(plan));
3197 : : }
3198 : :
3199 : : /* Process left and right child plans, if any */
3200 : 508461 : child_params = finalize_plan(root,
3201 : 508461 : plan->lefttree,
3202 : : gather_param,
3203 : : valid_params,
3204 : : scan_params);
3205 : 508461 : context.paramids = bms_add_members(context.paramids, child_params);
3206 : :
3207 [ + + ]: 508461 : if (nestloop_params)
3208 : : {
3209 : : /* right child can reference nestloop_params as well as valid_params */
3210 : 36585 : child_params = finalize_plan(root,
3211 : 36585 : plan->righttree,
3212 : : gather_param,
3213 : : bms_union(nestloop_params, valid_params),
3214 : : scan_params);
3215 : : /* ... and they don't count as parameters used at my level */
3216 : 36585 : child_params = bms_difference(child_params, nestloop_params);
3217 : 36585 : bms_free(nestloop_params);
3218 : : }
3219 : : else
3220 : : {
3221 : : /* easy case */
3222 : 471876 : child_params = finalize_plan(root,
3223 : 471876 : plan->righttree,
3224 : : gather_param,
3225 : : valid_params,
3226 : : scan_params);
3227 : : }
3228 : 508461 : context.paramids = bms_add_members(context.paramids, child_params);
3229 : :
3230 : : /*
3231 : : * Any locally generated parameter doesn't count towards its generating
3232 : : * plan node's external dependencies. (Note: if we changed valid_params
3233 : : * and/or scan_params, we leak those bitmapsets; not worth the notational
3234 : : * trouble to clean them up.)
3235 : : */
3236 [ + + ]: 508461 : if (locally_added_param >= 0)
3237 : : {
3238 : 73284 : context.paramids = bms_del_member(context.paramids,
3239 : : locally_added_param);
3240 : : }
3241 : :
3242 : : /* Now we have all the paramids referenced in this node and children */
3243 : :
3244 [ - + ]: 508461 : if (!bms_is_subset(context.paramids, valid_params))
3245 [ # # ]: 0 : elog(ERROR, "plan should not reference subplan's variable");
3246 : :
3247 : : /*
3248 : : * The plan node's allParam and extParam fields should include all its
3249 : : * referenced paramids, plus contributions from any child initPlans.
3250 : : * However, any setParams of the initPlans should not be present in the
3251 : : * parent node's extParams, only in its allParams. (It's possible that
3252 : : * some initPlans have extParams that are setParams of other initPlans.)
3253 : : */
3254 : :
3255 : : /* allParam must include initplans' extParams and setParams */
3256 : 508461 : plan->allParam = bms_union(context.paramids, initExtParam);
3257 : 508461 : plan->allParam = bms_add_members(plan->allParam, initSetParam);
3258 : : /* extParam must include any initplan extParams */
3259 : 508461 : plan->extParam = bms_union(context.paramids, initExtParam);
3260 : : /* but not any initplan setParams */
3261 : 508461 : plan->extParam = bms_del_members(plan->extParam, initSetParam);
3262 : :
3263 : 508461 : return plan->allParam;
3264 : : }
3265 : :
3266 : : /*
3267 : : * finalize_primnode: add IDs of all PARAM_EXEC params that appear (or will
3268 : : * appear) in the given expression tree to the result set.
3269 : : */
3270 : : static bool
3271 : 8538221 : finalize_primnode(Node *node, finalize_primnode_context *context)
3272 : : {
3273 [ + + ]: 8538221 : if (node == NULL)
3274 : 980812 : return false;
3275 [ + + ]: 7557409 : if (IsA(node, Param))
3276 : : {
3277 [ + + ]: 107560 : if (((Param *) node)->paramkind == PARAM_EXEC)
3278 : : {
3279 : 105342 : int paramid = ((Param *) node)->paramid;
3280 : :
3281 : 105342 : context->paramids = bms_add_member(context->paramids, paramid);
3282 : : }
3283 : 107560 : return false; /* no more to do here */
3284 : : }
3285 [ + + ]: 7449849 : else if (IsA(node, Aggref))
3286 : : {
3287 : : /*
3288 : : * Check to see if the aggregate will be replaced by a Param
3289 : : * referencing a subquery output during setrefs.c. If so, we must
3290 : : * account for that Param here. (For various reasons, it's not
3291 : : * convenient to perform that substitution earlier than setrefs.c, nor
3292 : : * to perform this processing after setrefs.c. Thus we need a wart
3293 : : * here.)
3294 : : */
3295 : 16025 : Aggref *aggref = (Aggref *) node;
3296 : : Param *aggparam;
3297 : :
3298 : 16025 : aggparam = find_minmax_agg_replacement_param(context->root, aggref);
3299 [ + + ]: 16025 : if (aggparam != NULL)
3300 : 460 : context->paramids = bms_add_member(context->paramids,
3301 : : aggparam->paramid);
3302 : : /* Fall through to examine the agg's arguments */
3303 : : }
3304 [ + + ]: 7433824 : else if (IsA(node, SubPlan))
3305 : : {
3306 : 28000 : SubPlan *subplan = (SubPlan *) node;
3307 : 28000 : Plan *plan = planner_subplan_get_plan(context->root, subplan);
3308 : : ListCell *lc;
3309 : : Bitmapset *subparamids;
3310 : :
3311 : : /* Recurse into the testexpr, but not into the Plan */
3312 : 28000 : finalize_primnode(subplan->testexpr, context);
3313 : :
3314 : : /*
3315 : : * Remove any param IDs of output parameters of the subplan that were
3316 : : * referenced in the testexpr. These are not interesting for
3317 : : * parameter change signaling since we always re-evaluate the subplan.
3318 : : * Note that this wouldn't work too well if there might be uses of the
3319 : : * same param IDs elsewhere in the plan, but that can't happen because
3320 : : * generate_new_exec_param never tries to merge params.
3321 : : */
3322 [ + + + + : 30752 : foreach(lc, subplan->paramIds)
+ + ]
3323 : : {
3324 : 2752 : context->paramids = bms_del_member(context->paramids,
3325 : : lfirst_int(lc));
3326 : : }
3327 : :
3328 : : /* Also examine args list */
3329 : 28000 : finalize_primnode((Node *) subplan->args, context);
3330 : :
3331 : : /*
3332 : : * Add params needed by the subplan to paramids, but excluding those
3333 : : * we will pass down to it. (We assume SS_finalize_plan was run on
3334 : : * the subplan already.)
3335 : : */
3336 : 28000 : subparamids = bms_copy(plan->extParam);
3337 [ + + + + : 68572 : foreach(lc, subplan->parParam)
+ + ]
3338 : : {
3339 : 40572 : subparamids = bms_del_member(subparamids, lfirst_int(lc));
3340 : : }
3341 : 28000 : context->paramids = bms_join(context->paramids, subparamids);
3342 : :
3343 : 28000 : return false; /* no more to do here */
3344 : : }
3345 : 7421849 : return expression_tree_walker(node, finalize_primnode, context);
3346 : : }
3347 : :
3348 : : /*
3349 : : * finalize_agg_primnode: find all Aggref nodes in the given expression tree,
3350 : : * and add IDs of all PARAM_EXEC params appearing within their aggregated
3351 : : * arguments to the result set.
3352 : : */
3353 : : static bool
3354 : 11661 : finalize_agg_primnode(Node *node, finalize_primnode_context *context)
3355 : : {
3356 [ + + ]: 11661 : if (node == NULL)
3357 : 1475 : return false;
3358 [ + + ]: 10186 : if (IsA(node, Aggref))
3359 : : {
3360 : 1016 : Aggref *agg = (Aggref *) node;
3361 : :
3362 : : /* we should not consider the direct arguments, if any */
3363 : 1016 : finalize_primnode((Node *) agg->args, context);
3364 : 1016 : finalize_primnode((Node *) agg->aggfilter, context);
3365 : 1016 : return false; /* there can't be any Aggrefs below here */
3366 : : }
3367 : 9170 : return expression_tree_walker(node, finalize_agg_primnode, context);
3368 : : }
3369 : :
3370 : : /*
3371 : : * SS_make_initplan_output_param - make a Param for an initPlan's output
3372 : : *
3373 : : * The plan is expected to return a scalar value of the given type/collation.
3374 : : *
3375 : : * Note that in some cases the initplan may not ever appear in the finished
3376 : : * plan tree. If that happens, we'll have wasted a PARAM_EXEC slot, which
3377 : : * is no big deal.
3378 : : */
3379 : : Param *
3380 : 365 : SS_make_initplan_output_param(PlannerInfo *root,
3381 : : Oid resulttype, int32 resulttypmod,
3382 : : Oid resultcollation)
3383 : : {
3384 : 365 : return generate_new_exec_param(root, resulttype,
3385 : : resulttypmod, resultcollation);
3386 : : }
3387 : :
3388 : : /*
3389 : : * SS_make_initplan_from_plan - given a plan tree, make it an InitPlan
3390 : : *
3391 : : * We build an EXPR_SUBLINK SubPlan node and put it into the initplan
3392 : : * list for the outer query level. A Param that represents the initplan's
3393 : : * output has already been assigned using SS_make_initplan_output_param.
3394 : : */
3395 : : void
3396 : 330 : SS_make_initplan_from_plan(PlannerInfo *root,
3397 : : PlannerInfo *subroot, Plan *plan,
3398 : : Param *prm)
3399 : : {
3400 : : SubPlan *node;
3401 : :
3402 : : /*
3403 : : * Add the subplan and its PlannerInfo, as well as a dummy path entry, to
3404 : : * the global lists. Ideally we'd save a real path, but right now our
3405 : : * sole caller doesn't build a path that exactly matches the plan. Since
3406 : : * we're not currently going to need the path for an initplan, it's not
3407 : : * worth requiring construction of such a path.
3408 : : */
3409 : 330 : root->glob->subplans = lappend(root->glob->subplans, plan);
3410 : 330 : root->glob->subpaths = lappend(root->glob->subpaths, NULL);
3411 : 330 : root->glob->subroots = lappend(root->glob->subroots, subroot);
3412 : :
3413 : : /*
3414 : : * Create a SubPlan node and add it to the outer list of InitPlans. Note
3415 : : * it has to appear after any other InitPlans it might depend on (see
3416 : : * comments in ExecReScan).
3417 : : */
3418 : 330 : node = makeNode(SubPlan);
3419 : 330 : node->subLinkType = EXPR_SUBLINK;
3420 : 330 : node->plan_id = list_length(root->glob->subplans);
3421 : 330 : node->plan_name = subroot->plan_name;
3422 : 330 : node->isInitPlan = true;
3423 : 330 : get_first_col_type(plan, &node->firstColType, &node->firstColTypmod,
3424 : : &node->firstColCollation);
3425 : 330 : node->parallel_safe = plan->parallel_safe;
3426 : 330 : node->setParam = list_make1_int(prm->paramid);
3427 : :
3428 : 330 : root->init_plans = lappend(root->init_plans, node);
3429 : :
3430 : : /*
3431 : : * The node can't have any inputs (since it's an initplan), so the
3432 : : * parParam and args lists remain empty.
3433 : : */
3434 : :
3435 : : /* Set costs of SubPlan using info from the plan tree */
3436 : 330 : cost_subplan(subroot, node, plan);
3437 : 330 : }
3438 : :
3439 : : /*
3440 : : * Get a string equivalent of a given subLinkType.
3441 : : */
3442 : : static const char *
3443 : 29196 : sublinktype_to_string(SubLinkType subLinkType)
3444 : : {
3445 [ + + + + : 29196 : switch (subLinkType)
+ + + -
- ]
3446 : : {
3447 : 1854 : case EXISTS_SUBLINK:
3448 : 1854 : return "exists";
3449 : 25 : case ALL_SUBLINK:
3450 : 25 : return "all";
3451 : 576 : case ANY_SUBLINK:
3452 : 576 : return "any";
3453 : 25 : case ROWCOMPARE_SUBLINK:
3454 : 25 : return "rowcompare";
3455 : 20376 : case EXPR_SUBLINK:
3456 : 20376 : return "expr";
3457 : 108 : case MULTIEXPR_SUBLINK:
3458 : 108 : return "multiexpr";
3459 : 6232 : case ARRAY_SUBLINK:
3460 : 6232 : return "array";
3461 : 0 : case CTE_SUBLINK:
3462 : 0 : return "cte";
3463 : : }
3464 : : Assert(false);
3465 : 0 : return "???";
3466 : : }
|