1 /*-------------------------------------------------------------------------
4 * Planning routines for subselects and parameters.
6 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
10 * $PostgreSQL: pgsql/src/backend/optimizer/plan/subselect.c,v 1.137 2008/08/20 19:58:24 tgl Exp $
12 *-------------------------------------------------------------------------
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"
36 typedef struct convert_testexpr_context
39 List *subst_nodes; /* Nodes to substitute for Params */
40 } convert_testexpr_context;
42 typedef struct process_sublinks_context
46 } process_sublinks_context;
48 typedef struct finalize_primnode_context
51 Bitmapset *paramids; /* Non-local PARAM_EXEC paramids found */
52 } finalize_primnode_context;
55 static List *generate_subquery_params(PlannerInfo *root, List *tlist,
57 static List *generate_subquery_vars(PlannerInfo *root, List *tlist,
59 static Node *convert_testexpr(PlannerInfo *root,
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,
72 Bitmapset *valid_params);
73 static bool finalize_primnode(Node *node, finalize_primnode_context *context);
77 * Generate a Param node to replace the given Var,
78 * which is expected to have varlevelsup > 0 (ie, it is not local).
81 replace_outer_var(PlannerInfo *root, Var *var)
85 PlannerParamItem *pitem;
89 Assert(var->varlevelsup > 0 && var->varlevelsup < root->query_level);
90 abslevel = root->query_level - var->varlevelsup;
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/typmod as well, I believe that
98 * this sort of aliasing will cause no trouble. The correct field should
99 * get stored into the Param slot at execution in each part of the tree.
102 foreach(ppl, root->glob->paramlist)
104 pitem = (PlannerParamItem *) lfirst(ppl);
105 if (pitem->abslevel == abslevel && IsA(pitem->item, Var))
107 Var *pvar = (Var *) pitem->item;
109 if (pvar->varno == var->varno &&
110 pvar->varattno == var->varattno &&
111 pvar->vartype == var->vartype &&
112 pvar->vartypmod == var->vartypmod)
120 /* Nope, so make a new one */
121 var = (Var *) copyObject(var);
122 var->varlevelsup = 0;
124 pitem = makeNode(PlannerParamItem);
125 pitem->item = (Node *) var;
126 pitem->abslevel = abslevel;
128 root->glob->paramlist = lappend(root->glob->paramlist, pitem);
129 /* i is already the correct index for the new item */
132 retval = makeNode(Param);
133 retval->paramkind = PARAM_EXEC;
135 retval->paramtype = var->vartype;
136 retval->paramtypmod = var->vartypmod;
142 * Generate a Param node to replace the given Aggref
143 * which is expected to have agglevelsup > 0 (ie, it is not local).
146 replace_outer_agg(PlannerInfo *root, Aggref *agg)
149 PlannerParamItem *pitem;
153 Assert(agg->agglevelsup > 0 && agg->agglevelsup < root->query_level);
154 abslevel = root->query_level - agg->agglevelsup;
157 * It does not seem worthwhile to try to match duplicate outer aggs. Just
158 * make a new slot every time.
160 agg = (Aggref *) copyObject(agg);
161 IncrementVarSublevelsUp((Node *) agg, -((int) agg->agglevelsup), 0);
162 Assert(agg->agglevelsup == 0);
164 pitem = makeNode(PlannerParamItem);
165 pitem->item = (Node *) agg;
166 pitem->abslevel = abslevel;
168 root->glob->paramlist = lappend(root->glob->paramlist, pitem);
169 i = list_length(root->glob->paramlist) - 1;
171 retval = makeNode(Param);
172 retval->paramkind = PARAM_EXEC;
174 retval->paramtype = agg->aggtype;
175 retval->paramtypmod = -1;
181 * Generate a new Param node that will not conflict with any other.
183 * This is used to allocate PARAM_EXEC slots for subplan outputs.
186 generate_new_param(PlannerInfo *root, Oid paramtype, int32 paramtypmod)
189 PlannerParamItem *pitem;
191 retval = makeNode(Param);
192 retval->paramkind = PARAM_EXEC;
193 retval->paramid = list_length(root->glob->paramlist);
194 retval->paramtype = paramtype;
195 retval->paramtypmod = paramtypmod;
197 pitem = makeNode(PlannerParamItem);
198 pitem->item = (Node *) retval;
199 pitem->abslevel = root->query_level;
201 root->glob->paramlist = lappend(root->glob->paramlist, pitem);
207 * Get the datatype of the first column of the plan's output.
209 * This is stored for ARRAY_SUBLINK and for exprType(), which doesn't have any
210 * way to get at the plan associated with a SubPlan node. We really only need
211 * the value for EXPR_SUBLINK and ARRAY_SUBLINK subplans, but for consistency
215 get_first_col_type(Plan *plan)
217 /* In cases such as EXISTS, tlist might be empty; arbitrarily use VOID */
218 if (plan->targetlist)
220 TargetEntry *tent = (TargetEntry *) linitial(plan->targetlist);
222 Assert(IsA(tent, TargetEntry));
224 return exprType((Node *) tent->expr);
230 * Convert a SubLink (as created by the parser) into a SubPlan.
232 * We are given the original SubLink and the already-processed testexpr
233 * (use this instead of the SubLink's own field). We are also told if
234 * this expression appears at top level of a WHERE/HAVING qual.
236 * The result is whatever we need to substitute in place of the SubLink
237 * node in the executable expression. This will be either the SubPlan
238 * node (if we have to do the subplan as a subplan), or a Param node
239 * representing the result of an InitPlan, or a row comparison expression
240 * tree containing InitPlan Param nodes.
243 make_subplan(PlannerInfo *root, SubLink *slink, Node *testexpr, bool isTopQual)
245 Query *subquery = (Query *) (slink->subselect);
246 double tuple_fraction;
249 PlannerInfo *subroot;
256 * Copy the source Query node. This is a quick and dirty kluge to resolve
257 * the fact that the parser can generate trees with multiple links to the
258 * same sub-Query node, but the planner wants to scribble on the Query.
259 * Try to clean this up when we do querytree redesign...
261 subquery = (Query *) copyObject(subquery);
264 * If it's an EXISTS subplan, we might be able to simplify it.
266 if (slink->subLinkType == EXISTS_SUBLINK)
267 (void) simplify_EXISTS_query(subquery);
270 * For an EXISTS subplan, tell lower-level planner to expect that only the
271 * first tuple will be retrieved. For ALL and ANY subplans, we will be
272 * able to stop evaluating if the test condition fails, so very often not
273 * all the tuples will be retrieved; for lack of a better idea, specify
274 * 50% retrieval. For EXPR and ROWCOMPARE subplans, use default behavior
275 * (we're only expecting one row out, anyway).
277 * NOTE: if you change these numbers, also change cost_qual_eval_walker()
278 * and get_initplan_cost() in path/costsize.c.
280 * XXX If an ALL/ANY subplan is uncorrelated, we may decide to hash or
281 * materialize its result below. In that case it would've been better to
282 * specify full retrieval. At present, however, we can only detect
283 * correlation or lack of it after we've made the subplan :-(. Perhaps
284 * detection of correlation should be done as a separate step. Meanwhile,
285 * we don't want to be too optimistic about the percentage of tuples
286 * retrieved, for fear of selecting a plan that's bad for the
287 * materialization case.
289 if (slink->subLinkType == EXISTS_SUBLINK)
290 tuple_fraction = 1.0; /* just like a LIMIT 1 */
291 else if (slink->subLinkType == ALL_SUBLINK ||
292 slink->subLinkType == ANY_SUBLINK)
293 tuple_fraction = 0.5; /* 50% */
295 tuple_fraction = 0.0; /* default behavior */
298 * Generate the plan for the subquery.
300 plan = subquery_planner(root->glob, subquery,
301 root->query_level + 1,
306 * Initialize the SubPlan node. Note plan_id isn't set yet.
308 splan = makeNode(SubPlan);
309 splan->subLinkType = slink->subLinkType;
310 splan->testexpr = NULL;
311 splan->paramIds = NIL;
312 splan->firstColType = get_first_col_type(plan);
313 splan->useHashTable = false;
314 /* At top level of a qual, can treat UNKNOWN the same as FALSE */
315 splan->unknownEqFalse = isTopQual;
316 splan->setParam = NIL;
317 splan->parParam = NIL;
321 * Make parParam list of params that current query level will pass to this
324 tmpset = bms_copy(plan->extParam);
325 while ((paramid = bms_first_member(tmpset)) >= 0)
327 PlannerParamItem *pitem = list_nth(root->glob->paramlist, paramid);
329 if (pitem->abslevel == root->query_level)
330 splan->parParam = lappend_int(splan->parParam, paramid);
335 * Un-correlated or undirect correlated plans of EXISTS, EXPR, ARRAY, or
336 * ROWCOMPARE types can be used as initPlans. For EXISTS, EXPR, or ARRAY,
337 * we just produce a Param referring to the result of evaluating the
338 * initPlan. For ROWCOMPARE, we must modify the testexpr tree to contain
339 * PARAM_EXEC Params instead of the PARAM_SUBLINK Params emitted by the
342 if (splan->parParam == NIL && slink->subLinkType == EXISTS_SUBLINK)
346 prm = generate_new_param(root, BOOLOID, -1);
347 splan->setParam = list_make1_int(prm->paramid);
349 result = (Node *) prm;
351 else if (splan->parParam == NIL && slink->subLinkType == EXPR_SUBLINK)
353 TargetEntry *te = linitial(plan->targetlist);
356 Assert(!te->resjunk);
357 prm = generate_new_param(root,
358 exprType((Node *) te->expr),
359 exprTypmod((Node *) te->expr));
360 splan->setParam = list_make1_int(prm->paramid);
362 result = (Node *) prm;
364 else if (splan->parParam == NIL && slink->subLinkType == ARRAY_SUBLINK)
366 TargetEntry *te = linitial(plan->targetlist);
370 Assert(!te->resjunk);
371 arraytype = get_array_type(exprType((Node *) te->expr));
372 if (!OidIsValid(arraytype))
373 elog(ERROR, "could not find array type for datatype %s",
374 format_type_be(exprType((Node *) te->expr)));
375 prm = generate_new_param(root,
377 exprTypmod((Node *) te->expr));
378 splan->setParam = list_make1_int(prm->paramid);
380 result = (Node *) prm;
382 else if (splan->parParam == NIL && slink->subLinkType == ROWCOMPARE_SUBLINK)
384 /* Adjust the Params */
387 params = generate_subquery_params(root,
390 result = convert_testexpr(root,
393 splan->setParam = list_copy(splan->paramIds);
397 * The executable expression is returned to become part of the outer
398 * plan's expression tree; it is not kept in the initplan node.
410 /* Adjust the Params in the testexpr */
411 params = generate_subquery_params(root,
414 splan->testexpr = convert_testexpr(root,
420 * We can't convert subplans of ALL_SUBLINK or ANY_SUBLINK types to
421 * initPlans, even when they are uncorrelated or undirect correlated,
422 * because we need to scan the output of the subplan for each outer
423 * tuple. But if it's an IN (= ANY) test, we might be able to use a
424 * hashtable to avoid comparing all the tuples.
426 if (subplan_is_hashable(slink, splan, plan))
427 splan->useHashTable = true;
430 * Otherwise, we have the option to tack a MATERIAL node onto the top
431 * of the subplan, to reduce the cost of reading it repeatedly. This
432 * is pointless for a direct-correlated subplan, since we'd have to
433 * recompute its results each time anyway. For uncorrelated/undirect
434 * correlated subplans, we add MATERIAL unless the subplan's top plan
435 * node would materialize its output anyway.
437 else if (splan->parParam == NIL)
441 switch (nodeTag(plan))
446 use_material = false;
453 plan = materialize_finished_plan(plan);
457 * Make splan->args from parParam.
460 foreach(l, splan->parParam)
462 PlannerParamItem *pitem = list_nth(root->glob->paramlist,
466 * The Var or Aggref has already been adjusted to have the correct
467 * varlevelsup or agglevelsup. We probably don't even need to
468 * copy it again, but be safe.
470 args = lappend(args, copyObject(pitem->item));
474 result = (Node *) splan;
479 * Add the subplan and its rtable to the global lists.
481 root->glob->subplans = lappend(root->glob->subplans,
483 root->glob->subrtables = lappend(root->glob->subrtables,
484 subroot->parse->rtable);
485 splan->plan_id = list_length(root->glob->subplans);
488 root->init_plans = lappend(root->init_plans, splan);
491 * A parameterless subplan (not initplan) should be prepared to handle
492 * REWIND efficiently. If it has direct parameters then there's no point
493 * since it'll be reset on each scan anyway; and if it's an initplan then
494 * there's no point since it won't get re-run without parameter changes
495 * anyway. The input of a hashed subplan doesn't need REWIND either.
497 if (splan->parParam == NIL && !isInitPlan && !splan->useHashTable)
498 root->glob->rewindPlanIDs = bms_add_member(root->glob->rewindPlanIDs,
505 * generate_subquery_params: build a list of Params representing the output
506 * columns of a sublink's sub-select, given the sub-select's targetlist.
508 * We also return an integer list of the paramids of the Params.
511 generate_subquery_params(PlannerInfo *root, List *tlist, List **paramIds)
520 TargetEntry *tent = (TargetEntry *) lfirst(lc);
526 param = generate_new_param(root,
527 exprType((Node *) tent->expr),
528 exprTypmod((Node *) tent->expr));
529 result = lappend(result, param);
530 ids = lappend_int(ids, param->paramid);
538 * generate_subquery_vars: build a list of Vars representing the output
539 * columns of a sublink's sub-select, given the sub-select's targetlist.
540 * The Vars have the specified varno (RTE index).
543 generate_subquery_vars(PlannerInfo *root, List *tlist, Index varno)
551 TargetEntry *tent = (TargetEntry *) lfirst(lc);
559 exprType((Node *) tent->expr),
560 exprTypmod((Node *) tent->expr),
562 result = lappend(result, var);
569 * convert_testexpr: convert the testexpr given by the parser into
570 * actually executable form. This entails replacing PARAM_SUBLINK Params
571 * with Params or Vars representing the results of the sub-select. The
572 * nodes to be substituted are passed in as the List result from
573 * generate_subquery_params or generate_subquery_vars.
575 * The given testexpr has already been recursively processed by
576 * process_sublinks_mutator. Hence it can no longer contain any
577 * PARAM_SUBLINK Params for lower SubLink nodes; we can safely assume that
578 * any we find are for our own level of SubLink.
581 convert_testexpr(PlannerInfo *root,
585 convert_testexpr_context context;
588 context.subst_nodes = subst_nodes;
589 return convert_testexpr_mutator(testexpr, &context);
593 convert_testexpr_mutator(Node *node,
594 convert_testexpr_context *context)
598 if (IsA(node, Param))
600 Param *param = (Param *) node;
602 if (param->paramkind == PARAM_SUBLINK)
604 if (param->paramid <= 0 ||
605 param->paramid > list_length(context->subst_nodes))
606 elog(ERROR, "unexpected PARAM_SUBLINK ID: %d", param->paramid);
609 * We copy the list item to avoid having doubly-linked
610 * substructure in the modified parse tree. This is probably
611 * unnecessary when it's a Param, but be safe.
613 return (Node *) copyObject(list_nth(context->subst_nodes,
614 param->paramid - 1));
617 return expression_tree_mutator(node,
618 convert_testexpr_mutator,
623 * subplan_is_hashable: decide whether we can implement a subplan by hashing
625 * Caution: the SubPlan node is not completely filled in yet. We can rely
626 * on its plan and parParam fields, however.
629 subplan_is_hashable(SubLink *slink, SubPlan *node, Plan *plan)
631 double subquery_size;
635 * The sublink type must be "= ANY" --- that is, an IN operator. We
636 * expect that the test expression will be either a single OpExpr, or an
637 * AND-clause containing OpExprs. (If it's anything else then the parser
638 * must have determined that the operators have non-equality-like
639 * semantics. In the OpExpr case we can't be sure what the operator's
640 * semantics are like, but the test below for hashability will reject
641 * anything that's not equality.)
643 if (slink->subLinkType != ANY_SUBLINK)
645 if (slink->testexpr == NULL ||
646 (!IsA(slink->testexpr, OpExpr) &&
647 !and_clause(slink->testexpr)))
651 * The subplan must not have any direct correlation vars --- else we'd
652 * have to recompute its output each time, so that the hashtable wouldn't
655 if (node->parParam != NIL)
659 * The estimated size of the subquery result must fit in work_mem. (Note:
660 * we use sizeof(HeapTupleHeaderData) here even though the tuples will
661 * actually be stored as MinimalTuples; this provides some fudge factor
662 * for hashtable overhead.)
664 subquery_size = plan->plan_rows *
665 (MAXALIGN(plan->plan_width) + MAXALIGN(sizeof(HeapTupleHeaderData)));
666 if (subquery_size > work_mem * 1024L)
670 * The combining operators must be hashable and strict. The need for
671 * hashability is obvious, since we want to use hashing. Without
672 * strictness, behavior in the presence of nulls is too unpredictable. We
673 * actually must assume even more than plain strictness: they can't yield
674 * NULL for non-null inputs, either (see nodeSubplan.c). However, hash
675 * indexes and hash joins assume that too.
677 if (IsA(slink->testexpr, OpExpr))
679 if (!hash_ok_operator((OpExpr *) slink->testexpr))
684 foreach(l, ((BoolExpr *) slink->testexpr)->args)
686 Node *andarg = (Node *) lfirst(l);
688 if (!IsA(andarg, OpExpr))
689 return false; /* probably can't happen */
690 if (!hash_ok_operator((OpExpr *) andarg))
699 hash_ok_operator(OpExpr *expr)
701 Oid opid = expr->opno;
703 Form_pg_operator optup;
705 tup = SearchSysCache(OPEROID,
706 ObjectIdGetDatum(opid),
708 if (!HeapTupleIsValid(tup))
709 elog(ERROR, "cache lookup failed for operator %u", opid);
710 optup = (Form_pg_operator) GETSTRUCT(tup);
711 if (!optup->oprcanhash || !func_strict(optup->oprcode))
713 ReleaseSysCache(tup);
716 ReleaseSysCache(tup);
721 * convert_ANY_sublink_to_join: can we convert an ANY SubLink to a join?
723 * The caller has found an ANY SubLink at the top level of one of the query's
724 * qual clauses, but has not checked the properties of the SubLink further.
725 * Decide whether it is appropriate to process this SubLink in join style.
726 * Return TRUE if so, FALSE if the SubLink cannot be converted.
728 * The only non-obvious input parameter is available_rels: this is the set
729 * of query rels that can safely be referenced in the sublink expression.
730 * (We must restrict this to avoid changing the semantics when a sublink
731 * is present in an outer join's ON qual.) The conversion must fail if
732 * the converted qual would reference any but these parent-query relids.
734 * On success, two output parameters are returned:
735 * *new_qual is set to the qual tree that should replace the SubLink in
736 * the parent query's qual tree. The qual clauses are wrapped in a
737 * FlattenedSubLink node to help later processing place them properly.
738 * *fromlist is set to a list of pulled-up jointree item(s) that must be
739 * added at the proper spot in the parent query's jointree.
741 * Side effects of a successful conversion include adding the SubLink's
742 * subselect to the query's rangetable.
745 convert_ANY_sublink_to_join(PlannerInfo *root, SubLink *sublink,
746 Relids available_rels,
747 Node **new_qual, List **fromlist)
749 Query *parse = root->parse;
750 Query *subselect = (Query *) sublink->subselect;
757 FlattenedSubLink *fslink;
759 Assert(sublink->subLinkType == ANY_SUBLINK);
762 * The sub-select must not refer to any Vars of the parent query. (Vars of
763 * higher levels should be okay, though.)
765 if (contain_vars_of_level((Node *) subselect, 1))
769 * The test expression must contain some Vars of the current query,
770 * else it's not gonna be a join. (Note that it won't have Vars
771 * referring to the subquery, rather Params.)
773 left_varnos = pull_varnos(sublink->testexpr);
774 if (bms_is_empty(left_varnos))
778 * However, it can't refer to anything outside available_rels.
780 if (!bms_is_subset(left_varnos, available_rels))
784 * The combining operators and left-hand expressions mustn't be volatile.
786 if (contain_volatile_functions(sublink->testexpr))
790 * Okay, pull up the sub-select into upper range table.
792 * We rely here on the assumption that the outer query has no references
793 * to the inner (necessarily true, other than the Vars that we build
794 * below). Therefore this is a lot easier than what pull_up_subqueries has
797 rte = addRangeTableEntryForSubquery(NULL,
799 makeAlias("ANY_subquery", NIL),
801 parse->rtable = lappend(parse->rtable, rte);
802 rtindex = list_length(parse->rtable);
805 * Form a RangeTblRef for the pulled-up sub-select. This must be added
806 * to the upper jointree, but it is caller's responsibility to figure
809 rtr = makeNode(RangeTblRef);
810 rtr->rtindex = rtindex;
811 *fromlist = list_make1(rtr);
814 * Build a list of Vars representing the subselect outputs.
816 subquery_vars = generate_subquery_vars(root,
817 subselect->targetList,
821 * Build the replacement qual expression, replacing Params with these Vars.
823 quals = (Expr *) convert_testexpr(root,
828 * And finally, build the FlattenedSubLink node.
830 fslink = makeNode(FlattenedSubLink);
831 fslink->jointype = JOIN_SEMI;
832 fslink->lefthand = left_varnos;
833 fslink->righthand = bms_make_singleton(rtindex);
834 fslink->quals = quals;
836 *new_qual = (Node *) fslink;
842 * simplify_EXISTS_query: remove any useless stuff in an EXISTS's subquery
844 * The only thing that matters about an EXISTS query is whether it returns
845 * zero or more than zero rows. Therefore, we can remove certain SQL features
846 * that won't affect that. The only part that is really likely to matter in
847 * typical usage is simplifying the targetlist: it's a common habit to write
848 * "SELECT * FROM" even though there is no need to evaluate any columns.
850 * Note: by suppressing the targetlist we could cause an observable behavioral
851 * change, namely that any errors that might occur in evaluating the tlist
852 * won't occur, nor will other side-effects of volatile functions. This seems
853 * unlikely to bother anyone in practice.
855 * Returns TRUE if was able to discard the targetlist, else FALSE.
858 simplify_EXISTS_query(Query *query)
861 * We don't try to simplify at all if the query uses set operations,
862 * aggregates, HAVING, LIMIT/OFFSET, or FOR UPDATE/SHARE; none of these
863 * seem likely in normal usage and their possible effects are complex.
865 if (query->commandType != CMD_SELECT ||
867 query->setOperations ||
870 query->limitOffset ||
876 * Mustn't throw away the targetlist if it contains set-returning
877 * functions; those could affect whether zero rows are returned!
879 if (expression_returns_set((Node *) query->targetList))
883 * Otherwise, we can throw away the targetlist, as well as any GROUP,
884 * DISTINCT, and ORDER BY clauses; none of those clauses will change
885 * a nonzero-rows result to zero rows or vice versa. (Furthermore,
886 * since our parsetree representation of these clauses depends on the
887 * targetlist, we'd better throw them away if we drop the targetlist.)
889 query->targetList = NIL;
890 query->groupClause = NIL;
891 query->distinctClause = NIL;
892 query->sortClause = NIL;
893 query->hasDistinctOn = false;
899 * convert_EXISTS_sublink_to_join: can we convert an EXISTS SubLink to a join?
901 * The API of this function is identical to convert_ANY_sublink_to_join's,
902 * except that we also support the case where the caller has found NOT EXISTS,
903 * so we need an additional input parameter "under_not".
906 convert_EXISTS_sublink_to_join(PlannerInfo *root, SubLink *sublink,
908 Relids available_rels,
909 Node **new_qual, List **fromlist)
911 Query *parse = root->parse;
912 Query *subselect = (Query *) sublink->subselect;
916 Relids clause_varnos;
919 Relids subselect_varnos;
920 FlattenedSubLink *fslink;
922 Assert(sublink->subLinkType == EXISTS_SUBLINK);
925 * Copy the subquery so we can modify it safely (see comments in
928 subselect = (Query *) copyObject(subselect);
931 * See if the subquery can be simplified based on the knowledge that
932 * it's being used in EXISTS(). If we aren't able to get rid of its
933 * targetlist, we have to fail, because the pullup operation leaves
934 * us with noplace to evaluate the targetlist.
936 if (!simplify_EXISTS_query(subselect))
940 * Separate out the WHERE clause. (We could theoretically also remove
941 * top-level plain JOIN/ON clauses, but it's probably not worth the
944 whereClause = subselect->jointree->quals;
945 subselect->jointree->quals = NULL;
948 * The rest of the sub-select must not refer to any Vars of the parent
949 * query. (Vars of higher levels should be okay, though.)
951 if (contain_vars_of_level((Node *) subselect, 1))
955 * On the other hand, the WHERE clause must contain some Vars of the
956 * parent query, else it's not gonna be a join.
958 if (!contain_vars_of_level(whereClause, 1))
962 * We don't risk optimizing if the WHERE clause is volatile, either.
964 if (contain_volatile_functions(whereClause))
968 * Prepare to pull up the sub-select into top range table.
970 * We rely here on the assumption that the outer query has no references
971 * to the inner (necessarily true). Therefore this is a lot easier than
972 * what pull_up_subqueries has to go through.
974 * In fact, it's even easier than what convert_ANY_sublink_to_join has
975 * to do. The machinations of simplify_EXISTS_query ensured that there
976 * is nothing interesting in the subquery except an rtable and jointree,
977 * and even the jointree FromExpr no longer has quals. So we can just
978 * append the rtable to our own and attach the fromlist to our own.
979 * But first, adjust all level-zero varnos in the subquery to account
980 * for the rtable merger.
982 rtoffset = list_length(parse->rtable);
983 OffsetVarNodes((Node *) subselect, rtoffset, 0);
984 OffsetVarNodes(whereClause, rtoffset, 0);
987 * Upper-level vars in subquery will now be one level closer to their
988 * parent than before; in particular, anything that had been level 1
989 * becomes level zero.
991 IncrementVarSublevelsUp((Node *) subselect, -1, 1);
992 IncrementVarSublevelsUp(whereClause, -1, 1);
995 * Now that the WHERE clause is adjusted to match the parent query
996 * environment, we can easily identify all the level-zero rels it uses.
997 * The ones <= rtoffset are "left rels" of the join we're forming,
998 * and the ones > rtoffset are "right rels".
1000 clause_varnos = pull_varnos(whereClause);
1001 left_varnos = right_varnos = NULL;
1002 while ((varno = bms_first_member(clause_varnos)) >= 0)
1004 if (varno <= rtoffset)
1005 left_varnos = bms_add_member(left_varnos, varno);
1007 right_varnos = bms_add_member(right_varnos, varno);
1009 bms_free(clause_varnos);
1010 Assert(!bms_is_empty(left_varnos));
1013 * Now that we've got the set of upper-level varnos, we can make the
1014 * last check: only available_rels can be referenced.
1016 if (!bms_is_subset(left_varnos, available_rels))
1019 /* Identify all the rels syntactically within the subselect */
1020 subselect_varnos = get_relids_in_jointree((Node *) subselect->jointree,
1022 Assert(bms_is_subset(right_varnos, subselect_varnos));
1024 /* Now we can attach the modified subquery rtable to the parent */
1025 parse->rtable = list_concat(parse->rtable, subselect->rtable);
1028 * Pass back the subquery fromlist to be attached to upper jointree
1029 * in a suitable place.
1031 *fromlist = subselect->jointree->fromlist;
1034 * And finally, build the FlattenedSubLink node.
1036 fslink = makeNode(FlattenedSubLink);
1037 fslink->jointype = under_not ? JOIN_ANTI : JOIN_SEMI;
1038 fslink->lefthand = left_varnos;
1039 fslink->righthand = subselect_varnos;
1040 fslink->quals = (Expr *) whereClause;
1042 *new_qual = (Node *) fslink;
1048 * Replace correlation vars (uplevel vars) with Params.
1050 * Uplevel aggregates are replaced, too.
1052 * Note: it is critical that this runs immediately after SS_process_sublinks.
1053 * Since we do not recurse into the arguments of uplevel aggregates, they will
1054 * get copied to the appropriate subplan args list in the parent query with
1055 * uplevel vars not replaced by Params, but only adjusted in level (see
1056 * replace_outer_agg). That's exactly what we want for the vars of the parent
1057 * level --- but if an aggregate's argument contains any further-up variables,
1058 * they have to be replaced with Params in their turn. That will happen when
1059 * the parent level runs SS_replace_correlation_vars. Therefore it must do
1060 * so after expanding its sublinks to subplans. And we don't want any steps
1061 * in between, else those steps would never get applied to the aggregate
1062 * argument expressions, either in the parent or the child level.
1065 SS_replace_correlation_vars(PlannerInfo *root, Node *expr)
1067 /* No setup needed for tree walk, so away we go */
1068 return replace_correlation_vars_mutator(expr, root);
1072 replace_correlation_vars_mutator(Node *node, PlannerInfo *root)
1078 if (((Var *) node)->varlevelsup > 0)
1079 return (Node *) replace_outer_var(root, (Var *) node);
1081 if (IsA(node, Aggref))
1083 if (((Aggref *) node)->agglevelsup > 0)
1084 return (Node *) replace_outer_agg(root, (Aggref *) node);
1086 return expression_tree_mutator(node,
1087 replace_correlation_vars_mutator,
1092 * Expand SubLinks to SubPlans in the given expression.
1094 * The isQual argument tells whether or not this expression is a WHERE/HAVING
1095 * qualifier expression. If it is, any sublinks appearing at top level need
1096 * not distinguish FALSE from UNKNOWN return values.
1099 SS_process_sublinks(PlannerInfo *root, Node *expr, bool isQual)
1101 process_sublinks_context context;
1103 context.root = root;
1104 context.isTopQual = isQual;
1105 return process_sublinks_mutator(expr, &context);
1109 process_sublinks_mutator(Node *node, process_sublinks_context *context)
1111 process_sublinks_context locContext;
1113 locContext.root = context->root;
1117 if (IsA(node, SubLink))
1119 SubLink *sublink = (SubLink *) node;
1123 * First, recursively process the lefthand-side expressions, if any.
1124 * They're not top-level anymore.
1126 locContext.isTopQual = false;
1127 testexpr = process_sublinks_mutator(sublink->testexpr, &locContext);
1130 * Now build the SubPlan node and make the expr to return.
1132 return make_subplan(context->root,
1135 context->isTopQual);
1139 * We should never see a SubPlan expression in the input (since this is
1140 * the very routine that creates 'em to begin with). We shouldn't find
1141 * ourselves invoked directly on a Query, either.
1143 Assert(!is_subplan(node));
1144 Assert(!IsA(node, Query));
1147 * Because make_subplan() could return an AND or OR clause, we have to
1148 * take steps to preserve AND/OR flatness of a qual. We assume the input
1149 * has been AND/OR flattened and so we need no recursion here.
1151 * (Due to the coding here, we will not get called on the List subnodes of
1152 * an AND; and the input is *not* yet in implicit-AND format. So no check
1153 * is needed for a bare List.)
1155 * Anywhere within the top-level AND/OR clause structure, we can tell
1156 * make_subplan() that NULL and FALSE are interchangeable. So isTopQual
1157 * propagates down in both cases. (Note that this is unlike the meaning
1158 * of "top level qual" used in most other places in Postgres.)
1160 if (and_clause(node))
1162 List *newargs = NIL;
1165 /* Still at qual top-level */
1166 locContext.isTopQual = context->isTopQual;
1168 foreach(l, ((BoolExpr *) node)->args)
1172 newarg = process_sublinks_mutator(lfirst(l), &locContext);
1173 if (and_clause(newarg))
1174 newargs = list_concat(newargs, ((BoolExpr *) newarg)->args);
1176 newargs = lappend(newargs, newarg);
1178 return (Node *) make_andclause(newargs);
1181 if (or_clause(node))
1183 List *newargs = NIL;
1186 /* Still at qual top-level */
1187 locContext.isTopQual = context->isTopQual;
1189 foreach(l, ((BoolExpr *) node)->args)
1193 newarg = process_sublinks_mutator(lfirst(l), &locContext);
1194 if (or_clause(newarg))
1195 newargs = list_concat(newargs, ((BoolExpr *) newarg)->args);
1197 newargs = lappend(newargs, newarg);
1199 return (Node *) make_orclause(newargs);
1203 * If we recurse down through anything other than an AND or OR node,
1204 * we are definitely not at top qual level anymore.
1206 locContext.isTopQual = false;
1208 return expression_tree_mutator(node,
1209 process_sublinks_mutator,
1210 (void *) &locContext);
1214 * SS_finalize_plan - do final sublink processing for a completed Plan.
1216 * This recursively computes the extParam and allParam sets for every Plan
1217 * node in the given plan tree. It also optionally attaches any previously
1218 * generated InitPlans to the top plan node. (Any InitPlans should already
1219 * have been put through SS_finalize_plan.)
1222 SS_finalize_plan(PlannerInfo *root, Plan *plan, bool attach_initplans)
1224 Bitmapset *valid_params,
1232 * Examine any initPlans to determine the set of external params they
1233 * reference, the set of output params they supply, and their total cost.
1234 * We'll use at least some of this info below. (Note we are assuming that
1235 * finalize_plan doesn't touch the initPlans.)
1237 * In the case where attach_initplans is false, we are assuming that the
1238 * existing initPlans are siblings that might supply params needed by the
1241 initExtParam = initSetParam = NULL;
1243 foreach(l, root->init_plans)
1245 SubPlan *initsubplan = (SubPlan *) lfirst(l);
1246 Plan *initplan = planner_subplan_get_plan(root, initsubplan);
1249 initExtParam = bms_add_members(initExtParam, initplan->extParam);
1250 foreach(l2, initsubplan->setParam)
1252 initSetParam = bms_add_member(initSetParam, lfirst_int(l2));
1254 initplan_cost += get_initplan_cost(root, initsubplan);
1258 * Now determine the set of params that are validly referenceable in this
1259 * query level; to wit, those available from outer query levels plus the
1260 * output parameters of any initPlans. (We do not include output
1261 * parameters of regular subplans. Those should only appear within the
1262 * testexpr of SubPlan nodes, and are taken care of locally within
1263 * finalize_primnode.)
1265 * Note: this is a bit overly generous since some parameters of upper
1266 * query levels might belong to query subtrees that don't include this
1267 * query. However, valid_params is only a debugging crosscheck, so it
1268 * doesn't seem worth expending lots of cycles to try to be exact.
1270 valid_params = bms_copy(initSetParam);
1272 foreach(l, root->glob->paramlist)
1274 PlannerParamItem *pitem = (PlannerParamItem *) lfirst(l);
1276 if (pitem->abslevel < root->query_level)
1278 /* valid outer-level parameter */
1279 valid_params = bms_add_member(valid_params, paramid);
1286 * Now recurse through plan tree.
1288 (void) finalize_plan(root, plan, valid_params);
1290 bms_free(valid_params);
1293 * Finally, attach any initPlans to the topmost plan node, and add their
1294 * extParams to the topmost node's, too. However, any setParams of the
1295 * initPlans should not be present in the topmost node's extParams, only
1296 * in its allParams. (As of PG 8.1, it's possible that some initPlans
1297 * have extParams that are setParams of other initPlans, so we have to
1298 * take care of this situation explicitly.)
1300 * We also add the eval cost of each initPlan to the startup cost of the
1301 * top node. This is a conservative overestimate, since in fact each
1302 * initPlan might be executed later than plan startup, or even not at all.
1304 if (attach_initplans)
1306 plan->initPlan = root->init_plans;
1307 root->init_plans = NIL; /* make sure they're not attached twice */
1309 /* allParam must include all these params */
1310 plan->allParam = bms_add_members(plan->allParam, initExtParam);
1311 plan->allParam = bms_add_members(plan->allParam, initSetParam);
1312 /* extParam must include any child extParam */
1313 plan->extParam = bms_add_members(plan->extParam, initExtParam);
1314 /* but extParam shouldn't include any setParams */
1315 plan->extParam = bms_del_members(plan->extParam, initSetParam);
1316 /* ensure extParam is exactly NULL if it's empty */
1317 if (bms_is_empty(plan->extParam))
1318 plan->extParam = NULL;
1320 plan->startup_cost += initplan_cost;
1321 plan->total_cost += initplan_cost;
1326 * Recursive processing of all nodes in the plan tree
1328 * The return value is the computed allParam set for the given Plan node.
1329 * This is just an internal notational convenience.
1332 finalize_plan(PlannerInfo *root, Plan *plan, Bitmapset *valid_params)
1334 finalize_primnode_context context;
1339 context.root = root;
1340 context.paramids = NULL; /* initialize set to empty */
1343 * When we call finalize_primnode, context.paramids sets are automatically
1344 * merged together. But when recursing to self, we have to do it the hard
1345 * way. We want the paramids set to include params in subplans as well as
1349 /* Find params in targetlist and qual */
1350 finalize_primnode((Node *) plan->targetlist, &context);
1351 finalize_primnode((Node *) plan->qual, &context);
1353 /* Check additional node-type-specific fields */
1354 switch (nodeTag(plan))
1357 finalize_primnode(((Result *) plan)->resconstantqual,
1362 finalize_primnode((Node *) ((IndexScan *) plan)->indexqual,
1366 * we need not look at indexqualorig, since it will have the same
1367 * param references as indexqual.
1371 case T_BitmapIndexScan:
1372 finalize_primnode((Node *) ((BitmapIndexScan *) plan)->indexqual,
1376 * we need not look at indexqualorig, since it will have the same
1377 * param references as indexqual.
1381 case T_BitmapHeapScan:
1382 finalize_primnode((Node *) ((BitmapHeapScan *) plan)->bitmapqualorig,
1387 finalize_primnode((Node *) ((TidScan *) plan)->tidquals,
1391 case T_SubqueryScan:
1394 * In a SubqueryScan, SS_finalize_plan has already been run on the
1395 * subplan by the inner invocation of subquery_planner, so there's
1396 * no need to do it again. Instead, just pull out the subplan's
1397 * extParams list, which represents the params it needs from my
1398 * level and higher levels.
1400 context.paramids = bms_add_members(context.paramids,
1401 ((SubqueryScan *) plan)->subplan->extParam);
1404 case T_FunctionScan:
1405 finalize_primnode(((FunctionScan *) plan)->funcexpr,
1410 finalize_primnode((Node *) ((ValuesScan *) plan)->values_lists,
1418 foreach(l, ((Append *) plan)->appendplans)
1421 bms_add_members(context.paramids,
1433 foreach(l, ((BitmapAnd *) plan)->bitmapplans)
1436 bms_add_members(context.paramids,
1448 foreach(l, ((BitmapOr *) plan)->bitmapplans)
1451 bms_add_members(context.paramids,
1460 finalize_primnode((Node *) ((Join *) plan)->joinqual,
1465 finalize_primnode((Node *) ((Join *) plan)->joinqual,
1467 finalize_primnode((Node *) ((MergeJoin *) plan)->mergeclauses,
1472 finalize_primnode((Node *) ((Join *) plan)->joinqual,
1474 finalize_primnode((Node *) ((HashJoin *) plan)->hashclauses,
1479 finalize_primnode(((Limit *) plan)->limitOffset,
1481 finalize_primnode(((Limit *) plan)->limitCount,
1496 elog(ERROR, "unrecognized node type: %d",
1497 (int) nodeTag(plan));
1500 /* Process left and right child plans, if any */
1501 context.paramids = bms_add_members(context.paramids,
1506 context.paramids = bms_add_members(context.paramids,
1511 /* Now we have all the paramids */
1513 if (!bms_is_subset(context.paramids, valid_params))
1514 elog(ERROR, "plan should not reference subplan's variable");
1517 * Note: by definition, extParam and allParam should have the same value
1518 * in any plan node that doesn't have child initPlans. We set them
1519 * equal here, and later SS_finalize_plan will update them properly
1520 * in node(s) that it attaches initPlans to.
1522 * For speed at execution time, make sure extParam/allParam are actually
1523 * NULL if they are empty sets.
1525 if (bms_is_empty(context.paramids))
1527 plan->extParam = NULL;
1528 plan->allParam = NULL;
1532 plan->extParam = context.paramids;
1533 plan->allParam = bms_copy(context.paramids);
1536 return plan->allParam;
1540 * finalize_primnode: add IDs of all PARAM_EXEC params appearing in the given
1541 * expression tree to the result set.
1544 finalize_primnode(Node *node, finalize_primnode_context *context)
1548 if (IsA(node, Param))
1550 if (((Param *) node)->paramkind == PARAM_EXEC)
1552 int paramid = ((Param *) node)->paramid;
1554 context->paramids = bms_add_member(context->paramids, paramid);
1556 return false; /* no more to do here */
1558 if (is_subplan(node))
1560 SubPlan *subplan = (SubPlan *) node;
1561 Plan *plan = planner_subplan_get_plan(context->root, subplan);
1563 Bitmapset *subparamids;
1565 /* Recurse into the testexpr, but not into the Plan */
1566 finalize_primnode(subplan->testexpr, context);
1569 * Remove any param IDs of output parameters of the subplan that were
1570 * referenced in the testexpr. These are not interesting for
1571 * parameter change signaling since we always re-evaluate the subplan.
1572 * Note that this wouldn't work too well if there might be uses of the
1573 * same param IDs elsewhere in the plan, but that can't happen because
1574 * generate_new_param never tries to merge params.
1576 foreach(lc, subplan->paramIds)
1578 context->paramids = bms_del_member(context->paramids,
1582 /* Also examine args list */
1583 finalize_primnode((Node *) subplan->args, context);
1586 * Add params needed by the subplan to paramids, but excluding those
1587 * we will pass down to it.
1589 subparamids = bms_copy(plan->extParam);
1590 foreach(lc, subplan->parParam)
1592 subparamids = bms_del_member(subparamids, lfirst_int(lc));
1594 context->paramids = bms_join(context->paramids, subparamids);
1596 return false; /* no more to do here */
1598 return expression_tree_walker(node, finalize_primnode,
1603 * SS_make_initplan_from_plan - given a plan tree, make it an InitPlan
1605 * The plan is expected to return a scalar value of the indicated type.
1606 * We build an EXPR_SUBLINK SubPlan node and put it into the initplan
1607 * list for the current query level. A Param that represents the initplan's
1608 * output is returned.
1610 * We assume the plan hasn't been put through SS_finalize_plan.
1613 SS_make_initplan_from_plan(PlannerInfo *root, Plan *plan,
1614 Oid resulttype, int32 resulttypmod)
1620 * We must run SS_finalize_plan(), since that's normally done before a
1621 * subplan gets put into the initplan list. Tell it not to attach any
1622 * pre-existing initplans to this one, since they are siblings not
1623 * children of this initplan. (This is something else that could perhaps
1624 * be cleaner if we did extParam/allParam processing in setrefs.c instead
1625 * of here? See notes for materialize_finished_plan.)
1629 * Build extParam/allParam sets for plan nodes.
1631 SS_finalize_plan(root, plan, false);
1634 * Add the subplan and its rtable to the global lists.
1636 root->glob->subplans = lappend(root->glob->subplans,
1638 root->glob->subrtables = lappend(root->glob->subrtables,
1639 root->parse->rtable);
1642 * Create a SubPlan node and add it to the outer list of InitPlans.
1643 * Note it has to appear after any other InitPlans it might depend on
1644 * (see comments in ExecReScan).
1646 node = makeNode(SubPlan);
1647 node->subLinkType = EXPR_SUBLINK;
1648 node->firstColType = get_first_col_type(plan);
1649 node->plan_id = list_length(root->glob->subplans);
1651 root->init_plans = lappend(root->init_plans, node);
1654 * The node can't have any inputs (since it's an initplan), so the
1655 * parParam and args lists remain empty.
1659 * Make a Param that will be the subplan's output.
1661 prm = generate_new_param(root, resulttype, resulttypmod);
1662 node->setParam = list_make1_int(prm->paramid);