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