]> granicus.if.org Git - postgresql/blob - src/backend/optimizer/plan/subselect.c
Add a concept of "placeholder" variables to the planner. These are variables
[postgresql] / src / backend / optimizer / plan / subselect.c
1 /*-------------------------------------------------------------------------
2  *
3  * subselect.c
4  *        Planning routines for subselects and parameters.
5  *
6  * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  * IDENTIFICATION
10  *        $PostgreSQL: pgsql/src/backend/optimizer/plan/subselect.c,v 1.142 2008/10/21 20:42:53 tgl Exp $
11  *
12  *-------------------------------------------------------------------------
13  */
14 #include "postgres.h"
15
16 #include "catalog/pg_operator.h"
17 #include "catalog/pg_type.h"
18 #include "miscadmin.h"
19 #include "nodes/makefuncs.h"
20 #include "nodes/nodeFuncs.h"
21 #include "optimizer/clauses.h"
22 #include "optimizer/cost.h"
23 #include "optimizer/planmain.h"
24 #include "optimizer/planner.h"
25 #include "optimizer/prep.h"
26 #include "optimizer/subselect.h"
27 #include "optimizer/var.h"
28 #include "parser/parse_relation.h"
29 #include "parser/parsetree.h"
30 #include "rewrite/rewriteManip.h"
31 #include "utils/builtins.h"
32 #include "utils/lsyscache.h"
33 #include "utils/syscache.h"
34
35
36 typedef struct convert_testexpr_context
37 {
38         PlannerInfo *root;
39         List       *subst_nodes;        /* Nodes to substitute for Params */
40 } convert_testexpr_context;
41
42 typedef struct process_sublinks_context
43 {
44         PlannerInfo *root;
45         bool            isTopQual;
46 } process_sublinks_context;
47
48 typedef struct finalize_primnode_context
49 {
50         PlannerInfo *root;
51         Bitmapset  *paramids;           /* Non-local PARAM_EXEC paramids found */
52 } finalize_primnode_context;
53
54
55 static Node *build_subplan(PlannerInfo *root, Plan *plan, List *rtable,
56                           SubLinkType subLinkType, Node *testexpr,
57                           bool adjust_testexpr, bool unknownEqFalse);
58 static List *generate_subquery_params(PlannerInfo *root, List *tlist,
59                                                                           List **paramIds);
60 static List *generate_subquery_vars(PlannerInfo *root, List *tlist,
61                                                                         Index varno);
62 static Node *convert_testexpr(PlannerInfo *root,
63                                  Node *testexpr,
64                                  List *subst_nodes);
65 static Node *convert_testexpr_mutator(Node *node,
66                                                  convert_testexpr_context *context);
67 static bool subplan_is_hashable(Plan *plan);
68 static bool testexpr_is_hashable(Node *testexpr);
69 static bool hash_ok_operator(OpExpr *expr);
70 static bool simplify_EXISTS_query(Query *query);
71 static Query *convert_EXISTS_to_ANY(PlannerInfo *root, Query *subselect,
72                                           Node **testexpr, List **paramIds);
73 static Node *replace_correlation_vars_mutator(Node *node, PlannerInfo *root);
74 static Node *process_sublinks_mutator(Node *node,
75                                                  process_sublinks_context *context);
76 static Bitmapset *finalize_plan(PlannerInfo *root,
77                           Plan *plan,
78                           Bitmapset *valid_params);
79 static bool finalize_primnode(Node *node, finalize_primnode_context *context);
80
81
82 /*
83  * Generate a Param node to replace the given Var,
84  * which is expected to have varlevelsup > 0 (ie, it is not local).
85  */
86 static Param *
87 replace_outer_var(PlannerInfo *root, Var *var)
88 {
89         Param      *retval;
90         ListCell   *ppl;
91         PlannerParamItem *pitem;
92         Index           abslevel;
93         int                     i;
94
95         Assert(var->varlevelsup > 0 && var->varlevelsup < root->query_level);
96         abslevel = root->query_level - var->varlevelsup;
97
98         /*
99          * If there's already a paramlist entry for this same Var, just use it.
100          * NOTE: in sufficiently complex querytrees, it is possible for the same
101          * varno/abslevel to refer to different RTEs in different parts of the
102          * parsetree, so that different fields might end up sharing the same Param
103          * number.      As long as we check the vartype/typmod as well, I believe that
104          * this sort of aliasing will cause no trouble.  The correct field should
105          * get stored into the Param slot at execution in each part of the tree.
106          */
107         i = 0;
108         foreach(ppl, root->glob->paramlist)
109         {
110                 pitem = (PlannerParamItem *) lfirst(ppl);
111                 if (pitem->abslevel == abslevel && IsA(pitem->item, Var))
112                 {
113                         Var                *pvar = (Var *) pitem->item;
114
115                         if (pvar->varno == var->varno &&
116                                 pvar->varattno == var->varattno &&
117                                 pvar->vartype == var->vartype &&
118                                 pvar->vartypmod == var->vartypmod)
119                                 break;
120                 }
121                 i++;
122         }
123
124         if (!ppl)
125         {
126                 /* Nope, so make a new one */
127                 var = (Var *) copyObject(var);
128                 var->varlevelsup = 0;
129
130                 pitem = makeNode(PlannerParamItem);
131                 pitem->item = (Node *) var;
132                 pitem->abslevel = abslevel;
133
134                 root->glob->paramlist = lappend(root->glob->paramlist, pitem);
135                 /* i is already the correct index for the new item */
136         }
137
138         retval = makeNode(Param);
139         retval->paramkind = PARAM_EXEC;
140         retval->paramid = i;
141         retval->paramtype = var->vartype;
142         retval->paramtypmod = var->vartypmod;
143         retval->location = -1;
144
145         return retval;
146 }
147
148 /*
149  * Generate a Param node to replace the given Aggref
150  * which is expected to have agglevelsup > 0 (ie, it is not local).
151  */
152 static Param *
153 replace_outer_agg(PlannerInfo *root, Aggref *agg)
154 {
155         Param      *retval;
156         PlannerParamItem *pitem;
157         Index           abslevel;
158         int                     i;
159
160         Assert(agg->agglevelsup > 0 && agg->agglevelsup < root->query_level);
161         abslevel = root->query_level - agg->agglevelsup;
162
163         /*
164          * It does not seem worthwhile to try to match duplicate outer aggs. Just
165          * make a new slot every time.
166          */
167         agg = (Aggref *) copyObject(agg);
168         IncrementVarSublevelsUp((Node *) agg, -((int) agg->agglevelsup), 0);
169         Assert(agg->agglevelsup == 0);
170
171         pitem = makeNode(PlannerParamItem);
172         pitem->item = (Node *) agg;
173         pitem->abslevel = abslevel;
174
175         root->glob->paramlist = lappend(root->glob->paramlist, pitem);
176         i = list_length(root->glob->paramlist) - 1;
177
178         retval = makeNode(Param);
179         retval->paramkind = PARAM_EXEC;
180         retval->paramid = i;
181         retval->paramtype = agg->aggtype;
182         retval->paramtypmod = -1;
183         retval->location = -1;
184
185         return retval;
186 }
187
188 /*
189  * Generate a new Param node that will not conflict with any other.
190  *
191  * This is used to allocate PARAM_EXEC slots for subplan outputs.
192  */
193 static Param *
194 generate_new_param(PlannerInfo *root, Oid paramtype, int32 paramtypmod)
195 {
196         Param      *retval;
197         PlannerParamItem *pitem;
198
199         retval = makeNode(Param);
200         retval->paramkind = PARAM_EXEC;
201         retval->paramid = list_length(root->glob->paramlist);
202         retval->paramtype = paramtype;
203         retval->paramtypmod = paramtypmod;
204         retval->location = -1;
205
206         pitem = makeNode(PlannerParamItem);
207         pitem->item = (Node *) retval;
208         pitem->abslevel = root->query_level;
209
210         root->glob->paramlist = lappend(root->glob->paramlist, pitem);
211
212         return retval;
213 }
214
215 /*
216  * Assign a (nonnegative) PARAM_EXEC ID for a recursive query's worktable.
217  */
218 int
219 SS_assign_worktable_param(PlannerInfo *root)
220 {
221         Param      *param;
222
223         /* We generate a Param of datatype INTERNAL */
224         param = generate_new_param(root, INTERNALOID, -1);
225         /* ... but the caller only cares about its ID */
226         return param->paramid;
227 }
228
229 /*
230  * Get the datatype of the first column of the plan's output.
231  *
232  * This is stored for ARRAY_SUBLINK and for exprType(), which doesn't have any
233  * way to get at the plan associated with a SubPlan node.  We really only need
234  * the value for EXPR_SUBLINK and ARRAY_SUBLINK subplans, but for consistency
235  * we set it always.
236  */
237 static Oid
238 get_first_col_type(Plan *plan)
239 {
240         /* In cases such as EXISTS, tlist might be empty; arbitrarily use VOID */
241         if (plan->targetlist)
242         {
243                 TargetEntry *tent = (TargetEntry *) linitial(plan->targetlist);
244
245                 Assert(IsA(tent, TargetEntry));
246                 if (!tent->resjunk)
247                         return exprType((Node *) tent->expr);
248         }
249         return VOIDOID;
250 }
251
252 /*
253  * Convert a SubLink (as created by the parser) into a SubPlan.
254  *
255  * We are given the SubLink's contained query, type, and testexpr.  We are
256  * also told if this expression appears at top level of a WHERE/HAVING qual.
257  *
258  * Note: we assume that the testexpr has been AND/OR flattened (actually,
259  * it's been through eval_const_expressions), but not converted to
260  * implicit-AND form; and any SubLinks in it should already have been
261  * converted to SubPlans.  The subquery is as yet untouched, however.
262  *
263  * The result is whatever we need to substitute in place of the SubLink
264  * node in the executable expression.  This will be either the SubPlan
265  * node (if we have to do the subplan as a subplan), or a Param node
266  * representing the result of an InitPlan, or a row comparison expression
267  * tree containing InitPlan Param nodes.
268  */
269 static Node *
270 make_subplan(PlannerInfo *root, Query *orig_subquery, SubLinkType subLinkType,
271                          Node *testexpr, bool isTopQual)
272 {
273         Query      *subquery;
274         bool            simple_exists = false;
275         double          tuple_fraction;
276         Plan       *plan;
277         PlannerInfo *subroot;
278         Node       *result;
279
280         /*
281          * Copy the source Query node.  This is a quick and dirty kluge to resolve
282          * the fact that the parser can generate trees with multiple links to the
283          * same sub-Query node, but the planner wants to scribble on the Query.
284          * Try to clean this up when we do querytree redesign...
285          */
286         subquery = (Query *) copyObject(orig_subquery);
287
288         /*
289          * If it's an EXISTS subplan, we might be able to simplify it.
290          */
291         if (subLinkType == EXISTS_SUBLINK)
292                 simple_exists = simplify_EXISTS_query(subquery);
293
294         /*
295          * For an EXISTS subplan, tell lower-level planner to expect that only the
296          * first tuple will be retrieved.  For ALL and ANY subplans, we will be
297          * able to stop evaluating if the test condition fails or matches, so very
298          * often not all the tuples will be retrieved; for lack of a better idea,
299          * specify 50% retrieval.  For EXPR and ROWCOMPARE subplans, use default
300          * behavior (we're only expecting one row out, anyway).
301          *
302          * NOTE: if you change these numbers, also change cost_subplan() in
303          * path/costsize.c.
304          *
305          * XXX If an ANY subplan is uncorrelated, build_subplan may decide to hash
306          * its output.  In that case it would've been better to specify full
307          * retrieval.  At present, however, we can only check hashability after
308          * we've made the subplan :-(.  (Determining whether it'll fit in work_mem
309          * is the really hard part.)  Therefore, we don't want to be too
310          * optimistic about the percentage of tuples retrieved, for fear of
311          * selecting a plan that's bad for the materialization case.
312          */
313         if (subLinkType == EXISTS_SUBLINK)
314                 tuple_fraction = 1.0;   /* just like a LIMIT 1 */
315         else if (subLinkType == ALL_SUBLINK ||
316                          subLinkType == ANY_SUBLINK)
317                 tuple_fraction = 0.5;   /* 50% */
318         else
319                 tuple_fraction = 0.0;   /* default behavior */
320
321         /*
322          * Generate the plan for the subquery.
323          */
324         plan = subquery_planner(root->glob, subquery,
325                                                         root,
326                                                         false, tuple_fraction,
327                                                         &subroot);
328
329         /* And convert to SubPlan or InitPlan format. */
330         result = build_subplan(root, plan, subroot->parse->rtable,
331                                                    subLinkType, testexpr, true, isTopQual);
332
333         /*
334          * If it's a correlated EXISTS with an unimportant targetlist, we might be
335          * able to transform it to the equivalent of an IN and then implement it
336          * by hashing.  We don't have enough information yet to tell which way
337          * is likely to be better (it depends on the expected number of executions
338          * of the EXISTS qual, and we are much too early in planning the outer
339          * query to be able to guess that).  So we generate both plans, if
340          * possible, and leave it to the executor to decide which to use.
341          */
342         if (simple_exists && IsA(result, SubPlan))
343         {
344                 Node       *newtestexpr;
345                 List       *paramIds;
346
347                 /* Make a second copy of the original subquery */
348                 subquery = (Query *) copyObject(orig_subquery);
349                 /* and re-simplify */
350                 simple_exists = simplify_EXISTS_query(subquery);
351                 Assert(simple_exists);
352                 /* See if it can be converted to an ANY query */
353                 subquery = convert_EXISTS_to_ANY(root, subquery,
354                                                                                  &newtestexpr, &paramIds);
355                 if (subquery)
356                 {
357                         /* Generate the plan for the ANY subquery; we'll need all rows */
358                         plan = subquery_planner(root->glob, subquery,
359                                                                         root,
360                                                                         false, 0.0,
361                                                                         &subroot);
362
363                         /* Now we can check if it'll fit in work_mem */
364                         if (subplan_is_hashable(plan))
365                         {
366                                 SubPlan    *hashplan;
367                                 AlternativeSubPlan *asplan;
368
369                                 /* OK, convert to SubPlan format. */
370                                 hashplan = (SubPlan *) build_subplan(root, plan,
371                                                                                                          subroot->parse->rtable,
372                                                                                                          ANY_SUBLINK, newtestexpr,
373                                                                                                          false, true);
374                                 /* Check we got what we expected */
375                                 Assert(IsA(hashplan, SubPlan));
376                                 Assert(hashplan->parParam == NIL);
377                                 Assert(hashplan->useHashTable);
378                                 /* build_subplan won't have filled in paramIds */
379                                 hashplan->paramIds = paramIds;
380
381                                 /* Leave it to the executor to decide which plan to use */
382                                 asplan = makeNode(AlternativeSubPlan);
383                                 asplan->subplans = list_make2(result, hashplan);
384                                 result = (Node *) asplan;
385                         }
386                 }
387         }
388
389         return result;
390 }
391
392 /*
393  * Build a SubPlan node given the raw inputs --- subroutine for make_subplan
394  *
395  * Returns either the SubPlan, or an expression using initplan output Params,
396  * as explained in the comments for make_subplan.
397  */
398 static Node *
399 build_subplan(PlannerInfo *root, Plan *plan, List *rtable,
400                           SubLinkType subLinkType, Node *testexpr,
401                           bool adjust_testexpr, bool unknownEqFalse)
402 {
403         Node       *result;
404         SubPlan    *splan;
405         bool            isInitPlan;
406         Bitmapset  *tmpset;
407         int                     paramid;
408
409         /*
410          * Initialize the SubPlan node.  Note plan_id isn't set till further down,
411          * likewise the cost fields.
412          */
413         splan = makeNode(SubPlan);
414         splan->subLinkType = subLinkType;
415         splan->testexpr = NULL;
416         splan->paramIds = NIL;
417         splan->firstColType = get_first_col_type(plan);
418         splan->useHashTable = false;
419         splan->unknownEqFalse = unknownEqFalse;
420         splan->setParam = NIL;
421         splan->parParam = NIL;
422         splan->args = NIL;
423
424         /*
425          * Make parParam and args lists of param IDs and expressions that current
426          * query level will pass to this child plan.
427          */
428         tmpset = bms_copy(plan->extParam);
429         while ((paramid = bms_first_member(tmpset)) >= 0)
430         {
431                 PlannerParamItem *pitem = list_nth(root->glob->paramlist, paramid);
432
433                 if (pitem->abslevel == root->query_level)
434                 {
435                         splan->parParam = lappend_int(splan->parParam, paramid);
436                         /*
437                          * The Var or Aggref has already been adjusted to have the correct
438                          * varlevelsup or agglevelsup.  We probably don't even need to
439                          * copy it again, but be safe.
440                          */
441                         splan->args = lappend(splan->args, copyObject(pitem->item));
442                 }
443         }
444         bms_free(tmpset);
445
446         /*
447          * Un-correlated or undirect correlated plans of EXISTS, EXPR, ARRAY, or
448          * ROWCOMPARE types can be used as initPlans.  For EXISTS, EXPR, or ARRAY,
449          * we just produce a Param referring to the result of evaluating the
450          * initPlan.  For ROWCOMPARE, we must modify the testexpr tree to contain
451          * PARAM_EXEC Params instead of the PARAM_SUBLINK Params emitted by the
452          * parser.
453          */
454         if (splan->parParam == NIL && subLinkType == EXISTS_SUBLINK)
455         {
456                 Param      *prm;
457
458                 Assert(testexpr == NULL);
459                 prm = generate_new_param(root, BOOLOID, -1);
460                 splan->setParam = list_make1_int(prm->paramid);
461                 isInitPlan = true;
462                 result = (Node *) prm;
463         }
464         else if (splan->parParam == NIL && subLinkType == EXPR_SUBLINK)
465         {
466                 TargetEntry *te = linitial(plan->targetlist);
467                 Param      *prm;
468
469                 Assert(!te->resjunk);
470                 Assert(testexpr == NULL);
471                 prm = generate_new_param(root,
472                                                                  exprType((Node *) te->expr),
473                                                                  exprTypmod((Node *) te->expr));
474                 splan->setParam = list_make1_int(prm->paramid);
475                 isInitPlan = true;
476                 result = (Node *) prm;
477         }
478         else if (splan->parParam == NIL && subLinkType == ARRAY_SUBLINK)
479         {
480                 TargetEntry *te = linitial(plan->targetlist);
481                 Oid                     arraytype;
482                 Param      *prm;
483
484                 Assert(!te->resjunk);
485                 Assert(testexpr == NULL);
486                 arraytype = get_array_type(exprType((Node *) te->expr));
487                 if (!OidIsValid(arraytype))
488                         elog(ERROR, "could not find array type for datatype %s",
489                                  format_type_be(exprType((Node *) te->expr)));
490                 prm = generate_new_param(root,
491                                                                  arraytype,
492                                                                  exprTypmod((Node *) te->expr));
493                 splan->setParam = list_make1_int(prm->paramid);
494                 isInitPlan = true;
495                 result = (Node *) prm;
496         }
497         else if (splan->parParam == NIL && subLinkType == ROWCOMPARE_SUBLINK)
498         {
499                 /* Adjust the Params */
500                 List       *params;
501
502                 Assert(testexpr != NULL);
503                 params = generate_subquery_params(root,
504                                                                                   plan->targetlist,
505                                                                                   &splan->paramIds);
506                 result = convert_testexpr(root,
507                                                                   testexpr,
508                                                                   params);
509                 splan->setParam = list_copy(splan->paramIds);
510                 isInitPlan = true;
511
512                 /*
513                  * The executable expression is returned to become part of the outer
514                  * plan's expression tree; it is not kept in the initplan node.
515                  */
516         }
517         else
518         {
519                 /*
520                  * Adjust the Params in the testexpr, unless caller said it's not
521                  * needed.
522                  */
523                 if (testexpr && adjust_testexpr)
524                 {
525                         List       *params;
526
527                         params = generate_subquery_params(root,
528                                                                                           plan->targetlist,
529                                                                                           &splan->paramIds);
530                         splan->testexpr = convert_testexpr(root,
531                                                                                            testexpr,
532                                                                                            params);
533                 }
534                 else
535                         splan->testexpr = testexpr;
536
537                 /*
538                  * We can't convert subplans of ALL_SUBLINK or ANY_SUBLINK types to
539                  * initPlans, even when they are uncorrelated or undirect correlated,
540                  * because we need to scan the output of the subplan for each outer
541                  * tuple.  But if it's a not-direct-correlated IN (= ANY) test, we
542                  * might be able to use a hashtable to avoid comparing all the tuples.
543                  */
544                 if (subLinkType == ANY_SUBLINK &&
545                         splan->parParam == NIL &&
546                         subplan_is_hashable(plan) &&
547                         testexpr_is_hashable(splan->testexpr))
548                         splan->useHashTable = true;
549
550                 /*
551                  * Otherwise, we have the option to tack a MATERIAL node onto the top
552                  * of the subplan, to reduce the cost of reading it repeatedly.  This
553                  * is pointless for a direct-correlated subplan, since we'd have to
554                  * recompute its results each time anyway.      For uncorrelated/undirect
555                  * correlated subplans, we add MATERIAL unless the subplan's top plan
556                  * node would materialize its output anyway.
557                  */
558                 else if (splan->parParam == NIL)
559                 {
560                         bool            use_material;
561
562                         switch (nodeTag(plan))
563                         {
564                                 case T_Material:
565                                 case T_FunctionScan:
566                                 case T_CteScan:
567                                 case T_WorkTableScan:
568                                 case T_Sort:
569                                         use_material = false;
570                                         break;
571                                 default:
572                                         use_material = true;
573                                         break;
574                         }
575                         if (use_material)
576                                 plan = materialize_finished_plan(plan);
577                 }
578
579                 result = (Node *) splan;
580                 isInitPlan = false;
581         }
582
583         /*
584          * Add the subplan and its rtable to the global lists.
585          */
586         root->glob->subplans = lappend(root->glob->subplans, plan);
587         root->glob->subrtables = lappend(root->glob->subrtables, rtable);
588         splan->plan_id = list_length(root->glob->subplans);
589
590         if (isInitPlan)
591                 root->init_plans = lappend(root->init_plans, splan);
592
593         /*
594          * A parameterless subplan (not initplan) should be prepared to handle
595          * REWIND efficiently.  If it has direct parameters then there's no point
596          * since it'll be reset on each scan anyway; and if it's an initplan then
597          * there's no point since it won't get re-run without parameter changes
598          * anyway.      The input of a hashed subplan doesn't need REWIND either.
599          */
600         if (splan->parParam == NIL && !isInitPlan && !splan->useHashTable)
601                 root->glob->rewindPlanIDs = bms_add_member(root->glob->rewindPlanIDs,
602                                                                                                    splan->plan_id);
603
604         /* Lastly, fill in the cost estimates for use later */
605         cost_subplan(root, splan, plan);
606
607         return result;
608 }
609
610 /*
611  * generate_subquery_params: build a list of Params representing the output
612  * columns of a sublink's sub-select, given the sub-select's targetlist.
613  *
614  * We also return an integer list of the paramids of the Params.
615  */
616 static List *
617 generate_subquery_params(PlannerInfo *root, List *tlist, List **paramIds)
618 {
619         List       *result;
620         List       *ids;
621         ListCell   *lc;
622
623         result = ids = NIL;
624         foreach(lc, tlist)
625         {
626                 TargetEntry *tent = (TargetEntry *) lfirst(lc);
627                 Param      *param;
628
629                 if (tent->resjunk)
630                         continue;
631
632                 param = generate_new_param(root,
633                                                                    exprType((Node *) tent->expr),
634                                                                    exprTypmod((Node *) tent->expr));
635                 result = lappend(result, param);
636                 ids = lappend_int(ids, param->paramid);
637         }
638
639         *paramIds = ids;
640         return result;
641 }
642
643 /*
644  * generate_subquery_vars: build a list of Vars representing the output
645  * columns of a sublink's sub-select, given the sub-select's targetlist.
646  * The Vars have the specified varno (RTE index).
647  */
648 static List *
649 generate_subquery_vars(PlannerInfo *root, List *tlist, Index varno)
650 {
651         List       *result;
652         ListCell   *lc;
653
654         result = NIL;
655         foreach(lc, tlist)
656         {
657                 TargetEntry *tent = (TargetEntry *) lfirst(lc);
658                 Var                *var;
659
660                 if (tent->resjunk)
661                         continue;
662
663                 var = makeVar(varno,
664                                           tent->resno,
665                                           exprType((Node *) tent->expr),
666                                           exprTypmod((Node *) tent->expr),
667                                           0);
668                 result = lappend(result, var);
669         }
670
671         return result;
672 }
673
674 /*
675  * convert_testexpr: convert the testexpr given by the parser into
676  * actually executable form.  This entails replacing PARAM_SUBLINK Params
677  * with Params or Vars representing the results of the sub-select.  The
678  * nodes to be substituted are passed in as the List result from
679  * generate_subquery_params or generate_subquery_vars.
680  *
681  * The given testexpr has already been recursively processed by
682  * process_sublinks_mutator.  Hence it can no longer contain any
683  * PARAM_SUBLINK Params for lower SubLink nodes; we can safely assume that
684  * any we find are for our own level of SubLink.
685  */
686 static Node *
687 convert_testexpr(PlannerInfo *root,
688                                  Node *testexpr,
689                                  List *subst_nodes)
690 {
691         convert_testexpr_context context;
692
693         context.root = root;
694         context.subst_nodes = subst_nodes;
695         return convert_testexpr_mutator(testexpr, &context);
696 }
697
698 static Node *
699 convert_testexpr_mutator(Node *node,
700                                                  convert_testexpr_context *context)
701 {
702         if (node == NULL)
703                 return NULL;
704         if (IsA(node, Param))
705         {
706                 Param      *param = (Param *) node;
707
708                 if (param->paramkind == PARAM_SUBLINK)
709                 {
710                         if (param->paramid <= 0 ||
711                                 param->paramid > list_length(context->subst_nodes))
712                                 elog(ERROR, "unexpected PARAM_SUBLINK ID: %d", param->paramid);
713
714                         /*
715                          * We copy the list item to avoid having doubly-linked
716                          * substructure in the modified parse tree.  This is probably
717                          * unnecessary when it's a Param, but be safe.
718                          */
719                         return (Node *) copyObject(list_nth(context->subst_nodes,
720                                                                                                 param->paramid - 1));
721                 }
722         }
723         return expression_tree_mutator(node,
724                                                                    convert_testexpr_mutator,
725                                                                    (void *) context);
726 }
727
728 /*
729  * subplan_is_hashable: can we implement an ANY subplan by hashing?
730  */
731 static bool
732 subplan_is_hashable(Plan *plan)
733 {
734         double          subquery_size;
735
736         /*
737          * The estimated size of the subquery result must fit in work_mem. (Note:
738          * we use sizeof(HeapTupleHeaderData) here even though the tuples will
739          * actually be stored as MinimalTuples; this provides some fudge factor
740          * for hashtable overhead.)
741          */
742         subquery_size = plan->plan_rows *
743                 (MAXALIGN(plan->plan_width) + MAXALIGN(sizeof(HeapTupleHeaderData)));
744         if (subquery_size > work_mem * 1024L)
745                 return false;
746
747         return true;
748 }
749
750 /*
751  * testexpr_is_hashable: is an ANY SubLink's test expression hashable?
752  */
753 static bool
754 testexpr_is_hashable(Node *testexpr)
755 {
756         /*
757          * The testexpr must be a single OpExpr, or an AND-clause containing
758          * only OpExprs.
759          *
760          * The combining operators must be hashable and strict. The need for
761          * hashability is obvious, since we want to use hashing. Without
762          * strictness, behavior in the presence of nulls is too unpredictable.  We
763          * actually must assume even more than plain strictness: they can't yield
764          * NULL for non-null inputs, either (see nodeSubplan.c).  However, hash
765          * indexes and hash joins assume that too.
766          */
767         if (testexpr && IsA(testexpr, OpExpr))
768         {
769                 if (hash_ok_operator((OpExpr *) testexpr))
770                         return true;
771         }
772         else if (and_clause(testexpr))
773         {
774                 ListCell   *l;
775
776                 foreach(l, ((BoolExpr *) testexpr)->args)
777                 {
778                         Node       *andarg = (Node *) lfirst(l);
779
780                         if (!IsA(andarg, OpExpr))
781                                 return false;
782                         if (!hash_ok_operator((OpExpr *) andarg))
783                                 return false;
784                 }
785                 return true;
786         }
787
788         return false;
789 }
790
791 static bool
792 hash_ok_operator(OpExpr *expr)
793 {
794         Oid                     opid = expr->opno;
795         HeapTuple       tup;
796         Form_pg_operator optup;
797
798         /* quick out if not a binary operator */
799         if (list_length(expr->args) != 2)
800                 return false;
801         /* else must look up the operator properties */
802         tup = SearchSysCache(OPEROID,
803                                                  ObjectIdGetDatum(opid),
804                                                  0, 0, 0);
805         if (!HeapTupleIsValid(tup))
806                 elog(ERROR, "cache lookup failed for operator %u", opid);
807         optup = (Form_pg_operator) GETSTRUCT(tup);
808         if (!optup->oprcanhash || !func_strict(optup->oprcode))
809         {
810                 ReleaseSysCache(tup);
811                 return false;
812         }
813         ReleaseSysCache(tup);
814         return true;
815 }
816
817
818 /*
819  * SS_process_ctes: process a query's WITH list
820  *
821  * We plan each interesting WITH item and convert it to an initplan.
822  * A side effect is to fill in root->cte_plan_ids with a list that
823  * parallels root->parse->cteList and provides the subplan ID for
824  * each CTE's initplan.
825  */
826 void
827 SS_process_ctes(PlannerInfo *root)
828 {
829         ListCell   *lc;
830
831         Assert(root->cte_plan_ids == NIL);
832
833         foreach(lc, root->parse->cteList)
834         {
835                 CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
836                 Query      *subquery;
837                 Plan       *plan;
838                 PlannerInfo *subroot;
839                 SubPlan    *splan;
840                 Bitmapset  *tmpset;
841                 int                     paramid;
842                 Param      *prm;
843
844                 /*
845                  * Ignore CTEs that are not actually referenced anywhere.
846                  */
847                 if (cte->cterefcount == 0)
848                 {
849                         /* Make a dummy entry in cte_plan_ids */
850                         root->cte_plan_ids = lappend_int(root->cte_plan_ids, -1);
851                         continue;
852                 }
853
854                 /*
855                  * Copy the source Query node.  Probably not necessary, but let's
856                  * keep this similar to make_subplan.
857                  */
858                 subquery = (Query *) copyObject(cte->ctequery);
859
860                 /*
861                  * Generate the plan for the CTE query.  Always plan for full
862                  * retrieval --- we don't have enough info to predict otherwise.
863                  */
864                 plan = subquery_planner(root->glob, subquery,
865                                                                 root,
866                                                                 cte->cterecursive, 0.0,
867                                                                 &subroot);
868
869                 /*
870                  * Make a SubPlan node for it.  This is just enough unlike
871                  * build_subplan that we can't share code.
872                  *
873                  * Note plan_id isn't set till further down, likewise the cost fields.
874                  */
875                 splan = makeNode(SubPlan);
876                 splan->subLinkType = CTE_SUBLINK;
877                 splan->testexpr = NULL;
878                 splan->paramIds = NIL;
879                 splan->firstColType = get_first_col_type(plan);
880                 splan->useHashTable = false;
881                 splan->unknownEqFalse = false;
882                 splan->setParam = NIL;
883                 splan->parParam = NIL;
884                 splan->args = NIL;
885
886                 /*
887                  * Make parParam and args lists of param IDs and expressions that
888                  * current query level will pass to this child plan.  Even though
889                  * this is an initplan, there could be side-references to earlier
890                  * initplan's outputs, specifically their CTE output parameters.
891                  */
892                 tmpset = bms_copy(plan->extParam);
893                 while ((paramid = bms_first_member(tmpset)) >= 0)
894                 {
895                         PlannerParamItem *pitem = list_nth(root->glob->paramlist, paramid);
896
897                         if (pitem->abslevel == root->query_level)
898                         {
899                                 prm = (Param *) pitem->item;
900                                 if (!IsA(prm, Param) ||
901                                         prm->paramtype != INTERNALOID)
902                                         elog(ERROR, "bogus local parameter passed to WITH query");
903
904                                 splan->parParam = lappend_int(splan->parParam, paramid);
905                                 splan->args = lappend(splan->args, copyObject(prm));
906                         }
907                 }
908                 bms_free(tmpset);
909
910                 /*
911                  * Assign a param to represent the query output.  We only really
912                  * care about reserving a parameter ID number.
913                  */
914                 prm = generate_new_param(root, INTERNALOID, -1);
915                 splan->setParam = list_make1_int(prm->paramid);
916
917                 /*
918                  * Add the subplan and its rtable to the global lists.
919                  */
920                 root->glob->subplans = lappend(root->glob->subplans, plan);
921                 root->glob->subrtables = lappend(root->glob->subrtables,
922                                                                                  subroot->parse->rtable);
923                 splan->plan_id = list_length(root->glob->subplans);
924
925                 root->init_plans = lappend(root->init_plans, splan);
926
927                 root->cte_plan_ids = lappend_int(root->cte_plan_ids, splan->plan_id);
928
929                 /* Lastly, fill in the cost estimates for use later */
930                 cost_subplan(root, splan, plan);
931         }
932 }
933
934 /*
935  * convert_ANY_sublink_to_join: can we convert an ANY SubLink to a join?
936  *
937  * The caller has found an ANY SubLink at the top level of one of the query's
938  * qual clauses, but has not checked the properties of the SubLink further.
939  * Decide whether it is appropriate to process this SubLink in join style.
940  * Return TRUE if so, FALSE if the SubLink cannot be converted.
941  *
942  * The only non-obvious input parameter is available_rels: this is the set
943  * of query rels that can safely be referenced in the sublink expression.
944  * (We must restrict this to avoid changing the semantics when a sublink
945  * is present in an outer join's ON qual.)  The conversion must fail if
946  * the converted qual would reference any but these parent-query relids.
947  *
948  * On success, two output parameters are returned:
949  *      *new_qual is set to the qual tree that should replace the SubLink in
950  *              the parent query's qual tree.  The qual clauses are wrapped in a
951  *              FlattenedSubLink node to help later processing place them properly.
952  *      *fromlist is set to a list of pulled-up jointree item(s) that must be
953  *              added at the proper spot in the parent query's jointree.
954  *
955  * Side effects of a successful conversion include adding the SubLink's
956  * subselect to the query's rangetable.
957  */
958 bool
959 convert_ANY_sublink_to_join(PlannerInfo *root, SubLink *sublink,
960                                                         Relids available_rels,
961                                                         Node **new_qual, List **fromlist)
962 {
963         Query      *parse = root->parse;
964         Query      *subselect = (Query *) sublink->subselect;
965         Relids          left_varnos;
966         int                     rtindex;
967         RangeTblEntry *rte;
968         RangeTblRef *rtr;
969         List       *subquery_vars;
970         Expr       *quals;
971         FlattenedSubLink *fslink;
972
973         Assert(sublink->subLinkType == ANY_SUBLINK);
974
975         /*
976          * The sub-select must not refer to any Vars of the parent query. (Vars of
977          * higher levels should be okay, though.)
978          */
979         if (contain_vars_of_level((Node *) subselect, 1))
980                 return false;
981
982         /*
983          * The test expression must contain some Vars of the current query,
984          * else it's not gonna be a join.  (Note that it won't have Vars
985          * referring to the subquery, rather Params.)
986          */
987         left_varnos = pull_varnos(sublink->testexpr);
988         if (bms_is_empty(left_varnos))
989                 return false;
990
991         /*
992          * However, it can't refer to anything outside available_rels.
993          */
994         if (!bms_is_subset(left_varnos, available_rels))
995                 return false;
996
997         /*
998          * The combining operators and left-hand expressions mustn't be volatile.
999          */
1000         if (contain_volatile_functions(sublink->testexpr))
1001                 return false;
1002
1003         /*
1004          * Okay, pull up the sub-select into upper range table.
1005          *
1006          * We rely here on the assumption that the outer query has no references
1007          * to the inner (necessarily true, other than the Vars that we build
1008          * below). Therefore this is a lot easier than what pull_up_subqueries has
1009          * to go through.
1010          */
1011         rte = addRangeTableEntryForSubquery(NULL,
1012                                                                                 subselect,
1013                                                                                 makeAlias("ANY_subquery", NIL),
1014                                                                                 false);
1015         parse->rtable = lappend(parse->rtable, rte);
1016         rtindex = list_length(parse->rtable);
1017
1018         /*
1019          * Form a RangeTblRef for the pulled-up sub-select.  This must be added
1020          * to the upper jointree, but it is caller's responsibility to figure
1021          * out where.
1022          */
1023         rtr = makeNode(RangeTblRef);
1024         rtr->rtindex = rtindex;
1025         *fromlist = list_make1(rtr);
1026
1027         /*
1028          * Build a list of Vars representing the subselect outputs.
1029          */
1030         subquery_vars = generate_subquery_vars(root,
1031                                                                                    subselect->targetList,
1032                                                                                    rtindex);
1033
1034         /*
1035          * Build the replacement qual expression, replacing Params with these Vars.
1036          */
1037         quals = (Expr *) convert_testexpr(root,
1038                                                                           sublink->testexpr,
1039                                                                           subquery_vars);
1040
1041         /*
1042          * And finally, build the FlattenedSubLink node.
1043          *
1044          * Note: at this point left_varnos may well contain join relids, since
1045          * the testexpr hasn't been run through flatten_join_alias_vars.  This
1046          * will get fixed when flatten_join_alias_vars is run.
1047          */
1048         fslink = makeNode(FlattenedSubLink);
1049         fslink->jointype = JOIN_SEMI;
1050         fslink->lefthand = left_varnos;
1051         fslink->righthand = bms_make_singleton(rtindex);
1052         fslink->quals = quals;
1053
1054         *new_qual = (Node *) fslink;
1055
1056         return true;
1057 }
1058
1059 /*
1060  * convert_EXISTS_sublink_to_join: can we convert an EXISTS SubLink to a join?
1061  *
1062  * The API of this function is identical to convert_ANY_sublink_to_join's,
1063  * except that we also support the case where the caller has found NOT EXISTS,
1064  * so we need an additional input parameter "under_not".
1065  */
1066 bool
1067 convert_EXISTS_sublink_to_join(PlannerInfo *root, SubLink *sublink,
1068                                                            bool under_not,
1069                                                            Relids available_rels,
1070                                                            Node **new_qual, List **fromlist)
1071 {
1072         Query      *parse = root->parse;
1073         Query      *subselect = (Query *) sublink->subselect;
1074         Node       *whereClause;
1075         int                     rtoffset;
1076         int                     varno;
1077         Relids          clause_varnos;
1078         Relids          left_varnos;
1079         Relids          right_varnos;
1080         Relids          subselect_varnos;
1081         FlattenedSubLink *fslink;
1082
1083         Assert(sublink->subLinkType == EXISTS_SUBLINK);
1084
1085         /*
1086          * Copy the subquery so we can modify it safely (see comments in
1087          * make_subplan).
1088          */
1089         subselect = (Query *) copyObject(subselect);
1090
1091         /*
1092          * See if the subquery can be simplified based on the knowledge that
1093          * it's being used in EXISTS().  If we aren't able to get rid of its
1094          * targetlist, we have to fail, because the pullup operation leaves
1095          * us with noplace to evaluate the targetlist.
1096          */
1097         if (!simplify_EXISTS_query(subselect))
1098                 return false;
1099
1100         /*
1101          * Separate out the WHERE clause.  (We could theoretically also remove
1102          * top-level plain JOIN/ON clauses, but it's probably not worth the
1103          * trouble.)
1104          */
1105         whereClause = subselect->jointree->quals;
1106         subselect->jointree->quals = NULL;
1107
1108         /*
1109          * The rest of the sub-select must not refer to any Vars of the parent
1110          * query.  (Vars of higher levels should be okay, though.)
1111          */
1112         if (contain_vars_of_level((Node *) subselect, 1))
1113                 return false;
1114
1115         /*
1116          * On the other hand, the WHERE clause must contain some Vars of the
1117          * parent query, else it's not gonna be a join.
1118          */
1119         if (!contain_vars_of_level(whereClause, 1))
1120                 return false;
1121
1122         /*
1123          * We don't risk optimizing if the WHERE clause is volatile, either.
1124          */
1125         if (contain_volatile_functions(whereClause))
1126                 return false;
1127
1128         /*
1129          * Prepare to pull up the sub-select into top range table.
1130          *
1131          * We rely here on the assumption that the outer query has no references
1132          * to the inner (necessarily true). Therefore this is a lot easier than
1133          * what pull_up_subqueries has to go through.
1134          *
1135          * In fact, it's even easier than what convert_ANY_sublink_to_join has
1136          * to do.  The machinations of simplify_EXISTS_query ensured that there
1137          * is nothing interesting in the subquery except an rtable and jointree,
1138          * and even the jointree FromExpr no longer has quals.  So we can just
1139          * append the rtable to our own and attach the fromlist to our own.
1140          * But first, adjust all level-zero varnos in the subquery to account
1141          * for the rtable merger.
1142          */
1143         rtoffset = list_length(parse->rtable);
1144         OffsetVarNodes((Node *) subselect, rtoffset, 0);
1145         OffsetVarNodes(whereClause, rtoffset, 0);
1146
1147         /*
1148          * Upper-level vars in subquery will now be one level closer to their
1149          * parent than before; in particular, anything that had been level 1
1150          * becomes level zero.
1151          */
1152         IncrementVarSublevelsUp((Node *) subselect, -1, 1);
1153         IncrementVarSublevelsUp(whereClause, -1, 1);
1154
1155         /*
1156          * Now that the WHERE clause is adjusted to match the parent query
1157          * environment, we can easily identify all the level-zero rels it uses.
1158          * The ones <= rtoffset are "left rels" of the join we're forming,
1159          * and the ones > rtoffset are "right rels".
1160          */
1161         clause_varnos = pull_varnos(whereClause);
1162         left_varnos = right_varnos = NULL;
1163         while ((varno = bms_first_member(clause_varnos)) >= 0)
1164         {
1165                 if (varno <= rtoffset)
1166                         left_varnos = bms_add_member(left_varnos, varno);
1167                 else
1168                         right_varnos = bms_add_member(right_varnos, varno);
1169         }
1170         bms_free(clause_varnos);
1171         Assert(!bms_is_empty(left_varnos));
1172
1173         /*
1174          * Now that we've got the set of upper-level varnos, we can make the
1175          * last check: only available_rels can be referenced.
1176          */
1177         if (!bms_is_subset(left_varnos, available_rels))
1178                 return false;
1179
1180         /* Identify all the rels syntactically within the subselect */
1181         subselect_varnos = get_relids_in_jointree((Node *) subselect->jointree,
1182                                                                                           true);
1183         Assert(bms_is_subset(right_varnos, subselect_varnos));
1184
1185         /* Now we can attach the modified subquery rtable to the parent */
1186         parse->rtable = list_concat(parse->rtable, subselect->rtable);
1187
1188         /*
1189          * Pass back the subquery fromlist to be attached to upper jointree
1190          * in a suitable place.
1191          */
1192         *fromlist = subselect->jointree->fromlist;
1193
1194         /*
1195          * And finally, build the FlattenedSubLink node.
1196          *
1197          * Note: at this point left_varnos and subselect_varnos may well contain
1198          * join relids.  This will get fixed when flatten_join_alias_vars is run.
1199          */
1200         fslink = makeNode(FlattenedSubLink);
1201         fslink->jointype = under_not ? JOIN_ANTI : JOIN_SEMI;
1202         fslink->lefthand = left_varnos;
1203         fslink->righthand = subselect_varnos;
1204         fslink->quals = (Expr *) whereClause;
1205
1206         *new_qual = (Node *) fslink;
1207
1208         return true;
1209 }
1210
1211 /*
1212  * simplify_EXISTS_query: remove any useless stuff in an EXISTS's subquery
1213  *
1214  * The only thing that matters about an EXISTS query is whether it returns
1215  * zero or more than zero rows.  Therefore, we can remove certain SQL features
1216  * that won't affect that.  The only part that is really likely to matter in
1217  * typical usage is simplifying the targetlist: it's a common habit to write
1218  * "SELECT * FROM" even though there is no need to evaluate any columns.
1219  *
1220  * Note: by suppressing the targetlist we could cause an observable behavioral
1221  * change, namely that any errors that might occur in evaluating the tlist
1222  * won't occur, nor will other side-effects of volatile functions.  This seems
1223  * unlikely to bother anyone in practice.
1224  *
1225  * Returns TRUE if was able to discard the targetlist, else FALSE.
1226  */
1227 static bool
1228 simplify_EXISTS_query(Query *query)
1229 {
1230         /*
1231          * We don't try to simplify at all if the query uses set operations,
1232          * aggregates, HAVING, LIMIT/OFFSET, or FOR UPDATE/SHARE; none of these
1233          * seem likely in normal usage and their possible effects are complex.
1234          */
1235         if (query->commandType != CMD_SELECT ||
1236                 query->intoClause ||
1237                 query->setOperations ||
1238                 query->hasAggs ||
1239                 query->havingQual ||
1240                 query->limitOffset ||
1241                 query->limitCount ||
1242                 query->rowMarks)
1243                 return false;
1244
1245         /*
1246          * Mustn't throw away the targetlist if it contains set-returning
1247          * functions; those could affect whether zero rows are returned!
1248          */
1249         if (expression_returns_set((Node *) query->targetList))
1250                 return false;
1251
1252         /*
1253          * Otherwise, we can throw away the targetlist, as well as any GROUP,
1254          * DISTINCT, and ORDER BY clauses; none of those clauses will change
1255          * a nonzero-rows result to zero rows or vice versa.  (Furthermore,
1256          * since our parsetree representation of these clauses depends on the
1257          * targetlist, we'd better throw them away if we drop the targetlist.)
1258          */
1259         query->targetList = NIL;
1260         query->groupClause = NIL;
1261         query->distinctClause = NIL;
1262         query->sortClause = NIL;
1263         query->hasDistinctOn = false;
1264
1265         return true;
1266 }
1267
1268 /*
1269  * convert_EXISTS_to_ANY: try to convert EXISTS to a hashable ANY sublink
1270  *
1271  * The subselect is expected to be a fresh copy that we can munge up,
1272  * and to have been successfully passed through simplify_EXISTS_query.
1273  *
1274  * On success, the modified subselect is returned, and we store a suitable
1275  * upper-level test expression at *testexpr, plus a list of the subselect's
1276  * output Params at *paramIds.  (The test expression is already Param-ified
1277  * and hence need not go through convert_testexpr, which is why we have to
1278  * deal with the Param IDs specially.)
1279  *
1280  * On failure, returns NULL.
1281  */
1282 static Query *
1283 convert_EXISTS_to_ANY(PlannerInfo *root, Query *subselect,
1284                                           Node **testexpr, List **paramIds)
1285 {
1286         Node       *whereClause;
1287         List       *leftargs,
1288                            *rightargs,
1289                            *opids,
1290                            *newWhere,
1291                            *tlist,
1292                            *testlist,
1293                            *paramids;
1294         ListCell   *lc,
1295                            *rc,
1296                            *oc;
1297         AttrNumber      resno;
1298
1299         /*
1300          * Query must not require a targetlist, since we have to insert a new one.
1301          * Caller should have dealt with the case already.
1302          */
1303         Assert(subselect->targetList == NIL);
1304
1305         /*
1306          * Separate out the WHERE clause.  (We could theoretically also remove
1307          * top-level plain JOIN/ON clauses, but it's probably not worth the
1308          * trouble.)
1309          */
1310         whereClause = subselect->jointree->quals;
1311         subselect->jointree->quals = NULL;
1312
1313         /*
1314          * The rest of the sub-select must not refer to any Vars of the parent
1315          * query.  (Vars of higher levels should be okay, though.)
1316          *
1317          * Note: we need not check for Aggs separately because we know the
1318          * sub-select is as yet unoptimized; any uplevel Agg must therefore
1319          * contain an uplevel Var reference.  This is not the case below ...
1320          */
1321         if (contain_vars_of_level((Node *) subselect, 1))
1322                 return NULL;
1323
1324         /*
1325          * We don't risk optimizing if the WHERE clause is volatile, either.
1326          */
1327         if (contain_volatile_functions(whereClause))
1328                 return NULL;
1329
1330         /*
1331          * Clean up the WHERE clause by doing const-simplification etc on it.
1332          * Aside from simplifying the processing we're about to do, this is
1333          * important for being able to pull chunks of the WHERE clause up into
1334          * the parent query.  Since we are invoked partway through the parent's
1335          * preprocess_expression() work, earlier steps of preprocess_expression()
1336          * wouldn't get applied to the pulled-up stuff unless we do them here.
1337          * For the parts of the WHERE clause that get put back into the child
1338          * query, this work is partially duplicative, but it shouldn't hurt.
1339          *
1340          * Note: we do not run flatten_join_alias_vars.  This is OK because
1341          * any parent aliases were flattened already, and we're not going to
1342          * pull any child Vars (of any description) into the parent.
1343          *
1344          * Note: passing the parent's root to eval_const_expressions is technically
1345          * wrong, but we can get away with it since only the boundParams (if any)
1346          * are used, and those would be the same in a subroot.
1347          */
1348         whereClause = eval_const_expressions(root, whereClause);
1349         whereClause = (Node *) canonicalize_qual((Expr *) whereClause);
1350         whereClause = (Node *) make_ands_implicit((Expr *) whereClause);
1351
1352         /*
1353          * We now have a flattened implicit-AND list of clauses, which we
1354          * try to break apart into "outervar = innervar" hash clauses.
1355          * Anything that can't be broken apart just goes back into the
1356          * newWhere list.  Note that we aren't trying hard yet to ensure
1357          * that we have only outer or only inner on each side; we'll check
1358          * that if we get to the end.
1359          */
1360         leftargs = rightargs = opids = newWhere = NIL;
1361         foreach(lc, (List *) whereClause)
1362         {
1363                 OpExpr     *expr = (OpExpr *) lfirst(lc);
1364
1365                 if (IsA(expr, OpExpr) &&
1366                         hash_ok_operator(expr))
1367                 {
1368                         Node   *leftarg = (Node *) linitial(expr->args);
1369                         Node   *rightarg = (Node *) lsecond(expr->args);
1370
1371                         if (contain_vars_of_level(leftarg, 1))
1372                         {
1373                                 leftargs = lappend(leftargs, leftarg);
1374                                 rightargs = lappend(rightargs, rightarg);
1375                                 opids = lappend_oid(opids, expr->opno);
1376                                 continue;
1377                         }
1378                         if (contain_vars_of_level(rightarg, 1))
1379                         {
1380                                 /*
1381                                  * We must commute the clause to put the outer var on the
1382                                  * left, because the hashing code in nodeSubplan.c expects
1383                                  * that.  This probably shouldn't ever fail, since hashable
1384                                  * operators ought to have commutators, but be paranoid.
1385                                  */
1386                                 expr->opno = get_commutator(expr->opno);
1387                                 if (OidIsValid(expr->opno) && hash_ok_operator(expr))
1388                                 {
1389                                         leftargs = lappend(leftargs, rightarg);
1390                                         rightargs = lappend(rightargs, leftarg);
1391                                         opids = lappend_oid(opids, expr->opno);
1392                                         continue;
1393                                 }
1394                                 /* If no commutator, no chance to optimize the WHERE clause */
1395                                 return NULL;
1396                         }
1397                 }
1398                 /* Couldn't handle it as a hash clause */
1399                 newWhere = lappend(newWhere, expr);
1400         }
1401
1402         /*
1403          * If we didn't find anything we could convert, fail.
1404          */
1405         if (leftargs == NIL)
1406                 return NULL;
1407
1408         /*
1409          * There mustn't be any parent Vars or Aggs in the stuff that we intend to
1410          * put back into the child query.  Note: you might think we don't need to
1411          * check for Aggs separately, because an uplevel Agg must contain an
1412          * uplevel Var in its argument.  But it is possible that the uplevel Var
1413          * got optimized away by eval_const_expressions.  Consider
1414          *
1415          * SUM(CASE WHEN false THEN uplevelvar ELSE 0 END)
1416          */
1417         if (contain_vars_of_level((Node *) newWhere, 1) ||
1418                 contain_vars_of_level((Node *) rightargs, 1))
1419                 return NULL;
1420         if (root->parse->hasAggs &&
1421                 (contain_aggs_of_level((Node *) newWhere, 1) ||
1422                  contain_aggs_of_level((Node *) rightargs, 1)))
1423                 return NULL;
1424
1425         /*
1426          * And there can't be any child Vars in the stuff we intend to pull up.
1427          * (Note: we'd need to check for child Aggs too, except we know the
1428          * child has no aggs at all because of simplify_EXISTS_query's check.)
1429          */
1430         if (contain_vars_of_level((Node *) leftargs, 0))
1431                 return NULL;
1432
1433         /*
1434          * Also reject sublinks in the stuff we intend to pull up.  (It might be
1435          * possible to support this, but doesn't seem worth the complication.)
1436          */
1437         if (contain_subplans((Node *) leftargs))
1438                 return NULL;
1439
1440         /*
1441          * Okay, adjust the sublevelsup in the stuff we're pulling up.
1442          */
1443         IncrementVarSublevelsUp((Node *) leftargs, -1, 1);
1444
1445         /*
1446          * Put back any child-level-only WHERE clauses.
1447          */
1448         if (newWhere)
1449                 subselect->jointree->quals = (Node *) make_ands_explicit(newWhere);
1450
1451         /*
1452          * Build a new targetlist for the child that emits the expressions
1453          * we need.  Concurrently, build a testexpr for the parent using
1454          * Params to reference the child outputs.  (Since we generate Params
1455          * directly here, there will be no need to convert the testexpr in
1456          * build_subplan.)
1457          */
1458         tlist = testlist = paramids = NIL;
1459         resno = 1;
1460         /* there's no "for3" so we have to chase one of the lists manually */
1461         oc = list_head(opids);
1462         forboth(lc, leftargs, rc, rightargs)
1463         {
1464                 Node       *leftarg = (Node *) lfirst(lc);
1465                 Node       *rightarg = (Node *) lfirst(rc);
1466                 Oid                     opid = lfirst_oid(oc);
1467                 Param      *param;
1468
1469                 oc = lnext(oc);
1470                 param = generate_new_param(root,
1471                                                                    exprType(rightarg),
1472                                                                    exprTypmod(rightarg));
1473                 tlist = lappend(tlist,
1474                                                 makeTargetEntry((Expr *) rightarg,
1475                                                                                 resno++,
1476                                                                                 NULL,
1477                                                                                 false));
1478                 testlist = lappend(testlist,
1479                                                    make_opclause(opid, BOOLOID, false,
1480                                                                                  (Expr *) leftarg, (Expr *) param));
1481                 paramids = lappend_int(paramids, param->paramid);
1482         }
1483
1484         /* Put everything where it should go, and we're done */
1485         subselect->targetList = tlist;
1486         *testexpr = (Node *) make_ands_explicit(testlist);
1487         *paramIds = paramids;
1488
1489         return subselect;
1490 }
1491
1492
1493 /*
1494  * Replace correlation vars (uplevel vars) with Params.
1495  *
1496  * Uplevel aggregates are replaced, too.
1497  *
1498  * Note: it is critical that this runs immediately after SS_process_sublinks.
1499  * Since we do not recurse into the arguments of uplevel aggregates, they will
1500  * get copied to the appropriate subplan args list in the parent query with
1501  * uplevel vars not replaced by Params, but only adjusted in level (see
1502  * replace_outer_agg).  That's exactly what we want for the vars of the parent
1503  * level --- but if an aggregate's argument contains any further-up variables,
1504  * they have to be replaced with Params in their turn.  That will happen when
1505  * the parent level runs SS_replace_correlation_vars.  Therefore it must do
1506  * so after expanding its sublinks to subplans.  And we don't want any steps
1507  * in between, else those steps would never get applied to the aggregate
1508  * argument expressions, either in the parent or the child level.
1509  */
1510 Node *
1511 SS_replace_correlation_vars(PlannerInfo *root, Node *expr)
1512 {
1513         /* No setup needed for tree walk, so away we go */
1514         return replace_correlation_vars_mutator(expr, root);
1515 }
1516
1517 static Node *
1518 replace_correlation_vars_mutator(Node *node, PlannerInfo *root)
1519 {
1520         if (node == NULL)
1521                 return NULL;
1522         if (IsA(node, Var))
1523         {
1524                 if (((Var *) node)->varlevelsup > 0)
1525                         return (Node *) replace_outer_var(root, (Var *) node);
1526         }
1527         if (IsA(node, Aggref))
1528         {
1529                 if (((Aggref *) node)->agglevelsup > 0)
1530                         return (Node *) replace_outer_agg(root, (Aggref *) node);
1531         }
1532         return expression_tree_mutator(node,
1533                                                                    replace_correlation_vars_mutator,
1534                                                                    (void *) root);
1535 }
1536
1537 /*
1538  * Expand SubLinks to SubPlans in the given expression.
1539  *
1540  * The isQual argument tells whether or not this expression is a WHERE/HAVING
1541  * qualifier expression.  If it is, any sublinks appearing at top level need
1542  * not distinguish FALSE from UNKNOWN return values.
1543  */
1544 Node *
1545 SS_process_sublinks(PlannerInfo *root, Node *expr, bool isQual)
1546 {
1547         process_sublinks_context context;
1548
1549         context.root = root;
1550         context.isTopQual = isQual;
1551         return process_sublinks_mutator(expr, &context);
1552 }
1553
1554 static Node *
1555 process_sublinks_mutator(Node *node, process_sublinks_context *context)
1556 {
1557         process_sublinks_context locContext;
1558
1559         locContext.root = context->root;
1560
1561         if (node == NULL)
1562                 return NULL;
1563         if (IsA(node, SubLink))
1564         {
1565                 SubLink    *sublink = (SubLink *) node;
1566                 Node       *testexpr;
1567
1568                 /*
1569                  * First, recursively process the lefthand-side expressions, if any.
1570                  * They're not top-level anymore.
1571                  */
1572                 locContext.isTopQual = false;
1573                 testexpr = process_sublinks_mutator(sublink->testexpr, &locContext);
1574
1575                 /*
1576                  * Now build the SubPlan node and make the expr to return.
1577                  */
1578                 return make_subplan(context->root,
1579                                                         (Query *) sublink->subselect,
1580                                                         sublink->subLinkType,
1581                                                         testexpr,
1582                                                         context->isTopQual);
1583         }
1584
1585         /*
1586          * We should never see a SubPlan expression in the input (since this is
1587          * the very routine that creates 'em to begin with).  We shouldn't find
1588          * ourselves invoked directly on a Query, either.
1589          */
1590         Assert(!IsA(node, SubPlan));
1591         Assert(!IsA(node, AlternativeSubPlan));
1592         Assert(!IsA(node, Query));
1593
1594         /*
1595          * Because make_subplan() could return an AND or OR clause, we have to
1596          * take steps to preserve AND/OR flatness of a qual.  We assume the input
1597          * has been AND/OR flattened and so we need no recursion here.
1598          *
1599          * (Due to the coding here, we will not get called on the List subnodes of
1600          * an AND; and the input is *not* yet in implicit-AND format.  So no check
1601          * is needed for a bare List.)
1602          *
1603          * Anywhere within the top-level AND/OR clause structure, we can tell
1604          * make_subplan() that NULL and FALSE are interchangeable.  So isTopQual
1605          * propagates down in both cases.  (Note that this is unlike the meaning
1606          * of "top level qual" used in most other places in Postgres.)
1607          */
1608         if (and_clause(node))
1609         {
1610                 List       *newargs = NIL;
1611                 ListCell   *l;
1612
1613                 /* Still at qual top-level */
1614                 locContext.isTopQual = context->isTopQual;
1615
1616                 foreach(l, ((BoolExpr *) node)->args)
1617                 {
1618                         Node       *newarg;
1619
1620                         newarg = process_sublinks_mutator(lfirst(l), &locContext);
1621                         if (and_clause(newarg))
1622                                 newargs = list_concat(newargs, ((BoolExpr *) newarg)->args);
1623                         else
1624                                 newargs = lappend(newargs, newarg);
1625                 }
1626                 return (Node *) make_andclause(newargs);
1627         }
1628
1629         if (or_clause(node))
1630         {
1631                 List       *newargs = NIL;
1632                 ListCell   *l;
1633
1634                 /* Still at qual top-level */
1635                 locContext.isTopQual = context->isTopQual;
1636
1637                 foreach(l, ((BoolExpr *) node)->args)
1638                 {
1639                         Node       *newarg;
1640
1641                         newarg = process_sublinks_mutator(lfirst(l), &locContext);
1642                         if (or_clause(newarg))
1643                                 newargs = list_concat(newargs, ((BoolExpr *) newarg)->args);
1644                         else
1645                                 newargs = lappend(newargs, newarg);
1646                 }
1647                 return (Node *) make_orclause(newargs);
1648         }
1649
1650         /*
1651          * If we recurse down through anything other than an AND or OR node,
1652          * we are definitely not at top qual level anymore.
1653          */
1654         locContext.isTopQual = false;
1655
1656         return expression_tree_mutator(node,
1657                                                                    process_sublinks_mutator,
1658                                                                    (void *) &locContext);
1659 }
1660
1661 /*
1662  * SS_finalize_plan - do final sublink processing for a completed Plan.
1663  *
1664  * This recursively computes the extParam and allParam sets for every Plan
1665  * node in the given plan tree.  It also optionally attaches any previously
1666  * generated InitPlans to the top plan node.  (Any InitPlans should already
1667  * have been put through SS_finalize_plan.)
1668  */
1669 void
1670 SS_finalize_plan(PlannerInfo *root, Plan *plan, bool attach_initplans)
1671 {
1672         Bitmapset  *valid_params,
1673                            *initExtParam,
1674                            *initSetParam;
1675         Cost            initplan_cost;
1676         int                     paramid;
1677         ListCell   *l;
1678
1679         /*
1680          * Examine any initPlans to determine the set of external params they
1681          * reference, the set of output params they supply, and their total cost.
1682          * We'll use at least some of this info below.  (Note we are assuming that
1683          * finalize_plan doesn't touch the initPlans.)
1684          *
1685          * In the case where attach_initplans is false, we are assuming that the
1686          * existing initPlans are siblings that might supply params needed by the
1687          * current plan.
1688          */
1689         initExtParam = initSetParam = NULL;
1690         initplan_cost = 0;
1691         foreach(l, root->init_plans)
1692         {
1693                 SubPlan    *initsubplan = (SubPlan *) lfirst(l);
1694                 Plan       *initplan = planner_subplan_get_plan(root, initsubplan);
1695                 ListCell   *l2;
1696
1697                 initExtParam = bms_add_members(initExtParam, initplan->extParam);
1698                 foreach(l2, initsubplan->setParam)
1699                 {
1700                         initSetParam = bms_add_member(initSetParam, lfirst_int(l2));
1701                 }
1702                 initplan_cost += initsubplan->startup_cost + initsubplan->per_call_cost;
1703         }
1704
1705         /*
1706          * Now determine the set of params that are validly referenceable in this
1707          * query level; to wit, those available from outer query levels plus the
1708          * output parameters of any initPlans.  (We do not include output
1709          * parameters of regular subplans.  Those should only appear within the
1710          * testexpr of SubPlan nodes, and are taken care of locally within
1711          * finalize_primnode.)
1712          *
1713          * Note: this is a bit overly generous since some parameters of upper
1714          * query levels might belong to query subtrees that don't include this
1715          * query.  However, valid_params is only a debugging crosscheck, so it
1716          * doesn't seem worth expending lots of cycles to try to be exact.
1717          */
1718         valid_params = bms_copy(initSetParam);
1719         paramid = 0;
1720         foreach(l, root->glob->paramlist)
1721         {
1722                 PlannerParamItem *pitem = (PlannerParamItem *) lfirst(l);
1723
1724                 if (pitem->abslevel < root->query_level)
1725                 {
1726                         /* valid outer-level parameter */
1727                         valid_params = bms_add_member(valid_params, paramid);
1728                 }
1729
1730                 paramid++;
1731         }
1732         /* Also include the recursion working table, if any */
1733         if (root->wt_param_id >= 0)
1734                 valid_params = bms_add_member(valid_params, root->wt_param_id);
1735
1736         /*
1737          * Now recurse through plan tree.
1738          */
1739         (void) finalize_plan(root, plan, valid_params);
1740
1741         bms_free(valid_params);
1742
1743         /*
1744          * Finally, attach any initPlans to the topmost plan node, and add their
1745          * extParams to the topmost node's, too.  However, any setParams of the
1746          * initPlans should not be present in the topmost node's extParams, only
1747          * in its allParams.  (As of PG 8.1, it's possible that some initPlans
1748          * have extParams that are setParams of other initPlans, so we have to
1749          * take care of this situation explicitly.)
1750          *
1751          * We also add the eval cost of each initPlan to the startup cost of the
1752          * top node.  This is a conservative overestimate, since in fact each
1753          * initPlan might be executed later than plan startup, or even not at all.
1754          */
1755         if (attach_initplans)
1756         {
1757                 plan->initPlan = root->init_plans;
1758                 root->init_plans = NIL;         /* make sure they're not attached twice */
1759
1760                 /* allParam must include all these params */
1761                 plan->allParam = bms_add_members(plan->allParam, initExtParam);
1762                 plan->allParam = bms_add_members(plan->allParam, initSetParam);
1763                 /* extParam must include any child extParam */
1764                 plan->extParam = bms_add_members(plan->extParam, initExtParam);
1765                 /* but extParam shouldn't include any setParams */
1766                 plan->extParam = bms_del_members(plan->extParam, initSetParam);
1767                 /* ensure extParam is exactly NULL if it's empty */
1768                 if (bms_is_empty(plan->extParam))
1769                         plan->extParam = NULL;
1770
1771                 plan->startup_cost += initplan_cost;
1772                 plan->total_cost += initplan_cost;
1773         }
1774 }
1775
1776 /*
1777  * Recursive processing of all nodes in the plan tree
1778  *
1779  * The return value is the computed allParam set for the given Plan node.
1780  * This is just an internal notational convenience.
1781  */
1782 static Bitmapset *
1783 finalize_plan(PlannerInfo *root, Plan *plan, Bitmapset *valid_params)
1784 {
1785         finalize_primnode_context context;
1786
1787         if (plan == NULL)
1788                 return NULL;
1789
1790         context.root = root;
1791         context.paramids = NULL;        /* initialize set to empty */
1792
1793         /*
1794          * When we call finalize_primnode, context.paramids sets are automatically
1795          * merged together.  But when recursing to self, we have to do it the hard
1796          * way.  We want the paramids set to include params in subplans as well as
1797          * at this level.
1798          */
1799
1800         /* Find params in targetlist and qual */
1801         finalize_primnode((Node *) plan->targetlist, &context);
1802         finalize_primnode((Node *) plan->qual, &context);
1803
1804         /* Check additional node-type-specific fields */
1805         switch (nodeTag(plan))
1806         {
1807                 case T_Result:
1808                         finalize_primnode(((Result *) plan)->resconstantqual,
1809                                                           &context);
1810                         break;
1811
1812                 case T_IndexScan:
1813                         finalize_primnode((Node *) ((IndexScan *) plan)->indexqual,
1814                                                           &context);
1815
1816                         /*
1817                          * we need not look at indexqualorig, since it will have the same
1818                          * param references as indexqual.
1819                          */
1820                         break;
1821
1822                 case T_BitmapIndexScan:
1823                         finalize_primnode((Node *) ((BitmapIndexScan *) plan)->indexqual,
1824                                                           &context);
1825
1826                         /*
1827                          * we need not look at indexqualorig, since it will have the same
1828                          * param references as indexqual.
1829                          */
1830                         break;
1831
1832                 case T_BitmapHeapScan:
1833                         finalize_primnode((Node *) ((BitmapHeapScan *) plan)->bitmapqualorig,
1834                                                           &context);
1835                         break;
1836
1837                 case T_TidScan:
1838                         finalize_primnode((Node *) ((TidScan *) plan)->tidquals,
1839                                                           &context);
1840                         break;
1841
1842                 case T_SubqueryScan:
1843
1844                         /*
1845                          * In a SubqueryScan, SS_finalize_plan has already been run on the
1846                          * subplan by the inner invocation of subquery_planner, so there's
1847                          * no need to do it again.      Instead, just pull out the subplan's
1848                          * extParams list, which represents the params it needs from my
1849                          * level and higher levels.
1850                          */
1851                         context.paramids = bms_add_members(context.paramids,
1852                                                                  ((SubqueryScan *) plan)->subplan->extParam);
1853                         break;
1854
1855                 case T_FunctionScan:
1856                         finalize_primnode(((FunctionScan *) plan)->funcexpr,
1857                                                           &context);
1858                         break;
1859
1860                 case T_ValuesScan:
1861                         finalize_primnode((Node *) ((ValuesScan *) plan)->values_lists,
1862                                                           &context);
1863                         break;
1864
1865                 case T_CteScan:
1866                         context.paramids =
1867                                 bms_add_member(context.paramids,
1868                                                            ((CteScan *) plan)->cteParam);
1869                         break;
1870
1871                 case T_WorkTableScan:
1872                         context.paramids =
1873                                 bms_add_member(context.paramids,
1874                                                            ((WorkTableScan *) plan)->wtParam);
1875                         break;
1876
1877                 case T_Append:
1878                         {
1879                                 ListCell   *l;
1880
1881                                 foreach(l, ((Append *) plan)->appendplans)
1882                                 {
1883                                         context.paramids =
1884                                                 bms_add_members(context.paramids,
1885                                                                                 finalize_plan(root,
1886                                                                                                           (Plan *) lfirst(l),
1887                                                                                                           valid_params));
1888                                 }
1889                         }
1890                         break;
1891
1892                 case T_BitmapAnd:
1893                         {
1894                                 ListCell   *l;
1895
1896                                 foreach(l, ((BitmapAnd *) plan)->bitmapplans)
1897                                 {
1898                                         context.paramids =
1899                                                 bms_add_members(context.paramids,
1900                                                                                 finalize_plan(root,
1901                                                                                                           (Plan *) lfirst(l),
1902                                                                                                           valid_params));
1903                                 }
1904                         }
1905                         break;
1906
1907                 case T_BitmapOr:
1908                         {
1909                                 ListCell   *l;
1910
1911                                 foreach(l, ((BitmapOr *) plan)->bitmapplans)
1912                                 {
1913                                         context.paramids =
1914                                                 bms_add_members(context.paramids,
1915                                                                                 finalize_plan(root,
1916                                                                                                           (Plan *) lfirst(l),
1917                                                                                                           valid_params));
1918                                 }
1919                         }
1920                         break;
1921
1922                 case T_NestLoop:
1923                         finalize_primnode((Node *) ((Join *) plan)->joinqual,
1924                                                           &context);
1925                         break;
1926
1927                 case T_MergeJoin:
1928                         finalize_primnode((Node *) ((Join *) plan)->joinqual,
1929                                                           &context);
1930                         finalize_primnode((Node *) ((MergeJoin *) plan)->mergeclauses,
1931                                                           &context);
1932                         break;
1933
1934                 case T_HashJoin:
1935                         finalize_primnode((Node *) ((Join *) plan)->joinqual,
1936                                                           &context);
1937                         finalize_primnode((Node *) ((HashJoin *) plan)->hashclauses,
1938                                                           &context);
1939                         break;
1940
1941                 case T_Limit:
1942                         finalize_primnode(((Limit *) plan)->limitOffset,
1943                                                           &context);
1944                         finalize_primnode(((Limit *) plan)->limitCount,
1945                                                           &context);
1946                         break;
1947
1948                 case T_RecursiveUnion:
1949                 case T_Hash:
1950                 case T_Agg:
1951                 case T_SeqScan:
1952                 case T_Material:
1953                 case T_Sort:
1954                 case T_Unique:
1955                 case T_SetOp:
1956                 case T_Group:
1957                         break;
1958
1959                 default:
1960                         elog(ERROR, "unrecognized node type: %d",
1961                                  (int) nodeTag(plan));
1962         }
1963
1964         /* Process left and right child plans, if any */
1965         context.paramids = bms_add_members(context.paramids,
1966                                                                            finalize_plan(root,
1967                                                                                                          plan->lefttree,
1968                                                                                                          valid_params));
1969
1970         context.paramids = bms_add_members(context.paramids,
1971                                                                            finalize_plan(root,
1972                                                                                                          plan->righttree,
1973                                                                                                          valid_params));
1974
1975         /*
1976          * RecursiveUnion *generates* its worktable param, so don't bubble that up
1977          */
1978         if (IsA(plan, RecursiveUnion))
1979         {
1980                 context.paramids = bms_del_member(context.paramids,
1981                                                                                   ((RecursiveUnion *) plan)->wtParam);
1982         }
1983
1984         /* Now we have all the paramids */
1985
1986         if (!bms_is_subset(context.paramids, valid_params))
1987                 elog(ERROR, "plan should not reference subplan's variable");
1988
1989         /*
1990          * Note: by definition, extParam and allParam should have the same value
1991          * in any plan node that doesn't have child initPlans.  We set them
1992          * equal here, and later SS_finalize_plan will update them properly
1993          * in node(s) that it attaches initPlans to.
1994          *
1995          * For speed at execution time, make sure extParam/allParam are actually
1996          * NULL if they are empty sets.
1997          */
1998         if (bms_is_empty(context.paramids))
1999         {
2000                 plan->extParam = NULL;
2001                 plan->allParam = NULL;
2002         }
2003         else
2004         {
2005                 plan->extParam = context.paramids;
2006                 plan->allParam = bms_copy(context.paramids);
2007         }
2008
2009         return plan->allParam;
2010 }
2011
2012 /*
2013  * finalize_primnode: add IDs of all PARAM_EXEC params appearing in the given
2014  * expression tree to the result set.
2015  */
2016 static bool
2017 finalize_primnode(Node *node, finalize_primnode_context *context)
2018 {
2019         if (node == NULL)
2020                 return false;
2021         if (IsA(node, Param))
2022         {
2023                 if (((Param *) node)->paramkind == PARAM_EXEC)
2024                 {
2025                         int                     paramid = ((Param *) node)->paramid;
2026
2027                         context->paramids = bms_add_member(context->paramids, paramid);
2028                 }
2029                 return false;                   /* no more to do here */
2030         }
2031         if (IsA(node, SubPlan))
2032         {
2033                 SubPlan    *subplan = (SubPlan *) node;
2034                 Plan       *plan = planner_subplan_get_plan(context->root, subplan);
2035                 ListCell   *lc;
2036                 Bitmapset  *subparamids;
2037
2038                 /* Recurse into the testexpr, but not into the Plan */
2039                 finalize_primnode(subplan->testexpr, context);
2040
2041                 /*
2042                  * Remove any param IDs of output parameters of the subplan that were
2043                  * referenced in the testexpr.  These are not interesting for
2044                  * parameter change signaling since we always re-evaluate the subplan.
2045                  * Note that this wouldn't work too well if there might be uses of the
2046                  * same param IDs elsewhere in the plan, but that can't happen because
2047                  * generate_new_param never tries to merge params.
2048                  */
2049                 foreach(lc, subplan->paramIds)
2050                 {
2051                         context->paramids = bms_del_member(context->paramids,
2052                                                                                            lfirst_int(lc));
2053                 }
2054
2055                 /* Also examine args list */
2056                 finalize_primnode((Node *) subplan->args, context);
2057
2058                 /*
2059                  * Add params needed by the subplan to paramids, but excluding those
2060                  * we will pass down to it.
2061                  */
2062                 subparamids = bms_copy(plan->extParam);
2063                 foreach(lc, subplan->parParam)
2064                 {
2065                         subparamids = bms_del_member(subparamids, lfirst_int(lc));
2066                 }
2067                 context->paramids = bms_join(context->paramids, subparamids);
2068
2069                 return false;                   /* no more to do here */
2070         }
2071         return expression_tree_walker(node, finalize_primnode,
2072                                                                   (void *) context);
2073 }
2074
2075 /*
2076  * SS_make_initplan_from_plan - given a plan tree, make it an InitPlan
2077  *
2078  * The plan is expected to return a scalar value of the indicated type.
2079  * We build an EXPR_SUBLINK SubPlan node and put it into the initplan
2080  * list for the current query level.  A Param that represents the initplan's
2081  * output is returned.
2082  *
2083  * We assume the plan hasn't been put through SS_finalize_plan.
2084  */
2085 Param *
2086 SS_make_initplan_from_plan(PlannerInfo *root, Plan *plan,
2087                                                    Oid resulttype, int32 resulttypmod)
2088 {
2089         SubPlan    *node;
2090         Param      *prm;
2091
2092         /*
2093          * We must run SS_finalize_plan(), since that's normally done before a
2094          * subplan gets put into the initplan list.  Tell it not to attach any
2095          * pre-existing initplans to this one, since they are siblings not
2096          * children of this initplan.  (This is something else that could perhaps
2097          * be cleaner if we did extParam/allParam processing in setrefs.c instead
2098          * of here?  See notes for materialize_finished_plan.)
2099          */
2100
2101         /*
2102          * Build extParam/allParam sets for plan nodes.
2103          */
2104         SS_finalize_plan(root, plan, false);
2105
2106         /*
2107          * Add the subplan and its rtable to the global lists.
2108          */
2109         root->glob->subplans = lappend(root->glob->subplans,
2110                                                                    plan);
2111         root->glob->subrtables = lappend(root->glob->subrtables,
2112                                                                          root->parse->rtable);
2113
2114         /*
2115          * Create a SubPlan node and add it to the outer list of InitPlans.
2116          * Note it has to appear after any other InitPlans it might depend on
2117          * (see comments in ExecReScan).
2118          */
2119         node = makeNode(SubPlan);
2120         node->subLinkType = EXPR_SUBLINK;
2121         node->firstColType = get_first_col_type(plan);
2122         node->plan_id = list_length(root->glob->subplans);
2123
2124         root->init_plans = lappend(root->init_plans, node);
2125
2126         /*
2127          * The node can't have any inputs (since it's an initplan), so the
2128          * parParam and args lists remain empty.
2129          */
2130
2131         cost_subplan(root, node, plan);
2132
2133         /*
2134          * Make a Param that will be the subplan's output.
2135          */
2136         prm = generate_new_param(root, resulttype, resulttypmod);
2137         node->setParam = list_make1_int(prm->paramid);
2138
2139         return prm;
2140 }