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