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