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