PostgreSQL Source Code  git master
subselect.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * subselect.c
4  * Planning routines for subselects and parameters.
5  *
6  * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  * IDENTIFICATION
10  * src/backend/optimizer/plan/subselect.c
11  *
12  *-------------------------------------------------------------------------
13  */
14 #include "postgres.h"
15 
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/pathnode.h"
26 #include "optimizer/planmain.h"
27 #include "optimizer/planner.h"
28 #include "optimizer/prep.h"
29 #include "optimizer/subselect.h"
30 #include "optimizer/var.h"
31 #include "parser/parse_relation.h"
32 #include "rewrite/rewriteManip.h"
33 #include "utils/builtins.h"
34 #include "utils/lsyscache.h"
35 #include "utils/syscache.h"
36 
37 
39 {
41  List *subst_nodes; /* Nodes to substitute for Params */
43 
45 {
47  bool isTopQual;
49 
51 {
53  Bitmapset *paramids; /* Non-local PARAM_EXEC paramids found */
55 
56 
57 static Node *build_subplan(PlannerInfo *root, Plan *plan, PlannerInfo *subroot,
58  List *plan_params,
59  SubLinkType subLinkType, int subLinkId,
60  Node *testexpr, bool adjust_testexpr,
61  bool unknownEqFalse);
63  List **paramIds);
65  Index varno);
67  Node *testexpr,
68  List *subst_nodes);
69 static Node *convert_testexpr_mutator(Node *node,
70  convert_testexpr_context *context);
71 static bool subplan_is_hashable(Plan *plan);
72 static bool testexpr_is_hashable(Node *testexpr);
73 static bool hash_ok_operator(OpExpr *expr);
74 static bool simplify_EXISTS_query(PlannerInfo *root, Query *query);
75 static Query *convert_EXISTS_to_ANY(PlannerInfo *root, Query *subselect,
76  Node **testexpr, List **paramIds);
78 static Node *process_sublinks_mutator(Node *node,
79  process_sublinks_context *context);
81  Plan *plan,
82  int gather_param,
83  Bitmapset *valid_params,
84  Bitmapset *scan_params);
85 static bool finalize_primnode(Node *node, finalize_primnode_context *context);
86 static bool finalize_agg_primnode(Node *node, finalize_primnode_context *context);
87 
88 
89 /*
90  * Select a PARAM_EXEC number to identify the given Var as a parameter for
91  * the current subquery, or for a nestloop's inner scan.
92  * If the Var already has a param in the current context, return that one.
93  */
94 static int
96 {
97  ListCell *ppl;
98  PlannerParamItem *pitem;
99  Index levelsup;
100 
101  /* Find the query level the Var belongs to */
102  for (levelsup = var->varlevelsup; levelsup > 0; levelsup--)
103  root = root->parent_root;
104 
105  /* If there's already a matching PlannerParamItem there, just use it */
106  foreach(ppl, root->plan_params)
107  {
108  pitem = (PlannerParamItem *) lfirst(ppl);
109  if (IsA(pitem->item, Var))
110  {
111  Var *pvar = (Var *) pitem->item;
112 
113  /*
114  * This comparison must match _equalVar(), except for ignoring
115  * varlevelsup. Note that _equalVar() ignores the location.
116  */
117  if (pvar->varno == var->varno &&
118  pvar->varattno == var->varattno &&
119  pvar->vartype == var->vartype &&
120  pvar->vartypmod == var->vartypmod &&
121  pvar->varcollid == var->varcollid &&
122  pvar->varnoold == var->varnoold &&
123  pvar->varoattno == var->varoattno)
124  return pitem->paramId;
125  }
126  }
127 
128  /* Nope, so make a new one */
129  var = copyObject(var);
130  var->varlevelsup = 0;
131 
132  pitem = makeNode(PlannerParamItem);
133  pitem->item = (Node *) var;
134  pitem->paramId = list_length(root->glob->paramExecTypes);
136  var->vartype);
137 
138  root->plan_params = lappend(root->plan_params, pitem);
139 
140  return pitem->paramId;
141 }
142 
143 /*
144  * Generate a Param node to replace the given Var,
145  * which is expected to have varlevelsup > 0 (ie, it is not local).
146  */
147 static Param *
149 {
150  Param *retval;
151  int i;
152 
153  Assert(var->varlevelsup > 0 && var->varlevelsup < root->query_level);
154 
155  /* Find the Var in the appropriate plan_params, or add it if not present */
156  i = assign_param_for_var(root, var);
157 
158  retval = makeNode(Param);
159  retval->paramkind = PARAM_EXEC;
160  retval->paramid = i;
161  retval->paramtype = var->vartype;
162  retval->paramtypmod = var->vartypmod;
163  retval->paramcollid = var->varcollid;
164  retval->location = var->location;
165 
166  return retval;
167 }
168 
169 /*
170  * Generate a Param node to replace the given Var, which will be supplied
171  * from an upper NestLoop join node.
172  *
173  * This is effectively the same as replace_outer_var, except that we expect
174  * the Var to be local to the current query level.
175  */
176 Param *
178 {
179  Param *retval;
180  int i;
181 
182  Assert(var->varlevelsup == 0);
183 
184  i = assign_param_for_var(root, var);
185 
186  retval = makeNode(Param);
187  retval->paramkind = PARAM_EXEC;
188  retval->paramid = i;
189  retval->paramtype = var->vartype;
190  retval->paramtypmod = var->vartypmod;
191  retval->paramcollid = var->varcollid;
192  retval->location = var->location;
193 
194  return retval;
195 }
196 
197 /*
198  * Select a PARAM_EXEC number to identify the given PlaceHolderVar as a
199  * parameter for the current subquery, or for a nestloop's inner scan.
200  * If the PHV already has a param in the current context, return that one.
201  *
202  * This is just like assign_param_for_var, except for PlaceHolderVars.
203  */
204 static int
206 {
207  ListCell *ppl;
208  PlannerParamItem *pitem;
209  Index levelsup;
210 
211  /* Find the query level the PHV belongs to */
212  for (levelsup = phv->phlevelsup; levelsup > 0; levelsup--)
213  root = root->parent_root;
214 
215  /* If there's already a matching PlannerParamItem there, just use it */
216  foreach(ppl, root->plan_params)
217  {
218  pitem = (PlannerParamItem *) lfirst(ppl);
219  if (IsA(pitem->item, PlaceHolderVar))
220  {
221  PlaceHolderVar *pphv = (PlaceHolderVar *) pitem->item;
222 
223  /* We assume comparing the PHIDs is sufficient */
224  if (pphv->phid == phv->phid)
225  return pitem->paramId;
226  }
227  }
228 
229  /* Nope, so make a new one */
230  phv = copyObject(phv);
231  if (phv->phlevelsup != 0)
232  {
233  IncrementVarSublevelsUp((Node *) phv, -((int) phv->phlevelsup), 0);
234  Assert(phv->phlevelsup == 0);
235  }
236 
237  pitem = makeNode(PlannerParamItem);
238  pitem->item = (Node *) phv;
239  pitem->paramId = list_length(root->glob->paramExecTypes);
241  exprType((Node *) phv->phexpr));
242 
243  root->plan_params = lappend(root->plan_params, pitem);
244 
245  return pitem->paramId;
246 }
247 
248 /*
249  * Generate a Param node to replace the given PlaceHolderVar,
250  * which is expected to have phlevelsup > 0 (ie, it is not local).
251  *
252  * This is just like replace_outer_var, except for PlaceHolderVars.
253  */
254 static Param *
256 {
257  Param *retval;
258  int i;
259 
260  Assert(phv->phlevelsup > 0 && phv->phlevelsup < root->query_level);
261 
262  /* Find the PHV in the appropriate plan_params, or add it if not present */
263  i = assign_param_for_placeholdervar(root, phv);
264 
265  retval = makeNode(Param);
266  retval->paramkind = PARAM_EXEC;
267  retval->paramid = i;
268  retval->paramtype = exprType((Node *) phv->phexpr);
269  retval->paramtypmod = exprTypmod((Node *) phv->phexpr);
270  retval->paramcollid = exprCollation((Node *) phv->phexpr);
271  retval->location = -1;
272 
273  return retval;
274 }
275 
276 /*
277  * Generate a Param node to replace the given PlaceHolderVar, which will be
278  * supplied from an upper NestLoop join node.
279  *
280  * This is just like assign_nestloop_param_var, except for PlaceHolderVars.
281  */
282 Param *
284 {
285  Param *retval;
286  int i;
287 
288  Assert(phv->phlevelsup == 0);
289 
290  i = assign_param_for_placeholdervar(root, phv);
291 
292  retval = makeNode(Param);
293  retval->paramkind = PARAM_EXEC;
294  retval->paramid = i;
295  retval->paramtype = exprType((Node *) phv->phexpr);
296  retval->paramtypmod = exprTypmod((Node *) phv->phexpr);
297  retval->paramcollid = exprCollation((Node *) phv->phexpr);
298  retval->location = -1;
299 
300  return retval;
301 }
302 
303 /*
304  * Generate a Param node to replace the given Aggref
305  * which is expected to have agglevelsup > 0 (ie, it is not local).
306  */
307 static Param *
309 {
310  Param *retval;
311  PlannerParamItem *pitem;
312  Index levelsup;
313 
314  Assert(agg->agglevelsup > 0 && agg->agglevelsup < root->query_level);
315 
316  /* Find the query level the Aggref belongs to */
317  for (levelsup = agg->agglevelsup; levelsup > 0; levelsup--)
318  root = root->parent_root;
319 
320  /*
321  * It does not seem worthwhile to try to match duplicate outer aggs. Just
322  * make a new slot every time.
323  */
324  agg = copyObject(agg);
325  IncrementVarSublevelsUp((Node *) agg, -((int) agg->agglevelsup), 0);
326  Assert(agg->agglevelsup == 0);
327 
328  pitem = makeNode(PlannerParamItem);
329  pitem->item = (Node *) agg;
330  pitem->paramId = list_length(root->glob->paramExecTypes);
332  agg->aggtype);
333 
334  root->plan_params = lappend(root->plan_params, pitem);
335 
336  retval = makeNode(Param);
337  retval->paramkind = PARAM_EXEC;
338  retval->paramid = pitem->paramId;
339  retval->paramtype = agg->aggtype;
340  retval->paramtypmod = -1;
341  retval->paramcollid = agg->aggcollid;
342  retval->location = agg->location;
343 
344  return retval;
345 }
346 
347 /*
348  * Generate a Param node to replace the given GroupingFunc expression which is
349  * expected to have agglevelsup > 0 (ie, it is not local).
350  */
351 static Param *
353 {
354  Param *retval;
355  PlannerParamItem *pitem;
356  Index levelsup;
357  Oid ptype;
358 
359  Assert(grp->agglevelsup > 0 && grp->agglevelsup < root->query_level);
360 
361  /* Find the query level the GroupingFunc belongs to */
362  for (levelsup = grp->agglevelsup; levelsup > 0; levelsup--)
363  root = root->parent_root;
364 
365  /*
366  * It does not seem worthwhile to try to match duplicate outer aggs. Just
367  * make a new slot every time.
368  */
369  grp = copyObject(grp);
370  IncrementVarSublevelsUp((Node *) grp, -((int) grp->agglevelsup), 0);
371  Assert(grp->agglevelsup == 0);
372  ptype = exprType((Node *) grp);
373 
374  pitem = makeNode(PlannerParamItem);
375  pitem->item = (Node *) grp;
376  pitem->paramId = list_length(root->glob->paramExecTypes);
378  ptype);
379 
380  root->plan_params = lappend(root->plan_params, pitem);
381 
382  retval = makeNode(Param);
383  retval->paramkind = PARAM_EXEC;
384  retval->paramid = pitem->paramId;
385  retval->paramtype = ptype;
386  retval->paramtypmod = -1;
387  retval->paramcollid = InvalidOid;
388  retval->location = grp->location;
389 
390  return retval;
391 }
392 
393 /*
394  * Generate a new Param node that will not conflict with any other.
395  *
396  * This is used to create Params representing subplan outputs.
397  * We don't need to build a PlannerParamItem for such a Param, but we do
398  * need to make sure we record the type in paramExecTypes (otherwise,
399  * there won't be a slot allocated for it).
400  */
401 static Param *
402 generate_new_param(PlannerInfo *root, Oid paramtype, int32 paramtypmod,
403  Oid paramcollation)
404 {
405  Param *retval;
406 
407  retval = makeNode(Param);
408  retval->paramkind = PARAM_EXEC;
409  retval->paramid = list_length(root->glob->paramExecTypes);
411  paramtype);
412  retval->paramtype = paramtype;
413  retval->paramtypmod = paramtypmod;
414  retval->paramcollid = paramcollation;
415  retval->location = -1;
416 
417  return retval;
418 }
419 
420 /*
421  * Assign a (nonnegative) PARAM_EXEC ID for a special parameter (one that
422  * is not actually used to carry a value at runtime). Such parameters are
423  * used for special runtime signaling purposes, such as connecting a
424  * recursive union node to its worktable scan node or forcing plan
425  * re-evaluation within the EvalPlanQual mechanism. No actual Param node
426  * exists with this ID, however.
427  */
428 int
430 {
431  int paramId = list_length(root->glob->paramExecTypes);
432 
434  InvalidOid);
435  return paramId;
436 }
437 
438 /*
439  * Get the datatype/typmod/collation of the first column of the plan's output.
440  *
441  * This information is stored for ARRAY_SUBLINK execution and for
442  * exprType()/exprTypmod()/exprCollation(), which have no way to get at the
443  * plan associated with a SubPlan node. We really only need the info for
444  * EXPR_SUBLINK and ARRAY_SUBLINK subplans, but for consistency we save it
445  * always.
446  */
447 static void
448 get_first_col_type(Plan *plan, Oid *coltype, int32 *coltypmod,
449  Oid *colcollation)
450 {
451  /* In cases such as EXISTS, tlist might be empty; arbitrarily use VOID */
452  if (plan->targetlist)
453  {
455 
456  if (!tent->resjunk)
457  {
458  *coltype = exprType((Node *) tent->expr);
459  *coltypmod = exprTypmod((Node *) tent->expr);
460  *colcollation = exprCollation((Node *) tent->expr);
461  return;
462  }
463  }
464  *coltype = VOIDOID;
465  *coltypmod = -1;
466  *colcollation = InvalidOid;
467 }
468 
469 /*
470  * Convert a SubLink (as created by the parser) into a SubPlan.
471  *
472  * We are given the SubLink's contained query, type, ID, and testexpr. We are
473  * also told if this expression appears at top level of a WHERE/HAVING qual.
474  *
475  * Note: we assume that the testexpr has been AND/OR flattened (actually,
476  * it's been through eval_const_expressions), but not converted to
477  * implicit-AND form; and any SubLinks in it should already have been
478  * converted to SubPlans. The subquery is as yet untouched, however.
479  *
480  * The result is whatever we need to substitute in place of the SubLink node
481  * in the executable expression. If we're going to do the subplan as a
482  * regular subplan, this will be the constructed SubPlan node. If we're going
483  * to do the subplan as an InitPlan, the SubPlan node instead goes into
484  * root->init_plans, and what we return here is an expression tree
485  * representing the InitPlan's result: usually just a Param node representing
486  * a single scalar result, but possibly a row comparison tree containing
487  * multiple Param nodes, or for a MULTIEXPR subquery a simple NULL constant
488  * (since the real output Params are elsewhere in the tree, and the MULTIEXPR
489  * subquery itself is in a resjunk tlist entry whose value is uninteresting).
490  */
491 static Node *
493  SubLinkType subLinkType, int subLinkId,
494  Node *testexpr, bool isTopQual)
495 {
496  Query *subquery;
497  bool simple_exists = false;
498  double tuple_fraction;
499  PlannerInfo *subroot;
500  RelOptInfo *final_rel;
501  Path *best_path;
502  Plan *plan;
503  List *plan_params;
504  Node *result;
505 
506  /*
507  * Copy the source Query node. This is a quick and dirty kluge to resolve
508  * the fact that the parser can generate trees with multiple links to the
509  * same sub-Query node, but the planner wants to scribble on the Query.
510  * Try to clean this up when we do querytree redesign...
511  */
512  subquery = copyObject(orig_subquery);
513 
514  /*
515  * If it's an EXISTS subplan, we might be able to simplify it.
516  */
517  if (subLinkType == EXISTS_SUBLINK)
518  simple_exists = simplify_EXISTS_query(root, subquery);
519 
520  /*
521  * For an EXISTS subplan, tell lower-level planner to expect that only the
522  * first tuple will be retrieved. For ALL and ANY subplans, we will be
523  * able to stop evaluating if the test condition fails or matches, so very
524  * often not all the tuples will be retrieved; for lack of a better idea,
525  * specify 50% retrieval. For EXPR, MULTIEXPR, and ROWCOMPARE subplans,
526  * use default behavior (we're only expecting one row out, anyway).
527  *
528  * NOTE: if you change these numbers, also change cost_subplan() in
529  * path/costsize.c.
530  *
531  * XXX If an ANY subplan is uncorrelated, build_subplan may decide to hash
532  * its output. In that case it would've been better to specify full
533  * retrieval. At present, however, we can only check hashability after
534  * we've made the subplan :-(. (Determining whether it'll fit in work_mem
535  * is the really hard part.) Therefore, we don't want to be too
536  * optimistic about the percentage of tuples retrieved, for fear of
537  * selecting a plan that's bad for the materialization case.
538  */
539  if (subLinkType == EXISTS_SUBLINK)
540  tuple_fraction = 1.0; /* just like a LIMIT 1 */
541  else if (subLinkType == ALL_SUBLINK ||
542  subLinkType == ANY_SUBLINK)
543  tuple_fraction = 0.5; /* 50% */
544  else
545  tuple_fraction = 0.0; /* default behavior */
546 
547  /* plan_params should not be in use in current query level */
548  Assert(root->plan_params == NIL);
549 
550  /* Generate Paths for the subquery */
551  subroot = subquery_planner(root->glob, subquery,
552  root,
553  false, tuple_fraction);
554 
555  /* Isolate the params needed by this specific subplan */
556  plan_params = root->plan_params;
557  root->plan_params = NIL;
558 
559  /*
560  * Select best Path and turn it into a Plan. At least for now, there
561  * seems no reason to postpone doing that.
562  */
563  final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
564  best_path = get_cheapest_fractional_path(final_rel, tuple_fraction);
565 
566  plan = create_plan(subroot, best_path);
567 
568  /* And convert to SubPlan or InitPlan format. */
569  result = build_subplan(root, plan, subroot, plan_params,
570  subLinkType, subLinkId,
571  testexpr, true, isTopQual);
572 
573  /*
574  * If it's a correlated EXISTS with an unimportant targetlist, we might be
575  * able to transform it to the equivalent of an IN and then implement it
576  * by hashing. We don't have enough information yet to tell which way is
577  * likely to be better (it depends on the expected number of executions of
578  * the EXISTS qual, and we are much too early in planning the outer query
579  * to be able to guess that). So we generate both plans, if possible, and
580  * leave it to the executor to decide which to use.
581  */
582  if (simple_exists && IsA(result, SubPlan))
583  {
584  Node *newtestexpr;
585  List *paramIds;
586 
587  /* Make a second copy of the original subquery */
588  subquery = copyObject(orig_subquery);
589  /* and re-simplify */
590  simple_exists = simplify_EXISTS_query(root, subquery);
591  Assert(simple_exists);
592  /* See if it can be converted to an ANY query */
593  subquery = convert_EXISTS_to_ANY(root, subquery,
594  &newtestexpr, &paramIds);
595  if (subquery)
596  {
597  /* Generate Paths for the ANY subquery; we'll need all rows */
598  subroot = subquery_planner(root->glob, subquery,
599  root,
600  false, 0.0);
601 
602  /* Isolate the params needed by this specific subplan */
603  plan_params = root->plan_params;
604  root->plan_params = NIL;
605 
606  /* Select best Path and turn it into a Plan */
607  final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
608  best_path = final_rel->cheapest_total_path;
609 
610  plan = create_plan(subroot, best_path);
611 
612  /* Now we can check if it'll fit in work_mem */
613  /* XXX can we check this at the Path stage? */
614  if (subplan_is_hashable(plan))
615  {
616  SubPlan *hashplan;
617  AlternativeSubPlan *asplan;
618 
619  /* OK, convert to SubPlan format. */
620  hashplan = castNode(SubPlan,
621  build_subplan(root, plan, subroot,
622  plan_params,
623  ANY_SUBLINK, 0,
624  newtestexpr,
625  false, true));
626  /* Check we got what we expected */
627  Assert(hashplan->parParam == NIL);
628  Assert(hashplan->useHashTable);
629  /* build_subplan won't have filled in paramIds */
630  hashplan->paramIds = paramIds;
631 
632  /* Leave it to the executor to decide which plan to use */
633  asplan = makeNode(AlternativeSubPlan);
634  asplan->subplans = list_make2(result, hashplan);
635  result = (Node *) asplan;
636  }
637  }
638  }
639 
640  return result;
641 }
642 
643 /*
644  * Build a SubPlan node given the raw inputs --- subroutine for make_subplan
645  *
646  * Returns either the SubPlan, or a replacement expression if we decide to
647  * make it an InitPlan, as explained in the comments for make_subplan.
648  */
649 static Node *
651  List *plan_params,
652  SubLinkType subLinkType, int subLinkId,
653  Node *testexpr, bool adjust_testexpr,
654  bool unknownEqFalse)
655 {
656  Node *result;
657  SubPlan *splan;
658  bool isInitPlan;
659  ListCell *lc;
660 
661  /*
662  * Initialize the SubPlan node. Note plan_id, plan_name, and cost fields
663  * are set further down.
664  */
665  splan = makeNode(SubPlan);
666  splan->subLinkType = subLinkType;
667  splan->testexpr = NULL;
668  splan->paramIds = NIL;
669  get_first_col_type(plan, &splan->firstColType, &splan->firstColTypmod,
670  &splan->firstColCollation);
671  splan->useHashTable = false;
672  splan->unknownEqFalse = unknownEqFalse;
673  splan->parallel_safe = plan->parallel_safe;
674  splan->setParam = NIL;
675  splan->parParam = NIL;
676  splan->args = NIL;
677 
678  /*
679  * Make parParam and args lists of param IDs and expressions that current
680  * query level will pass to this child plan.
681  */
682  foreach(lc, plan_params)
683  {
684  PlannerParamItem *pitem = (PlannerParamItem *) lfirst(lc);
685  Node *arg = pitem->item;
686 
687  /*
688  * The Var, PlaceHolderVar, or Aggref has already been adjusted to
689  * have the correct varlevelsup, phlevelsup, or agglevelsup.
690  *
691  * If it's a PlaceHolderVar or Aggref, its arguments might contain
692  * SubLinks, which have not yet been processed (see the comments for
693  * SS_replace_correlation_vars). Do that now.
694  */
695  if (IsA(arg, PlaceHolderVar) ||
696  IsA(arg, Aggref))
697  arg = SS_process_sublinks(root, arg, false);
698 
699  splan->parParam = lappend_int(splan->parParam, pitem->paramId);
700  splan->args = lappend(splan->args, arg);
701  }
702 
703  /*
704  * Un-correlated or undirect correlated plans of EXISTS, EXPR, ARRAY,
705  * ROWCOMPARE, or MULTIEXPR types can be used as initPlans. For EXISTS,
706  * EXPR, or ARRAY, we return a Param referring to the result of evaluating
707  * the initPlan. For ROWCOMPARE, we must modify the testexpr tree to
708  * contain PARAM_EXEC Params instead of the PARAM_SUBLINK Params emitted
709  * by the parser, and then return that tree. For MULTIEXPR, we return a
710  * null constant: the resjunk targetlist item containing the SubLink does
711  * not need to return anything useful, since the referencing Params are
712  * elsewhere.
713  */
714  if (splan->parParam == NIL && subLinkType == EXISTS_SUBLINK)
715  {
716  Param *prm;
717 
718  Assert(testexpr == NULL);
719  prm = generate_new_param(root, BOOLOID, -1, InvalidOid);
720  splan->setParam = list_make1_int(prm->paramid);
721  isInitPlan = true;
722  result = (Node *) prm;
723  }
724  else if (splan->parParam == NIL && subLinkType == EXPR_SUBLINK)
725  {
726  TargetEntry *te = linitial(plan->targetlist);
727  Param *prm;
728 
729  Assert(!te->resjunk);
730  Assert(testexpr == NULL);
731  prm = generate_new_param(root,
732  exprType((Node *) te->expr),
733  exprTypmod((Node *) te->expr),
734  exprCollation((Node *) te->expr));
735  splan->setParam = list_make1_int(prm->paramid);
736  isInitPlan = true;
737  result = (Node *) prm;
738  }
739  else if (splan->parParam == NIL && subLinkType == ARRAY_SUBLINK)
740  {
741  TargetEntry *te = linitial(plan->targetlist);
742  Oid arraytype;
743  Param *prm;
744 
745  Assert(!te->resjunk);
746  Assert(testexpr == NULL);
747  arraytype = get_promoted_array_type(exprType((Node *) te->expr));
748  if (!OidIsValid(arraytype))
749  elog(ERROR, "could not find array type for datatype %s",
750  format_type_be(exprType((Node *) te->expr)));
751  prm = generate_new_param(root,
752  arraytype,
753  exprTypmod((Node *) te->expr),
754  exprCollation((Node *) te->expr));
755  splan->setParam = list_make1_int(prm->paramid);
756  isInitPlan = true;
757  result = (Node *) prm;
758  }
759  else if (splan->parParam == NIL && subLinkType == ROWCOMPARE_SUBLINK)
760  {
761  /* Adjust the Params */
762  List *params;
763 
764  Assert(testexpr != NULL);
765  params = generate_subquery_params(root,
766  plan->targetlist,
767  &splan->paramIds);
768  result = convert_testexpr(root,
769  testexpr,
770  params);
771  splan->setParam = list_copy(splan->paramIds);
772  isInitPlan = true;
773 
774  /*
775  * The executable expression is returned to become part of the outer
776  * plan's expression tree; it is not kept in the initplan node.
777  */
778  }
779  else if (subLinkType == MULTIEXPR_SUBLINK)
780  {
781  /*
782  * Whether it's an initplan or not, it needs to set a PARAM_EXEC Param
783  * for each output column.
784  */
785  List *params;
786 
787  Assert(testexpr == NULL);
788  params = generate_subquery_params(root,
789  plan->targetlist,
790  &splan->setParam);
791 
792  /*
793  * Save the list of replacement Params in the n'th cell of
794  * root->multiexpr_params; setrefs.c will use it to replace
795  * PARAM_MULTIEXPR Params.
796  */
797  while (list_length(root->multiexpr_params) < subLinkId)
799  lc = list_nth_cell(root->multiexpr_params, subLinkId - 1);
800  Assert(lfirst(lc) == NIL);
801  lfirst(lc) = params;
802 
803  /* It can be an initplan if there are no parParams. */
804  if (splan->parParam == NIL)
805  {
806  isInitPlan = true;
807  result = (Node *) makeNullConst(RECORDOID, -1, InvalidOid);
808  }
809  else
810  {
811  isInitPlan = false;
812  result = (Node *) splan;
813  }
814  }
815  else
816  {
817  /*
818  * Adjust the Params in the testexpr, unless caller said it's not
819  * needed.
820  */
821  if (testexpr && adjust_testexpr)
822  {
823  List *params;
824 
825  params = generate_subquery_params(root,
826  plan->targetlist,
827  &splan->paramIds);
828  splan->testexpr = convert_testexpr(root,
829  testexpr,
830  params);
831  }
832  else
833  splan->testexpr = testexpr;
834 
835  /*
836  * We can't convert subplans of ALL_SUBLINK or ANY_SUBLINK types to
837  * initPlans, even when they are uncorrelated or undirect correlated,
838  * because we need to scan the output of the subplan for each outer
839  * tuple. But if it's a not-direct-correlated IN (= ANY) test, we
840  * might be able to use a hashtable to avoid comparing all the tuples.
841  */
842  if (subLinkType == ANY_SUBLINK &&
843  splan->parParam == NIL &&
844  subplan_is_hashable(plan) &&
846  splan->useHashTable = true;
847 
848  /*
849  * Otherwise, we have the option to tack a Material node onto the top
850  * of the subplan, to reduce the cost of reading it repeatedly. This
851  * is pointless for a direct-correlated subplan, since we'd have to
852  * recompute its results each time anyway. For uncorrelated/undirect
853  * correlated subplans, we add Material unless the subplan's top plan
854  * node would materialize its output anyway. Also, if enable_material
855  * is false, then the user does not want us to materialize anything
856  * unnecessarily, so we don't.
857  */
858  else if (splan->parParam == NIL && enable_material &&
860  plan = materialize_finished_plan(plan);
861 
862  result = (Node *) splan;
863  isInitPlan = false;
864  }
865 
866  /*
867  * Add the subplan and its PlannerInfo to the global lists.
868  */
869  root->glob->subplans = lappend(root->glob->subplans, plan);
870  root->glob->subroots = lappend(root->glob->subroots, subroot);
871  splan->plan_id = list_length(root->glob->subplans);
872 
873  if (isInitPlan)
874  root->init_plans = lappend(root->init_plans, splan);
875 
876  /*
877  * A parameterless subplan (not initplan) should be prepared to handle
878  * REWIND efficiently. If it has direct parameters then there's no point
879  * since it'll be reset on each scan anyway; and if it's an initplan then
880  * there's no point since it won't get re-run without parameter changes
881  * anyway. The input of a hashed subplan doesn't need REWIND either.
882  */
883  if (splan->parParam == NIL && !isInitPlan && !splan->useHashTable)
885  splan->plan_id);
886 
887  /* Label the subplan for EXPLAIN purposes */
888  splan->plan_name = palloc(32 + 12 * list_length(splan->setParam));
889  sprintf(splan->plan_name, "%s %d",
890  isInitPlan ? "InitPlan" : "SubPlan",
891  splan->plan_id);
892  if (splan->setParam)
893  {
894  char *ptr = splan->plan_name + strlen(splan->plan_name);
895 
896  ptr += sprintf(ptr, " (returns ");
897  foreach(lc, splan->setParam)
898  {
899  ptr += sprintf(ptr, "$%d%s",
900  lfirst_int(lc),
901  lnext(lc) ? "," : ")");
902  }
903  }
904 
905  /* Lastly, fill in the cost estimates for use later */
906  cost_subplan(root, splan, plan);
907 
908  return result;
909 }
910 
911 /*
912  * generate_subquery_params: build a list of Params representing the output
913  * columns of a sublink's sub-select, given the sub-select's targetlist.
914  *
915  * We also return an integer list of the paramids of the Params.
916  */
917 static List *
919 {
920  List *result;
921  List *ids;
922  ListCell *lc;
923 
924  result = ids = NIL;
925  foreach(lc, tlist)
926  {
927  TargetEntry *tent = (TargetEntry *) lfirst(lc);
928  Param *param;
929 
930  if (tent->resjunk)
931  continue;
932 
933  param = generate_new_param(root,
934  exprType((Node *) tent->expr),
935  exprTypmod((Node *) tent->expr),
936  exprCollation((Node *) tent->expr));
937  result = lappend(result, param);
938  ids = lappend_int(ids, param->paramid);
939  }
940 
941  *paramIds = ids;
942  return result;
943 }
944 
945 /*
946  * generate_subquery_vars: build a list of Vars representing the output
947  * columns of a sublink's sub-select, given the sub-select's targetlist.
948  * The Vars have the specified varno (RTE index).
949  */
950 static List *
952 {
953  List *result;
954  ListCell *lc;
955 
956  result = NIL;
957  foreach(lc, tlist)
958  {
959  TargetEntry *tent = (TargetEntry *) lfirst(lc);
960  Var *var;
961 
962  if (tent->resjunk)
963  continue;
964 
965  var = makeVarFromTargetEntry(varno, tent);
966  result = lappend(result, var);
967  }
968 
969  return result;
970 }
971 
972 /*
973  * convert_testexpr: convert the testexpr given by the parser into
974  * actually executable form. This entails replacing PARAM_SUBLINK Params
975  * with Params or Vars representing the results of the sub-select. The
976  * nodes to be substituted are passed in as the List result from
977  * generate_subquery_params or generate_subquery_vars.
978  */
979 static Node *
981  Node *testexpr,
982  List *subst_nodes)
983 {
984  convert_testexpr_context context;
985 
986  context.root = root;
987  context.subst_nodes = subst_nodes;
988  return convert_testexpr_mutator(testexpr, &context);
989 }
990 
991 static Node *
993  convert_testexpr_context *context)
994 {
995  if (node == NULL)
996  return NULL;
997  if (IsA(node, Param))
998  {
999  Param *param = (Param *) node;
1000 
1001  if (param->paramkind == PARAM_SUBLINK)
1002  {
1003  if (param->paramid <= 0 ||
1004  param->paramid > list_length(context->subst_nodes))
1005  elog(ERROR, "unexpected PARAM_SUBLINK ID: %d", param->paramid);
1006 
1007  /*
1008  * We copy the list item to avoid having doubly-linked
1009  * substructure in the modified parse tree. This is probably
1010  * unnecessary when it's a Param, but be safe.
1011  */
1012  return (Node *) copyObject(list_nth(context->subst_nodes,
1013  param->paramid - 1));
1014  }
1015  }
1016  if (IsA(node, SubLink))
1017  {
1018  /*
1019  * If we come across a nested SubLink, it is neither necessary nor
1020  * correct to recurse into it: any PARAM_SUBLINKs we might find inside
1021  * belong to the inner SubLink not the outer. So just return it as-is.
1022  *
1023  * This reasoning depends on the assumption that nothing will pull
1024  * subexpressions into or out of the testexpr field of a SubLink, at
1025  * least not without replacing PARAM_SUBLINKs first. If we did want
1026  * to do that we'd need to rethink the parser-output representation
1027  * altogether, since currently PARAM_SUBLINKs are only unique per
1028  * SubLink not globally across the query. The whole point of
1029  * replacing them with Vars or PARAM_EXEC nodes is to make them
1030  * globally unique before they escape from the SubLink's testexpr.
1031  *
1032  * Note: this can't happen when called during SS_process_sublinks,
1033  * because that recursively processes inner SubLinks first. It can
1034  * happen when called from convert_ANY_sublink_to_join, though.
1035  */
1036  return node;
1037  }
1038  return expression_tree_mutator(node,
1040  (void *) context);
1041 }
1042 
1043 /*
1044  * subplan_is_hashable: can we implement an ANY subplan by hashing?
1045  */
1046 static bool
1048 {
1049  double subquery_size;
1050 
1051  /*
1052  * The estimated size of the subquery result must fit in work_mem. (Note:
1053  * we use heap tuple overhead here even though the tuples will actually be
1054  * stored as MinimalTuples; this provides some fudge factor for hashtable
1055  * overhead.)
1056  */
1057  subquery_size = plan->plan_rows *
1059  if (subquery_size > work_mem * 1024L)
1060  return false;
1061 
1062  return true;
1063 }
1064 
1065 /*
1066  * testexpr_is_hashable: is an ANY SubLink's test expression hashable?
1067  */
1068 static bool
1070 {
1071  /*
1072  * The testexpr must be a single OpExpr, or an AND-clause containing only
1073  * OpExprs.
1074  *
1075  * The combining operators must be hashable and strict. The need for
1076  * hashability is obvious, since we want to use hashing. Without
1077  * strictness, behavior in the presence of nulls is too unpredictable. We
1078  * actually must assume even more than plain strictness: they can't yield
1079  * NULL for non-null inputs, either (see nodeSubplan.c). However, hash
1080  * indexes and hash joins assume that too.
1081  */
1082  if (testexpr && IsA(testexpr, OpExpr))
1083  {
1084  if (hash_ok_operator((OpExpr *) testexpr))
1085  return true;
1086  }
1087  else if (and_clause(testexpr))
1088  {
1089  ListCell *l;
1090 
1091  foreach(l, ((BoolExpr *) testexpr)->args)
1092  {
1093  Node *andarg = (Node *) lfirst(l);
1094 
1095  if (!IsA(andarg, OpExpr))
1096  return false;
1097  if (!hash_ok_operator((OpExpr *) andarg))
1098  return false;
1099  }
1100  return true;
1101  }
1102 
1103  return false;
1104 }
1105 
1106 /*
1107  * Check expression is hashable + strict
1108  *
1109  * We could use op_hashjoinable() and op_strict(), but do it like this to
1110  * avoid a redundant cache lookup.
1111  */
1112 static bool
1114 {
1115  Oid opid = expr->opno;
1116 
1117  /* quick out if not a binary operator */
1118  if (list_length(expr->args) != 2)
1119  return false;
1120  if (opid == ARRAY_EQ_OP)
1121  {
1122  /* array_eq is strict, but must check input type to ensure hashable */
1123  /* XXX record_eq will need same treatment when it becomes hashable */
1124  Node *leftarg = linitial(expr->args);
1125 
1126  return op_hashjoinable(opid, exprType(leftarg));
1127  }
1128  else
1129  {
1130  /* else must look up the operator properties */
1131  HeapTuple tup;
1132  Form_pg_operator optup;
1133 
1135  if (!HeapTupleIsValid(tup))
1136  elog(ERROR, "cache lookup failed for operator %u", opid);
1137  optup = (Form_pg_operator) GETSTRUCT(tup);
1138  if (!optup->oprcanhash || !func_strict(optup->oprcode))
1139  {
1140  ReleaseSysCache(tup);
1141  return false;
1142  }
1143  ReleaseSysCache(tup);
1144  return true;
1145  }
1146 }
1147 
1148 
1149 /*
1150  * SS_process_ctes: process a query's WITH list
1151  *
1152  * We plan each interesting WITH item and convert it to an initplan.
1153  * A side effect is to fill in root->cte_plan_ids with a list that
1154  * parallels root->parse->cteList and provides the subplan ID for
1155  * each CTE's initplan.
1156  */
1157 void
1159 {
1160  ListCell *lc;
1161 
1162  Assert(root->cte_plan_ids == NIL);
1163 
1164  foreach(lc, root->parse->cteList)
1165  {
1166  CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
1167  CmdType cmdType = ((Query *) cte->ctequery)->commandType;
1168  Query *subquery;
1169  PlannerInfo *subroot;
1170  RelOptInfo *final_rel;
1171  Path *best_path;
1172  Plan *plan;
1173  SubPlan *splan;
1174  int paramid;
1175 
1176  /*
1177  * Ignore SELECT CTEs that are not actually referenced anywhere.
1178  */
1179  if (cte->cterefcount == 0 && cmdType == CMD_SELECT)
1180  {
1181  /* Make a dummy entry in cte_plan_ids */
1182  root->cte_plan_ids = lappend_int(root->cte_plan_ids, -1);
1183  continue;
1184  }
1185 
1186  /*
1187  * Copy the source Query node. Probably not necessary, but let's keep
1188  * this similar to make_subplan.
1189  */
1190  subquery = (Query *) copyObject(cte->ctequery);
1191 
1192  /* plan_params should not be in use in current query level */
1193  Assert(root->plan_params == NIL);
1194 
1195  /*
1196  * Generate Paths for the CTE query. Always plan for full retrieval
1197  * --- we don't have enough info to predict otherwise.
1198  */
1199  subroot = subquery_planner(root->glob, subquery,
1200  root,
1201  cte->cterecursive, 0.0);
1202 
1203  /*
1204  * Since the current query level doesn't yet contain any RTEs, it
1205  * should not be possible for the CTE to have requested parameters of
1206  * this level.
1207  */
1208  if (root->plan_params)
1209  elog(ERROR, "unexpected outer reference in CTE query");
1210 
1211  /*
1212  * Select best Path and turn it into a Plan. At least for now, there
1213  * seems no reason to postpone doing that.
1214  */
1215  final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
1216  best_path = final_rel->cheapest_total_path;
1217 
1218  plan = create_plan(subroot, best_path);
1219 
1220  /*
1221  * Make a SubPlan node for it. This is just enough unlike
1222  * build_subplan that we can't share code.
1223  *
1224  * Note plan_id, plan_name, and cost fields are set further down.
1225  */
1226  splan = makeNode(SubPlan);
1227  splan->subLinkType = CTE_SUBLINK;
1228  splan->testexpr = NULL;
1229  splan->paramIds = NIL;
1230  get_first_col_type(plan, &splan->firstColType, &splan->firstColTypmod,
1231  &splan->firstColCollation);
1232  splan->useHashTable = false;
1233  splan->unknownEqFalse = false;
1234 
1235  /*
1236  * CTE scans are not considered for parallelism (cf
1237  * set_rel_consider_parallel), and even if they were, initPlans aren't
1238  * parallel-safe.
1239  */
1240  splan->parallel_safe = false;
1241  splan->setParam = NIL;
1242  splan->parParam = NIL;
1243  splan->args = NIL;
1244 
1245  /*
1246  * The node can't have any inputs (since it's an initplan), so the
1247  * parParam and args lists remain empty. (It could contain references
1248  * to earlier CTEs' output param IDs, but CTE outputs are not
1249  * propagated via the args list.)
1250  */
1251 
1252  /*
1253  * Assign a param ID to represent the CTE's output. No ordinary
1254  * "evaluation" of this param slot ever happens, but we use the param
1255  * ID for setParam/chgParam signaling just as if the CTE plan were
1256  * returning a simple scalar output. (Also, the executor abuses the
1257  * ParamExecData slot for this param ID for communication among
1258  * multiple CteScan nodes that might be scanning this CTE.)
1259  */
1260  paramid = SS_assign_special_param(root);
1261  splan->setParam = list_make1_int(paramid);
1262 
1263  /*
1264  * Add the subplan and its PlannerInfo to the global lists.
1265  */
1266  root->glob->subplans = lappend(root->glob->subplans, plan);
1267  root->glob->subroots = lappend(root->glob->subroots, subroot);
1268  splan->plan_id = list_length(root->glob->subplans);
1269 
1270  root->init_plans = lappend(root->init_plans, splan);
1271 
1272  root->cte_plan_ids = lappend_int(root->cte_plan_ids, splan->plan_id);
1273 
1274  /* Label the subplan for EXPLAIN purposes */
1275  splan->plan_name = psprintf("CTE %s", cte->ctename);
1276 
1277  /* Lastly, fill in the cost estimates for use later */
1278  cost_subplan(root, splan, plan);
1279  }
1280 }
1281 
1282 /*
1283  * convert_ANY_sublink_to_join: try to convert an ANY SubLink to a join
1284  *
1285  * The caller has found an ANY SubLink at the top level of one of the query's
1286  * qual clauses, but has not checked the properties of the SubLink further.
1287  * Decide whether it is appropriate to process this SubLink in join style.
1288  * If so, form a JoinExpr and return it. Return NULL if the SubLink cannot
1289  * be converted to a join.
1290  *
1291  * The only non-obvious input parameter is available_rels: this is the set
1292  * of query rels that can safely be referenced in the sublink expression.
1293  * (We must restrict this to avoid changing the semantics when a sublink
1294  * is present in an outer join's ON qual.) The conversion must fail if
1295  * the converted qual would reference any but these parent-query relids.
1296  *
1297  * On success, the returned JoinExpr has larg = NULL and rarg = the jointree
1298  * item representing the pulled-up subquery. The caller must set larg to
1299  * represent the relation(s) on the lefthand side of the new join, and insert
1300  * the JoinExpr into the upper query's jointree at an appropriate place
1301  * (typically, where the lefthand relation(s) had been). Note that the
1302  * passed-in SubLink must also be removed from its original position in the
1303  * query quals, since the quals of the returned JoinExpr replace it.
1304  * (Notionally, we replace the SubLink with a constant TRUE, then elide the
1305  * redundant constant from the qual.)
1306  *
1307  * On success, the caller is also responsible for recursively applying
1308  * pull_up_sublinks processing to the rarg and quals of the returned JoinExpr.
1309  * (On failure, there is no need to do anything, since pull_up_sublinks will
1310  * be applied when we recursively plan the sub-select.)
1311  *
1312  * Side effects of a successful conversion include adding the SubLink's
1313  * subselect to the query's rangetable, so that it can be referenced in
1314  * the JoinExpr's rarg.
1315  */
1316 JoinExpr *
1318  Relids available_rels)
1319 {
1320  JoinExpr *result;
1321  Query *parse = root->parse;
1322  Query *subselect = (Query *) sublink->subselect;
1323  Relids upper_varnos;
1324  int rtindex;
1325  RangeTblEntry *rte;
1326  RangeTblRef *rtr;
1327  List *subquery_vars;
1328  Node *quals;
1329  ParseState *pstate;
1330 
1331  Assert(sublink->subLinkType == ANY_SUBLINK);
1332 
1333  /*
1334  * The sub-select must not refer to any Vars of the parent query. (Vars of
1335  * higher levels should be okay, though.)
1336  */
1337  if (contain_vars_of_level((Node *) subselect, 1))
1338  return NULL;
1339 
1340  /*
1341  * The test expression must contain some Vars of the parent query, else
1342  * it's not gonna be a join. (Note that it won't have Vars referring to
1343  * the subquery, rather Params.)
1344  */
1345  upper_varnos = pull_varnos(sublink->testexpr);
1346  if (bms_is_empty(upper_varnos))
1347  return NULL;
1348 
1349  /*
1350  * However, it can't refer to anything outside available_rels.
1351  */
1352  if (!bms_is_subset(upper_varnos, available_rels))
1353  return NULL;
1354 
1355  /*
1356  * The combining operators and left-hand expressions mustn't be volatile.
1357  */
1358  if (contain_volatile_functions(sublink->testexpr))
1359  return NULL;
1360 
1361  /* Create a dummy ParseState for addRangeTableEntryForSubquery */
1362  pstate = make_parsestate(NULL);
1363 
1364  /*
1365  * Okay, pull up the sub-select into upper range table.
1366  *
1367  * We rely here on the assumption that the outer query has no references
1368  * to the inner (necessarily true, other than the Vars that we build
1369  * below). Therefore this is a lot easier than what pull_up_subqueries has
1370  * to go through.
1371  */
1372  rte = addRangeTableEntryForSubquery(pstate,
1373  subselect,
1374  makeAlias("ANY_subquery", NIL),
1375  false,
1376  false);
1377  parse->rtable = lappend(parse->rtable, rte);
1378  rtindex = list_length(parse->rtable);
1379 
1380  /*
1381  * Form a RangeTblRef for the pulled-up sub-select.
1382  */
1383  rtr = makeNode(RangeTblRef);
1384  rtr->rtindex = rtindex;
1385 
1386  /*
1387  * Build a list of Vars representing the subselect outputs.
1388  */
1389  subquery_vars = generate_subquery_vars(root,
1390  subselect->targetList,
1391  rtindex);
1392 
1393  /*
1394  * Build the new join's qual expression, replacing Params with these Vars.
1395  */
1396  quals = convert_testexpr(root, sublink->testexpr, subquery_vars);
1397 
1398  /*
1399  * And finally, build the JoinExpr node.
1400  */
1401  result = makeNode(JoinExpr);
1402  result->jointype = JOIN_SEMI;
1403  result->isNatural = false;
1404  result->larg = NULL; /* caller must fill this in */
1405  result->rarg = (Node *) rtr;
1406  result->usingClause = NIL;
1407  result->quals = quals;
1408  result->alias = NULL;
1409  result->rtindex = 0; /* we don't need an RTE for it */
1410 
1411  return result;
1412 }
1413 
1414 /*
1415  * convert_EXISTS_sublink_to_join: try to convert an EXISTS SubLink to a join
1416  *
1417  * The API of this function is identical to convert_ANY_sublink_to_join's,
1418  * except that we also support the case where the caller has found NOT EXISTS,
1419  * so we need an additional input parameter "under_not".
1420  */
1421 JoinExpr *
1423  bool under_not, Relids available_rels)
1424 {
1425  JoinExpr *result;
1426  Query *parse = root->parse;
1427  Query *subselect = (Query *) sublink->subselect;
1428  Node *whereClause;
1429  int rtoffset;
1430  int varno;
1431  Relids clause_varnos;
1432  Relids upper_varnos;
1433 
1434  Assert(sublink->subLinkType == EXISTS_SUBLINK);
1435 
1436  /*
1437  * Can't flatten if it contains WITH. (We could arrange to pull up the
1438  * WITH into the parent query's cteList, but that risks changing the
1439  * semantics, since a WITH ought to be executed once per associated query
1440  * call.) Note that convert_ANY_sublink_to_join doesn't have to reject
1441  * this case, since it just produces a subquery RTE that doesn't have to
1442  * get flattened into the parent query.
1443  */
1444  if (subselect->cteList)
1445  return NULL;
1446 
1447  /*
1448  * Copy the subquery so we can modify it safely (see comments in
1449  * make_subplan).
1450  */
1451  subselect = copyObject(subselect);
1452 
1453  /*
1454  * See if the subquery can be simplified based on the knowledge that it's
1455  * being used in EXISTS(). If we aren't able to get rid of its
1456  * targetlist, we have to fail, because the pullup operation leaves us
1457  * with noplace to evaluate the targetlist.
1458  */
1459  if (!simplify_EXISTS_query(root, subselect))
1460  return NULL;
1461 
1462  /*
1463  * The subquery must have a nonempty jointree, else we won't have a join.
1464  */
1465  if (subselect->jointree->fromlist == NIL)
1466  return NULL;
1467 
1468  /*
1469  * Separate out the WHERE clause. (We could theoretically also remove
1470  * top-level plain JOIN/ON clauses, but it's probably not worth the
1471  * trouble.)
1472  */
1473  whereClause = subselect->jointree->quals;
1474  subselect->jointree->quals = NULL;
1475 
1476  /*
1477  * The rest of the sub-select must not refer to any Vars of the parent
1478  * query. (Vars of higher levels should be okay, though.)
1479  */
1480  if (contain_vars_of_level((Node *) subselect, 1))
1481  return NULL;
1482 
1483  /*
1484  * On the other hand, the WHERE clause must contain some Vars of the
1485  * parent query, else it's not gonna be a join.
1486  */
1487  if (!contain_vars_of_level(whereClause, 1))
1488  return NULL;
1489 
1490  /*
1491  * We don't risk optimizing if the WHERE clause is volatile, either.
1492  */
1493  if (contain_volatile_functions(whereClause))
1494  return NULL;
1495 
1496  /*
1497  * Prepare to pull up the sub-select into top range table.
1498  *
1499  * We rely here on the assumption that the outer query has no references
1500  * to the inner (necessarily true). Therefore this is a lot easier than
1501  * what pull_up_subqueries has to go through.
1502  *
1503  * In fact, it's even easier than what convert_ANY_sublink_to_join has to
1504  * do. The machinations of simplify_EXISTS_query ensured that there is
1505  * nothing interesting in the subquery except an rtable and jointree, and
1506  * even the jointree FromExpr no longer has quals. So we can just append
1507  * the rtable to our own and use the FromExpr in our jointree. But first,
1508  * adjust all level-zero varnos in the subquery to account for the rtable
1509  * merger.
1510  */
1511  rtoffset = list_length(parse->rtable);
1512  OffsetVarNodes((Node *) subselect, rtoffset, 0);
1513  OffsetVarNodes(whereClause, rtoffset, 0);
1514 
1515  /*
1516  * Upper-level vars in subquery will now be one level closer to their
1517  * parent than before; in particular, anything that had been level 1
1518  * becomes level zero.
1519  */
1520  IncrementVarSublevelsUp((Node *) subselect, -1, 1);
1521  IncrementVarSublevelsUp(whereClause, -1, 1);
1522 
1523  /*
1524  * Now that the WHERE clause is adjusted to match the parent query
1525  * environment, we can easily identify all the level-zero rels it uses.
1526  * The ones <= rtoffset belong to the upper query; the ones > rtoffset do
1527  * not.
1528  */
1529  clause_varnos = pull_varnos(whereClause);
1530  upper_varnos = NULL;
1531  while ((varno = bms_first_member(clause_varnos)) >= 0)
1532  {
1533  if (varno <= rtoffset)
1534  upper_varnos = bms_add_member(upper_varnos, varno);
1535  }
1536  bms_free(clause_varnos);
1537  Assert(!bms_is_empty(upper_varnos));
1538 
1539  /*
1540  * Now that we've got the set of upper-level varnos, we can make the last
1541  * check: only available_rels can be referenced.
1542  */
1543  if (!bms_is_subset(upper_varnos, available_rels))
1544  return NULL;
1545 
1546  /* Now we can attach the modified subquery rtable to the parent */
1547  parse->rtable = list_concat(parse->rtable, subselect->rtable);
1548 
1549  /*
1550  * And finally, build the JoinExpr node.
1551  */
1552  result = makeNode(JoinExpr);
1553  result->jointype = under_not ? JOIN_ANTI : JOIN_SEMI;
1554  result->isNatural = false;
1555  result->larg = NULL; /* caller must fill this in */
1556  /* flatten out the FromExpr node if it's useless */
1557  if (list_length(subselect->jointree->fromlist) == 1)
1558  result->rarg = (Node *) linitial(subselect->jointree->fromlist);
1559  else
1560  result->rarg = (Node *) subselect->jointree;
1561  result->usingClause = NIL;
1562  result->quals = whereClause;
1563  result->alias = NULL;
1564  result->rtindex = 0; /* we don't need an RTE for it */
1565 
1566  return result;
1567 }
1568 
1569 /*
1570  * simplify_EXISTS_query: remove any useless stuff in an EXISTS's subquery
1571  *
1572  * The only thing that matters about an EXISTS query is whether it returns
1573  * zero or more than zero rows. Therefore, we can remove certain SQL features
1574  * that won't affect that. The only part that is really likely to matter in
1575  * typical usage is simplifying the targetlist: it's a common habit to write
1576  * "SELECT * FROM" even though there is no need to evaluate any columns.
1577  *
1578  * Note: by suppressing the targetlist we could cause an observable behavioral
1579  * change, namely that any errors that might occur in evaluating the tlist
1580  * won't occur, nor will other side-effects of volatile functions. This seems
1581  * unlikely to bother anyone in practice.
1582  *
1583  * Returns true if was able to discard the targetlist, else false.
1584  */
1585 static bool
1587 {
1588  /*
1589  * We don't try to simplify at all if the query uses set operations,
1590  * aggregates, grouping sets, SRFs, modifying CTEs, HAVING, OFFSET, or FOR
1591  * UPDATE/SHARE; none of these seem likely in normal usage and their
1592  * possible effects are complex. (Note: we could ignore an "OFFSET 0"
1593  * clause, but that traditionally is used as an optimization fence, so we
1594  * don't.)
1595  */
1596  if (query->commandType != CMD_SELECT ||
1597  query->setOperations ||
1598  query->hasAggs ||
1599  query->groupingSets ||
1600  query->hasWindowFuncs ||
1601  query->hasTargetSRFs ||
1602  query->hasModifyingCTE ||
1603  query->havingQual ||
1604  query->limitOffset ||
1605  query->rowMarks)
1606  return false;
1607 
1608  /*
1609  * LIMIT with a constant positive (or NULL) value doesn't affect the
1610  * semantics of EXISTS, so let's ignore such clauses. This is worth doing
1611  * because people accustomed to certain other DBMSes may be in the habit
1612  * of writing EXISTS(SELECT ... LIMIT 1) as an optimization. If there's a
1613  * LIMIT with anything else as argument, though, we can't simplify.
1614  */
1615  if (query->limitCount)
1616  {
1617  /*
1618  * The LIMIT clause has not yet been through eval_const_expressions,
1619  * so we have to apply that here. It might seem like this is a waste
1620  * of cycles, since the only case plausibly worth worrying about is
1621  * "LIMIT 1" ... but what we'll actually see is "LIMIT int8(1::int4)",
1622  * so we have to fold constants or we're not going to recognize it.
1623  */
1624  Node *node = eval_const_expressions(root, query->limitCount);
1625  Const *limit;
1626 
1627  /* Might as well update the query if we simplified the clause. */
1628  query->limitCount = node;
1629 
1630  if (!IsA(node, Const))
1631  return false;
1632 
1633  limit = (Const *) node;
1634  Assert(limit->consttype == INT8OID);
1635  if (!limit->constisnull && DatumGetInt64(limit->constvalue) <= 0)
1636  return false;
1637 
1638  /* Whether or not the targetlist is safe, we can drop the LIMIT. */
1639  query->limitCount = NULL;
1640  }
1641 
1642  /*
1643  * Otherwise, we can throw away the targetlist, as well as any GROUP,
1644  * WINDOW, DISTINCT, and ORDER BY clauses; none of those clauses will
1645  * change a nonzero-rows result to zero rows or vice versa. (Furthermore,
1646  * since our parsetree representation of these clauses depends on the
1647  * targetlist, we'd better throw them away if we drop the targetlist.)
1648  */
1649  query->targetList = NIL;
1650  query->groupClause = NIL;
1651  query->windowClause = NIL;
1652  query->distinctClause = NIL;
1653  query->sortClause = NIL;
1654  query->hasDistinctOn = false;
1655 
1656  return true;
1657 }
1658 
1659 /*
1660  * convert_EXISTS_to_ANY: try to convert EXISTS to a hashable ANY sublink
1661  *
1662  * The subselect is expected to be a fresh copy that we can munge up,
1663  * and to have been successfully passed through simplify_EXISTS_query.
1664  *
1665  * On success, the modified subselect is returned, and we store a suitable
1666  * upper-level test expression at *testexpr, plus a list of the subselect's
1667  * output Params at *paramIds. (The test expression is already Param-ified
1668  * and hence need not go through convert_testexpr, which is why we have to
1669  * deal with the Param IDs specially.)
1670  *
1671  * On failure, returns NULL.
1672  */
1673 static Query *
1675  Node **testexpr, List **paramIds)
1676 {
1677  Node *whereClause;
1678  List *leftargs,
1679  *rightargs,
1680  *opids,
1681  *opcollations,
1682  *newWhere,
1683  *tlist,
1684  *testlist,
1685  *paramids;
1686  ListCell *lc,
1687  *rc,
1688  *oc,
1689  *cc;
1690  AttrNumber resno;
1691 
1692  /*
1693  * Query must not require a targetlist, since we have to insert a new one.
1694  * Caller should have dealt with the case already.
1695  */
1696  Assert(subselect->targetList == NIL);
1697 
1698  /*
1699  * Separate out the WHERE clause. (We could theoretically also remove
1700  * top-level plain JOIN/ON clauses, but it's probably not worth the
1701  * trouble.)
1702  */
1703  whereClause = subselect->jointree->quals;
1704  subselect->jointree->quals = NULL;
1705 
1706  /*
1707  * The rest of the sub-select must not refer to any Vars of the parent
1708  * query. (Vars of higher levels should be okay, though.)
1709  *
1710  * Note: we need not check for Aggrefs separately because we know the
1711  * sub-select is as yet unoptimized; any uplevel Aggref must therefore
1712  * contain an uplevel Var reference. This is not the case below ...
1713  */
1714  if (contain_vars_of_level((Node *) subselect, 1))
1715  return NULL;
1716 
1717  /*
1718  * We don't risk optimizing if the WHERE clause is volatile, either.
1719  */
1720  if (contain_volatile_functions(whereClause))
1721  return NULL;
1722 
1723  /*
1724  * Clean up the WHERE clause by doing const-simplification etc on it.
1725  * Aside from simplifying the processing we're about to do, this is
1726  * important for being able to pull chunks of the WHERE clause up into the
1727  * parent query. Since we are invoked partway through the parent's
1728  * preprocess_expression() work, earlier steps of preprocess_expression()
1729  * wouldn't get applied to the pulled-up stuff unless we do them here. For
1730  * the parts of the WHERE clause that get put back into the child query,
1731  * this work is partially duplicative, but it shouldn't hurt.
1732  *
1733  * Note: we do not run flatten_join_alias_vars. This is OK because any
1734  * parent aliases were flattened already, and we're not going to pull any
1735  * child Vars (of any description) into the parent.
1736  *
1737  * Note: passing the parent's root to eval_const_expressions is
1738  * technically wrong, but we can get away with it since only the
1739  * boundParams (if any) are used, and those would be the same in a
1740  * subroot.
1741  */
1742  whereClause = eval_const_expressions(root, whereClause);
1743  whereClause = (Node *) canonicalize_qual((Expr *) whereClause);
1744  whereClause = (Node *) make_ands_implicit((Expr *) whereClause);
1745 
1746  /*
1747  * We now have a flattened implicit-AND list of clauses, which we try to
1748  * break apart into "outervar = innervar" hash clauses. Anything that
1749  * can't be broken apart just goes back into the newWhere list. Note that
1750  * we aren't trying hard yet to ensure that we have only outer or only
1751  * inner on each side; we'll check that if we get to the end.
1752  */
1753  leftargs = rightargs = opids = opcollations = newWhere = NIL;
1754  foreach(lc, (List *) whereClause)
1755  {
1756  OpExpr *expr = (OpExpr *) lfirst(lc);
1757 
1758  if (IsA(expr, OpExpr) &&
1759  hash_ok_operator(expr))
1760  {
1761  Node *leftarg = (Node *) linitial(expr->args);
1762  Node *rightarg = (Node *) lsecond(expr->args);
1763 
1764  if (contain_vars_of_level(leftarg, 1))
1765  {
1766  leftargs = lappend(leftargs, leftarg);
1767  rightargs = lappend(rightargs, rightarg);
1768  opids = lappend_oid(opids, expr->opno);
1769  opcollations = lappend_oid(opcollations, expr->inputcollid);
1770  continue;
1771  }
1772  if (contain_vars_of_level(rightarg, 1))
1773  {
1774  /*
1775  * We must commute the clause to put the outer var on the
1776  * left, because the hashing code in nodeSubplan.c expects
1777  * that. This probably shouldn't ever fail, since hashable
1778  * operators ought to have commutators, but be paranoid.
1779  */
1780  expr->opno = get_commutator(expr->opno);
1781  if (OidIsValid(expr->opno) && hash_ok_operator(expr))
1782  {
1783  leftargs = lappend(leftargs, rightarg);
1784  rightargs = lappend(rightargs, leftarg);
1785  opids = lappend_oid(opids, expr->opno);
1786  opcollations = lappend_oid(opcollations, expr->inputcollid);
1787  continue;
1788  }
1789  /* If no commutator, no chance to optimize the WHERE clause */
1790  return NULL;
1791  }
1792  }
1793  /* Couldn't handle it as a hash clause */
1794  newWhere = lappend(newWhere, expr);
1795  }
1796 
1797  /*
1798  * If we didn't find anything we could convert, fail.
1799  */
1800  if (leftargs == NIL)
1801  return NULL;
1802 
1803  /*
1804  * There mustn't be any parent Vars or Aggs in the stuff that we intend to
1805  * put back into the child query. Note: you might think we don't need to
1806  * check for Aggs separately, because an uplevel Agg must contain an
1807  * uplevel Var in its argument. But it is possible that the uplevel Var
1808  * got optimized away by eval_const_expressions. Consider
1809  *
1810  * SUM(CASE WHEN false THEN uplevelvar ELSE 0 END)
1811  */
1812  if (contain_vars_of_level((Node *) newWhere, 1) ||
1813  contain_vars_of_level((Node *) rightargs, 1))
1814  return NULL;
1815  if (root->parse->hasAggs &&
1816  (contain_aggs_of_level((Node *) newWhere, 1) ||
1817  contain_aggs_of_level((Node *) rightargs, 1)))
1818  return NULL;
1819 
1820  /*
1821  * And there can't be any child Vars in the stuff we intend to pull up.
1822  * (Note: we'd need to check for child Aggs too, except we know the child
1823  * has no aggs at all because of simplify_EXISTS_query's check. The same
1824  * goes for window functions.)
1825  */
1826  if (contain_vars_of_level((Node *) leftargs, 0))
1827  return NULL;
1828 
1829  /*
1830  * Also reject sublinks in the stuff we intend to pull up. (It might be
1831  * possible to support this, but doesn't seem worth the complication.)
1832  */
1833  if (contain_subplans((Node *) leftargs))
1834  return NULL;
1835 
1836  /*
1837  * Okay, adjust the sublevelsup in the stuff we're pulling up.
1838  */
1839  IncrementVarSublevelsUp((Node *) leftargs, -1, 1);
1840 
1841  /*
1842  * Put back any child-level-only WHERE clauses.
1843  */
1844  if (newWhere)
1845  subselect->jointree->quals = (Node *) make_ands_explicit(newWhere);
1846 
1847  /*
1848  * Build a new targetlist for the child that emits the expressions we
1849  * need. Concurrently, build a testexpr for the parent using Params to
1850  * reference the child outputs. (Since we generate Params directly here,
1851  * there will be no need to convert the testexpr in build_subplan.)
1852  */
1853  tlist = testlist = paramids = NIL;
1854  resno = 1;
1855  /* there's no "forfour" so we have to chase one of the lists manually */
1856  cc = list_head(opcollations);
1857  forthree(lc, leftargs, rc, rightargs, oc, opids)
1858  {
1859  Node *leftarg = (Node *) lfirst(lc);
1860  Node *rightarg = (Node *) lfirst(rc);
1861  Oid opid = lfirst_oid(oc);
1862  Oid opcollation = lfirst_oid(cc);
1863  Param *param;
1864 
1865  cc = lnext(cc);
1866  param = generate_new_param(root,
1867  exprType(rightarg),
1868  exprTypmod(rightarg),
1869  exprCollation(rightarg));
1870  tlist = lappend(tlist,
1871  makeTargetEntry((Expr *) rightarg,
1872  resno++,
1873  NULL,
1874  false));
1875  testlist = lappend(testlist,
1876  make_opclause(opid, BOOLOID, false,
1877  (Expr *) leftarg, (Expr *) param,
1878  InvalidOid, opcollation));
1879  paramids = lappend_int(paramids, param->paramid);
1880  }
1881 
1882  /* Put everything where it should go, and we're done */
1883  subselect->targetList = tlist;
1884  *testexpr = (Node *) make_ands_explicit(testlist);
1885  *paramIds = paramids;
1886 
1887  return subselect;
1888 }
1889 
1890 
1891 /*
1892  * Replace correlation vars (uplevel vars) with Params.
1893  *
1894  * Uplevel PlaceHolderVars and aggregates are replaced, too.
1895  *
1896  * Note: it is critical that this runs immediately after SS_process_sublinks.
1897  * Since we do not recurse into the arguments of uplevel PHVs and aggregates,
1898  * they will get copied to the appropriate subplan args list in the parent
1899  * query with uplevel vars not replaced by Params, but only adjusted in level
1900  * (see replace_outer_placeholdervar and replace_outer_agg). That's exactly
1901  * what we want for the vars of the parent level --- but if a PHV's or
1902  * aggregate's argument contains any further-up variables, they have to be
1903  * replaced with Params in their turn. That will happen when the parent level
1904  * runs SS_replace_correlation_vars. Therefore it must do so after expanding
1905  * its sublinks to subplans. And we don't want any steps in between, else
1906  * those steps would never get applied to the argument expressions, either in
1907  * the parent or the child level.
1908  *
1909  * Another fairly tricky thing going on here is the handling of SubLinks in
1910  * the arguments of uplevel PHVs/aggregates. Those are not touched inside the
1911  * intermediate query level, either. Instead, SS_process_sublinks recurses on
1912  * them after copying the PHV or Aggref expression into the parent plan level
1913  * (this is actually taken care of in build_subplan).
1914  */
1915 Node *
1917 {
1918  /* No setup needed for tree walk, so away we go */
1919  return replace_correlation_vars_mutator(expr, root);
1920 }
1921 
1922 static Node *
1924 {
1925  if (node == NULL)
1926  return NULL;
1927  if (IsA(node, Var))
1928  {
1929  if (((Var *) node)->varlevelsup > 0)
1930  return (Node *) replace_outer_var(root, (Var *) node);
1931  }
1932  if (IsA(node, PlaceHolderVar))
1933  {
1934  if (((PlaceHolderVar *) node)->phlevelsup > 0)
1935  return (Node *) replace_outer_placeholdervar(root,
1936  (PlaceHolderVar *) node);
1937  }
1938  if (IsA(node, Aggref))
1939  {
1940  if (((Aggref *) node)->agglevelsup > 0)
1941  return (Node *) replace_outer_agg(root, (Aggref *) node);
1942  }
1943  if (IsA(node, GroupingFunc))
1944  {
1945  if (((GroupingFunc *) node)->agglevelsup > 0)
1946  return (Node *) replace_outer_grouping(root, (GroupingFunc *) node);
1947  }
1948  return expression_tree_mutator(node,
1950  (void *) root);
1951 }
1952 
1953 /*
1954  * Expand SubLinks to SubPlans in the given expression.
1955  *
1956  * The isQual argument tells whether or not this expression is a WHERE/HAVING
1957  * qualifier expression. If it is, any sublinks appearing at top level need
1958  * not distinguish FALSE from UNKNOWN return values.
1959  */
1960 Node *
1962 {
1963  process_sublinks_context context;
1964 
1965  context.root = root;
1966  context.isTopQual = isQual;
1967  return process_sublinks_mutator(expr, &context);
1968 }
1969 
1970 static Node *
1972 {
1973  process_sublinks_context locContext;
1974 
1975  locContext.root = context->root;
1976 
1977  if (node == NULL)
1978  return NULL;
1979  if (IsA(node, SubLink))
1980  {
1981  SubLink *sublink = (SubLink *) node;
1982  Node *testexpr;
1983 
1984  /*
1985  * First, recursively process the lefthand-side expressions, if any.
1986  * They're not top-level anymore.
1987  */
1988  locContext.isTopQual = false;
1989  testexpr = process_sublinks_mutator(sublink->testexpr, &locContext);
1990 
1991  /*
1992  * Now build the SubPlan node and make the expr to return.
1993  */
1994  return make_subplan(context->root,
1995  (Query *) sublink->subselect,
1996  sublink->subLinkType,
1997  sublink->subLinkId,
1998  testexpr,
1999  context->isTopQual);
2000  }
2001 
2002  /*
2003  * Don't recurse into the arguments of an outer PHV or aggregate here. Any
2004  * SubLinks in the arguments have to be dealt with at the outer query
2005  * level; they'll be handled when build_subplan collects the PHV or Aggref
2006  * into the arguments to be passed down to the current subplan.
2007  */
2008  if (IsA(node, PlaceHolderVar))
2009  {
2010  if (((PlaceHolderVar *) node)->phlevelsup > 0)
2011  return node;
2012  }
2013  else if (IsA(node, Aggref))
2014  {
2015  if (((Aggref *) node)->agglevelsup > 0)
2016  return node;
2017  }
2018 
2019  /*
2020  * We should never see a SubPlan expression in the input (since this is
2021  * the very routine that creates 'em to begin with). We shouldn't find
2022  * ourselves invoked directly on a Query, either.
2023  */
2024  Assert(!IsA(node, SubPlan));
2025  Assert(!IsA(node, AlternativeSubPlan));
2026  Assert(!IsA(node, Query));
2027 
2028  /*
2029  * Because make_subplan() could return an AND or OR clause, we have to
2030  * take steps to preserve AND/OR flatness of a qual. We assume the input
2031  * has been AND/OR flattened and so we need no recursion here.
2032  *
2033  * (Due to the coding here, we will not get called on the List subnodes of
2034  * an AND; and the input is *not* yet in implicit-AND format. So no check
2035  * is needed for a bare List.)
2036  *
2037  * Anywhere within the top-level AND/OR clause structure, we can tell
2038  * make_subplan() that NULL and FALSE are interchangeable. So isTopQual
2039  * propagates down in both cases. (Note that this is unlike the meaning
2040  * of "top level qual" used in most other places in Postgres.)
2041  */
2042  if (and_clause(node))
2043  {
2044  List *newargs = NIL;
2045  ListCell *l;
2046 
2047  /* Still at qual top-level */
2048  locContext.isTopQual = context->isTopQual;
2049 
2050  foreach(l, ((BoolExpr *) node)->args)
2051  {
2052  Node *newarg;
2053 
2054  newarg = process_sublinks_mutator(lfirst(l), &locContext);
2055  if (and_clause(newarg))
2056  newargs = list_concat(newargs, ((BoolExpr *) newarg)->args);
2057  else
2058  newargs = lappend(newargs, newarg);
2059  }
2060  return (Node *) make_andclause(newargs);
2061  }
2062 
2063  if (or_clause(node))
2064  {
2065  List *newargs = NIL;
2066  ListCell *l;
2067 
2068  /* Still at qual top-level */
2069  locContext.isTopQual = context->isTopQual;
2070 
2071  foreach(l, ((BoolExpr *) node)->args)
2072  {
2073  Node *newarg;
2074 
2075  newarg = process_sublinks_mutator(lfirst(l), &locContext);
2076  if (or_clause(newarg))
2077  newargs = list_concat(newargs, ((BoolExpr *) newarg)->args);
2078  else
2079  newargs = lappend(newargs, newarg);
2080  }
2081  return (Node *) make_orclause(newargs);
2082  }
2083 
2084  /*
2085  * If we recurse down through anything other than an AND or OR node, we
2086  * are definitely not at top qual level anymore.
2087  */
2088  locContext.isTopQual = false;
2089 
2090  return expression_tree_mutator(node,
2092  (void *) &locContext);
2093 }
2094 
2095 /*
2096  * SS_identify_outer_params - identify the Params available from outer levels
2097  *
2098  * This must be run after SS_replace_correlation_vars and SS_process_sublinks
2099  * processing is complete in a given query level as well as all of its
2100  * descendant levels (which means it's most practical to do it at the end of
2101  * processing the query level). We compute the set of paramIds that outer
2102  * levels will make available to this level+descendants, and record it in
2103  * root->outer_params for use while computing extParam/allParam sets in final
2104  * plan cleanup. (We can't just compute it then, because the upper levels'
2105  * plan_params lists are transient and will be gone by then.)
2106  */
2107 void
2109 {
2110  Bitmapset *outer_params;
2111  PlannerInfo *proot;
2112  ListCell *l;
2113 
2114  /*
2115  * If no parameters have been assigned anywhere in the tree, we certainly
2116  * don't need to do anything here.
2117  */
2118  if (root->glob->paramExecTypes == NIL)
2119  return;
2120 
2121  /*
2122  * Scan all query levels above this one to see which parameters are due to
2123  * be available from them, either because lower query levels have
2124  * requested them (via plan_params) or because they will be available from
2125  * initPlans of those levels.
2126  */
2127  outer_params = NULL;
2128  for (proot = root->parent_root; proot != NULL; proot = proot->parent_root)
2129  {
2130  /* Include ordinary Var/PHV/Aggref params */
2131  foreach(l, proot->plan_params)
2132  {
2133  PlannerParamItem *pitem = (PlannerParamItem *) lfirst(l);
2134 
2135  outer_params = bms_add_member(outer_params, pitem->paramId);
2136  }
2137  /* Include any outputs of outer-level initPlans */
2138  foreach(l, proot->init_plans)
2139  {
2140  SubPlan *initsubplan = (SubPlan *) lfirst(l);
2141  ListCell *l2;
2142 
2143  foreach(l2, initsubplan->setParam)
2144  {
2145  outer_params = bms_add_member(outer_params, lfirst_int(l2));
2146  }
2147  }
2148  /* Include worktable ID, if a recursive query is being planned */
2149  if (proot->wt_param_id >= 0)
2150  outer_params = bms_add_member(outer_params, proot->wt_param_id);
2151  }
2152  root->outer_params = outer_params;
2153 }
2154 
2155 /*
2156  * SS_charge_for_initplans - account for initplans in Path costs & parallelism
2157  *
2158  * If any initPlans have been created in the current query level, they will
2159  * get attached to the Plan tree created from whichever Path we select from
2160  * the given rel. Increment all that rel's Paths' costs to account for them,
2161  * and make sure the paths get marked as parallel-unsafe, since we can't
2162  * currently transmit initPlans to parallel workers.
2163  *
2164  * This is separate from SS_attach_initplans because we might conditionally
2165  * create more initPlans during create_plan(), depending on which Path we
2166  * select. However, Paths that would generate such initPlans are expected
2167  * to have included their cost already.
2168  */
2169 void
2171 {
2172  Cost initplan_cost;
2173  ListCell *lc;
2174 
2175  /* Nothing to do if no initPlans */
2176  if (root->init_plans == NIL)
2177  return;
2178 
2179  /*
2180  * Compute the cost increment just once, since it will be the same for all
2181  * Paths. We assume each initPlan gets run once during top plan startup.
2182  * This is a conservative overestimate, since in fact an initPlan might be
2183  * executed later than plan startup, or even not at all.
2184  */
2185  initplan_cost = 0;
2186  foreach(lc, root->init_plans)
2187  {
2188  SubPlan *initsubplan = (SubPlan *) lfirst(lc);
2189 
2190  initplan_cost += initsubplan->startup_cost + initsubplan->per_call_cost;
2191  }
2192 
2193  /*
2194  * Now adjust the costs and parallel_safe flags.
2195  */
2196  foreach(lc, final_rel->pathlist)
2197  {
2198  Path *path = (Path *) lfirst(lc);
2199 
2200  path->startup_cost += initplan_cost;
2201  path->total_cost += initplan_cost;
2202  path->parallel_safe = false;
2203  }
2204 
2205  /* We needn't do set_cheapest() here, caller will do it */
2206 }
2207 
2208 /*
2209  * SS_attach_initplans - attach initplans to topmost plan node
2210  *
2211  * Attach any initplans created in the current query level to the specified
2212  * plan node, which should normally be the topmost node for the query level.
2213  * (In principle the initPlans could go in any node at or above where they're
2214  * referenced; but there seems no reason to put them any lower than the
2215  * topmost node, so we don't bother to track exactly where they came from.)
2216  * We do not touch the plan node's cost; the initplans should have been
2217  * accounted for in path costing.
2218  */
2219 void
2221 {
2222  plan->initPlan = root->init_plans;
2223 }
2224 
2225 /*
2226  * SS_finalize_plan - do final parameter processing for a completed Plan.
2227  *
2228  * This recursively computes the extParam and allParam sets for every Plan
2229  * node in the given plan tree. (Oh, and RangeTblFunction.funcparams too.)
2230  *
2231  * We assume that SS_finalize_plan has already been run on any initplans or
2232  * subplans the plan tree could reference.
2233  */
2234 void
2236 {
2237  /* No setup needed, just recurse through plan tree. */
2238  (void) finalize_plan(root, plan, -1, root->outer_params, NULL);
2239 }
2240 
2241 /*
2242  * Recursive processing of all nodes in the plan tree
2243  *
2244  * gather_param is the rescan_param of an ancestral Gather/GatherMerge,
2245  * or -1 if there is none.
2246  *
2247  * valid_params is the set of param IDs supplied by outer plan levels
2248  * that are valid to reference in this plan node or its children.
2249  *
2250  * scan_params is a set of param IDs to force scan plan nodes to reference.
2251  * This is for EvalPlanQual support, and is always NULL at the top of the
2252  * recursion.
2253  *
2254  * The return value is the computed allParam set for the given Plan node.
2255  * This is just an internal notational convenience: we can add a child
2256  * plan's allParams to the set of param IDs of interest to this level
2257  * in the same statement that recurses to that child.
2258  *
2259  * Do not scribble on caller's values of valid_params or scan_params!
2260  *
2261  * Note: although we attempt to deal with initPlans anywhere in the tree, the
2262  * logic is not really right. The problem is that a plan node might return an
2263  * output Param of its initPlan as a targetlist item, in which case it's valid
2264  * for the parent plan level to reference that same Param; the parent's usage
2265  * will be converted into a Var referencing the child plan node by setrefs.c.
2266  * But this function would see the parent's reference as out of scope and
2267  * complain about it. For now, this does not matter because the planner only
2268  * attaches initPlans to the topmost plan node in a query level, so the case
2269  * doesn't arise. If we ever merge this processing into setrefs.c, maybe it
2270  * can be handled more cleanly.
2271  */
2272 static Bitmapset *
2274  int gather_param,
2275  Bitmapset *valid_params,
2276  Bitmapset *scan_params)
2277 {
2278  finalize_primnode_context context;
2279  int locally_added_param;
2280  Bitmapset *nestloop_params;
2281  Bitmapset *initExtParam;
2282  Bitmapset *initSetParam;
2283  Bitmapset *child_params;
2284  ListCell *l;
2285 
2286  if (plan == NULL)
2287  return NULL;
2288 
2289  context.root = root;
2290  context.paramids = NULL; /* initialize set to empty */
2291  locally_added_param = -1; /* there isn't one */
2292  nestloop_params = NULL; /* there aren't any */
2293 
2294  /*
2295  * Examine any initPlans to determine the set of external params they
2296  * reference and the set of output params they supply. (We assume
2297  * SS_finalize_plan was run on them already.)
2298  */
2299  initExtParam = initSetParam = NULL;
2300  foreach(l, plan->initPlan)
2301  {
2302  SubPlan *initsubplan = (SubPlan *) lfirst(l);
2303  Plan *initplan = planner_subplan_get_plan(root, initsubplan);
2304  ListCell *l2;
2305 
2306  initExtParam = bms_add_members(initExtParam, initplan->extParam);
2307  foreach(l2, initsubplan->setParam)
2308  {
2309  initSetParam = bms_add_member(initSetParam, lfirst_int(l2));
2310  }
2311  }
2312 
2313  /* Any setParams are validly referenceable in this node and children */
2314  if (initSetParam)
2315  valid_params = bms_union(valid_params, initSetParam);
2316 
2317  /*
2318  * When we call finalize_primnode, context.paramids sets are automatically
2319  * merged together. But when recursing to self, we have to do it the hard
2320  * way. We want the paramids set to include params in subplans as well as
2321  * at this level.
2322  */
2323 
2324  /* Find params in targetlist and qual */
2325  finalize_primnode((Node *) plan->targetlist, &context);
2326  finalize_primnode((Node *) plan->qual, &context);
2327 
2328  /*
2329  * If it's a parallel-aware scan node, mark it as dependent on the parent
2330  * Gather/GatherMerge's rescan Param.
2331  */
2332  if (plan->parallel_aware)
2333  {
2334  if (gather_param < 0)
2335  elog(ERROR, "parallel-aware plan node is not below a Gather");
2336  context.paramids =
2337  bms_add_member(context.paramids, gather_param);
2338  }
2339 
2340  /* Check additional node-type-specific fields */
2341  switch (nodeTag(plan))
2342  {
2343  case T_Result:
2344  finalize_primnode(((Result *) plan)->resconstantqual,
2345  &context);
2346  break;
2347 
2348  case T_SeqScan:
2349  context.paramids = bms_add_members(context.paramids, scan_params);
2350  break;
2351 
2352  case T_SampleScan:
2353  finalize_primnode((Node *) ((SampleScan *) plan)->tablesample,
2354  &context);
2355  context.paramids = bms_add_members(context.paramids, scan_params);
2356  break;
2357 
2358  case T_IndexScan:
2359  finalize_primnode((Node *) ((IndexScan *) plan)->indexqual,
2360  &context);
2361  finalize_primnode((Node *) ((IndexScan *) plan)->indexorderby,
2362  &context);
2363 
2364  /*
2365  * we need not look at indexqualorig, since it will have the same
2366  * param references as indexqual. Likewise, we can ignore
2367  * indexorderbyorig.
2368  */
2369  context.paramids = bms_add_members(context.paramids, scan_params);
2370  break;
2371 
2372  case T_IndexOnlyScan:
2373  finalize_primnode((Node *) ((IndexOnlyScan *) plan)->indexqual,
2374  &context);
2375  finalize_primnode((Node *) ((IndexOnlyScan *) plan)->indexorderby,
2376  &context);
2377 
2378  /*
2379  * we need not look at indextlist, since it cannot contain Params.
2380  */
2381  context.paramids = bms_add_members(context.paramids, scan_params);
2382  break;
2383 
2384  case T_BitmapIndexScan:
2385  finalize_primnode((Node *) ((BitmapIndexScan *) plan)->indexqual,
2386  &context);
2387 
2388  /*
2389  * we need not look at indexqualorig, since it will have the same
2390  * param references as indexqual.
2391  */
2392  break;
2393 
2394  case T_BitmapHeapScan:
2395  finalize_primnode((Node *) ((BitmapHeapScan *) plan)->bitmapqualorig,
2396  &context);
2397  context.paramids = bms_add_members(context.paramids, scan_params);
2398  break;
2399 
2400  case T_TidScan:
2401  finalize_primnode((Node *) ((TidScan *) plan)->tidquals,
2402  &context);
2403  context.paramids = bms_add_members(context.paramids, scan_params);
2404  break;
2405 
2406  case T_SubqueryScan:
2407  {
2408  SubqueryScan *sscan = (SubqueryScan *) plan;
2409  RelOptInfo *rel;
2410 
2411  /* We must run SS_finalize_plan on the subquery */
2412  rel = find_base_rel(root, sscan->scan.scanrelid);
2413  SS_finalize_plan(rel->subroot, sscan->subplan);
2414 
2415  /* Now we can add its extParams to the parent's params */
2416  context.paramids = bms_add_members(context.paramids,
2417  sscan->subplan->extParam);
2418  /* We need scan_params too, though */
2419  context.paramids = bms_add_members(context.paramids,
2420  scan_params);
2421  }
2422  break;
2423 
2424  case T_FunctionScan:
2425  {
2426  FunctionScan *fscan = (FunctionScan *) plan;
2427  ListCell *lc;
2428 
2429  /*
2430  * Call finalize_primnode independently on each function
2431  * expression, so that we can record which params are
2432  * referenced in each, in order to decide which need
2433  * re-evaluating during rescan.
2434  */
2435  foreach(lc, fscan->functions)
2436  {
2437  RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
2438  finalize_primnode_context funccontext;
2439 
2440  funccontext = context;
2441  funccontext.paramids = NULL;
2442 
2443  finalize_primnode(rtfunc->funcexpr, &funccontext);
2444 
2445  /* remember results for execution */
2446  rtfunc->funcparams = funccontext.paramids;
2447 
2448  /* add the function's params to the overall set */
2449  context.paramids = bms_add_members(context.paramids,
2450  funccontext.paramids);
2451  }
2452 
2453  context.paramids = bms_add_members(context.paramids,
2454  scan_params);
2455  }
2456  break;
2457 
2458  case T_TableFuncScan:
2459  finalize_primnode((Node *) ((TableFuncScan *) plan)->tablefunc,
2460  &context);
2461  context.paramids = bms_add_members(context.paramids, scan_params);
2462  break;
2463 
2464  case T_ValuesScan:
2465  finalize_primnode((Node *) ((ValuesScan *) plan)->values_lists,
2466  &context);
2467  context.paramids = bms_add_members(context.paramids, scan_params);
2468  break;
2469 
2470  case T_CteScan:
2471  {
2472  /*
2473  * You might think we should add the node's cteParam to
2474  * paramids, but we shouldn't because that param is just a
2475  * linkage mechanism for multiple CteScan nodes for the same
2476  * CTE; it is never used for changed-param signaling. What we
2477  * have to do instead is to find the referenced CTE plan and
2478  * incorporate its external paramids, so that the correct
2479  * things will happen if the CTE references outer-level
2480  * variables. See test cases for bug #4902. (We assume
2481  * SS_finalize_plan was run on the CTE plan already.)
2482  */
2483  int plan_id = ((CteScan *) plan)->ctePlanId;
2484  Plan *cteplan;
2485 
2486  /* so, do this ... */
2487  if (plan_id < 1 || plan_id > list_length(root->glob->subplans))
2488  elog(ERROR, "could not find plan for CteScan referencing plan ID %d",
2489  plan_id);
2490  cteplan = (Plan *) list_nth(root->glob->subplans, plan_id - 1);
2491  context.paramids =
2492  bms_add_members(context.paramids, cteplan->extParam);
2493 
2494 #ifdef NOT_USED
2495  /* ... but not this */
2496  context.paramids =
2497  bms_add_member(context.paramids,
2498  ((CteScan *) plan)->cteParam);
2499 #endif
2500 
2501  context.paramids = bms_add_members(context.paramids,
2502  scan_params);
2503  }
2504  break;
2505 
2506  case T_WorkTableScan:
2507  context.paramids =
2508  bms_add_member(context.paramids,
2509  ((WorkTableScan *) plan)->wtParam);
2510  context.paramids = bms_add_members(context.paramids, scan_params);
2511  break;
2512 
2513  case T_NamedTuplestoreScan:
2514  context.paramids = bms_add_members(context.paramids, scan_params);
2515  break;
2516 
2517  case T_ForeignScan:
2518  {
2519  ForeignScan *fscan = (ForeignScan *) plan;
2520 
2521  finalize_primnode((Node *) fscan->fdw_exprs,
2522  &context);
2524  &context);
2525 
2526  /* We assume fdw_scan_tlist cannot contain Params */
2527  context.paramids = bms_add_members(context.paramids,
2528  scan_params);
2529  }
2530  break;
2531 
2532  case T_CustomScan:
2533  {
2534  CustomScan *cscan = (CustomScan *) plan;
2535  ListCell *lc;
2536 
2537  finalize_primnode((Node *) cscan->custom_exprs,
2538  &context);
2539  /* We assume custom_scan_tlist cannot contain Params */
2540  context.paramids =
2541  bms_add_members(context.paramids, scan_params);
2542 
2543  /* child nodes if any */
2544  foreach(lc, cscan->custom_plans)
2545  {
2546  context.paramids =
2547  bms_add_members(context.paramids,
2548  finalize_plan(root,
2549  (Plan *) lfirst(lc),
2550  gather_param,
2551  valid_params,
2552  scan_params));
2553  }
2554  }
2555  break;
2556 
2557  case T_ModifyTable:
2558  {
2559  ModifyTable *mtplan = (ModifyTable *) plan;
2560  ListCell *l;
2561 
2562  /* Force descendant scan nodes to reference epqParam */
2563  locally_added_param = mtplan->epqParam;
2564  valid_params = bms_add_member(bms_copy(valid_params),
2565  locally_added_param);
2566  scan_params = bms_add_member(bms_copy(scan_params),
2567  locally_added_param);
2569  &context);
2570  finalize_primnode((Node *) mtplan->onConflictSet,
2571  &context);
2573  &context);
2574  /* exclRelTlist contains only Vars, doesn't need examination */
2575  foreach(l, mtplan->plans)
2576  {
2577  context.paramids =
2578  bms_add_members(context.paramids,
2579  finalize_plan(root,
2580  (Plan *) lfirst(l),
2581  gather_param,
2582  valid_params,
2583  scan_params));
2584  }
2585  }
2586  break;
2587 
2588  case T_Append:
2589  {
2590  ListCell *l;
2591 
2592  foreach(l, ((Append *) plan)->appendplans)
2593  {
2594  context.paramids =
2595  bms_add_members(context.paramids,
2596  finalize_plan(root,
2597  (Plan *) lfirst(l),
2598  gather_param,
2599  valid_params,
2600  scan_params));
2601  }
2602  }
2603  break;
2604 
2605  case T_MergeAppend:
2606  {
2607  ListCell *l;
2608 
2609  foreach(l, ((MergeAppend *) plan)->mergeplans)
2610  {
2611  context.paramids =
2612  bms_add_members(context.paramids,
2613  finalize_plan(root,
2614  (Plan *) lfirst(l),
2615  gather_param,
2616  valid_params,
2617  scan_params));
2618  }
2619  }
2620  break;
2621 
2622  case T_BitmapAnd:
2623  {
2624  ListCell *l;
2625 
2626  foreach(l, ((BitmapAnd *) plan)->bitmapplans)
2627  {
2628  context.paramids =
2629  bms_add_members(context.paramids,
2630  finalize_plan(root,
2631  (Plan *) lfirst(l),
2632  gather_param,
2633  valid_params,
2634  scan_params));
2635  }
2636  }
2637  break;
2638 
2639  case T_BitmapOr:
2640  {
2641  ListCell *l;
2642 
2643  foreach(l, ((BitmapOr *) plan)->bitmapplans)
2644  {
2645  context.paramids =
2646  bms_add_members(context.paramids,
2647  finalize_plan(root,
2648  (Plan *) lfirst(l),
2649  gather_param,
2650  valid_params,
2651  scan_params));
2652  }
2653  }
2654  break;
2655 
2656  case T_NestLoop:
2657  {
2658  ListCell *l;
2659 
2660  finalize_primnode((Node *) ((Join *) plan)->joinqual,
2661  &context);
2662  /* collect set of params that will be passed to right child */
2663  foreach(l, ((NestLoop *) plan)->nestParams)
2664  {
2665  NestLoopParam *nlp = (NestLoopParam *) lfirst(l);
2666 
2667  nestloop_params = bms_add_member(nestloop_params,
2668  nlp->paramno);
2669  }
2670  }
2671  break;
2672 
2673  case T_MergeJoin:
2674  finalize_primnode((Node *) ((Join *) plan)->joinqual,
2675  &context);
2676  finalize_primnode((Node *) ((MergeJoin *) plan)->mergeclauses,
2677  &context);
2678  break;
2679 
2680  case T_HashJoin:
2681  finalize_primnode((Node *) ((Join *) plan)->joinqual,
2682  &context);
2683  finalize_primnode((Node *) ((HashJoin *) plan)->hashclauses,
2684  &context);
2685  break;
2686 
2687  case T_Limit:
2688  finalize_primnode(((Limit *) plan)->limitOffset,
2689  &context);
2690  finalize_primnode(((Limit *) plan)->limitCount,
2691  &context);
2692  break;
2693 
2694  case T_RecursiveUnion:
2695  /* child nodes are allowed to reference wtParam */
2696  locally_added_param = ((RecursiveUnion *) plan)->wtParam;
2697  valid_params = bms_add_member(bms_copy(valid_params),
2698  locally_added_param);
2699  /* wtParam does *not* get added to scan_params */
2700  break;
2701 
2702  case T_LockRows:
2703  /* Force descendant scan nodes to reference epqParam */
2704  locally_added_param = ((LockRows *) plan)->epqParam;
2705  valid_params = bms_add_member(bms_copy(valid_params),
2706  locally_added_param);
2707  scan_params = bms_add_member(bms_copy(scan_params),
2708  locally_added_param);
2709  break;
2710 
2711  case T_Agg:
2712  {
2713  Agg *agg = (Agg *) plan;
2714 
2715  /*
2716  * AGG_HASHED plans need to know which Params are referenced
2717  * in aggregate calls. Do a separate scan to identify them.
2718  */
2719  if (agg->aggstrategy == AGG_HASHED)
2720  {
2721  finalize_primnode_context aggcontext;
2722 
2723  aggcontext.root = root;
2724  aggcontext.paramids = NULL;
2726  &aggcontext);
2728  &aggcontext);
2729  agg->aggParams = aggcontext.paramids;
2730  }
2731  }
2732  break;
2733 
2734  case T_WindowAgg:
2735  finalize_primnode(((WindowAgg *) plan)->startOffset,
2736  &context);
2737  finalize_primnode(((WindowAgg *) plan)->endOffset,
2738  &context);
2739  break;
2740 
2741  case T_Gather:
2742  /* child nodes are allowed to reference rescan_param, if any */
2743  locally_added_param = ((Gather *) plan)->rescan_param;
2744  if (locally_added_param >= 0)
2745  {
2746  valid_params = bms_add_member(bms_copy(valid_params),
2747  locally_added_param);
2748 
2749  /*
2750  * We currently don't support nested Gathers. The issue so
2751  * far as this function is concerned would be how to identify
2752  * which child nodes depend on which Gather.
2753  */
2754  Assert(gather_param < 0);
2755  /* Pass down rescan_param to child parallel-aware nodes */
2756  gather_param = locally_added_param;
2757  }
2758  /* rescan_param does *not* get added to scan_params */
2759  break;
2760 
2761  case T_GatherMerge:
2762  /* child nodes are allowed to reference rescan_param, if any */
2763  locally_added_param = ((GatherMerge *) plan)->rescan_param;
2764  if (locally_added_param >= 0)
2765  {
2766  valid_params = bms_add_member(bms_copy(valid_params),
2767  locally_added_param);
2768 
2769  /*
2770  * We currently don't support nested Gathers. The issue so
2771  * far as this function is concerned would be how to identify
2772  * which child nodes depend on which Gather.
2773  */
2774  Assert(gather_param < 0);
2775  /* Pass down rescan_param to child parallel-aware nodes */
2776  gather_param = locally_added_param;
2777  }
2778  /* rescan_param does *not* get added to scan_params */
2779  break;
2780 
2781  case T_ProjectSet:
2782  case T_Hash:
2783  case T_Material:
2784  case T_Sort:
2785  case T_Unique:
2786  case T_SetOp:
2787  case T_Group:
2788  /* no node-type-specific fields need fixing */
2789  break;
2790 
2791  default:
2792  elog(ERROR, "unrecognized node type: %d",
2793  (int) nodeTag(plan));
2794  }
2795 
2796  /* Process left and right child plans, if any */
2797  child_params = finalize_plan(root,
2798  plan->lefttree,
2799  gather_param,
2800  valid_params,
2801  scan_params);
2802  context.paramids = bms_add_members(context.paramids, child_params);
2803 
2804  if (nestloop_params)
2805  {
2806  /* right child can reference nestloop_params as well as valid_params */
2807  child_params = finalize_plan(root,
2808  plan->righttree,
2809  gather_param,
2810  bms_union(nestloop_params, valid_params),
2811  scan_params);
2812  /* ... and they don't count as parameters used at my level */
2813  child_params = bms_difference(child_params, nestloop_params);
2814  bms_free(nestloop_params);
2815  }
2816  else
2817  {
2818  /* easy case */
2819  child_params = finalize_plan(root,
2820  plan->righttree,
2821  gather_param,
2822  valid_params,
2823  scan_params);
2824  }
2825  context.paramids = bms_add_members(context.paramids, child_params);
2826 
2827  /*
2828  * Any locally generated parameter doesn't count towards its generating
2829  * plan node's external dependencies. (Note: if we changed valid_params
2830  * and/or scan_params, we leak those bitmapsets; not worth the notational
2831  * trouble to clean them up.)
2832  */
2833  if (locally_added_param >= 0)
2834  {
2835  context.paramids = bms_del_member(context.paramids,
2836  locally_added_param);
2837  }
2838 
2839  /* Now we have all the paramids referenced in this node and children */
2840 
2841  if (!bms_is_subset(context.paramids, valid_params))
2842  elog(ERROR, "plan should not reference subplan's variable");
2843 
2844  /*
2845  * The plan node's allParam and extParam fields should include all its
2846  * referenced paramids, plus contributions from any child initPlans.
2847  * However, any setParams of the initPlans should not be present in the
2848  * parent node's extParams, only in its allParams. (It's possible that
2849  * some initPlans have extParams that are setParams of other initPlans.)
2850  */
2851 
2852  /* allParam must include initplans' extParams and setParams */
2853  plan->allParam = bms_union(context.paramids, initExtParam);
2854  plan->allParam = bms_add_members(plan->allParam, initSetParam);
2855  /* extParam must include any initplan extParams */
2856  plan->extParam = bms_union(context.paramids, initExtParam);
2857  /* but not any initplan setParams */
2858  plan->extParam = bms_del_members(plan->extParam, initSetParam);
2859 
2860  /*
2861  * For speed at execution time, make sure extParam/allParam are actually
2862  * NULL if they are empty sets.
2863  */
2864  if (bms_is_empty(plan->extParam))
2865  plan->extParam = NULL;
2866  if (bms_is_empty(plan->allParam))
2867  plan->allParam = NULL;
2868 
2869  return plan->allParam;
2870 }
2871 
2872 /*
2873  * finalize_primnode: add IDs of all PARAM_EXEC params appearing in the given
2874  * expression tree to the result set.
2875  */
2876 static bool
2878 {
2879  if (node == NULL)
2880  return false;
2881  if (IsA(node, Param))
2882  {
2883  if (((Param *) node)->paramkind == PARAM_EXEC)
2884  {
2885  int paramid = ((Param *) node)->paramid;
2886 
2887  context->paramids = bms_add_member(context->paramids, paramid);
2888  }
2889  return false; /* no more to do here */
2890  }
2891  if (IsA(node, SubPlan))
2892  {
2893  SubPlan *subplan = (SubPlan *) node;
2894  Plan *plan = planner_subplan_get_plan(context->root, subplan);
2895  ListCell *lc;
2896  Bitmapset *subparamids;
2897 
2898  /* Recurse into the testexpr, but not into the Plan */
2899  finalize_primnode(subplan->testexpr, context);
2900 
2901  /*
2902  * Remove any param IDs of output parameters of the subplan that were
2903  * referenced in the testexpr. These are not interesting for
2904  * parameter change signaling since we always re-evaluate the subplan.
2905  * Note that this wouldn't work too well if there might be uses of the
2906  * same param IDs elsewhere in the plan, but that can't happen because
2907  * generate_new_param never tries to merge params.
2908  */
2909  foreach(lc, subplan->paramIds)
2910  {
2911  context->paramids = bms_del_member(context->paramids,
2912  lfirst_int(lc));
2913  }
2914 
2915  /* Also examine args list */
2916  finalize_primnode((Node *) subplan->args, context);
2917 
2918  /*
2919  * Add params needed by the subplan to paramids, but excluding those
2920  * we will pass down to it. (We assume SS_finalize_plan was run on
2921  * the subplan already.)
2922  */
2923  subparamids = bms_copy(plan->extParam);
2924  foreach(lc, subplan->parParam)
2925  {
2926  subparamids = bms_del_member(subparamids, lfirst_int(lc));
2927  }
2928  context->paramids = bms_join(context->paramids, subparamids);
2929 
2930  return false; /* no more to do here */
2931  }
2933  (void *) context);
2934 }
2935 
2936 /*
2937  * finalize_agg_primnode: find all Aggref nodes in the given expression tree,
2938  * and add IDs of all PARAM_EXEC params appearing within their aggregated
2939  * arguments to the result set.
2940  */
2941 static bool
2943 {
2944  if (node == NULL)
2945  return false;
2946  if (IsA(node, Aggref))
2947  {
2948  Aggref *agg = (Aggref *) node;
2949 
2950  /* we should not consider the direct arguments, if any */
2951  finalize_primnode((Node *) agg->args, context);
2952  finalize_primnode((Node *) agg->aggfilter, context);
2953  return false; /* there can't be any Aggrefs below here */
2954  }
2956  (void *) context);
2957 }
2958 
2959 /*
2960  * SS_make_initplan_output_param - make a Param for an initPlan's output
2961  *
2962  * The plan is expected to return a scalar value of the given type/collation.
2963  *
2964  * Note that in some cases the initplan may not ever appear in the finished
2965  * plan tree. If that happens, we'll have wasted a PARAM_EXEC slot, which
2966  * is no big deal.
2967  */
2968 Param *
2970  Oid resulttype, int32 resulttypmod,
2971  Oid resultcollation)
2972 {
2973  return generate_new_param(root, resulttype, resulttypmod, resultcollation);
2974 }
2975 
2976 /*
2977  * SS_make_initplan_from_plan - given a plan tree, make it an InitPlan
2978  *
2979  * We build an EXPR_SUBLINK SubPlan node and put it into the initplan
2980  * list for the outer query level. A Param that represents the initplan's
2981  * output has already been assigned using SS_make_initplan_output_param.
2982  */
2983 void
2985  PlannerInfo *subroot, Plan *plan,
2986  Param *prm)
2987 {
2988  SubPlan *node;
2989 
2990  /*
2991  * Add the subplan and its PlannerInfo to the global lists.
2992  */
2993  root->glob->subplans = lappend(root->glob->subplans, plan);
2994  root->glob->subroots = lappend(root->glob->subroots, subroot);
2995 
2996  /*
2997  * Create a SubPlan node and add it to the outer list of InitPlans. Note
2998  * it has to appear after any other InitPlans it might depend on (see
2999  * comments in ExecReScan).
3000  */
3001  node = makeNode(SubPlan);
3002  node->subLinkType = EXPR_SUBLINK;
3003  node->plan_id = list_length(root->glob->subplans);
3004  node->plan_name = psprintf("InitPlan %d (returns $%d)",
3005  node->plan_id, prm->paramid);
3006  get_first_col_type(plan, &node->firstColType, &node->firstColTypmod,
3007  &node->firstColCollation);
3008  node->setParam = list_make1_int(prm->paramid);
3009 
3010  root->init_plans = lappend(root->init_plans, node);
3011 
3012  /*
3013  * The node can't have any inputs (since it's an initplan), so the
3014  * parParam and args lists remain empty.
3015  */
3016 
3017  /* Set costs of SubPlan using info from the plan tree */
3018  cost_subplan(subroot, node, plan);
3019 }
Datum constvalue
Definition: primnodes.h:196
#define list_make2(x1, x2)
Definition: pg_list.h:140
static int assign_param_for_placeholdervar(PlannerInfo *root, PlaceHolderVar *phv)
Definition: subselect.c:205
Node * limitOffset
Definition: parsenodes.h:158
static Node * convert_testexpr(PlannerInfo *root, Node *testexpr, List *subst_nodes)
Definition: subselect.c:980
#define NIL
Definition: pg_list.h:69
static Node * make_subplan(PlannerInfo *root, Query *orig_subquery, SubLinkType subLinkType, int subLinkId, Node *testexpr, bool isTopQual)
Definition: subselect.c:492
Oid firstColType
Definition: primnodes.h:693
static Param * replace_outer_agg(PlannerInfo *root, Aggref *agg)
Definition: subselect.c:308
List * qual
Definition: plannodes.h:145
#define SizeofHeapTupleHeader
Definition: htup_details.h:175
double plan_rows
Definition: plannodes.h:131
Definition: nodes.h:77
int bms_first_member(Bitmapset *a)
Definition: bitmapset.c:957
#define IsA(nodeptr, _type_)
Definition: nodes.h:563
static Node * convert_testexpr_mutator(Node *node, convert_testexpr_context *context)
Definition: subselect.c:992
Query * parse
Definition: relation.h:155
void OffsetVarNodes(Node *node, int offset, int sublevels_up)
Definition: rewriteManip.c:424
PlannerInfo * root
Definition: subselect.c:52
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1313
Index varlevelsup
Definition: primnodes.h:173
Node * expression_tree_mutator(Node *node, Node *(*mutator)(), void *context)
Definition: nodeFuncs.c:2409
int plan_id
Definition: primnodes.h:689
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
Bitmapset * bms_copy(const Bitmapset *a)
Definition: bitmapset.c:111
List * plan_params
Definition: relation.h:169
List * sortClause
Definition: parsenodes.h:156
Definition: nodes.h:79
Index scanrelid
Definition: plannodes.h:330
void IncrementVarSublevelsUp(Node *node, int delta_sublevels_up, int min_sublevels_up)
Definition: rewriteManip.c:773
FromExpr * jointree
Definition: parsenodes.h:136
static Param * replace_outer_var(PlannerInfo *root, Var *var)
Definition: subselect.c:148
int SS_assign_special_param(PlannerInfo *root)
Definition: subselect.c:429
static void get_first_col_type(Plan *plan, Oid *coltype, int32 *coltypmod, Oid *colcollation)
Definition: subselect.c:448
#define castNode(_type_, nodeptr)
Definition: nodes.h:581
List * functions
Definition: plannodes.h:509
static bool subplan_is_hashable(Plan *plan)
Definition: subselect.c:1047
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:276
#define forthree(cell1, list1, cell2, list2, cell3, list3)
Definition: pg_list.h:203
static int assign_param_for_var(PlannerInfo *root, Var *var)
Definition: subselect.c:95
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
List * fdw_exprs
Definition: plannodes.h:601
bool hasAggs
Definition: parsenodes.h:123
Bitmapset * bms_difference(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:284
void SS_charge_for_initplans(PlannerInfo *root, RelOptInfo *final_rel)
Definition: subselect.c:2170
Var * makeVarFromTargetEntry(Index varno, TargetEntry *tle)
Definition: makefuncs.c:104
SubLinkType subLinkType
Definition: primnodes.h:684
List * groupingSets
Definition: parsenodes.h:148
ParamKind paramkind
Definition: primnodes.h:244
static List * generate_subquery_params(PlannerInfo *root, List *tlist, List **paramIds)
Definition: subselect.c:918
List * list_copy(const List *oldlist)
Definition: list.c:1160
Definition: nodes.h:512
List * custom_exprs
Definition: plannodes.h:630
Definition: nodes.h:48
List * args
Definition: primnodes.h:301
AttrNumber varattno
Definition: primnodes.h:168
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2459
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
List * list_concat(List *list1, List *list2)
Definition: list.c:321
List * paramIds
Definition: primnodes.h:687
Node * SS_process_sublinks(PlannerInfo *root, Node *expr, bool isQual)
Definition: subselect.c:1961
static Param * replace_outer_grouping(PlannerInfo *root, GroupingFunc *grp)
Definition: subselect.c:352
JoinExpr * convert_ANY_sublink_to_join(PlannerInfo *root, SubLink *sublink, Relids available_rels)
Definition: subselect.c:1317
Expr * make_opclause(Oid opno, Oid opresulttype, bool opretset, Expr *leftop, Expr *rightop, Oid opcollid, Oid inputcollid)
Definition: clauses.c:172
Definition: nodes.h:75
List * fromlist
Definition: primnodes.h:1478
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:957
static bool hash_ok_operator(OpExpr *expr)
Definition: subselect.c:1113
ListCell * list_nth_cell(const List *list, int n)
Definition: list.c:386
unsigned int Oid
Definition: postgres_ext.h:31
List * rowMarks
Definition: parsenodes.h:161
Definition: primnodes.h:163
#define linitial_node(type, l)
Definition: pg_list.h:114
static bool simplify_EXISTS_query(PlannerInfo *root, Query *query)
Definition: subselect.c:1586
List * custom_plans
Definition: plannodes.h:629
List * lappend_oid(List *list, Oid datum)
Definition: list.c:164
#define OidIsValid(objectId)
Definition: c.h:576
List * plans
Definition: plannodes.h:225
Node * quals
Definition: primnodes.h:1479
#define lsecond(l)
Definition: pg_list.h:116
bool hasDistinctOn
Definition: parsenodes.h:127
signed int int32
Definition: c.h:284
List * onConflictSet
Definition: plannodes.h:234
List * windowClause
Definition: parsenodes.h:152
static Node * process_sublinks_mutator(Node *node, process_sublinks_context *context)
Definition: subselect.c:1971
List * targetList
Definition: parsenodes.h:138
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:336
JoinExpr * convert_EXISTS_sublink_to_join(PlannerInfo *root, SubLink *sublink, bool under_not, Relids available_rels)
Definition: subselect.c:1422
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
List * multiexpr_params
Definition: relation.h:232
Node * larg
Definition: primnodes.h:1458
Expr * make_ands_explicit(List *andclauses)
Definition: clauses.c:367
Plan * create_plan(PlannerInfo *root, Path *best_path)
Definition: createplan.c:305
PlannerInfo * subroot
Definition: relation.h:627
bool contain_subplans(Node *clause)
Definition: clauses.c:843
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:386
Oid consttype
Definition: primnodes.h:192
Index varnoold
Definition: primnodes.h:176
int wt_param_id
Definition: relation.h:311
struct Plan * righttree
Definition: plannodes.h:147
static Node * build_subplan(PlannerInfo *root, Plan *plan, PlannerInfo *subroot, List *plan_params, SubLinkType subLinkType, int subLinkId, Node *testexpr, bool adjust_testexpr, bool unknownEqFalse)
Definition: subselect.c:650
AggStrategy aggstrategy
Definition: plannodes.h:784
bool op_hashjoinable(Oid opno, Oid inputtype)
Definition: lsyscache.c:1246
bool resjunk
Definition: primnodes.h:1382
#define linitial(l)
Definition: pg_list.h:111
#define VOIDOID
Definition: pg_type.h:690
Definition: nodes.h:45
List * rtable
Definition: parsenodes.h:135
List * make_ands_implicit(Expr *clause)
Definition: clauses.c:378
List * distinctClause
Definition: parsenodes.h:154
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
List * paramExecTypes
Definition: relation.h:117
Expr * phexpr
Definition: relation.h:1946
Oid paramcollid
Definition: primnodes.h:248
#define lfirst_int(lc)
Definition: pg_list.h:107
int location
Definition: primnodes.h:249
Oid vartype
Definition: primnodes.h:170
Cost startup_cost
Definition: relation.h:1053
Bitmapset * bms_join(Bitmapset *a, Bitmapset *b)
Definition: bitmapset.c:910
static bool finalize_primnode(Node *node, finalize_primnode_context *context)
Definition: subselect.c:2877
#define planner_subplan_get_plan(root, subplan)
Definition: relation.h:137
Bitmapset * rewindPlanIDs
Definition: relation.h:102
#define DatumGetInt64(X)
Definition: postgres.h:613
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:308
Definition: nodes.h:76
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1137
int location
Definition: primnodes.h:178
struct Path * cheapest_total_path
Definition: relation.h:603
bool and_clause(Node *clause)
Definition: clauses.c:314
static List * generate_subquery_vars(PlannerInfo *root, List *tlist, Index varno)
Definition: subselect.c:951
Node * limitCount
Definition: parsenodes.h:159
void * list_nth(const List *list, int n)
Definition: list.c:410
List * subplans
Definition: relation.h:98
PlannerInfo * root
Definition: subselect.c:40
Bitmapset * aggParams
Definition: plannodes.h:790
PlannerGlobal * glob
Definition: relation.h:157
Plan * materialize_finished_plan(Plan *subplan)
Definition: createplan.c:5997
Index agglevelsup
Definition: primnodes.h:309
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
bool parallel_aware
Definition: plannodes.h:137
Bitmapset * allParam
Definition: plannodes.h:163
#define RECORDOID
Definition: pg_type.h:680
List * fdw_recheck_quals
Definition: plannodes.h:604
static Bitmapset * finalize_plan(PlannerInfo *root, Plan *plan, int gather_param, Bitmapset *valid_params, Bitmapset *scan_params)
Definition: subselect.c:2273
void SS_process_ctes(PlannerInfo *root)
Definition: subselect.c:1158
static SPIPlanPtr splan
Definition: regress.c:449
#define list_make1_int(x1)
Definition: pg_list.h:145
#define lnext(lc)
Definition: pg_list.h:105
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:237
struct convert_testexpr_context convert_testexpr_context
Relids pull_varnos(Node *node)
Definition: var.c:95
List * lappend_int(List *list, int datum)
Definition: list.c:146
SubLinkType
Definition: primnodes.h:618
List * lappend(List *list, void *datum)
Definition: list.c:128
RangeTblEntry * addRangeTableEntryForSubquery(ParseState *pstate, Query *subquery, Alias *alias, bool lateral, bool inFromCl)
struct PlannerInfo * parent_root
Definition: relation.h:161
bool isNatural
Definition: primnodes.h:1457
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:663
List * usingClause
Definition: primnodes.h:1460
Index varno
Definition: primnodes.h:166
Plan plan
Definition: plannodes.h:783
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
static Query * convert_EXISTS_to_ANY(PlannerInfo *root, Query *subselect, Node **testexpr, List **paramIds)
Definition: subselect.c:1674
Oid get_promoted_array_type(Oid typid)
Definition: lsyscache.c:2569
static bool finalize_agg_primnode(Node *node, finalize_primnode_context *context)
Definition: subselect.c:2942
Node * quals
Definition: primnodes.h:1461
Index agglevelsup
Definition: primnodes.h:345
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
List * cte_plan_ids
Definition: relation.h:230
Expr * canonicalize_qual(Expr *qual)
Definition: prepqual.c:286
bool or_clause(Node *clause)
Definition: clauses.c:280
Node * testexpr
Definition: primnodes.h:686
int work_mem
Definition: globals.c:113
unsigned int Index
Definition: c.h:413
Param * assign_nestloop_param_var(PlannerInfo *root, Var *var)
Definition: subselect.c:177
List * init_plans
Definition: relation.h:228
static bool testexpr_is_hashable(Node *testexpr)
Definition: subselect.c:1069
Definition: nodes.h:82
Cost per_call_cost
Definition: primnodes.h:713
#define InvalidOid
Definition: postgres_ext.h:36
static Param * generate_new_param(PlannerInfo *root, Oid paramtype, int32 paramtypmod, Oid paramcollation)
Definition: subselect.c:402
int32 firstColTypmod
Definition: primnodes.h:694
Cost total_cost
Definition: relation.h:1054
#define INT8OID
Definition: pg_type.h:304
CmdType commandType
Definition: parsenodes.h:110
int32 paramtypmod
Definition: primnodes.h:247
bool hasTargetSRFs
Definition: parsenodes.h:125
void bms_free(Bitmapset *a)
Definition: bitmapset.c:201
struct process_sublinks_context process_sublinks_context
#define makeNode(_type_)
Definition: nodes.h:560
char * plan_name
Definition: primnodes.h:691
Node * rarg
Definition: primnodes.h:1459
int plan_width
Definition: plannodes.h:132
Alias * alias
Definition: primnodes.h:1462
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
JoinType jointype
Definition: primnodes.h:1456
#define Assert(condition)
Definition: c.h:670
#define lfirst(lc)
Definition: pg_list.h:106
bool hasWindowFuncs
Definition: parsenodes.h:124
void SS_identify_outer_params(PlannerInfo *root)
Definition: subselect.c:2108
List * setParam
Definition: primnodes.h:707
bool parallel_safe
Definition: relation.h:1048
bool contain_vars_of_level(Node *node, int levelsup)
Definition: var.c:369
Param * SS_make_initplan_output_param(PlannerInfo *root, Oid resulttype, int32 resulttypmod, Oid resultcollation)
Definition: subselect.c:2969
Expr * expr
Definition: primnodes.h:1375
int paramid
Definition: primnodes.h:245
void cost_subplan(PlannerInfo *root, SubPlan *subplan, Plan *plan)
Definition: costsize.c:3472
Bitmapset * outer_params
Definition: relation.h:170
bool unknownEqFalse
Definition: primnodes.h:700
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:218
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1834
static int list_length(const List *l)
Definition: pg_list.h:89
Node * SS_replace_correlation_vars(PlannerInfo *root, Node *expr)
Definition: subselect.c:1916
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:720
void SS_attach_initplans(PlannerInfo *root, Plan *plan)
Definition: subselect.c:2220
List * subroots
Definition: relation.h:100
Expr * aggfilter
Definition: primnodes.h:304
Bitmapset * extParam
Definition: plannodes.h:162
#define MAXALIGN(LEN)
Definition: c.h:623
Bitmapset * funcparams
Definition: parsenodes.h:1095
List * parParam
Definition: primnodes.h:709
Oid inputcollid
Definition: primnodes.h:501
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:698
#define BOOLOID
Definition: pg_type.h:288
void SS_make_initplan_from_plan(PlannerInfo *root, PlannerInfo *subroot, Plan *plan, Param *prm)
Definition: subselect.c:2984
struct Plan * lefttree
Definition: plannodes.h:146
#define ARRAY_EQ_OP
Definition: pg_operator.h:776
FormData_pg_operator * Form_pg_operator
Definition: pg_operator.h:57
bool func_strict(Oid funcid)
Definition: lsyscache.c:1565
bool parallel_safe
Definition: primnodes.h:703
Index query_level
Definition: relation.h:159
#define nodeTag(nodeptr)
Definition: nodes.h:517
List * targetlist
Definition: plannodes.h:144
bool contain_aggs_of_level(Node *node, int levelsup)
Definition: rewriteManip.c:67
AttrNumber varoattno
Definition: primnodes.h:177
Bitmapset * bms_del_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:889
Definition: nodes.h:83
static Param * replace_outer_placeholdervar(PlannerInfo *root, PlaceHolderVar *phv)
Definition: subselect.c:255
List * cteList
Definition: parsenodes.h:133
Node * setOperations
Definition: parsenodes.h:163
Index phlevelsup
Definition: relation.h:1949
List * groupClause
Definition: parsenodes.h:146
void * palloc(Size size)
Definition: mcxt.c:848
List * initPlan
Definition: plannodes.h:148
Definition: nodes.h:80
int i
Oid varcollid
Definition: primnodes.h:172
bool hasModifyingCTE
Definition: parsenodes.h:129
void * arg
bool ExecMaterializesOutput(NodeTag plantype)
Definition: execAmi.c:577
bool useHashTable
Definition: primnodes.h:698
List * returningLists
Definition: plannodes.h:227
bool parallel_safe
Definition: plannodes.h:138
Oid firstColCollation
Definition: primnodes.h:695
Cost startup_cost
Definition: primnodes.h:712
Expr * make_andclause(List *andclauses)
Definition: clauses.c:327
List * pathlist
Definition: relation.h:599
Oid opno
Definition: primnodes.h:496
Definition: plannodes.h:781
#define elog
Definition: elog.h:219
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:277
#define copyObject(obj)
Definition: nodes.h:625
List * args
Definition: primnodes.h:502
Node * havingQual
Definition: parsenodes.h:150
void SS_finalize_plan(PlannerInfo *root, Plan *plan)
Definition: subselect.c:2235
Bitmapset * bms_del_member(Bitmapset *a, int x)
Definition: bitmapset.c:735
struct finalize_primnode_context finalize_primnode_context
int rtindex
Definition: primnodes.h:1463
Definition: pg_list.h:45
int16 AttrNumber
Definition: attnum.h:21
PlannerInfo * subquery_planner(PlannerGlobal *glob, Query *parse, PlannerInfo *parent_root, bool hasRecursion, double tuple_fraction)
Definition: planner.c:517
Expr * make_orclause(List *orclauses)
Definition: clauses.c:293
Oid paramtype
Definition: primnodes.h:246
CmdType
Definition: nodes.h:652
static Node * replace_correlation_vars_mutator(Node *node, PlannerInfo *root)
Definition: subselect.c:1923
bool constisnull
Definition: primnodes.h:197
Param * assign_nestloop_param_placeholdervar(PlannerInfo *root, PlaceHolderVar *phv)
Definition: subselect.c:283
double Cost
Definition: nodes.h:643
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:755
Plan * subplan
Definition: plannodes.h:499
Path * get_cheapest_fractional_path(RelOptInfo *rel, double tuple_fraction)
Definition: planner.c:5873
#define lfirst_oid(lc)
Definition: pg_list.h:108
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649
int epqParam
Definition: plannodes.h:231
Node * onConflictWhere
Definition: plannodes.h:235
bool enable_material
Definition: costsize.c:126
Definition: nodes.h:85
int32 vartypmod
Definition: primnodes.h:171
List * args
Definition: primnodes.h:710