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