1 /*-------------------------------------------------------------------------
4 * Planning routines for subselects and parameters.
6 * Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
10 * src/backend/optimizer/plan/subselect.c
12 *-------------------------------------------------------------------------
16 #include "access/htup_details.h"
17 #include "catalog/pg_operator.h"
18 #include "catalog/pg_type.h"
19 #include "executor/executor.h"
20 #include "miscadmin.h"
21 #include "nodes/makefuncs.h"
22 #include "nodes/nodeFuncs.h"
23 #include "optimizer/clauses.h"
24 #include "optimizer/cost.h"
25 #include "optimizer/planmain.h"
26 #include "optimizer/planner.h"
27 #include "optimizer/prep.h"
28 #include "optimizer/subselect.h"
29 #include "optimizer/var.h"
30 #include "parser/parse_relation.h"
31 #include "rewrite/rewriteManip.h"
32 #include "utils/builtins.h"
33 #include "utils/lsyscache.h"
34 #include "utils/syscache.h"
37 typedef struct convert_testexpr_context
40 List *subst_nodes; /* Nodes to substitute for Params */
41 } convert_testexpr_context;
43 typedef struct process_sublinks_context
47 } process_sublinks_context;
49 typedef struct finalize_primnode_context
52 Bitmapset *paramids; /* Non-local PARAM_EXEC paramids found */
53 } finalize_primnode_context;
56 static Node *build_subplan(PlannerInfo *root, Plan *plan, PlannerInfo *subroot,
58 SubLinkType subLinkType, Node *testexpr,
59 bool adjust_testexpr, bool unknownEqFalse);
60 static List *generate_subquery_params(PlannerInfo *root, List *tlist,
62 static List *generate_subquery_vars(PlannerInfo *root, List *tlist,
64 static Node *convert_testexpr(PlannerInfo *root,
67 static Node *convert_testexpr_mutator(Node *node,
68 convert_testexpr_context *context);
69 static bool subplan_is_hashable(Plan *plan);
70 static bool testexpr_is_hashable(Node *testexpr);
71 static bool hash_ok_operator(OpExpr *expr);
72 static bool simplify_EXISTS_query(Query *query);
73 static Query *convert_EXISTS_to_ANY(PlannerInfo *root, Query *subselect,
74 Node **testexpr, List **paramIds);
75 static Node *replace_correlation_vars_mutator(Node *node, PlannerInfo *root);
76 static Node *process_sublinks_mutator(Node *node,
77 process_sublinks_context *context);
78 static Bitmapset *finalize_plan(PlannerInfo *root,
80 Bitmapset *valid_params,
81 Bitmapset *scan_params);
82 static bool finalize_primnode(Node *node, finalize_primnode_context *context);
86 * Select a PARAM_EXEC number to identify the given Var as a parameter for
87 * the current subquery, or for a nestloop's inner scan.
88 * If the Var already has a param in the current context, return that one.
91 assign_param_for_var(PlannerInfo *root, Var *var)
94 PlannerParamItem *pitem;
97 /* Find the query level the Var belongs to */
98 for (levelsup = var->varlevelsup; levelsup > 0; levelsup--)
99 root = root->parent_root;
101 /* If there's already a matching PlannerParamItem there, just use it */
102 foreach(ppl, root->plan_params)
104 pitem = (PlannerParamItem *) lfirst(ppl);
105 if (IsA(pitem->item, Var))
107 Var *pvar = (Var *) pitem->item;
110 * This comparison must match _equalVar(), except for ignoring
111 * varlevelsup. Note that _equalVar() ignores the location.
113 if (pvar->varno == var->varno &&
114 pvar->varattno == var->varattno &&
115 pvar->vartype == var->vartype &&
116 pvar->vartypmod == var->vartypmod &&
117 pvar->varcollid == var->varcollid &&
118 pvar->varnoold == var->varnoold &&
119 pvar->varoattno == var->varoattno)
120 return pitem->paramId;
124 /* Nope, so make a new one */
125 var = (Var *) copyObject(var);
126 var->varlevelsup = 0;
128 pitem = makeNode(PlannerParamItem);
129 pitem->item = (Node *) var;
130 pitem->paramId = root->glob->nParamExec++;
132 root->plan_params = lappend(root->plan_params, pitem);
134 return pitem->paramId;
138 * Generate a Param node to replace the given Var,
139 * which is expected to have varlevelsup > 0 (ie, it is not local).
142 replace_outer_var(PlannerInfo *root, Var *var)
147 Assert(var->varlevelsup > 0 && var->varlevelsup < root->query_level);
149 /* Find the Var in the appropriate plan_params, or add it if not present */
150 i = assign_param_for_var(root, var);
152 retval = makeNode(Param);
153 retval->paramkind = PARAM_EXEC;
155 retval->paramtype = var->vartype;
156 retval->paramtypmod = var->vartypmod;
157 retval->paramcollid = var->varcollid;
158 retval->location = var->location;
164 * Generate a Param node to replace the given Var, which will be supplied
165 * from an upper NestLoop join node.
167 * This is effectively the same as replace_outer_var, except that we expect
168 * the Var to be local to the current query level.
171 assign_nestloop_param_var(PlannerInfo *root, Var *var)
176 Assert(var->varlevelsup == 0);
178 i = assign_param_for_var(root, var);
180 retval = makeNode(Param);
181 retval->paramkind = PARAM_EXEC;
183 retval->paramtype = var->vartype;
184 retval->paramtypmod = var->vartypmod;
185 retval->paramcollid = var->varcollid;
186 retval->location = var->location;
192 * Select a PARAM_EXEC number to identify the given PlaceHolderVar as a
193 * parameter for the current subquery, or for a nestloop's inner scan.
194 * If the PHV already has a param in the current context, return that one.
196 * This is just like assign_param_for_var, except for PlaceHolderVars.
199 assign_param_for_placeholdervar(PlannerInfo *root, PlaceHolderVar *phv)
202 PlannerParamItem *pitem;
205 /* Find the query level the PHV belongs to */
206 for (levelsup = phv->phlevelsup; levelsup > 0; levelsup--)
207 root = root->parent_root;
209 /* If there's already a matching PlannerParamItem there, just use it */
210 foreach(ppl, root->plan_params)
212 pitem = (PlannerParamItem *) lfirst(ppl);
213 if (IsA(pitem->item, PlaceHolderVar))
215 PlaceHolderVar *pphv = (PlaceHolderVar *) pitem->item;
217 /* We assume comparing the PHIDs is sufficient */
218 if (pphv->phid == phv->phid)
219 return pitem->paramId;
223 /* Nope, so make a new one */
224 phv = (PlaceHolderVar *) copyObject(phv);
225 if (phv->phlevelsup != 0)
227 IncrementVarSublevelsUp((Node *) phv, -((int) phv->phlevelsup), 0);
228 Assert(phv->phlevelsup == 0);
231 pitem = makeNode(PlannerParamItem);
232 pitem->item = (Node *) phv;
233 pitem->paramId = root->glob->nParamExec++;
235 root->plan_params = lappend(root->plan_params, pitem);
237 return pitem->paramId;
241 * Generate a Param node to replace the given PlaceHolderVar,
242 * which is expected to have phlevelsup > 0 (ie, it is not local).
244 * This is just like replace_outer_var, except for PlaceHolderVars.
247 replace_outer_placeholdervar(PlannerInfo *root, PlaceHolderVar *phv)
252 Assert(phv->phlevelsup > 0 && phv->phlevelsup < root->query_level);
254 /* Find the PHV in the appropriate plan_params, or add it if not present */
255 i = assign_param_for_placeholdervar(root, phv);
257 retval = makeNode(Param);
258 retval->paramkind = PARAM_EXEC;
260 retval->paramtype = exprType((Node *) phv->phexpr);
261 retval->paramtypmod = exprTypmod((Node *) phv->phexpr);
262 retval->paramcollid = exprCollation((Node *) phv->phexpr);
263 retval->location = -1;
269 * Generate a Param node to replace the given PlaceHolderVar, which will be
270 * supplied from an upper NestLoop join node.
272 * This is just like assign_nestloop_param_var, except for PlaceHolderVars.
275 assign_nestloop_param_placeholdervar(PlannerInfo *root, PlaceHolderVar *phv)
280 Assert(phv->phlevelsup == 0);
282 i = assign_param_for_placeholdervar(root, phv);
284 retval = makeNode(Param);
285 retval->paramkind = PARAM_EXEC;
287 retval->paramtype = exprType((Node *) phv->phexpr);
288 retval->paramtypmod = exprTypmod((Node *) phv->phexpr);
289 retval->paramcollid = exprCollation((Node *) phv->phexpr);
290 retval->location = -1;
296 * Generate a Param node to replace the given Aggref
297 * which is expected to have agglevelsup > 0 (ie, it is not local).
300 replace_outer_agg(PlannerInfo *root, Aggref *agg)
303 PlannerParamItem *pitem;
306 Assert(agg->agglevelsup > 0 && agg->agglevelsup < root->query_level);
308 /* Find the query level the Aggref belongs to */
309 for (levelsup = agg->agglevelsup; levelsup > 0; levelsup--)
310 root = root->parent_root;
313 * It does not seem worthwhile to try to match duplicate outer aggs. Just
314 * make a new slot every time.
316 agg = (Aggref *) copyObject(agg);
317 IncrementVarSublevelsUp((Node *) agg, -((int) agg->agglevelsup), 0);
318 Assert(agg->agglevelsup == 0);
320 pitem = makeNode(PlannerParamItem);
321 pitem->item = (Node *) agg;
322 pitem->paramId = root->glob->nParamExec++;
324 root->plan_params = lappend(root->plan_params, pitem);
326 retval = makeNode(Param);
327 retval->paramkind = PARAM_EXEC;
328 retval->paramid = pitem->paramId;
329 retval->paramtype = agg->aggtype;
330 retval->paramtypmod = -1;
331 retval->paramcollid = agg->aggcollid;
332 retval->location = agg->location;
338 * Generate a new Param node that will not conflict with any other.
340 * This is used to create Params representing subplan outputs.
341 * We don't need to build a PlannerParamItem for such a Param, but we do
342 * need to record the PARAM_EXEC slot number as being allocated.
345 generate_new_param(PlannerInfo *root, Oid paramtype, int32 paramtypmod,
350 retval = makeNode(Param);
351 retval->paramkind = PARAM_EXEC;
352 retval->paramid = root->glob->nParamExec++;
353 retval->paramtype = paramtype;
354 retval->paramtypmod = paramtypmod;
355 retval->paramcollid = paramcollation;
356 retval->location = -1;
362 * Assign a (nonnegative) PARAM_EXEC ID for a special parameter (one that
363 * is not actually used to carry a value at runtime). Such parameters are
364 * used for special runtime signaling purposes, such as connecting a
365 * recursive union node to its worktable scan node or forcing plan
366 * re-evaluation within the EvalPlanQual mechanism. No actual Param node
367 * exists with this ID, however.
370 SS_assign_special_param(PlannerInfo *root)
372 return root->glob->nParamExec++;
376 * Get the datatype/typmod/collation of the first column of the plan's output.
378 * This information is stored for ARRAY_SUBLINK execution and for
379 * exprType()/exprTypmod()/exprCollation(), which have no way to get at the
380 * plan associated with a SubPlan node. We really only need the info for
381 * EXPR_SUBLINK and ARRAY_SUBLINK subplans, but for consistency we save it
385 get_first_col_type(Plan *plan, Oid *coltype, int32 *coltypmod,
388 /* In cases such as EXISTS, tlist might be empty; arbitrarily use VOID */
389 if (plan->targetlist)
391 TargetEntry *tent = (TargetEntry *) linitial(plan->targetlist);
393 Assert(IsA(tent, TargetEntry));
396 *coltype = exprType((Node *) tent->expr);
397 *coltypmod = exprTypmod((Node *) tent->expr);
398 *colcollation = exprCollation((Node *) tent->expr);
404 *colcollation = InvalidOid;
408 * Convert a SubLink (as created by the parser) into a SubPlan.
410 * We are given the SubLink's contained query, type, and testexpr. We are
411 * also told if this expression appears at top level of a WHERE/HAVING qual.
413 * Note: we assume that the testexpr has been AND/OR flattened (actually,
414 * it's been through eval_const_expressions), but not converted to
415 * implicit-AND form; and any SubLinks in it should already have been
416 * converted to SubPlans. The subquery is as yet untouched, however.
418 * The result is whatever we need to substitute in place of the SubLink
419 * node in the executable expression. This will be either the SubPlan
420 * node (if we have to do the subplan as a subplan), or a Param node
421 * representing the result of an InitPlan, or a row comparison expression
422 * tree containing InitPlan Param nodes.
425 make_subplan(PlannerInfo *root, Query *orig_subquery, SubLinkType subLinkType,
426 Node *testexpr, bool isTopQual)
429 bool simple_exists = false;
430 double tuple_fraction;
432 PlannerInfo *subroot;
437 * Copy the source Query node. This is a quick and dirty kluge to resolve
438 * the fact that the parser can generate trees with multiple links to the
439 * same sub-Query node, but the planner wants to scribble on the Query.
440 * Try to clean this up when we do querytree redesign...
442 subquery = (Query *) copyObject(orig_subquery);
445 * If it's an EXISTS subplan, we might be able to simplify it.
447 if (subLinkType == EXISTS_SUBLINK)
448 simple_exists = simplify_EXISTS_query(subquery);
451 * For an EXISTS subplan, tell lower-level planner to expect that only the
452 * first tuple will be retrieved. For ALL and ANY subplans, we will be
453 * able to stop evaluating if the test condition fails or matches, so very
454 * often not all the tuples will be retrieved; for lack of a better idea,
455 * specify 50% retrieval. For EXPR and ROWCOMPARE subplans, use default
456 * behavior (we're only expecting one row out, anyway).
458 * NOTE: if you change these numbers, also change cost_subplan() in
461 * XXX If an ANY subplan is uncorrelated, build_subplan may decide to hash
462 * its output. In that case it would've been better to specify full
463 * retrieval. At present, however, we can only check hashability after
464 * we've made the subplan :-(. (Determining whether it'll fit in work_mem
465 * is the really hard part.) Therefore, we don't want to be too
466 * optimistic about the percentage of tuples retrieved, for fear of
467 * selecting a plan that's bad for the materialization case.
469 if (subLinkType == EXISTS_SUBLINK)
470 tuple_fraction = 1.0; /* just like a LIMIT 1 */
471 else if (subLinkType == ALL_SUBLINK ||
472 subLinkType == ANY_SUBLINK)
473 tuple_fraction = 0.5; /* 50% */
475 tuple_fraction = 0.0; /* default behavior */
477 /* plan_params should not be in use in current query level */
478 Assert(root->plan_params == NIL);
481 * Generate the plan for the subquery.
483 plan = subquery_planner(root->glob, subquery,
485 false, tuple_fraction,
488 /* Isolate the params needed by this specific subplan */
489 plan_params = root->plan_params;
490 root->plan_params = NIL;
492 /* And convert to SubPlan or InitPlan format. */
493 result = build_subplan(root, plan, subroot, plan_params,
494 subLinkType, testexpr, true, isTopQual);
497 * If it's a correlated EXISTS with an unimportant targetlist, we might be
498 * able to transform it to the equivalent of an IN and then implement it
499 * by hashing. We don't have enough information yet to tell which way is
500 * likely to be better (it depends on the expected number of executions of
501 * the EXISTS qual, and we are much too early in planning the outer query
502 * to be able to guess that). So we generate both plans, if possible, and
503 * leave it to the executor to decide which to use.
505 if (simple_exists && IsA(result, SubPlan))
510 /* Make a second copy of the original subquery */
511 subquery = (Query *) copyObject(orig_subquery);
512 /* and re-simplify */
513 simple_exists = simplify_EXISTS_query(subquery);
514 Assert(simple_exists);
515 /* See if it can be converted to an ANY query */
516 subquery = convert_EXISTS_to_ANY(root, subquery,
517 &newtestexpr, ¶mIds);
520 /* Generate the plan for the ANY subquery; we'll need all rows */
521 plan = subquery_planner(root->glob, subquery,
526 /* Isolate the params needed by this specific subplan */
527 plan_params = root->plan_params;
528 root->plan_params = NIL;
530 /* Now we can check if it'll fit in work_mem */
531 if (subplan_is_hashable(plan))
534 AlternativeSubPlan *asplan;
536 /* OK, convert to SubPlan format. */
537 hashplan = (SubPlan *) build_subplan(root, plan, subroot,
539 ANY_SUBLINK, newtestexpr,
541 /* Check we got what we expected */
542 Assert(IsA(hashplan, SubPlan));
543 Assert(hashplan->parParam == NIL);
544 Assert(hashplan->useHashTable);
545 /* build_subplan won't have filled in paramIds */
546 hashplan->paramIds = paramIds;
548 /* Leave it to the executor to decide which plan to use */
549 asplan = makeNode(AlternativeSubPlan);
550 asplan->subplans = list_make2(result, hashplan);
551 result = (Node *) asplan;
560 * Build a SubPlan node given the raw inputs --- subroutine for make_subplan
562 * Returns either the SubPlan, or an expression using initplan output Params,
563 * as explained in the comments for make_subplan.
566 build_subplan(PlannerInfo *root, Plan *plan, PlannerInfo *subroot,
568 SubLinkType subLinkType, Node *testexpr,
569 bool adjust_testexpr, bool unknownEqFalse)
577 * Initialize the SubPlan node. Note plan_id, plan_name, and cost fields
578 * are set further down.
580 splan = makeNode(SubPlan);
581 splan->subLinkType = subLinkType;
582 splan->testexpr = NULL;
583 splan->paramIds = NIL;
584 get_first_col_type(plan, &splan->firstColType, &splan->firstColTypmod,
585 &splan->firstColCollation);
586 splan->useHashTable = false;
587 splan->unknownEqFalse = unknownEqFalse;
588 splan->setParam = NIL;
589 splan->parParam = NIL;
593 * Make parParam and args lists of param IDs and expressions that current
594 * query level will pass to this child plan.
596 foreach(lc, plan_params)
598 PlannerParamItem *pitem = (PlannerParamItem *) lfirst(lc);
599 Node *arg = pitem->item;
602 * The Var, PlaceHolderVar, or Aggref has already been adjusted to
603 * have the correct varlevelsup, phlevelsup, or agglevelsup.
605 * If it's a PlaceHolderVar or Aggref, its arguments might contain
606 * SubLinks, which have not yet been processed (see the comments for
607 * SS_replace_correlation_vars). Do that now.
609 if (IsA(arg, PlaceHolderVar) ||
611 arg = SS_process_sublinks(root, arg, false);
613 splan->parParam = lappend_int(splan->parParam, pitem->paramId);
614 splan->args = lappend(splan->args, arg);
618 * Un-correlated or undirect correlated plans of EXISTS, EXPR, ARRAY, or
619 * ROWCOMPARE types can be used as initPlans. For EXISTS, EXPR, or ARRAY,
620 * we just produce a Param referring to the result of evaluating the
621 * initPlan. For ROWCOMPARE, we must modify the testexpr tree to contain
622 * PARAM_EXEC Params instead of the PARAM_SUBLINK Params emitted by the
625 if (splan->parParam == NIL && subLinkType == EXISTS_SUBLINK)
629 Assert(testexpr == NULL);
630 prm = generate_new_param(root, BOOLOID, -1, InvalidOid);
631 splan->setParam = list_make1_int(prm->paramid);
633 result = (Node *) prm;
635 else if (splan->parParam == NIL && subLinkType == EXPR_SUBLINK)
637 TargetEntry *te = linitial(plan->targetlist);
640 Assert(!te->resjunk);
641 Assert(testexpr == NULL);
642 prm = generate_new_param(root,
643 exprType((Node *) te->expr),
644 exprTypmod((Node *) te->expr),
645 exprCollation((Node *) te->expr));
646 splan->setParam = list_make1_int(prm->paramid);
648 result = (Node *) prm;
650 else if (splan->parParam == NIL && subLinkType == ARRAY_SUBLINK)
652 TargetEntry *te = linitial(plan->targetlist);
656 Assert(!te->resjunk);
657 Assert(testexpr == NULL);
658 arraytype = get_array_type(exprType((Node *) te->expr));
659 if (!OidIsValid(arraytype))
660 elog(ERROR, "could not find array type for datatype %s",
661 format_type_be(exprType((Node *) te->expr)));
662 prm = generate_new_param(root,
664 exprTypmod((Node *) te->expr),
665 exprCollation((Node *) te->expr));
666 splan->setParam = list_make1_int(prm->paramid);
668 result = (Node *) prm;
670 else if (splan->parParam == NIL && subLinkType == ROWCOMPARE_SUBLINK)
672 /* Adjust the Params */
675 Assert(testexpr != NULL);
676 params = generate_subquery_params(root,
679 result = convert_testexpr(root,
682 splan->setParam = list_copy(splan->paramIds);
686 * The executable expression is returned to become part of the outer
687 * plan's expression tree; it is not kept in the initplan node.
693 * Adjust the Params in the testexpr, unless caller said it's not
696 if (testexpr && adjust_testexpr)
700 params = generate_subquery_params(root,
703 splan->testexpr = convert_testexpr(root,
708 splan->testexpr = testexpr;
711 * We can't convert subplans of ALL_SUBLINK or ANY_SUBLINK types to
712 * initPlans, even when they are uncorrelated or undirect correlated,
713 * because we need to scan the output of the subplan for each outer
714 * tuple. But if it's a not-direct-correlated IN (= ANY) test, we
715 * might be able to use a hashtable to avoid comparing all the tuples.
717 if (subLinkType == ANY_SUBLINK &&
718 splan->parParam == NIL &&
719 subplan_is_hashable(plan) &&
720 testexpr_is_hashable(splan->testexpr))
721 splan->useHashTable = true;
724 * Otherwise, we have the option to tack a Material node onto the top
725 * of the subplan, to reduce the cost of reading it repeatedly. This
726 * is pointless for a direct-correlated subplan, since we'd have to
727 * recompute its results each time anyway. For uncorrelated/undirect
728 * correlated subplans, we add Material unless the subplan's top plan
729 * node would materialize its output anyway. Also, if enable_material
730 * is false, then the user does not want us to materialize anything
731 * unnecessarily, so we don't.
733 else if (splan->parParam == NIL && enable_material &&
734 !ExecMaterializesOutput(nodeTag(plan)))
735 plan = materialize_finished_plan(plan);
737 result = (Node *) splan;
742 * Add the subplan and its PlannerInfo to the global lists.
744 root->glob->subplans = lappend(root->glob->subplans, plan);
745 root->glob->subroots = lappend(root->glob->subroots, subroot);
746 splan->plan_id = list_length(root->glob->subplans);
749 root->init_plans = lappend(root->init_plans, splan);
752 * A parameterless subplan (not initplan) should be prepared to handle
753 * REWIND efficiently. If it has direct parameters then there's no point
754 * since it'll be reset on each scan anyway; and if it's an initplan then
755 * there's no point since it won't get re-run without parameter changes
756 * anyway. The input of a hashed subplan doesn't need REWIND either.
758 if (splan->parParam == NIL && !isInitPlan && !splan->useHashTable)
759 root->glob->rewindPlanIDs = bms_add_member(root->glob->rewindPlanIDs,
762 /* Label the subplan for EXPLAIN purposes */
768 splan->plan_name = palloc(32 + 12 * list_length(splan->setParam));
769 sprintf(splan->plan_name, "InitPlan %d (returns ", splan->plan_id);
770 offset = strlen(splan->plan_name);
771 foreach(lc, splan->setParam)
773 sprintf(splan->plan_name + offset, "$%d%s",
775 lnext(lc) ? "," : "");
776 offset += strlen(splan->plan_name + offset);
778 sprintf(splan->plan_name + offset, ")");
782 splan->plan_name = palloc(32);
783 sprintf(splan->plan_name, "SubPlan %d", splan->plan_id);
786 /* Lastly, fill in the cost estimates for use later */
787 cost_subplan(root, splan, plan);
793 * generate_subquery_params: build a list of Params representing the output
794 * columns of a sublink's sub-select, given the sub-select's targetlist.
796 * We also return an integer list of the paramids of the Params.
799 generate_subquery_params(PlannerInfo *root, List *tlist, List **paramIds)
808 TargetEntry *tent = (TargetEntry *) lfirst(lc);
814 param = generate_new_param(root,
815 exprType((Node *) tent->expr),
816 exprTypmod((Node *) tent->expr),
817 exprCollation((Node *) tent->expr));
818 result = lappend(result, param);
819 ids = lappend_int(ids, param->paramid);
827 * generate_subquery_vars: build a list of Vars representing the output
828 * columns of a sublink's sub-select, given the sub-select's targetlist.
829 * The Vars have the specified varno (RTE index).
832 generate_subquery_vars(PlannerInfo *root, List *tlist, Index varno)
840 TargetEntry *tent = (TargetEntry *) lfirst(lc);
846 var = makeVarFromTargetEntry(varno, tent);
847 result = lappend(result, var);
854 * convert_testexpr: convert the testexpr given by the parser into
855 * actually executable form. This entails replacing PARAM_SUBLINK Params
856 * with Params or Vars representing the results of the sub-select. The
857 * nodes to be substituted are passed in as the List result from
858 * generate_subquery_params or generate_subquery_vars.
860 * The given testexpr has already been recursively processed by
861 * process_sublinks_mutator. Hence it can no longer contain any
862 * PARAM_SUBLINK Params for lower SubLink nodes; we can safely assume that
863 * any we find are for our own level of SubLink.
866 convert_testexpr(PlannerInfo *root,
870 convert_testexpr_context context;
873 context.subst_nodes = subst_nodes;
874 return convert_testexpr_mutator(testexpr, &context);
878 convert_testexpr_mutator(Node *node,
879 convert_testexpr_context *context)
883 if (IsA(node, Param))
885 Param *param = (Param *) node;
887 if (param->paramkind == PARAM_SUBLINK)
889 if (param->paramid <= 0 ||
890 param->paramid > list_length(context->subst_nodes))
891 elog(ERROR, "unexpected PARAM_SUBLINK ID: %d", param->paramid);
894 * We copy the list item to avoid having doubly-linked
895 * substructure in the modified parse tree. This is probably
896 * unnecessary when it's a Param, but be safe.
898 return (Node *) copyObject(list_nth(context->subst_nodes,
899 param->paramid - 1));
902 return expression_tree_mutator(node,
903 convert_testexpr_mutator,
908 * subplan_is_hashable: can we implement an ANY subplan by hashing?
911 subplan_is_hashable(Plan *plan)
913 double subquery_size;
916 * The estimated size of the subquery result must fit in work_mem. (Note:
917 * we use sizeof(HeapTupleHeaderData) here even though the tuples will
918 * actually be stored as MinimalTuples; this provides some fudge factor
919 * for hashtable overhead.)
921 subquery_size = plan->plan_rows *
922 (MAXALIGN(plan->plan_width) + MAXALIGN(sizeof(HeapTupleHeaderData)));
923 if (subquery_size > work_mem * 1024L)
930 * testexpr_is_hashable: is an ANY SubLink's test expression hashable?
933 testexpr_is_hashable(Node *testexpr)
936 * The testexpr must be a single OpExpr, or an AND-clause containing only
939 * The combining operators must be hashable and strict. The need for
940 * hashability is obvious, since we want to use hashing. Without
941 * strictness, behavior in the presence of nulls is too unpredictable. We
942 * actually must assume even more than plain strictness: they can't yield
943 * NULL for non-null inputs, either (see nodeSubplan.c). However, hash
944 * indexes and hash joins assume that too.
946 if (testexpr && IsA(testexpr, OpExpr))
948 if (hash_ok_operator((OpExpr *) testexpr))
951 else if (and_clause(testexpr))
955 foreach(l, ((BoolExpr *) testexpr)->args)
957 Node *andarg = (Node *) lfirst(l);
959 if (!IsA(andarg, OpExpr))
961 if (!hash_ok_operator((OpExpr *) andarg))
971 * Check expression is hashable + strict
973 * We could use op_hashjoinable() and op_strict(), but do it like this to
974 * avoid a redundant cache lookup.
977 hash_ok_operator(OpExpr *expr)
979 Oid opid = expr->opno;
981 /* quick out if not a binary operator */
982 if (list_length(expr->args) != 2)
984 if (opid == ARRAY_EQ_OP)
986 /* array_eq is strict, but must check input type to ensure hashable */
987 /* XXX record_eq will need same treatment when it becomes hashable */
988 Node *leftarg = linitial(expr->args);
990 return op_hashjoinable(opid, exprType(leftarg));
994 /* else must look up the operator properties */
996 Form_pg_operator optup;
998 tup = SearchSysCache1(OPEROID, ObjectIdGetDatum(opid));
999 if (!HeapTupleIsValid(tup))
1000 elog(ERROR, "cache lookup failed for operator %u", opid);
1001 optup = (Form_pg_operator) GETSTRUCT(tup);
1002 if (!optup->oprcanhash || !func_strict(optup->oprcode))
1004 ReleaseSysCache(tup);
1007 ReleaseSysCache(tup);
1014 * SS_process_ctes: process a query's WITH list
1016 * We plan each interesting WITH item and convert it to an initplan.
1017 * A side effect is to fill in root->cte_plan_ids with a list that
1018 * parallels root->parse->cteList and provides the subplan ID for
1019 * each CTE's initplan.
1022 SS_process_ctes(PlannerInfo *root)
1026 Assert(root->cte_plan_ids == NIL);
1028 foreach(lc, root->parse->cteList)
1030 CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
1031 CmdType cmdType = ((Query *) cte->ctequery)->commandType;
1034 PlannerInfo *subroot;
1039 * Ignore SELECT CTEs that are not actually referenced anywhere.
1041 if (cte->cterefcount == 0 && cmdType == CMD_SELECT)
1043 /* Make a dummy entry in cte_plan_ids */
1044 root->cte_plan_ids = lappend_int(root->cte_plan_ids, -1);
1049 * Copy the source Query node. Probably not necessary, but let's keep
1050 * this similar to make_subplan.
1052 subquery = (Query *) copyObject(cte->ctequery);
1054 /* plan_params should not be in use in current query level */
1055 Assert(root->plan_params == NIL);
1058 * Generate the plan for the CTE query. Always plan for full
1059 * retrieval --- we don't have enough info to predict otherwise.
1061 plan = subquery_planner(root->glob, subquery,
1063 cte->cterecursive, 0.0,
1067 * Since the current query level doesn't yet contain any RTEs, it
1068 * should not be possible for the CTE to have requested parameters of
1071 if (root->plan_params)
1072 elog(ERROR, "unexpected outer reference in CTE query");
1075 * Make a SubPlan node for it. This is just enough unlike
1076 * build_subplan that we can't share code.
1078 * Note plan_id, plan_name, and cost fields are set further down.
1080 splan = makeNode(SubPlan);
1081 splan->subLinkType = CTE_SUBLINK;
1082 splan->testexpr = NULL;
1083 splan->paramIds = NIL;
1084 get_first_col_type(plan, &splan->firstColType, &splan->firstColTypmod,
1085 &splan->firstColCollation);
1086 splan->useHashTable = false;
1087 splan->unknownEqFalse = false;
1088 splan->setParam = NIL;
1089 splan->parParam = NIL;
1093 * The node can't have any inputs (since it's an initplan), so the
1094 * parParam and args lists remain empty. (It could contain references
1095 * to earlier CTEs' output param IDs, but CTE outputs are not
1096 * propagated via the args list.)
1100 * Assign a param ID to represent the CTE's output. No ordinary
1101 * "evaluation" of this param slot ever happens, but we use the param
1102 * ID for setParam/chgParam signaling just as if the CTE plan were
1103 * returning a simple scalar output. (Also, the executor abuses the
1104 * ParamExecData slot for this param ID for communication among
1105 * multiple CteScan nodes that might be scanning this CTE.)
1107 paramid = SS_assign_special_param(root);
1108 splan->setParam = list_make1_int(paramid);
1111 * Add the subplan and its PlannerInfo to the global lists.
1113 root->glob->subplans = lappend(root->glob->subplans, plan);
1114 root->glob->subroots = lappend(root->glob->subroots, subroot);
1115 splan->plan_id = list_length(root->glob->subplans);
1117 root->init_plans = lappend(root->init_plans, splan);
1119 root->cte_plan_ids = lappend_int(root->cte_plan_ids, splan->plan_id);
1121 /* Label the subplan for EXPLAIN purposes */
1122 splan->plan_name = palloc(4 + strlen(cte->ctename) + 1);
1123 sprintf(splan->plan_name, "CTE %s", cte->ctename);
1125 /* Lastly, fill in the cost estimates for use later */
1126 cost_subplan(root, splan, plan);
1131 * convert_ANY_sublink_to_join: try to convert an ANY SubLink to a join
1133 * The caller has found an ANY SubLink at the top level of one of the query's
1134 * qual clauses, but has not checked the properties of the SubLink further.
1135 * Decide whether it is appropriate to process this SubLink in join style.
1136 * If so, form a JoinExpr and return it. Return NULL if the SubLink cannot
1137 * be converted to a join.
1139 * The only non-obvious input parameter is available_rels: this is the set
1140 * of query rels that can safely be referenced in the sublink expression.
1141 * (We must restrict this to avoid changing the semantics when a sublink
1142 * is present in an outer join's ON qual.) The conversion must fail if
1143 * the converted qual would reference any but these parent-query relids.
1145 * On success, the returned JoinExpr has larg = NULL and rarg = the jointree
1146 * item representing the pulled-up subquery. The caller must set larg to
1147 * represent the relation(s) on the lefthand side of the new join, and insert
1148 * the JoinExpr into the upper query's jointree at an appropriate place
1149 * (typically, where the lefthand relation(s) had been). Note that the
1150 * passed-in SubLink must also be removed from its original position in the
1151 * query quals, since the quals of the returned JoinExpr replace it.
1152 * (Notionally, we replace the SubLink with a constant TRUE, then elide the
1153 * redundant constant from the qual.)
1155 * On success, the caller is also responsible for recursively applying
1156 * pull_up_sublinks processing to the rarg and quals of the returned JoinExpr.
1157 * (On failure, there is no need to do anything, since pull_up_sublinks will
1158 * be applied when we recursively plan the sub-select.)
1160 * Side effects of a successful conversion include adding the SubLink's
1161 * subselect to the query's rangetable, so that it can be referenced in
1162 * the JoinExpr's rarg.
1165 convert_ANY_sublink_to_join(PlannerInfo *root, SubLink *sublink,
1166 Relids available_rels)
1169 Query *parse = root->parse;
1170 Query *subselect = (Query *) sublink->subselect;
1171 Relids upper_varnos;
1175 List *subquery_vars;
1178 Assert(sublink->subLinkType == ANY_SUBLINK);
1181 * The sub-select must not refer to any Vars of the parent query. (Vars of
1182 * higher levels should be okay, though.)
1184 if (contain_vars_of_level((Node *) subselect, 1))
1188 * The test expression must contain some Vars of the parent query, else
1189 * it's not gonna be a join. (Note that it won't have Vars referring to
1190 * the subquery, rather Params.)
1192 upper_varnos = pull_varnos(sublink->testexpr);
1193 if (bms_is_empty(upper_varnos))
1197 * However, it can't refer to anything outside available_rels.
1199 if (!bms_is_subset(upper_varnos, available_rels))
1203 * The combining operators and left-hand expressions mustn't be volatile.
1205 if (contain_volatile_functions(sublink->testexpr))
1209 * Okay, pull up the sub-select into upper range table.
1211 * We rely here on the assumption that the outer query has no references
1212 * to the inner (necessarily true, other than the Vars that we build
1213 * below). Therefore this is a lot easier than what pull_up_subqueries has
1216 rte = addRangeTableEntryForSubquery(NULL,
1218 makeAlias("ANY_subquery", NIL),
1221 parse->rtable = lappend(parse->rtable, rte);
1222 rtindex = list_length(parse->rtable);
1225 * Form a RangeTblRef for the pulled-up sub-select.
1227 rtr = makeNode(RangeTblRef);
1228 rtr->rtindex = rtindex;
1231 * Build a list of Vars representing the subselect outputs.
1233 subquery_vars = generate_subquery_vars(root,
1234 subselect->targetList,
1238 * Build the new join's qual expression, replacing Params with these Vars.
1240 quals = convert_testexpr(root, sublink->testexpr, subquery_vars);
1243 * And finally, build the JoinExpr node.
1245 result = makeNode(JoinExpr);
1246 result->jointype = JOIN_SEMI;
1247 result->isNatural = false;
1248 result->larg = NULL; /* caller must fill this in */
1249 result->rarg = (Node *) rtr;
1250 result->usingClause = NIL;
1251 result->quals = quals;
1252 result->alias = NULL;
1253 result->rtindex = 0; /* we don't need an RTE for it */
1259 * convert_EXISTS_sublink_to_join: try to convert an EXISTS SubLink to a join
1261 * The API of this function is identical to convert_ANY_sublink_to_join's,
1262 * except that we also support the case where the caller has found NOT EXISTS,
1263 * so we need an additional input parameter "under_not".
1266 convert_EXISTS_sublink_to_join(PlannerInfo *root, SubLink *sublink,
1267 bool under_not, Relids available_rels)
1270 Query *parse = root->parse;
1271 Query *subselect = (Query *) sublink->subselect;
1275 Relids clause_varnos;
1276 Relids upper_varnos;
1278 Assert(sublink->subLinkType == EXISTS_SUBLINK);
1281 * Can't flatten if it contains WITH. (We could arrange to pull up the
1282 * WITH into the parent query's cteList, but that risks changing the
1283 * semantics, since a WITH ought to be executed once per associated query
1284 * call.) Note that convert_ANY_sublink_to_join doesn't have to reject
1285 * this case, since it just produces a subquery RTE that doesn't have to
1286 * get flattened into the parent query.
1288 if (subselect->cteList)
1292 * Copy the subquery so we can modify it safely (see comments in
1295 subselect = (Query *) copyObject(subselect);
1298 * See if the subquery can be simplified based on the knowledge that it's
1299 * being used in EXISTS(). If we aren't able to get rid of its
1300 * targetlist, we have to fail, because the pullup operation leaves us
1301 * with noplace to evaluate the targetlist.
1303 if (!simplify_EXISTS_query(subselect))
1307 * The subquery must have a nonempty jointree, else we won't have a join.
1309 if (subselect->jointree->fromlist == NIL)
1313 * Separate out the WHERE clause. (We could theoretically also remove
1314 * top-level plain JOIN/ON clauses, but it's probably not worth the
1317 whereClause = subselect->jointree->quals;
1318 subselect->jointree->quals = NULL;
1321 * The rest of the sub-select must not refer to any Vars of the parent
1322 * query. (Vars of higher levels should be okay, though.)
1324 if (contain_vars_of_level((Node *) subselect, 1))
1328 * On the other hand, the WHERE clause must contain some Vars of the
1329 * parent query, else it's not gonna be a join.
1331 if (!contain_vars_of_level(whereClause, 1))
1335 * We don't risk optimizing if the WHERE clause is volatile, either.
1337 if (contain_volatile_functions(whereClause))
1341 * Prepare to pull up the sub-select into top range table.
1343 * We rely here on the assumption that the outer query has no references
1344 * to the inner (necessarily true). Therefore this is a lot easier than
1345 * what pull_up_subqueries has to go through.
1347 * In fact, it's even easier than what convert_ANY_sublink_to_join has to
1348 * do. The machinations of simplify_EXISTS_query ensured that there is
1349 * nothing interesting in the subquery except an rtable and jointree, and
1350 * even the jointree FromExpr no longer has quals. So we can just append
1351 * the rtable to our own and use the FromExpr in our jointree. But first,
1352 * adjust all level-zero varnos in the subquery to account for the rtable
1355 rtoffset = list_length(parse->rtable);
1356 OffsetVarNodes((Node *) subselect, rtoffset, 0);
1357 OffsetVarNodes(whereClause, rtoffset, 0);
1360 * Upper-level vars in subquery will now be one level closer to their
1361 * parent than before; in particular, anything that had been level 1
1362 * becomes level zero.
1364 IncrementVarSublevelsUp((Node *) subselect, -1, 1);
1365 IncrementVarSublevelsUp(whereClause, -1, 1);
1368 * Now that the WHERE clause is adjusted to match the parent query
1369 * environment, we can easily identify all the level-zero rels it uses.
1370 * The ones <= rtoffset belong to the upper query; the ones > rtoffset do
1373 clause_varnos = pull_varnos(whereClause);
1374 upper_varnos = NULL;
1375 while ((varno = bms_first_member(clause_varnos)) >= 0)
1377 if (varno <= rtoffset)
1378 upper_varnos = bms_add_member(upper_varnos, varno);
1380 bms_free(clause_varnos);
1381 Assert(!bms_is_empty(upper_varnos));
1384 * Now that we've got the set of upper-level varnos, we can make the last
1385 * check: only available_rels can be referenced.
1387 if (!bms_is_subset(upper_varnos, available_rels))
1390 /* Now we can attach the modified subquery rtable to the parent */
1391 parse->rtable = list_concat(parse->rtable, subselect->rtable);
1394 * And finally, build the JoinExpr node.
1396 result = makeNode(JoinExpr);
1397 result->jointype = under_not ? JOIN_ANTI : JOIN_SEMI;
1398 result->isNatural = false;
1399 result->larg = NULL; /* caller must fill this in */
1400 /* flatten out the FromExpr node if it's useless */
1401 if (list_length(subselect->jointree->fromlist) == 1)
1402 result->rarg = (Node *) linitial(subselect->jointree->fromlist);
1404 result->rarg = (Node *) subselect->jointree;
1405 result->usingClause = NIL;
1406 result->quals = whereClause;
1407 result->alias = NULL;
1408 result->rtindex = 0; /* we don't need an RTE for it */
1414 * simplify_EXISTS_query: remove any useless stuff in an EXISTS's subquery
1416 * The only thing that matters about an EXISTS query is whether it returns
1417 * zero or more than zero rows. Therefore, we can remove certain SQL features
1418 * that won't affect that. The only part that is really likely to matter in
1419 * typical usage is simplifying the targetlist: it's a common habit to write
1420 * "SELECT * FROM" even though there is no need to evaluate any columns.
1422 * Note: by suppressing the targetlist we could cause an observable behavioral
1423 * change, namely that any errors that might occur in evaluating the tlist
1424 * won't occur, nor will other side-effects of volatile functions. This seems
1425 * unlikely to bother anyone in practice.
1427 * Returns TRUE if was able to discard the targetlist, else FALSE.
1430 simplify_EXISTS_query(Query *query)
1433 * We don't try to simplify at all if the query uses set operations,
1434 * aggregates, modifying CTEs, HAVING, LIMIT/OFFSET, or FOR UPDATE/SHARE;
1435 * none of these seem likely in normal usage and their possible effects
1438 if (query->commandType != CMD_SELECT ||
1439 query->setOperations ||
1441 query->hasWindowFuncs ||
1442 query->hasModifyingCTE ||
1443 query->havingQual ||
1444 query->limitOffset ||
1445 query->limitCount ||
1450 * Mustn't throw away the targetlist if it contains set-returning
1451 * functions; those could affect whether zero rows are returned!
1453 if (expression_returns_set((Node *) query->targetList))
1457 * Otherwise, we can throw away the targetlist, as well as any GROUP,
1458 * WINDOW, DISTINCT, and ORDER BY clauses; none of those clauses will
1459 * change a nonzero-rows result to zero rows or vice versa. (Furthermore,
1460 * since our parsetree representation of these clauses depends on the
1461 * targetlist, we'd better throw them away if we drop the targetlist.)
1463 query->targetList = NIL;
1464 query->groupClause = NIL;
1465 query->windowClause = NIL;
1466 query->distinctClause = NIL;
1467 query->sortClause = NIL;
1468 query->hasDistinctOn = false;
1474 * convert_EXISTS_to_ANY: try to convert EXISTS to a hashable ANY sublink
1476 * The subselect is expected to be a fresh copy that we can munge up,
1477 * and to have been successfully passed through simplify_EXISTS_query.
1479 * On success, the modified subselect is returned, and we store a suitable
1480 * upper-level test expression at *testexpr, plus a list of the subselect's
1481 * output Params at *paramIds. (The test expression is already Param-ified
1482 * and hence need not go through convert_testexpr, which is why we have to
1483 * deal with the Param IDs specially.)
1485 * On failure, returns NULL.
1488 convert_EXISTS_to_ANY(PlannerInfo *root, Query *subselect,
1489 Node **testexpr, List **paramIds)
1507 * Query must not require a targetlist, since we have to insert a new one.
1508 * Caller should have dealt with the case already.
1510 Assert(subselect->targetList == NIL);
1513 * Separate out the WHERE clause. (We could theoretically also remove
1514 * top-level plain JOIN/ON clauses, but it's probably not worth the
1517 whereClause = subselect->jointree->quals;
1518 subselect->jointree->quals = NULL;
1521 * The rest of the sub-select must not refer to any Vars of the parent
1522 * query. (Vars of higher levels should be okay, though.)
1524 * Note: we need not check for Aggrefs separately because we know the
1525 * sub-select is as yet unoptimized; any uplevel Aggref must therefore
1526 * contain an uplevel Var reference. This is not the case below ...
1528 if (contain_vars_of_level((Node *) subselect, 1))
1532 * We don't risk optimizing if the WHERE clause is volatile, either.
1534 if (contain_volatile_functions(whereClause))
1538 * Clean up the WHERE clause by doing const-simplification etc on it.
1539 * Aside from simplifying the processing we're about to do, this is
1540 * important for being able to pull chunks of the WHERE clause up into the
1541 * parent query. Since we are invoked partway through the parent's
1542 * preprocess_expression() work, earlier steps of preprocess_expression()
1543 * wouldn't get applied to the pulled-up stuff unless we do them here. For
1544 * the parts of the WHERE clause that get put back into the child query,
1545 * this work is partially duplicative, but it shouldn't hurt.
1547 * Note: we do not run flatten_join_alias_vars. This is OK because any
1548 * parent aliases were flattened already, and we're not going to pull any
1549 * child Vars (of any description) into the parent.
1551 * Note: passing the parent's root to eval_const_expressions is
1552 * technically wrong, but we can get away with it since only the
1553 * boundParams (if any) are used, and those would be the same in a
1556 whereClause = eval_const_expressions(root, whereClause);
1557 whereClause = (Node *) canonicalize_qual((Expr *) whereClause);
1558 whereClause = (Node *) make_ands_implicit((Expr *) whereClause);
1561 * We now have a flattened implicit-AND list of clauses, which we try to
1562 * break apart into "outervar = innervar" hash clauses. Anything that
1563 * can't be broken apart just goes back into the newWhere list. Note that
1564 * we aren't trying hard yet to ensure that we have only outer or only
1565 * inner on each side; we'll check that if we get to the end.
1567 leftargs = rightargs = opids = opcollations = newWhere = NIL;
1568 foreach(lc, (List *) whereClause)
1570 OpExpr *expr = (OpExpr *) lfirst(lc);
1572 if (IsA(expr, OpExpr) &&
1573 hash_ok_operator(expr))
1575 Node *leftarg = (Node *) linitial(expr->args);
1576 Node *rightarg = (Node *) lsecond(expr->args);
1578 if (contain_vars_of_level(leftarg, 1))
1580 leftargs = lappend(leftargs, leftarg);
1581 rightargs = lappend(rightargs, rightarg);
1582 opids = lappend_oid(opids, expr->opno);
1583 opcollations = lappend_oid(opcollations, expr->inputcollid);
1586 if (contain_vars_of_level(rightarg, 1))
1589 * We must commute the clause to put the outer var on the
1590 * left, because the hashing code in nodeSubplan.c expects
1591 * that. This probably shouldn't ever fail, since hashable
1592 * operators ought to have commutators, but be paranoid.
1594 expr->opno = get_commutator(expr->opno);
1595 if (OidIsValid(expr->opno) && hash_ok_operator(expr))
1597 leftargs = lappend(leftargs, rightarg);
1598 rightargs = lappend(rightargs, leftarg);
1599 opids = lappend_oid(opids, expr->opno);
1600 opcollations = lappend_oid(opcollations, expr->inputcollid);
1603 /* If no commutator, no chance to optimize the WHERE clause */
1607 /* Couldn't handle it as a hash clause */
1608 newWhere = lappend(newWhere, expr);
1612 * If we didn't find anything we could convert, fail.
1614 if (leftargs == NIL)
1618 * There mustn't be any parent Vars or Aggs in the stuff that we intend to
1619 * put back into the child query. Note: you might think we don't need to
1620 * check for Aggs separately, because an uplevel Agg must contain an
1621 * uplevel Var in its argument. But it is possible that the uplevel Var
1622 * got optimized away by eval_const_expressions. Consider
1624 * SUM(CASE WHEN false THEN uplevelvar ELSE 0 END)
1626 if (contain_vars_of_level((Node *) newWhere, 1) ||
1627 contain_vars_of_level((Node *) rightargs, 1))
1629 if (root->parse->hasAggs &&
1630 (contain_aggs_of_level((Node *) newWhere, 1) ||
1631 contain_aggs_of_level((Node *) rightargs, 1)))
1635 * And there can't be any child Vars in the stuff we intend to pull up.
1636 * (Note: we'd need to check for child Aggs too, except we know the child
1637 * has no aggs at all because of simplify_EXISTS_query's check. The same
1638 * goes for window functions.)
1640 if (contain_vars_of_level((Node *) leftargs, 0))
1644 * Also reject sublinks in the stuff we intend to pull up. (It might be
1645 * possible to support this, but doesn't seem worth the complication.)
1647 if (contain_subplans((Node *) leftargs))
1651 * Okay, adjust the sublevelsup in the stuff we're pulling up.
1653 IncrementVarSublevelsUp((Node *) leftargs, -1, 1);
1656 * Put back any child-level-only WHERE clauses.
1659 subselect->jointree->quals = (Node *) make_ands_explicit(newWhere);
1662 * Build a new targetlist for the child that emits the expressions we
1663 * need. Concurrently, build a testexpr for the parent using Params to
1664 * reference the child outputs. (Since we generate Params directly here,
1665 * there will be no need to convert the testexpr in build_subplan.)
1667 tlist = testlist = paramids = NIL;
1669 /* there's no "forfour" so we have to chase one of the lists manually */
1670 cc = list_head(opcollations);
1671 forthree(lc, leftargs, rc, rightargs, oc, opids)
1673 Node *leftarg = (Node *) lfirst(lc);
1674 Node *rightarg = (Node *) lfirst(rc);
1675 Oid opid = lfirst_oid(oc);
1676 Oid opcollation = lfirst_oid(cc);
1680 param = generate_new_param(root,
1682 exprTypmod(rightarg),
1683 exprCollation(rightarg));
1684 tlist = lappend(tlist,
1685 makeTargetEntry((Expr *) rightarg,
1689 testlist = lappend(testlist,
1690 make_opclause(opid, BOOLOID, false,
1691 (Expr *) leftarg, (Expr *) param,
1692 InvalidOid, opcollation));
1693 paramids = lappend_int(paramids, param->paramid);
1696 /* Put everything where it should go, and we're done */
1697 subselect->targetList = tlist;
1698 *testexpr = (Node *) make_ands_explicit(testlist);
1699 *paramIds = paramids;
1706 * Replace correlation vars (uplevel vars) with Params.
1708 * Uplevel PlaceHolderVars and aggregates are replaced, too.
1710 * Note: it is critical that this runs immediately after SS_process_sublinks.
1711 * Since we do not recurse into the arguments of uplevel PHVs and aggregates,
1712 * they will get copied to the appropriate subplan args list in the parent
1713 * query with uplevel vars not replaced by Params, but only adjusted in level
1714 * (see replace_outer_placeholdervar and replace_outer_agg). That's exactly
1715 * what we want for the vars of the parent level --- but if a PHV's or
1716 * aggregate's argument contains any further-up variables, they have to be
1717 * replaced with Params in their turn. That will happen when the parent level
1718 * runs SS_replace_correlation_vars. Therefore it must do so after expanding
1719 * its sublinks to subplans. And we don't want any steps in between, else
1720 * those steps would never get applied to the argument expressions, either in
1721 * the parent or the child level.
1723 * Another fairly tricky thing going on here is the handling of SubLinks in
1724 * the arguments of uplevel PHVs/aggregates. Those are not touched inside the
1725 * intermediate query level, either. Instead, SS_process_sublinks recurses on
1726 * them after copying the PHV or Aggref expression into the parent plan level
1727 * (this is actually taken care of in build_subplan).
1730 SS_replace_correlation_vars(PlannerInfo *root, Node *expr)
1732 /* No setup needed for tree walk, so away we go */
1733 return replace_correlation_vars_mutator(expr, root);
1737 replace_correlation_vars_mutator(Node *node, PlannerInfo *root)
1743 if (((Var *) node)->varlevelsup > 0)
1744 return (Node *) replace_outer_var(root, (Var *) node);
1746 if (IsA(node, PlaceHolderVar))
1748 if (((PlaceHolderVar *) node)->phlevelsup > 0)
1749 return (Node *) replace_outer_placeholdervar(root,
1750 (PlaceHolderVar *) node);
1752 if (IsA(node, Aggref))
1754 if (((Aggref *) node)->agglevelsup > 0)
1755 return (Node *) replace_outer_agg(root, (Aggref *) node);
1757 return expression_tree_mutator(node,
1758 replace_correlation_vars_mutator,
1763 * Expand SubLinks to SubPlans in the given expression.
1765 * The isQual argument tells whether or not this expression is a WHERE/HAVING
1766 * qualifier expression. If it is, any sublinks appearing at top level need
1767 * not distinguish FALSE from UNKNOWN return values.
1770 SS_process_sublinks(PlannerInfo *root, Node *expr, bool isQual)
1772 process_sublinks_context context;
1774 context.root = root;
1775 context.isTopQual = isQual;
1776 return process_sublinks_mutator(expr, &context);
1780 process_sublinks_mutator(Node *node, process_sublinks_context *context)
1782 process_sublinks_context locContext;
1784 locContext.root = context->root;
1788 if (IsA(node, SubLink))
1790 SubLink *sublink = (SubLink *) node;
1794 * First, recursively process the lefthand-side expressions, if any.
1795 * They're not top-level anymore.
1797 locContext.isTopQual = false;
1798 testexpr = process_sublinks_mutator(sublink->testexpr, &locContext);
1801 * Now build the SubPlan node and make the expr to return.
1803 return make_subplan(context->root,
1804 (Query *) sublink->subselect,
1805 sublink->subLinkType,
1807 context->isTopQual);
1811 * Don't recurse into the arguments of an outer PHV or aggregate here. Any
1812 * SubLinks in the arguments have to be dealt with at the outer query
1813 * level; they'll be handled when build_subplan collects the PHV or Aggref
1814 * into the arguments to be passed down to the current subplan.
1816 if (IsA(node, PlaceHolderVar))
1818 if (((PlaceHolderVar *) node)->phlevelsup > 0)
1821 else if (IsA(node, Aggref))
1823 if (((Aggref *) node)->agglevelsup > 0)
1828 * We should never see a SubPlan expression in the input (since this is
1829 * the very routine that creates 'em to begin with). We shouldn't find
1830 * ourselves invoked directly on a Query, either.
1832 Assert(!IsA(node, SubPlan));
1833 Assert(!IsA(node, AlternativeSubPlan));
1834 Assert(!IsA(node, Query));
1837 * Because make_subplan() could return an AND or OR clause, we have to
1838 * take steps to preserve AND/OR flatness of a qual. We assume the input
1839 * has been AND/OR flattened and so we need no recursion here.
1841 * (Due to the coding here, we will not get called on the List subnodes of
1842 * an AND; and the input is *not* yet in implicit-AND format. So no check
1843 * is needed for a bare List.)
1845 * Anywhere within the top-level AND/OR clause structure, we can tell
1846 * make_subplan() that NULL and FALSE are interchangeable. So isTopQual
1847 * propagates down in both cases. (Note that this is unlike the meaning
1848 * of "top level qual" used in most other places in Postgres.)
1850 if (and_clause(node))
1852 List *newargs = NIL;
1855 /* Still at qual top-level */
1856 locContext.isTopQual = context->isTopQual;
1858 foreach(l, ((BoolExpr *) node)->args)
1862 newarg = process_sublinks_mutator(lfirst(l), &locContext);
1863 if (and_clause(newarg))
1864 newargs = list_concat(newargs, ((BoolExpr *) newarg)->args);
1866 newargs = lappend(newargs, newarg);
1868 return (Node *) make_andclause(newargs);
1871 if (or_clause(node))
1873 List *newargs = NIL;
1876 /* Still at qual top-level */
1877 locContext.isTopQual = context->isTopQual;
1879 foreach(l, ((BoolExpr *) node)->args)
1883 newarg = process_sublinks_mutator(lfirst(l), &locContext);
1884 if (or_clause(newarg))
1885 newargs = list_concat(newargs, ((BoolExpr *) newarg)->args);
1887 newargs = lappend(newargs, newarg);
1889 return (Node *) make_orclause(newargs);
1893 * If we recurse down through anything other than an AND or OR node, we
1894 * are definitely not at top qual level anymore.
1896 locContext.isTopQual = false;
1898 return expression_tree_mutator(node,
1899 process_sublinks_mutator,
1900 (void *) &locContext);
1904 * SS_finalize_plan - do final sublink and parameter processing for a
1907 * This recursively computes the extParam and allParam sets for every Plan
1908 * node in the given plan tree. It also optionally attaches any previously
1909 * generated InitPlans to the top plan node. (Any InitPlans should already
1910 * have been put through SS_finalize_plan.)
1913 SS_finalize_plan(PlannerInfo *root, Plan *plan, bool attach_initplans)
1915 Bitmapset *valid_params,
1923 * Examine any initPlans to determine the set of external params they
1924 * reference, the set of output params they supply, and their total cost.
1925 * We'll use at least some of this info below. (Note we are assuming that
1926 * finalize_plan doesn't touch the initPlans.)
1928 * In the case where attach_initplans is false, we are assuming that the
1929 * existing initPlans are siblings that might supply params needed by the
1932 initExtParam = initSetParam = NULL;
1934 foreach(l, root->init_plans)
1936 SubPlan *initsubplan = (SubPlan *) lfirst(l);
1937 Plan *initplan = planner_subplan_get_plan(root, initsubplan);
1940 initExtParam = bms_add_members(initExtParam, initplan->extParam);
1941 foreach(l2, initsubplan->setParam)
1943 initSetParam = bms_add_member(initSetParam, lfirst_int(l2));
1945 initplan_cost += initsubplan->startup_cost + initsubplan->per_call_cost;
1949 * Now determine the set of params that are validly referenceable in this
1950 * query level; to wit, those available from outer query levels plus the
1951 * output parameters of any local initPlans. (We do not include output
1952 * parameters of regular subplans. Those should only appear within the
1953 * testexpr of SubPlan nodes, and are taken care of locally within
1954 * finalize_primnode. Likewise, special parameters that are generated by
1955 * nodes such as ModifyTable are handled within finalize_plan.)
1957 valid_params = bms_copy(initSetParam);
1958 for (proot = root->parent_root; proot != NULL; proot = proot->parent_root)
1960 /* Include ordinary Var/PHV/Aggref params */
1961 foreach(l, proot->plan_params)
1963 PlannerParamItem *pitem = (PlannerParamItem *) lfirst(l);
1965 valid_params = bms_add_member(valid_params, pitem->paramId);
1967 /* Include any outputs of outer-level initPlans */
1968 foreach(l, proot->init_plans)
1970 SubPlan *initsubplan = (SubPlan *) lfirst(l);
1973 foreach(l2, initsubplan->setParam)
1975 valid_params = bms_add_member(valid_params, lfirst_int(l2));
1978 /* Include worktable ID, if a recursive query is being planned */
1979 if (proot->wt_param_id >= 0)
1980 valid_params = bms_add_member(valid_params, proot->wt_param_id);
1984 * Now recurse through plan tree.
1986 (void) finalize_plan(root, plan, valid_params, NULL);
1988 bms_free(valid_params);
1991 * Finally, attach any initPlans to the topmost plan node, and add their
1992 * extParams to the topmost node's, too. However, any setParams of the
1993 * initPlans should not be present in the topmost node's extParams, only
1994 * in its allParams. (As of PG 8.1, it's possible that some initPlans
1995 * have extParams that are setParams of other initPlans, so we have to
1996 * take care of this situation explicitly.)
1998 * We also add the eval cost of each initPlan to the startup cost of the
1999 * top node. This is a conservative overestimate, since in fact each
2000 * initPlan might be executed later than plan startup, or even not at all.
2002 if (attach_initplans)
2004 plan->initPlan = root->init_plans;
2005 root->init_plans = NIL; /* make sure they're not attached twice */
2007 /* allParam must include all these params */
2008 plan->allParam = bms_add_members(plan->allParam, initExtParam);
2009 plan->allParam = bms_add_members(plan->allParam, initSetParam);
2010 /* extParam must include any child extParam */
2011 plan->extParam = bms_add_members(plan->extParam, initExtParam);
2012 /* but extParam shouldn't include any setParams */
2013 plan->extParam = bms_del_members(plan->extParam, initSetParam);
2014 /* ensure extParam is exactly NULL if it's empty */
2015 if (bms_is_empty(plan->extParam))
2016 plan->extParam = NULL;
2018 plan->startup_cost += initplan_cost;
2019 plan->total_cost += initplan_cost;
2024 * Recursive processing of all nodes in the plan tree
2026 * valid_params is the set of param IDs considered valid to reference in
2027 * this plan node or its children.
2028 * scan_params is a set of param IDs to force scan plan nodes to reference.
2029 * This is for EvalPlanQual support, and is always NULL at the top of the
2032 * The return value is the computed allParam set for the given Plan node.
2033 * This is just an internal notational convenience.
2036 finalize_plan(PlannerInfo *root, Plan *plan, Bitmapset *valid_params,
2037 Bitmapset *scan_params)
2039 finalize_primnode_context context;
2040 int locally_added_param;
2041 Bitmapset *nestloop_params;
2042 Bitmapset *child_params;
2047 context.root = root;
2048 context.paramids = NULL; /* initialize set to empty */
2049 locally_added_param = -1; /* there isn't one */
2050 nestloop_params = NULL; /* there aren't any */
2053 * When we call finalize_primnode, context.paramids sets are automatically
2054 * merged together. But when recursing to self, we have to do it the hard
2055 * way. We want the paramids set to include params in subplans as well as
2059 /* Find params in targetlist and qual */
2060 finalize_primnode((Node *) plan->targetlist, &context);
2061 finalize_primnode((Node *) plan->qual, &context);
2063 /* Check additional node-type-specific fields */
2064 switch (nodeTag(plan))
2067 finalize_primnode(((Result *) plan)->resconstantqual,
2072 context.paramids = bms_add_members(context.paramids, scan_params);
2076 finalize_primnode((Node *) ((IndexScan *) plan)->indexqual,
2078 finalize_primnode((Node *) ((IndexScan *) plan)->indexorderby,
2082 * we need not look at indexqualorig, since it will have the same
2083 * param references as indexqual. Likewise, we can ignore
2086 context.paramids = bms_add_members(context.paramids, scan_params);
2089 case T_IndexOnlyScan:
2090 finalize_primnode((Node *) ((IndexOnlyScan *) plan)->indexqual,
2092 finalize_primnode((Node *) ((IndexOnlyScan *) plan)->indexorderby,
2096 * we need not look at indextlist, since it cannot contain Params.
2098 context.paramids = bms_add_members(context.paramids, scan_params);
2101 case T_BitmapIndexScan:
2102 finalize_primnode((Node *) ((BitmapIndexScan *) plan)->indexqual,
2106 * we need not look at indexqualorig, since it will have the same
2107 * param references as indexqual.
2111 case T_BitmapHeapScan:
2112 finalize_primnode((Node *) ((BitmapHeapScan *) plan)->bitmapqualorig,
2114 context.paramids = bms_add_members(context.paramids, scan_params);
2118 finalize_primnode((Node *) ((TidScan *) plan)->tidquals,
2120 context.paramids = bms_add_members(context.paramids, scan_params);
2123 case T_SubqueryScan:
2126 * In a SubqueryScan, SS_finalize_plan has already been run on the
2127 * subplan by the inner invocation of subquery_planner, so there's
2128 * no need to do it again. Instead, just pull out the subplan's
2129 * extParams list, which represents the params it needs from my
2130 * level and higher levels.
2132 context.paramids = bms_add_members(context.paramids,
2133 ((SubqueryScan *) plan)->subplan->extParam);
2134 /* We need scan_params too, though */
2135 context.paramids = bms_add_members(context.paramids, scan_params);
2138 case T_FunctionScan:
2139 finalize_primnode(((FunctionScan *) plan)->funcexpr,
2141 context.paramids = bms_add_members(context.paramids, scan_params);
2145 finalize_primnode((Node *) ((ValuesScan *) plan)->values_lists,
2147 context.paramids = bms_add_members(context.paramids, scan_params);
2153 * You might think we should add the node's cteParam to
2154 * paramids, but we shouldn't because that param is just a
2155 * linkage mechanism for multiple CteScan nodes for the same
2156 * CTE; it is never used for changed-param signaling. What we
2157 * have to do instead is to find the referenced CTE plan and
2158 * incorporate its external paramids, so that the correct
2159 * things will happen if the CTE references outer-level
2160 * variables. See test cases for bug #4902.
2162 int plan_id = ((CteScan *) plan)->ctePlanId;
2165 /* so, do this ... */
2166 if (plan_id < 1 || plan_id > list_length(root->glob->subplans))
2167 elog(ERROR, "could not find plan for CteScan referencing plan ID %d",
2169 cteplan = (Plan *) list_nth(root->glob->subplans, plan_id - 1);
2171 bms_add_members(context.paramids, cteplan->extParam);
2174 /* ... but not this */
2176 bms_add_member(context.paramids,
2177 ((CteScan *) plan)->cteParam);
2180 context.paramids = bms_add_members(context.paramids,
2185 case T_WorkTableScan:
2187 bms_add_member(context.paramids,
2188 ((WorkTableScan *) plan)->wtParam);
2189 context.paramids = bms_add_members(context.paramids, scan_params);
2193 finalize_primnode((Node *) ((ForeignScan *) plan)->fdw_exprs,
2195 context.paramids = bms_add_members(context.paramids, scan_params);
2200 ModifyTable *mtplan = (ModifyTable *) plan;
2203 /* Force descendant scan nodes to reference epqParam */
2204 locally_added_param = mtplan->epqParam;
2205 valid_params = bms_add_member(bms_copy(valid_params),
2206 locally_added_param);
2207 scan_params = bms_add_member(bms_copy(scan_params),
2208 locally_added_param);
2209 finalize_primnode((Node *) mtplan->returningLists,
2211 foreach(l, mtplan->plans)
2214 bms_add_members(context.paramids,
2227 foreach(l, ((Append *) plan)->appendplans)
2230 bms_add_members(context.paramids,
2243 foreach(l, ((MergeAppend *) plan)->mergeplans)
2246 bms_add_members(context.paramids,
2259 foreach(l, ((BitmapAnd *) plan)->bitmapplans)
2262 bms_add_members(context.paramids,
2275 foreach(l, ((BitmapOr *) plan)->bitmapplans)
2278 bms_add_members(context.paramids,
2291 finalize_primnode((Node *) ((Join *) plan)->joinqual,
2293 /* collect set of params that will be passed to right child */
2294 foreach(l, ((NestLoop *) plan)->nestParams)
2296 NestLoopParam *nlp = (NestLoopParam *) lfirst(l);
2298 nestloop_params = bms_add_member(nestloop_params,
2305 finalize_primnode((Node *) ((Join *) plan)->joinqual,
2307 finalize_primnode((Node *) ((MergeJoin *) plan)->mergeclauses,
2312 finalize_primnode((Node *) ((Join *) plan)->joinqual,
2314 finalize_primnode((Node *) ((HashJoin *) plan)->hashclauses,
2319 finalize_primnode(((Limit *) plan)->limitOffset,
2321 finalize_primnode(((Limit *) plan)->limitCount,
2325 case T_RecursiveUnion:
2326 /* child nodes are allowed to reference wtParam */
2327 locally_added_param = ((RecursiveUnion *) plan)->wtParam;
2328 valid_params = bms_add_member(bms_copy(valid_params),
2329 locally_added_param);
2330 /* wtParam does *not* get added to scan_params */
2334 /* Force descendant scan nodes to reference epqParam */
2335 locally_added_param = ((LockRows *) plan)->epqParam;
2336 valid_params = bms_add_member(bms_copy(valid_params),
2337 locally_added_param);
2338 scan_params = bms_add_member(bms_copy(scan_params),
2339 locally_added_param);
2343 finalize_primnode(((WindowAgg *) plan)->startOffset,
2345 finalize_primnode(((WindowAgg *) plan)->endOffset,
2359 elog(ERROR, "unrecognized node type: %d",
2360 (int) nodeTag(plan));
2363 /* Process left and right child plans, if any */
2364 child_params = finalize_plan(root,
2368 context.paramids = bms_add_members(context.paramids, child_params);
2370 if (nestloop_params)
2372 /* right child can reference nestloop_params as well as valid_params */
2373 child_params = finalize_plan(root,
2375 bms_union(nestloop_params, valid_params),
2377 /* ... and they don't count as parameters used at my level */
2378 child_params = bms_difference(child_params, nestloop_params);
2379 bms_free(nestloop_params);
2384 child_params = finalize_plan(root,
2389 context.paramids = bms_add_members(context.paramids, child_params);
2392 * Any locally generated parameter doesn't count towards its generating
2393 * plan node's external dependencies. (Note: if we changed valid_params
2394 * and/or scan_params, we leak those bitmapsets; not worth the notational
2395 * trouble to clean them up.)
2397 if (locally_added_param >= 0)
2399 context.paramids = bms_del_member(context.paramids,
2400 locally_added_param);
2403 /* Now we have all the paramids */
2405 if (!bms_is_subset(context.paramids, valid_params))
2406 elog(ERROR, "plan should not reference subplan's variable");
2409 * Note: by definition, extParam and allParam should have the same value
2410 * in any plan node that doesn't have child initPlans. We set them equal
2411 * here, and later SS_finalize_plan will update them properly in node(s)
2412 * that it attaches initPlans to.
2414 * For speed at execution time, make sure extParam/allParam are actually
2415 * NULL if they are empty sets.
2417 if (bms_is_empty(context.paramids))
2419 plan->extParam = NULL;
2420 plan->allParam = NULL;
2424 plan->extParam = context.paramids;
2425 plan->allParam = bms_copy(context.paramids);
2428 return plan->allParam;
2432 * finalize_primnode: add IDs of all PARAM_EXEC params appearing in the given
2433 * expression tree to the result set.
2436 finalize_primnode(Node *node, finalize_primnode_context *context)
2440 if (IsA(node, Param))
2442 if (((Param *) node)->paramkind == PARAM_EXEC)
2444 int paramid = ((Param *) node)->paramid;
2446 context->paramids = bms_add_member(context->paramids, paramid);
2448 return false; /* no more to do here */
2450 if (IsA(node, SubPlan))
2452 SubPlan *subplan = (SubPlan *) node;
2453 Plan *plan = planner_subplan_get_plan(context->root, subplan);
2455 Bitmapset *subparamids;
2457 /* Recurse into the testexpr, but not into the Plan */
2458 finalize_primnode(subplan->testexpr, context);
2461 * Remove any param IDs of output parameters of the subplan that were
2462 * referenced in the testexpr. These are not interesting for
2463 * parameter change signaling since we always re-evaluate the subplan.
2464 * Note that this wouldn't work too well if there might be uses of the
2465 * same param IDs elsewhere in the plan, but that can't happen because
2466 * generate_new_param never tries to merge params.
2468 foreach(lc, subplan->paramIds)
2470 context->paramids = bms_del_member(context->paramids,
2474 /* Also examine args list */
2475 finalize_primnode((Node *) subplan->args, context);
2478 * Add params needed by the subplan to paramids, but excluding those
2479 * we will pass down to it.
2481 subparamids = bms_copy(plan->extParam);
2482 foreach(lc, subplan->parParam)
2484 subparamids = bms_del_member(subparamids, lfirst_int(lc));
2486 context->paramids = bms_join(context->paramids, subparamids);
2488 return false; /* no more to do here */
2490 return expression_tree_walker(node, finalize_primnode,
2495 * SS_make_initplan_from_plan - given a plan tree, make it an InitPlan
2497 * The plan is expected to return a scalar value of the given type/collation.
2498 * We build an EXPR_SUBLINK SubPlan node and put it into the initplan
2499 * list for the current query level. A Param that represents the initplan's
2500 * output is returned.
2502 * We assume the plan hasn't been put through SS_finalize_plan.
2505 SS_make_initplan_from_plan(PlannerInfo *root, Plan *plan,
2506 Oid resulttype, int32 resulttypmod,
2507 Oid resultcollation)
2513 * We must run SS_finalize_plan(), since that's normally done before a
2514 * subplan gets put into the initplan list. Tell it not to attach any
2515 * pre-existing initplans to this one, since they are siblings not
2516 * children of this initplan. (This is something else that could perhaps
2517 * be cleaner if we did extParam/allParam processing in setrefs.c instead
2518 * of here? See notes for materialize_finished_plan.)
2522 * Build extParam/allParam sets for plan nodes.
2524 SS_finalize_plan(root, plan, false);
2527 * Add the subplan and its PlannerInfo to the global lists.
2529 root->glob->subplans = lappend(root->glob->subplans, plan);
2530 root->glob->subroots = lappend(root->glob->subroots, root);
2533 * Create a SubPlan node and add it to the outer list of InitPlans. Note
2534 * it has to appear after any other InitPlans it might depend on (see
2535 * comments in ExecReScan).
2537 node = makeNode(SubPlan);
2538 node->subLinkType = EXPR_SUBLINK;
2539 get_first_col_type(plan, &node->firstColType, &node->firstColTypmod,
2540 &node->firstColCollation);
2541 node->plan_id = list_length(root->glob->subplans);
2543 root->init_plans = lappend(root->init_plans, node);
2546 * The node can't have any inputs (since it's an initplan), so the
2547 * parParam and args lists remain empty.
2550 cost_subplan(root, node, plan);
2553 * Make a Param that will be the subplan's output.
2555 prm = generate_new_param(root, resulttype, resulttypmod, resultcollation);
2556 node->setParam = list_make1_int(prm->paramid);
2558 /* Label the subplan for EXPLAIN purposes */
2559 node->plan_name = palloc(64);
2560 sprintf(node->plan_name, "InitPlan %d (returns $%d)",
2561 node->plan_id, prm->paramid);