]> granicus.if.org Git - postgresql/blob - src/backend/optimizer/plan/subselect.c
1e4e9fe565b74579759e1e256bd3e2a2b869775d
[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.133 2008/08/14 18:47:59 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 "optimizer/clauses.h"
21 #include "optimizer/cost.h"
22 #include "optimizer/planmain.h"
23 #include "optimizer/planner.h"
24 #include "optimizer/prep.h"
25 #include "optimizer/subselect.h"
26 #include "optimizer/var.h"
27 #include "parser/parse_expr.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 List *generate_subquery_params(PlannerInfo *root, List *tlist,
56                                                                           List **paramIds);
57 static List *generate_subquery_vars(PlannerInfo *root, List *tlist,
58                                                                         Index varno);
59 static Node *convert_testexpr(PlannerInfo *root,
60                                  Node *testexpr,
61                                  List *subst_nodes);
62 static Node *convert_testexpr_mutator(Node *node,
63                                                  convert_testexpr_context *context);
64 static bool subplan_is_hashable(SubLink *slink, SubPlan *node, Plan *plan);
65 static bool hash_ok_operator(OpExpr *expr);
66 static bool simplify_EXISTS_query(Query *query);
67 static Node *replace_correlation_vars_mutator(Node *node, PlannerInfo *root);
68 static Node *process_sublinks_mutator(Node *node,
69                                                  process_sublinks_context *context);
70 static Bitmapset *finalize_plan(PlannerInfo *root,
71                           Plan *plan,
72                           Bitmapset *valid_params);
73 static bool finalize_primnode(Node *node, finalize_primnode_context *context);
74
75
76 /*
77  * Generate a Param node to replace the given Var,
78  * which is expected to have varlevelsup > 0 (ie, it is not local).
79  */
80 static Param *
81 replace_outer_var(PlannerInfo *root, Var *var)
82 {
83         Param      *retval;
84         ListCell   *ppl;
85         PlannerParamItem *pitem;
86         Index           abslevel;
87         int                     i;
88
89         Assert(var->varlevelsup > 0 && var->varlevelsup < root->query_level);
90         abslevel = root->query_level - var->varlevelsup;
91
92         /*
93          * If there's already a paramlist entry for this same Var, just use it.
94          * NOTE: in sufficiently complex querytrees, it is possible for the same
95          * varno/abslevel to refer to different RTEs in different parts of the
96          * parsetree, so that different fields might end up sharing the same Param
97          * number.      As long as we check the vartype as well, I believe that this
98          * sort of aliasing will cause no trouble. The correct field should get
99          * stored into the Param slot at execution in each part of the tree.
100          *
101          * We also need to demand a match on vartypmod.  This does not matter for
102          * the Param itself, since those are not typmod-dependent, but it does
103          * matter when make_subplan() instantiates a modified copy of the Var for
104          * a subplan's args list.
105          */
106         i = 0;
107         foreach(ppl, root->glob->paramlist)
108         {
109                 pitem = (PlannerParamItem *) lfirst(ppl);
110                 if (pitem->abslevel == abslevel && IsA(pitem->item, Var))
111                 {
112                         Var                *pvar = (Var *) pitem->item;
113
114                         if (pvar->varno == var->varno &&
115                                 pvar->varattno == var->varattno &&
116                                 pvar->vartype == var->vartype &&
117                                 pvar->vartypmod == var->vartypmod)
118                                 break;
119                 }
120                 i++;
121         }
122
123         if (!ppl)
124         {
125                 /* Nope, so make a new one */
126                 var = (Var *) copyObject(var);
127                 var->varlevelsup = 0;
128
129                 pitem = makeNode(PlannerParamItem);
130                 pitem->item = (Node *) var;
131                 pitem->abslevel = abslevel;
132
133                 root->glob->paramlist = lappend(root->glob->paramlist, pitem);
134                 /* i is already the correct index for the new item */
135         }
136
137         retval = makeNode(Param);
138         retval->paramkind = PARAM_EXEC;
139         retval->paramid = i;
140         retval->paramtype = var->vartype;
141         retval->paramtypmod = var->vartypmod;
142
143         return retval;
144 }
145
146 /*
147  * Generate a Param node to replace the given Aggref
148  * which is expected to have agglevelsup > 0 (ie, it is not local).
149  */
150 static Param *
151 replace_outer_agg(PlannerInfo *root, Aggref *agg)
152 {
153         Param      *retval;
154         PlannerParamItem *pitem;
155         Index           abslevel;
156         int                     i;
157
158         Assert(agg->agglevelsup > 0 && agg->agglevelsup < root->query_level);
159         abslevel = root->query_level - agg->agglevelsup;
160
161         /*
162          * It does not seem worthwhile to try to match duplicate outer aggs. Just
163          * make a new slot every time.
164          */
165         agg = (Aggref *) copyObject(agg);
166         IncrementVarSublevelsUp((Node *) agg, -((int) agg->agglevelsup), 0);
167         Assert(agg->agglevelsup == 0);
168
169         pitem = makeNode(PlannerParamItem);
170         pitem->item = (Node *) agg;
171         pitem->abslevel = abslevel;
172
173         root->glob->paramlist = lappend(root->glob->paramlist, pitem);
174         i = list_length(root->glob->paramlist) - 1;
175
176         retval = makeNode(Param);
177         retval->paramkind = PARAM_EXEC;
178         retval->paramid = i;
179         retval->paramtype = agg->aggtype;
180         retval->paramtypmod = -1;
181
182         return retval;
183 }
184
185 /*
186  * Generate a new Param node that will not conflict with any other.
187  *
188  * This is used to allocate PARAM_EXEC slots for subplan outputs.
189  */
190 static Param *
191 generate_new_param(PlannerInfo *root, Oid paramtype, int32 paramtypmod)
192 {
193         Param      *retval;
194         PlannerParamItem *pitem;
195
196         retval = makeNode(Param);
197         retval->paramkind = PARAM_EXEC;
198         retval->paramid = list_length(root->glob->paramlist);
199         retval->paramtype = paramtype;
200         retval->paramtypmod = paramtypmod;
201
202         pitem = makeNode(PlannerParamItem);
203         pitem->item = (Node *) retval;
204         pitem->abslevel = root->query_level;
205
206         root->glob->paramlist = lappend(root->glob->paramlist, pitem);
207
208         return retval;
209 }
210
211 /*
212  * Get the datatype of the first column of the plan's output.
213  *
214  * This is stored for ARRAY_SUBLINK and for exprType(), which doesn't have any
215  * way to get at the plan associated with a SubPlan node.  We really only need
216  * the value for EXPR_SUBLINK and ARRAY_SUBLINK subplans, but for consistency
217  * we set it always.
218  */
219 static Oid
220 get_first_col_type(Plan *plan)
221 {
222         /* In cases such as EXISTS, tlist might be empty; arbitrarily use VOID */
223         if (plan->targetlist)
224         {
225                 TargetEntry *tent = (TargetEntry *) linitial(plan->targetlist);
226
227                 Assert(IsA(tent, TargetEntry));
228                 if (!tent->resjunk)
229                         return exprType((Node *) tent->expr);
230         }
231         return VOIDOID;
232 }
233
234 /*
235  * Convert a SubLink (as created by the parser) into a SubPlan.
236  *
237  * We are given the original SubLink and the already-processed testexpr
238  * (use this instead of the SubLink's own field).  We are also told if
239  * this expression appears at top level of a WHERE/HAVING qual.
240  *
241  * The result is whatever we need to substitute in place of the SubLink
242  * node in the executable expression.  This will be either the SubPlan
243  * node (if we have to do the subplan as a subplan), or a Param node
244  * representing the result of an InitPlan, or a row comparison expression
245  * tree containing InitPlan Param nodes.
246  */
247 static Node *
248 make_subplan(PlannerInfo *root, SubLink *slink, Node *testexpr, bool isTopQual)
249 {
250         Query      *subquery = (Query *) (slink->subselect);
251         double          tuple_fraction;
252         SubPlan    *splan;
253         Plan       *plan;
254         PlannerInfo *subroot;
255         bool            isInitPlan;
256         Bitmapset  *tmpset;
257         int                     paramid;
258         Node       *result;
259
260         /*
261          * Copy the source Query node.  This is a quick and dirty kluge to resolve
262          * the fact that the parser can generate trees with multiple links to the
263          * same sub-Query node, but the planner wants to scribble on the Query.
264          * Try to clean this up when we do querytree redesign...
265          */
266         subquery = (Query *) copyObject(subquery);
267
268         /*
269          * If it's an EXISTS subplan, we might be able to simplify it.
270          */
271         if (slink->subLinkType == EXISTS_SUBLINK)
272                 (void) simplify_EXISTS_query(subquery);
273
274         /*
275          * For an EXISTS subplan, tell lower-level planner to expect that only the
276          * first tuple will be retrieved.  For ALL and ANY subplans, we will be
277          * able to stop evaluating if the test condition fails, so very often not
278          * all the tuples will be retrieved; for lack of a better idea, specify
279          * 50% retrieval.  For EXPR and ROWCOMPARE subplans, use default behavior
280          * (we're only expecting one row out, anyway).
281          *
282          * NOTE: if you change these numbers, also change cost_qual_eval_walker()
283          * and get_initplan_cost() in path/costsize.c.
284          *
285          * XXX If an ALL/ANY subplan is uncorrelated, we may decide to hash or
286          * materialize its result below.  In that case it would've been better to
287          * specify full retrieval.      At present, however, we can only detect
288          * correlation or lack of it after we've made the subplan :-(. Perhaps
289          * detection of correlation should be done as a separate step. Meanwhile,
290          * we don't want to be too optimistic about the percentage of tuples
291          * retrieved, for fear of selecting a plan that's bad for the
292          * materialization case.
293          */
294         if (slink->subLinkType == EXISTS_SUBLINK)
295                 tuple_fraction = 1.0;   /* just like a LIMIT 1 */
296         else if (slink->subLinkType == ALL_SUBLINK ||
297                          slink->subLinkType == ANY_SUBLINK)
298                 tuple_fraction = 0.5;   /* 50% */
299         else
300                 tuple_fraction = 0.0;   /* default behavior */
301
302         /*
303          * Generate the plan for the subquery.
304          */
305         plan = subquery_planner(root->glob, subquery,
306                                                         root->query_level + 1,
307                                                         tuple_fraction,
308                                                         &subroot);
309
310         /*
311          * Initialize the SubPlan node.  Note plan_id isn't set yet.
312          */
313         splan = makeNode(SubPlan);
314         splan->subLinkType = slink->subLinkType;
315         splan->testexpr = NULL;
316         splan->paramIds = NIL;
317         splan->firstColType = get_first_col_type(plan);
318         splan->useHashTable = false;
319         /* At top level of a qual, can treat UNKNOWN the same as FALSE */
320         splan->unknownEqFalse = isTopQual;
321         splan->setParam = NIL;
322         splan->parParam = NIL;
323         splan->args = NIL;
324
325         /*
326          * Make parParam list of params that current query level will pass to this
327          * child plan.
328          */
329         tmpset = bms_copy(plan->extParam);
330         while ((paramid = bms_first_member(tmpset)) >= 0)
331         {
332                 PlannerParamItem *pitem = list_nth(root->glob->paramlist, paramid);
333
334                 if (pitem->abslevel == root->query_level)
335                         splan->parParam = lappend_int(splan->parParam, paramid);
336         }
337         bms_free(tmpset);
338
339         /*
340          * Un-correlated or undirect correlated plans of EXISTS, EXPR, ARRAY, or
341          * ROWCOMPARE types can be used as initPlans.  For EXISTS, EXPR, or ARRAY,
342          * we just produce a Param referring to the result of evaluating the
343          * initPlan.  For ROWCOMPARE, we must modify the testexpr tree to contain
344          * PARAM_EXEC Params instead of the PARAM_SUBLINK Params emitted by the
345          * parser.
346          */
347         if (splan->parParam == NIL && slink->subLinkType == EXISTS_SUBLINK)
348         {
349                 Param      *prm;
350
351                 prm = generate_new_param(root, BOOLOID, -1);
352                 splan->setParam = list_make1_int(prm->paramid);
353                 isInitPlan = true;
354                 result = (Node *) prm;
355         }
356         else if (splan->parParam == NIL && slink->subLinkType == EXPR_SUBLINK)
357         {
358                 TargetEntry *te = linitial(plan->targetlist);
359                 Param      *prm;
360
361                 Assert(!te->resjunk);
362                 prm = generate_new_param(root,
363                                                                  exprType((Node *) te->expr),
364                                                                  exprTypmod((Node *) te->expr));
365                 splan->setParam = list_make1_int(prm->paramid);
366                 isInitPlan = true;
367                 result = (Node *) prm;
368         }
369         else if (splan->parParam == NIL && slink->subLinkType == ARRAY_SUBLINK)
370         {
371                 TargetEntry *te = linitial(plan->targetlist);
372                 Oid                     arraytype;
373                 Param      *prm;
374
375                 Assert(!te->resjunk);
376                 arraytype = get_array_type(exprType((Node *) te->expr));
377                 if (!OidIsValid(arraytype))
378                         elog(ERROR, "could not find array type for datatype %s",
379                                  format_type_be(exprType((Node *) te->expr)));
380                 prm = generate_new_param(root,
381                                                                  arraytype,
382                                                                  exprTypmod((Node *) te->expr));
383                 splan->setParam = list_make1_int(prm->paramid);
384                 isInitPlan = true;
385                 result = (Node *) prm;
386         }
387         else if (splan->parParam == NIL && slink->subLinkType == ROWCOMPARE_SUBLINK)
388         {
389                 /* Adjust the Params */
390                 List       *params;
391
392                 params = generate_subquery_params(root,
393                                                                                   plan->targetlist,
394                                                                                   &splan->paramIds);
395                 result = convert_testexpr(root,
396                                                                   testexpr,
397                                                                   params);
398                 splan->setParam = list_copy(splan->paramIds);
399                 isInitPlan = true;
400
401                 /*
402                  * The executable expression is returned to become part of the outer
403                  * plan's expression tree; it is not kept in the initplan node.
404                  */
405         }
406         else
407         {
408                 List       *args;
409                 ListCell   *l;
410
411                 if (testexpr)
412                 {
413                         List       *params;
414
415                         /* Adjust the Params in the testexpr */
416                         params = generate_subquery_params(root,
417                                                                                           plan->targetlist,
418                                                                                           &splan->paramIds);
419                         splan->testexpr = convert_testexpr(root,
420                                                                                            testexpr,
421                                                                                            params);
422                 }
423
424                 /*
425                  * We can't convert subplans of ALL_SUBLINK or ANY_SUBLINK types to
426                  * initPlans, even when they are uncorrelated or undirect correlated,
427                  * because we need to scan the output of the subplan for each outer
428                  * tuple.  But if it's an IN (= ANY) test, we might be able to use a
429                  * hashtable to avoid comparing all the tuples.
430                  */
431                 if (subplan_is_hashable(slink, splan, plan))
432                         splan->useHashTable = true;
433
434                 /*
435                  * Otherwise, we have the option to tack a MATERIAL node onto the top
436                  * of the subplan, to reduce the cost of reading it repeatedly.  This
437                  * is pointless for a direct-correlated subplan, since we'd have to
438                  * recompute its results each time anyway.      For uncorrelated/undirect
439                  * correlated subplans, we add MATERIAL unless the subplan's top plan
440                  * node would materialize its output anyway.
441                  */
442                 else if (splan->parParam == NIL)
443                 {
444                         bool            use_material;
445
446                         switch (nodeTag(plan))
447                         {
448                                 case T_Material:
449                                 case T_FunctionScan:
450                                 case T_Sort:
451                                         use_material = false;
452                                         break;
453                                 default:
454                                         use_material = true;
455                                         break;
456                         }
457                         if (use_material)
458                                 plan = materialize_finished_plan(plan);
459                 }
460
461                 /*
462                  * Make splan->args from parParam.
463                  */
464                 args = NIL;
465                 foreach(l, splan->parParam)
466                 {
467                         PlannerParamItem *pitem = list_nth(root->glob->paramlist,
468                                                                                            lfirst_int(l));
469
470                         /*
471                          * The Var or Aggref has already been adjusted to have the correct
472                          * varlevelsup or agglevelsup.  We probably don't even need to
473                          * copy it again, but be safe.
474                          */
475                         args = lappend(args, copyObject(pitem->item));
476                 }
477                 splan->args = args;
478
479                 result = (Node *) splan;
480                 isInitPlan = false;
481         }
482
483         /*
484          * Add the subplan and its rtable to the global lists.
485          */
486         root->glob->subplans = lappend(root->glob->subplans,
487                                                                    plan);
488         root->glob->subrtables = lappend(root->glob->subrtables,
489                                                                          subroot->parse->rtable);
490         splan->plan_id = list_length(root->glob->subplans);
491
492         if (isInitPlan)
493                 root->init_plans = lappend(root->init_plans, splan);
494
495         /*
496          * A parameterless subplan (not initplan) should be prepared to handle
497          * REWIND efficiently.  If it has direct parameters then there's no point
498          * since it'll be reset on each scan anyway; and if it's an initplan then
499          * there's no point since it won't get re-run without parameter changes
500          * anyway.      The input of a hashed subplan doesn't need REWIND either.
501          */
502         if (splan->parParam == NIL && !isInitPlan && !splan->useHashTable)
503                 root->glob->rewindPlanIDs = bms_add_member(root->glob->rewindPlanIDs,
504                                                                                                    splan->plan_id);
505
506         return result;
507 }
508
509 /*
510  * generate_subquery_params: build a list of Params representing the output
511  * columns of a sublink's sub-select, given the sub-select's targetlist.
512  *
513  * We also return an integer list of the paramids of the Params.
514  */
515 static List *
516 generate_subquery_params(PlannerInfo *root, List *tlist, List **paramIds)
517 {
518         List       *result;
519         List       *ids;
520         ListCell   *lc;
521
522         result = ids = NIL;
523         foreach(lc, tlist)
524         {
525                 TargetEntry *tent = (TargetEntry *) lfirst(lc);
526                 Param      *param;
527
528                 if (tent->resjunk)
529                         continue;
530
531                 param = generate_new_param(root,
532                                                                    exprType((Node *) tent->expr),
533                                                                    exprTypmod((Node *) tent->expr));
534                 result = lappend(result, param);
535                 ids = lappend_int(ids, param->paramid);
536         }
537
538         *paramIds = ids;
539         return result;
540 }
541
542 /*
543  * generate_subquery_vars: build a list of Vars representing the output
544  * columns of a sublink's sub-select, given the sub-select's targetlist.
545  * The Vars have the specified varno (RTE index).
546  */
547 static List *
548 generate_subquery_vars(PlannerInfo *root, List *tlist, Index varno)
549 {
550         List       *result;
551         ListCell   *lc;
552
553         result = NIL;
554         foreach(lc, tlist)
555         {
556                 TargetEntry *tent = (TargetEntry *) lfirst(lc);
557                 Var                *var;
558
559                 if (tent->resjunk)
560                         continue;
561
562                 var = makeVar(varno,
563                                           tent->resno,
564                                           exprType((Node *) tent->expr),
565                                           exprTypmod((Node *) tent->expr),
566                                           0);
567                 result = lappend(result, var);
568         }
569
570         return result;
571 }
572
573 /*
574  * convert_testexpr: convert the testexpr given by the parser into
575  * actually executable form.  This entails replacing PARAM_SUBLINK Params
576  * with Params or Vars representing the results of the sub-select.  The
577  * nodes to be substituted are passed in as the List result from
578  * generate_subquery_params or generate_subquery_vars.
579  *
580  * The given testexpr has already been recursively processed by
581  * process_sublinks_mutator.  Hence it can no longer contain any
582  * PARAM_SUBLINK Params for lower SubLink nodes; we can safely assume that
583  * any we find are for our own level of SubLink.
584  */
585 static Node *
586 convert_testexpr(PlannerInfo *root,
587                                  Node *testexpr,
588                                  List *subst_nodes)
589 {
590         convert_testexpr_context context;
591
592         context.root = root;
593         context.subst_nodes = subst_nodes;
594         return convert_testexpr_mutator(testexpr, &context);
595 }
596
597 static Node *
598 convert_testexpr_mutator(Node *node,
599                                                  convert_testexpr_context *context)
600 {
601         if (node == NULL)
602                 return NULL;
603         if (IsA(node, Param))
604         {
605                 Param      *param = (Param *) node;
606
607                 if (param->paramkind == PARAM_SUBLINK)
608                 {
609                         if (param->paramid <= 0 ||
610                                 param->paramid > list_length(context->subst_nodes))
611                                 elog(ERROR, "unexpected PARAM_SUBLINK ID: %d", param->paramid);
612
613                         /*
614                          * We copy the list item to avoid having doubly-linked
615                          * substructure in the modified parse tree.  This is probably
616                          * unnecessary when it's a Param, but be safe.
617                          */
618                         return (Node *) copyObject(list_nth(context->subst_nodes,
619                                                                                                 param->paramid - 1));
620                 }
621         }
622         return expression_tree_mutator(node,
623                                                                    convert_testexpr_mutator,
624                                                                    (void *) context);
625 }
626
627 /*
628  * subplan_is_hashable: decide whether we can implement a subplan by hashing
629  *
630  * Caution: the SubPlan node is not completely filled in yet.  We can rely
631  * on its plan and parParam fields, however.
632  */
633 static bool
634 subplan_is_hashable(SubLink *slink, SubPlan *node, Plan *plan)
635 {
636         double          subquery_size;
637         ListCell   *l;
638
639         /*
640          * The sublink type must be "= ANY" --- that is, an IN operator.  We
641          * expect that the test expression will be either a single OpExpr, or an
642          * AND-clause containing OpExprs.  (If it's anything else then the parser
643          * must have determined that the operators have non-equality-like
644          * semantics.  In the OpExpr case we can't be sure what the operator's
645          * semantics are like, but the test below for hashability will reject
646          * anything that's not equality.)
647          */
648         if (slink->subLinkType != ANY_SUBLINK)
649                 return false;
650         if (slink->testexpr == NULL ||
651                 (!IsA(slink->testexpr, OpExpr) &&
652                  !and_clause(slink->testexpr)))
653                 return false;
654
655         /*
656          * The subplan must not have any direct correlation vars --- else we'd
657          * have to recompute its output each time, so that the hashtable wouldn't
658          * gain anything.
659          */
660         if (node->parParam != NIL)
661                 return false;
662
663         /*
664          * The estimated size of the subquery result must fit in work_mem. (Note:
665          * we use sizeof(HeapTupleHeaderData) here even though the tuples will
666          * actually be stored as MinimalTuples; this provides some fudge factor
667          * for hashtable overhead.)
668          */
669         subquery_size = plan->plan_rows *
670                 (MAXALIGN(plan->plan_width) + MAXALIGN(sizeof(HeapTupleHeaderData)));
671         if (subquery_size > work_mem * 1024L)
672                 return false;
673
674         /*
675          * The combining operators must be hashable and strict. The need for
676          * hashability is obvious, since we want to use hashing. Without
677          * strictness, behavior in the presence of nulls is too unpredictable.  We
678          * actually must assume even more than plain strictness: they can't yield
679          * NULL for non-null inputs, either (see nodeSubplan.c).  However, hash
680          * indexes and hash joins assume that too.
681          */
682         if (IsA(slink->testexpr, OpExpr))
683         {
684                 if (!hash_ok_operator((OpExpr *) slink->testexpr))
685                         return false;
686         }
687         else
688         {
689                 foreach(l, ((BoolExpr *) slink->testexpr)->args)
690                 {
691                         Node       *andarg = (Node *) lfirst(l);
692
693                         if (!IsA(andarg, OpExpr))
694                                 return false;   /* probably can't happen */
695                         if (!hash_ok_operator((OpExpr *) andarg))
696                                 return false;
697                 }
698         }
699
700         return true;
701 }
702
703 static bool
704 hash_ok_operator(OpExpr *expr)
705 {
706         Oid                     opid = expr->opno;
707         HeapTuple       tup;
708         Form_pg_operator optup;
709
710         tup = SearchSysCache(OPEROID,
711                                                  ObjectIdGetDatum(opid),
712                                                  0, 0, 0);
713         if (!HeapTupleIsValid(tup))
714                 elog(ERROR, "cache lookup failed for operator %u", opid);
715         optup = (Form_pg_operator) GETSTRUCT(tup);
716         if (!optup->oprcanhash || !func_strict(optup->oprcode))
717         {
718                 ReleaseSysCache(tup);
719                 return false;
720         }
721         ReleaseSysCache(tup);
722         return true;
723 }
724
725 /*
726  * convert_ANY_sublink_to_join: can we convert an ANY SubLink to a join?
727  *
728  * The caller has found an ANY SubLink at the top level of WHERE, but has not
729  * checked the properties of the SubLink further.  Decide whether it is
730  * appropriate to process this SubLink in join style.  If not, return NULL.
731  * If so, build the qual clause(s) to replace the SubLink, and return them.
732  * The qual clauses are wrapped in a FlattenedSubLink node to help later
733  * processing place them properly.
734  *
735  * Side effects of a successful conversion include adding the SubLink's
736  * subselect to the query's rangetable.
737  */
738 Node *
739 convert_ANY_sublink_to_join(PlannerInfo *root, SubLink *sublink)
740 {
741         Query      *parse = root->parse;
742         Query      *subselect = (Query *) sublink->subselect;
743         Relids          left_varnos;
744         int                     rtindex;
745         RangeTblEntry *rte;
746         RangeTblRef *rtr;
747         List       *subquery_vars;
748         Expr       *quals;
749         FlattenedSubLink *fslink;
750
751         Assert(sublink->subLinkType == ANY_SUBLINK);
752
753         /*
754          * The sub-select must not refer to any Vars of the parent query. (Vars of
755          * higher levels should be okay, though.)
756          */
757         if (contain_vars_of_level((Node *) subselect, 1))
758                 return NULL;
759
760         /*
761          * The test expression must contain some Vars of the current query,
762          * else it's not gonna be a join.  (Note that it won't have Vars
763          * referring to the subquery, rather Params.)
764          */
765         left_varnos = pull_varnos(sublink->testexpr);
766         if (bms_is_empty(left_varnos))
767                 return NULL;
768
769         /*
770          * The combining operators and left-hand expressions mustn't be volatile.
771          */
772         if (contain_volatile_functions(sublink->testexpr))
773                 return NULL;
774
775         /*
776          * Okay, pull up the sub-select into top range table and jointree.
777          *
778          * We rely here on the assumption that the outer query has no references
779          * to the inner (necessarily true, other than the Vars that we build
780          * below). Therefore this is a lot easier than what pull_up_subqueries has
781          * to go through.
782          */
783         rte = addRangeTableEntryForSubquery(NULL,
784                                                                                 subselect,
785                                                                                 makeAlias("ANY_subquery", NIL),
786                                                                                 false);
787         parse->rtable = lappend(parse->rtable, rte);
788         rtindex = list_length(parse->rtable);
789         rtr = makeNode(RangeTblRef);
790         rtr->rtindex = rtindex;
791
792         /*
793          * We assume it's okay to add the pulled-up subquery to the topmost FROM
794          * list.  This should be all right for ANY clauses appearing in WHERE
795          * or in upper-level plain JOIN/ON clauses.  ANYs appearing below any
796          * outer joins couldn't be placed there, however.
797          */
798         parse->jointree->fromlist = lappend(parse->jointree->fromlist, rtr);
799
800         /*
801          * Build a list of Vars representing the subselect outputs.
802          */
803         subquery_vars = generate_subquery_vars(root,
804                                                                                    subselect->targetList,
805                                                                                    rtindex);
806
807         /*
808          * Build the result qual expression, replacing Params with these Vars.
809          */
810         quals = (Expr *) convert_testexpr(root,
811                                                                           sublink->testexpr,
812                                                                           subquery_vars);
813
814         /*
815          * Now build the FlattenedSubLink node.
816          */
817         fslink = makeNode(FlattenedSubLink);
818         fslink->jointype = JOIN_SEMI;
819         fslink->lefthand = left_varnos;
820         fslink->righthand = bms_make_singleton(rtindex);
821         fslink->quals = quals;
822
823         return (Node *) fslink;
824 }
825
826 /*
827  * simplify_EXISTS_query: remove any useless stuff in an EXISTS's subquery
828  *
829  * The only thing that matters about an EXISTS query is whether it returns
830  * zero or more than zero rows.  Therefore, we can remove certain SQL features
831  * that won't affect that.  The only part that is really likely to matter in
832  * typical usage is simplifying the targetlist: it's a common habit to write
833  * "SELECT * FROM" even though there is no need to evaluate any columns.
834  *
835  * Note: by suppressing the targetlist we could cause an observable behavioral
836  * change, namely that any errors that might occur in evaluating the tlist
837  * won't occur, nor will other side-effects of volatile functions.  This seems
838  * unlikely to bother anyone in practice.
839  *
840  * Returns TRUE if was able to discard the targetlist, else FALSE.
841  */
842 static bool
843 simplify_EXISTS_query(Query *query)
844 {
845         /*
846          * We don't try to simplify at all if the query uses set operations,
847          * aggregates, HAVING, LIMIT/OFFSET, or FOR UPDATE/SHARE; none of these
848          * seem likely in normal usage and their possible effects are complex.
849          */
850         if (query->commandType != CMD_SELECT ||
851                 query->intoClause ||
852                 query->setOperations ||
853                 query->hasAggs ||
854                 query->havingQual ||
855                 query->limitOffset ||
856                 query->limitCount ||
857                 query->rowMarks)
858                 return false;
859
860         /*
861          * Mustn't throw away the targetlist if it contains set-returning
862          * functions; those could affect whether zero rows are returned!
863          */
864         if (expression_returns_set((Node *) query->targetList))
865                 return false;
866
867         /*
868          * Otherwise, we can throw away the targetlist, as well as any GROUP,
869          * DISTINCT, and ORDER BY clauses; none of those clauses will change
870          * a nonzero-rows result to zero rows or vice versa.  (Furthermore,
871          * since our parsetree representation of these clauses depends on the
872          * targetlist, we'd better throw them away if we drop the targetlist.)
873          */
874         query->targetList = NIL;
875         query->groupClause = NIL;
876         query->distinctClause = NIL;
877         query->sortClause = NIL;
878         query->hasDistinctOn = false;
879
880         return true;
881 }
882
883 /*
884  * convert_EXISTS_sublink_to_join: can we convert an EXISTS SubLink to a join?
885  *
886  * The caller has found an EXISTS SubLink at the top level of WHERE, or just
887  * underneath a NOT, but has not checked the properties of the SubLink
888  * further.  Decide whether it is appropriate to process this SubLink in join
889  * style.  If not, return NULL.  If so, build the qual clause(s) to replace
890  * the SubLink, and return them.  (In the NOT case, the returned clauses are
891  * intended to replace the NOT as well.)  The qual clauses are wrapped in a
892  * FlattenedSubLink node to help later processing place them properly.
893  *
894  * Side effects of a successful conversion include adding the SubLink's
895  * subselect to the query's rangetable.
896  */
897 Node *
898 convert_EXISTS_sublink_to_join(PlannerInfo *root, SubLink *sublink,
899                                                            bool under_not)
900 {
901         Query      *parse = root->parse;
902         Query      *subselect = (Query *) sublink->subselect;
903         Node       *whereClause;
904         int                     rtoffset;
905         int                     varno;
906         Relids          clause_varnos;
907         Relids          left_varnos;
908         Relids          right_varnos;
909         Relids          subselect_varnos;
910         FlattenedSubLink *fslink;
911
912         Assert(sublink->subLinkType == EXISTS_SUBLINK);
913
914         /*
915          * Copy the subquery so we can modify it safely (see comments in
916          * make_subplan).
917          */
918         subselect = (Query *) copyObject(subselect);
919
920         /*
921          * See if the subquery can be simplified based on the knowledge that
922          * it's being used in EXISTS().  If we aren't able to get rid of its
923          * targetlist, we have to fail, because the pullup operation leaves
924          * us with noplace to evaluate the targetlist.
925          */
926         if (!simplify_EXISTS_query(subselect))
927                 return NULL;
928
929         /*
930          * Separate out the WHERE clause.  (We could theoretically also remove
931          * top-level plain JOIN/ON clauses, but it's probably not worth the
932          * trouble.)
933          */
934         whereClause = subselect->jointree->quals;
935         subselect->jointree->quals = NULL;
936
937         /*
938          * The rest of the sub-select must not refer to any Vars of the parent
939          * query.  (Vars of higher levels should be okay, though.)
940          */
941         if (contain_vars_of_level((Node *) subselect, 1))
942                 return NULL;
943
944         /*
945          * On the other hand, the WHERE clause must contain some Vars of the
946          * parent query, else it's not gonna be a join.
947          */
948         if (!contain_vars_of_level(whereClause, 1))
949                 return NULL;
950
951         /*
952          * We don't risk optimizing if the WHERE clause is volatile, either.
953          */
954         if (contain_volatile_functions(whereClause))
955                 return NULL;
956
957         /*
958          * Also disallow SubLinks within the WHERE clause.  (XXX this could
959          * probably be supported, but it would complicate the transformation
960          * below, and it doesn't seem worth worrying about in a first pass.)
961          */
962         if (contain_subplans(whereClause))
963                 return NULL;
964
965         /*
966          * Okay, pull up the sub-select into top range table and jointree.
967          *
968          * We rely here on the assumption that the outer query has no references
969          * to the inner (necessarily true). Therefore this is a lot easier than
970          * what pull_up_subqueries has to go through.
971          *
972          * In fact, it's even easier than what convert_ANY_sublink_to_join has
973          * to do.  The machinations of simplify_EXISTS_query ensured that there
974          * is nothing interesting in the subquery except an rtable and jointree,
975          * and even the jointree FromExpr no longer has quals.  So we can just
976          * append the rtable to our own and append the fromlist to our own.
977          * But first, adjust all level-zero varnos in the subquery to account
978          * for the rtable merger.
979          */
980         rtoffset = list_length(parse->rtable);
981         OffsetVarNodes((Node *) subselect, rtoffset, 0);
982         OffsetVarNodes(whereClause, rtoffset, 0);
983
984         /*
985          * Upper-level vars in subquery will now be one level closer to their
986          * parent than before; in particular, anything that had been level 1
987          * becomes level zero.
988          */
989         IncrementVarSublevelsUp((Node *) subselect, -1, 1);
990         IncrementVarSublevelsUp(whereClause, -1, 1);
991
992         /*
993          * Now that the WHERE clause is adjusted to match the parent query
994          * environment, we can easily identify all the level-zero rels it uses.
995          * The ones <= rtoffset are "left rels" of the join we're forming,
996          * and the ones > rtoffset are "right rels".
997          */
998         clause_varnos = pull_varnos(whereClause);
999         left_varnos = right_varnos = NULL;
1000         while ((varno = bms_first_member(clause_varnos)) >= 0)
1001         {
1002                 if (varno <= rtoffset)
1003                         left_varnos = bms_add_member(left_varnos, varno);
1004                 else
1005                         right_varnos = bms_add_member(right_varnos, varno);
1006         }
1007         bms_free(clause_varnos);
1008         Assert(!bms_is_empty(left_varnos));
1009
1010         /* Also identify all the rels syntactically within the subselect */
1011         subselect_varnos = get_relids_in_jointree((Node *) subselect->jointree);
1012         Assert(bms_is_subset(right_varnos, subselect_varnos));
1013
1014         /* Now we can attach the modified subquery rtable to the parent */
1015         parse->rtable = list_concat(parse->rtable, subselect->rtable);
1016
1017         /*
1018          * We assume it's okay to add the pulled-up subquery to the topmost FROM
1019          * list.  This should be all right for EXISTS clauses appearing in WHERE
1020          * or in upper-level plain JOIN/ON clauses.  EXISTS appearing below any
1021          * outer joins couldn't be placed there, however.
1022          */
1023         parse->jointree->fromlist = list_concat(parse->jointree->fromlist,
1024                                                                                         subselect->jointree->fromlist);
1025
1026         /*
1027          * Now build the FlattenedSubLink node.
1028          */
1029         fslink = makeNode(FlattenedSubLink);
1030         fslink->jointype = under_not ? JOIN_ANTI : JOIN_SEMI;
1031         fslink->lefthand = left_varnos;
1032         fslink->righthand = subselect_varnos;
1033         fslink->quals = (Expr *) whereClause;
1034
1035         return (Node *) fslink;
1036 }
1037
1038 /*
1039  * Replace correlation vars (uplevel vars) with Params.
1040  *
1041  * Uplevel aggregates are replaced, too.
1042  *
1043  * Note: it is critical that this runs immediately after SS_process_sublinks.
1044  * Since we do not recurse into the arguments of uplevel aggregates, they will
1045  * get copied to the appropriate subplan args list in the parent query with
1046  * uplevel vars not replaced by Params, but only adjusted in level (see
1047  * replace_outer_agg).  That's exactly what we want for the vars of the parent
1048  * level --- but if an aggregate's argument contains any further-up variables,
1049  * they have to be replaced with Params in their turn.  That will happen when
1050  * the parent level runs SS_replace_correlation_vars.  Therefore it must do
1051  * so after expanding its sublinks to subplans.  And we don't want any steps
1052  * in between, else those steps would never get applied to the aggregate
1053  * argument expressions, either in the parent or the child level.
1054  */
1055 Node *
1056 SS_replace_correlation_vars(PlannerInfo *root, Node *expr)
1057 {
1058         /* No setup needed for tree walk, so away we go */
1059         return replace_correlation_vars_mutator(expr, root);
1060 }
1061
1062 static Node *
1063 replace_correlation_vars_mutator(Node *node, PlannerInfo *root)
1064 {
1065         if (node == NULL)
1066                 return NULL;
1067         if (IsA(node, Var))
1068         {
1069                 if (((Var *) node)->varlevelsup > 0)
1070                         return (Node *) replace_outer_var(root, (Var *) node);
1071         }
1072         if (IsA(node, Aggref))
1073         {
1074                 if (((Aggref *) node)->agglevelsup > 0)
1075                         return (Node *) replace_outer_agg(root, (Aggref *) node);
1076         }
1077         return expression_tree_mutator(node,
1078                                                                    replace_correlation_vars_mutator,
1079                                                                    (void *) root);
1080 }
1081
1082 /*
1083  * Expand SubLinks to SubPlans in the given expression.
1084  *
1085  * The isQual argument tells whether or not this expression is a WHERE/HAVING
1086  * qualifier expression.  If it is, any sublinks appearing at top level need
1087  * not distinguish FALSE from UNKNOWN return values.
1088  */
1089 Node *
1090 SS_process_sublinks(PlannerInfo *root, Node *expr, bool isQual)
1091 {
1092         process_sublinks_context context;
1093
1094         context.root = root;
1095         context.isTopQual = isQual;
1096         return process_sublinks_mutator(expr, &context);
1097 }
1098
1099 static Node *
1100 process_sublinks_mutator(Node *node, process_sublinks_context *context)
1101 {
1102         process_sublinks_context locContext;
1103
1104         locContext.root = context->root;
1105
1106         if (node == NULL)
1107                 return NULL;
1108         if (IsA(node, SubLink))
1109         {
1110                 SubLink    *sublink = (SubLink *) node;
1111                 Node       *testexpr;
1112
1113                 /*
1114                  * First, recursively process the lefthand-side expressions, if any.
1115                  * They're not top-level anymore.
1116                  */
1117                 locContext.isTopQual = false;
1118                 testexpr = process_sublinks_mutator(sublink->testexpr, &locContext);
1119
1120                 /*
1121                  * Now build the SubPlan node and make the expr to return.
1122                  */
1123                 return make_subplan(context->root,
1124                                                         sublink,
1125                                                         testexpr,
1126                                                         context->isTopQual);
1127         }
1128
1129         /*
1130          * We should never see a SubPlan expression in the input (since this is
1131          * the very routine that creates 'em to begin with).  We shouldn't find
1132          * ourselves invoked directly on a Query, either.
1133          */
1134         Assert(!is_subplan(node));
1135         Assert(!IsA(node, Query));
1136
1137         /*
1138          * Because make_subplan() could return an AND or OR clause, we have to
1139          * take steps to preserve AND/OR flatness of a qual.  We assume the input
1140          * has been AND/OR flattened and so we need no recursion here.
1141          *
1142          * If we recurse down through anything other than an AND node, we are
1143          * definitely not at top qual level anymore.  (Due to the coding here, we
1144          * will not get called on the List subnodes of an AND, so no check is
1145          * needed for List.)
1146          */
1147         if (and_clause(node))
1148         {
1149                 List       *newargs = NIL;
1150                 ListCell   *l;
1151
1152                 /* Still at qual top-level */
1153                 locContext.isTopQual = context->isTopQual;
1154
1155                 foreach(l, ((BoolExpr *) node)->args)
1156                 {
1157                         Node       *newarg;
1158
1159                         newarg = process_sublinks_mutator(lfirst(l), &locContext);
1160                         if (and_clause(newarg))
1161                                 newargs = list_concat(newargs, ((BoolExpr *) newarg)->args);
1162                         else
1163                                 newargs = lappend(newargs, newarg);
1164                 }
1165                 return (Node *) make_andclause(newargs);
1166         }
1167
1168         /* otherwise not at qual top-level */
1169         locContext.isTopQual = false;
1170
1171         if (or_clause(node))
1172         {
1173                 List       *newargs = NIL;
1174                 ListCell   *l;
1175
1176                 foreach(l, ((BoolExpr *) node)->args)
1177                 {
1178                         Node       *newarg;
1179
1180                         newarg = process_sublinks_mutator(lfirst(l), &locContext);
1181                         if (or_clause(newarg))
1182                                 newargs = list_concat(newargs, ((BoolExpr *) newarg)->args);
1183                         else
1184                                 newargs = lappend(newargs, newarg);
1185                 }
1186                 return (Node *) make_orclause(newargs);
1187         }
1188
1189         return expression_tree_mutator(node,
1190                                                                    process_sublinks_mutator,
1191                                                                    (void *) &locContext);
1192 }
1193
1194 /*
1195  * SS_finalize_plan - do final sublink processing for a completed Plan.
1196  *
1197  * This recursively computes the extParam and allParam sets for every Plan
1198  * node in the given plan tree.  It also optionally attaches any previously
1199  * generated InitPlans to the top plan node.  (Any InitPlans should already
1200  * have been put through SS_finalize_plan.)
1201  */
1202 void
1203 SS_finalize_plan(PlannerInfo *root, Plan *plan, bool attach_initplans)
1204 {
1205         Bitmapset  *valid_params,
1206                            *initExtParam,
1207                            *initSetParam;
1208         Cost            initplan_cost;
1209         int                     paramid;
1210         ListCell   *l;
1211
1212         /*
1213          * Examine any initPlans to determine the set of external params they
1214          * reference, the set of output params they supply, and their total cost.
1215          * We'll use at least some of this info below.  (Note we are assuming that
1216          * finalize_plan doesn't touch the initPlans.)
1217          *
1218          * In the case where attach_initplans is false, we are assuming that the
1219          * existing initPlans are siblings that might supply params needed by the
1220          * current plan.
1221          */
1222         initExtParam = initSetParam = NULL;
1223         initplan_cost = 0;
1224         foreach(l, root->init_plans)
1225         {
1226                 SubPlan    *initsubplan = (SubPlan *) lfirst(l);
1227                 Plan       *initplan = planner_subplan_get_plan(root, initsubplan);
1228                 ListCell   *l2;
1229
1230                 initExtParam = bms_add_members(initExtParam, initplan->extParam);
1231                 foreach(l2, initsubplan->setParam)
1232                 {
1233                         initSetParam = bms_add_member(initSetParam, lfirst_int(l2));
1234                 }
1235                 initplan_cost += get_initplan_cost(root, initsubplan);
1236         }
1237
1238         /*
1239          * Now determine the set of params that are validly referenceable in this
1240          * query level; to wit, those available from outer query levels plus the
1241          * output parameters of any initPlans.  (We do not include output
1242          * parameters of regular subplans.  Those should only appear within the
1243          * testexpr of SubPlan nodes, and are taken care of locally within
1244          * finalize_primnode.)
1245          *
1246          * Note: this is a bit overly generous since some parameters of upper
1247          * query levels might belong to query subtrees that don't include this
1248          * query.  However, valid_params is only a debugging crosscheck, so it
1249          * doesn't seem worth expending lots of cycles to try to be exact.
1250          */
1251         valid_params = bms_copy(initSetParam);
1252         paramid = 0;
1253         foreach(l, root->glob->paramlist)
1254         {
1255                 PlannerParamItem *pitem = (PlannerParamItem *) lfirst(l);
1256
1257                 if (pitem->abslevel < root->query_level)
1258                 {
1259                         /* valid outer-level parameter */
1260                         valid_params = bms_add_member(valid_params, paramid);
1261                 }
1262
1263                 paramid++;
1264         }
1265
1266         /*
1267          * Now recurse through plan tree.
1268          */
1269         (void) finalize_plan(root, plan, valid_params);
1270
1271         bms_free(valid_params);
1272
1273         /*
1274          * Finally, attach any initPlans to the topmost plan node, and add their
1275          * extParams to the topmost node's, too.  However, any setParams of the
1276          * initPlans should not be present in the topmost node's extParams, only
1277          * in its allParams.  (As of PG 8.1, it's possible that some initPlans
1278          * have extParams that are setParams of other initPlans, so we have to
1279          * take care of this situation explicitly.)
1280          *
1281          * We also add the eval cost of each initPlan to the startup cost of the
1282          * top node.  This is a conservative overestimate, since in fact each
1283          * initPlan might be executed later than plan startup, or even not at all.
1284          */
1285         if (attach_initplans)
1286         {
1287                 plan->initPlan = root->init_plans;
1288                 root->init_plans = NIL;         /* make sure they're not attached twice */
1289
1290                 /* allParam must include all these params */
1291                 plan->allParam = bms_add_members(plan->allParam, initExtParam);
1292                 plan->allParam = bms_add_members(plan->allParam, initSetParam);
1293                 /* extParam must include any child extParam */
1294                 plan->extParam = bms_add_members(plan->extParam, initExtParam);
1295                 /* but extParam shouldn't include any setParams */
1296                 plan->extParam = bms_del_members(plan->extParam, initSetParam);
1297                 /* ensure extParam is exactly NULL if it's empty */
1298                 if (bms_is_empty(plan->extParam))
1299                         plan->extParam = NULL;
1300
1301                 plan->startup_cost += initplan_cost;
1302                 plan->total_cost += initplan_cost;
1303         }
1304 }
1305
1306 /*
1307  * Recursive processing of all nodes in the plan tree
1308  *
1309  * The return value is the computed allParam set for the given Plan node.
1310  * This is just an internal notational convenience.
1311  */
1312 static Bitmapset *
1313 finalize_plan(PlannerInfo *root, Plan *plan, Bitmapset *valid_params)
1314 {
1315         finalize_primnode_context context;
1316
1317         if (plan == NULL)
1318                 return NULL;
1319
1320         context.root = root;
1321         context.paramids = NULL;        /* initialize set to empty */
1322
1323         /*
1324          * When we call finalize_primnode, context.paramids sets are automatically
1325          * merged together.  But when recursing to self, we have to do it the hard
1326          * way.  We want the paramids set to include params in subplans as well as
1327          * at this level.
1328          */
1329
1330         /* Find params in targetlist and qual */
1331         finalize_primnode((Node *) plan->targetlist, &context);
1332         finalize_primnode((Node *) plan->qual, &context);
1333
1334         /* Check additional node-type-specific fields */
1335         switch (nodeTag(plan))
1336         {
1337                 case T_Result:
1338                         finalize_primnode(((Result *) plan)->resconstantqual,
1339                                                           &context);
1340                         break;
1341
1342                 case T_IndexScan:
1343                         finalize_primnode((Node *) ((IndexScan *) plan)->indexqual,
1344                                                           &context);
1345
1346                         /*
1347                          * we need not look at indexqualorig, since it will have the same
1348                          * param references as indexqual.
1349                          */
1350                         break;
1351
1352                 case T_BitmapIndexScan:
1353                         finalize_primnode((Node *) ((BitmapIndexScan *) plan)->indexqual,
1354                                                           &context);
1355
1356                         /*
1357                          * we need not look at indexqualorig, since it will have the same
1358                          * param references as indexqual.
1359                          */
1360                         break;
1361
1362                 case T_BitmapHeapScan:
1363                         finalize_primnode((Node *) ((BitmapHeapScan *) plan)->bitmapqualorig,
1364                                                           &context);
1365                         break;
1366
1367                 case T_TidScan:
1368                         finalize_primnode((Node *) ((TidScan *) plan)->tidquals,
1369                                                           &context);
1370                         break;
1371
1372                 case T_SubqueryScan:
1373
1374                         /*
1375                          * In a SubqueryScan, SS_finalize_plan has already been run on the
1376                          * subplan by the inner invocation of subquery_planner, so there's
1377                          * no need to do it again.      Instead, just pull out the subplan's
1378                          * extParams list, which represents the params it needs from my
1379                          * level and higher levels.
1380                          */
1381                         context.paramids = bms_add_members(context.paramids,
1382                                                                  ((SubqueryScan *) plan)->subplan->extParam);
1383                         break;
1384
1385                 case T_FunctionScan:
1386                         finalize_primnode(((FunctionScan *) plan)->funcexpr,
1387                                                           &context);
1388                         break;
1389
1390                 case T_ValuesScan:
1391                         finalize_primnode((Node *) ((ValuesScan *) plan)->values_lists,
1392                                                           &context);
1393                         break;
1394
1395                 case T_Append:
1396                         {
1397                                 ListCell   *l;
1398
1399                                 foreach(l, ((Append *) plan)->appendplans)
1400                                 {
1401                                         context.paramids =
1402                                                 bms_add_members(context.paramids,
1403                                                                                 finalize_plan(root,
1404                                                                                                           (Plan *) lfirst(l),
1405                                                                                                           valid_params));
1406                                 }
1407                         }
1408                         break;
1409
1410                 case T_BitmapAnd:
1411                         {
1412                                 ListCell   *l;
1413
1414                                 foreach(l, ((BitmapAnd *) plan)->bitmapplans)
1415                                 {
1416                                         context.paramids =
1417                                                 bms_add_members(context.paramids,
1418                                                                                 finalize_plan(root,
1419                                                                                                           (Plan *) lfirst(l),
1420                                                                                                           valid_params));
1421                                 }
1422                         }
1423                         break;
1424
1425                 case T_BitmapOr:
1426                         {
1427                                 ListCell   *l;
1428
1429                                 foreach(l, ((BitmapOr *) plan)->bitmapplans)
1430                                 {
1431                                         context.paramids =
1432                                                 bms_add_members(context.paramids,
1433                                                                                 finalize_plan(root,
1434                                                                                                           (Plan *) lfirst(l),
1435                                                                                                           valid_params));
1436                                 }
1437                         }
1438                         break;
1439
1440                 case T_NestLoop:
1441                         finalize_primnode((Node *) ((Join *) plan)->joinqual,
1442                                                           &context);
1443                         break;
1444
1445                 case T_MergeJoin:
1446                         finalize_primnode((Node *) ((Join *) plan)->joinqual,
1447                                                           &context);
1448                         finalize_primnode((Node *) ((MergeJoin *) plan)->mergeclauses,
1449                                                           &context);
1450                         break;
1451
1452                 case T_HashJoin:
1453                         finalize_primnode((Node *) ((Join *) plan)->joinqual,
1454                                                           &context);
1455                         finalize_primnode((Node *) ((HashJoin *) plan)->hashclauses,
1456                                                           &context);
1457                         break;
1458
1459                 case T_Limit:
1460                         finalize_primnode(((Limit *) plan)->limitOffset,
1461                                                           &context);
1462                         finalize_primnode(((Limit *) plan)->limitCount,
1463                                                           &context);
1464                         break;
1465
1466                 case T_Hash:
1467                 case T_Agg:
1468                 case T_SeqScan:
1469                 case T_Material:
1470                 case T_Sort:
1471                 case T_Unique:
1472                 case T_SetOp:
1473                 case T_Group:
1474                         break;
1475
1476                 default:
1477                         elog(ERROR, "unrecognized node type: %d",
1478                                  (int) nodeTag(plan));
1479         }
1480
1481         /* Process left and right child plans, if any */
1482         context.paramids = bms_add_members(context.paramids,
1483                                                                            finalize_plan(root,
1484                                                                                                          plan->lefttree,
1485                                                                                                          valid_params));
1486
1487         context.paramids = bms_add_members(context.paramids,
1488                                                                            finalize_plan(root,
1489                                                                                                          plan->righttree,
1490                                                                                                          valid_params));
1491
1492         /* Now we have all the paramids */
1493
1494         if (!bms_is_subset(context.paramids, valid_params))
1495                 elog(ERROR, "plan should not reference subplan's variable");
1496
1497         /*
1498          * Note: by definition, extParam and allParam should have the same value
1499          * in any plan node that doesn't have child initPlans.  We set them
1500          * equal here, and later SS_finalize_plan will update them properly
1501          * in node(s) that it attaches initPlans to.
1502          *
1503          * For speed at execution time, make sure extParam/allParam are actually
1504          * NULL if they are empty sets.
1505          */
1506         if (bms_is_empty(context.paramids))
1507         {
1508                 plan->extParam = NULL;
1509                 plan->allParam = NULL;
1510         }
1511         else
1512         {
1513                 plan->extParam = context.paramids;
1514                 plan->allParam = bms_copy(context.paramids);
1515         }
1516
1517         return plan->allParam;
1518 }
1519
1520 /*
1521  * finalize_primnode: add IDs of all PARAM_EXEC params appearing in the given
1522  * expression tree to the result set.
1523  */
1524 static bool
1525 finalize_primnode(Node *node, finalize_primnode_context *context)
1526 {
1527         if (node == NULL)
1528                 return false;
1529         if (IsA(node, Param))
1530         {
1531                 if (((Param *) node)->paramkind == PARAM_EXEC)
1532                 {
1533                         int                     paramid = ((Param *) node)->paramid;
1534
1535                         context->paramids = bms_add_member(context->paramids, paramid);
1536                 }
1537                 return false;                   /* no more to do here */
1538         }
1539         if (is_subplan(node))
1540         {
1541                 SubPlan    *subplan = (SubPlan *) node;
1542                 Plan       *plan = planner_subplan_get_plan(context->root, subplan);
1543                 ListCell   *lc;
1544                 Bitmapset  *subparamids;
1545
1546                 /* Recurse into the testexpr, but not into the Plan */
1547                 finalize_primnode(subplan->testexpr, context);
1548
1549                 /*
1550                  * Remove any param IDs of output parameters of the subplan that were
1551                  * referenced in the testexpr.  These are not interesting for
1552                  * parameter change signaling since we always re-evaluate the subplan.
1553                  * Note that this wouldn't work too well if there might be uses of the
1554                  * same param IDs elsewhere in the plan, but that can't happen because
1555                  * generate_new_param never tries to merge params.
1556                  */
1557                 foreach(lc, subplan->paramIds)
1558                 {
1559                         context->paramids = bms_del_member(context->paramids,
1560                                                                                            lfirst_int(lc));
1561                 }
1562
1563                 /* Also examine args list */
1564                 finalize_primnode((Node *) subplan->args, context);
1565
1566                 /*
1567                  * Add params needed by the subplan to paramids, but excluding those
1568                  * we will pass down to it.
1569                  */
1570                 subparamids = bms_copy(plan->extParam);
1571                 foreach(lc, subplan->parParam)
1572                 {
1573                         subparamids = bms_del_member(subparamids, lfirst_int(lc));
1574                 }
1575                 context->paramids = bms_join(context->paramids, subparamids);
1576
1577                 return false;                   /* no more to do here */
1578         }
1579         return expression_tree_walker(node, finalize_primnode,
1580                                                                   (void *) context);
1581 }
1582
1583 /*
1584  * SS_make_initplan_from_plan - given a plan tree, make it an InitPlan
1585  *
1586  * The plan is expected to return a scalar value of the indicated type.
1587  * We build an EXPR_SUBLINK SubPlan node and put it into the initplan
1588  * list for the current query level.  A Param that represents the initplan's
1589  * output is returned.
1590  *
1591  * We assume the plan hasn't been put through SS_finalize_plan.
1592  */
1593 Param *
1594 SS_make_initplan_from_plan(PlannerInfo *root, Plan *plan,
1595                                                    Oid resulttype, int32 resulttypmod)
1596 {
1597         SubPlan    *node;
1598         Param      *prm;
1599
1600         /*
1601          * We must run SS_finalize_plan(), since that's normally done before a
1602          * subplan gets put into the initplan list.  Tell it not to attach any
1603          * pre-existing initplans to this one, since they are siblings not
1604          * children of this initplan.  (This is something else that could perhaps
1605          * be cleaner if we did extParam/allParam processing in setrefs.c instead
1606          * of here?  See notes for materialize_finished_plan.)
1607          */
1608
1609         /*
1610          * Build extParam/allParam sets for plan nodes.
1611          */
1612         SS_finalize_plan(root, plan, false);
1613
1614         /*
1615          * Add the subplan and its rtable to the global lists.
1616          */
1617         root->glob->subplans = lappend(root->glob->subplans,
1618                                                                    plan);
1619         root->glob->subrtables = lappend(root->glob->subrtables,
1620                                                                          root->parse->rtable);
1621
1622         /*
1623          * Create a SubPlan node and add it to the outer list of InitPlans.
1624          * Note it has to appear after any other InitPlans it might depend on
1625          * (see comments in ExecReScan).
1626          */
1627         node = makeNode(SubPlan);
1628         node->subLinkType = EXPR_SUBLINK;
1629         node->firstColType = get_first_col_type(plan);
1630         node->plan_id = list_length(root->glob->subplans);
1631
1632         root->init_plans = lappend(root->init_plans, node);
1633
1634         /*
1635          * The node can't have any inputs (since it's an initplan), so the
1636          * parParam and args lists remain empty.
1637          */
1638
1639         /*
1640          * Make a Param that will be the subplan's output.
1641          */
1642         prm = generate_new_param(root, resulttype, resulttypmod);
1643         node->setParam = list_make1_int(prm->paramid);
1644
1645         return prm;
1646 }