1 /*-------------------------------------------------------------------------
4 * routines to support sub-selects appearing in expressions
6 * This module is concerned with executing SubPlan expression nodes, which
7 * should not be confused with sub-SELECTs appearing in FROM. SubPlans are
8 * divided into "initplans", which are those that need only one evaluation per
9 * query (among other restrictions, this requires that they don't use any
10 * direct correlation variables from the parent plan level), and "regular"
11 * subplans, which are re-evaluated every time their result is required.
14 * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
15 * Portions Copyright (c) 1994, Regents of the University of California
18 * src/backend/executor/nodeSubplan.c
20 *-------------------------------------------------------------------------
24 * ExecSubPlan - process a subselect
25 * ExecInitSubPlan - initialize a subselect
32 #include "access/htup_details.h"
33 #include "executor/executor.h"
34 #include "executor/nodeSubplan.h"
35 #include "nodes/makefuncs.h"
36 #include "optimizer/clauses.h"
37 #include "utils/array.h"
38 #include "utils/lsyscache.h"
39 #include "utils/memutils.h"
42 static Datum ExecHashSubPlan(SubPlanState *node,
43 ExprContext *econtext,
45 static Datum ExecScanSubPlan(SubPlanState *node,
46 ExprContext *econtext,
48 static void buildSubPlanHash(SubPlanState *node, ExprContext *econtext);
49 static bool findPartialMatch(TupleHashTable hashtable, TupleTableSlot *slot,
50 FmgrInfo *eqfunctions);
51 static bool slotAllNulls(TupleTableSlot *slot);
52 static bool slotNoNulls(TupleTableSlot *slot);
55 /* ----------------------------------------------------------------
58 * This is the main entry point for execution of a regular SubPlan.
59 * ----------------------------------------------------------------
62 ExecSubPlan(SubPlanState *node,
63 ExprContext *econtext,
66 SubPlan *subplan = node->subplan;
68 /* Set non-null as default */
72 if (subplan->subLinkType == CTE_SUBLINK)
73 elog(ERROR, "CTE subplans should not be executed via ExecSubPlan");
74 if (subplan->setParam != NIL && subplan->subLinkType != MULTIEXPR_SUBLINK)
75 elog(ERROR, "cannot set parent params from subquery");
77 /* Select appropriate evaluation strategy */
78 if (subplan->useHashTable)
79 return ExecHashSubPlan(node, econtext, isNull);
81 return ExecScanSubPlan(node, econtext, isNull);
85 * ExecHashSubPlan: store subselect result in an in-memory hash table
88 ExecHashSubPlan(SubPlanState *node,
89 ExprContext *econtext,
92 SubPlan *subplan = node->subplan;
93 PlanState *planstate = node->planstate;
96 /* Shouldn't have any direct correlation Vars */
97 if (subplan->parParam != NIL || node->args != NIL)
98 elog(ERROR, "hashed subplan with direct correlation not supported");
101 * If first time through or we need to rescan the subplan, build the hash
104 if (node->hashtable == NULL || planstate->chgParam != NULL)
105 buildSubPlanHash(node, econtext);
108 * The result for an empty subplan is always FALSE; no need to evaluate
112 if (!node->havehashrows && !node->havenullrows)
113 return BoolGetDatum(false);
116 * Evaluate lefthand expressions and form a projection tuple. First we
117 * have to set the econtext to use (hack alert!).
119 node->projLeft->pi_exprContext = econtext;
120 slot = ExecProject(node->projLeft);
123 * Note: because we are typically called in a per-tuple context, we have
124 * to explicitly clear the projected tuple before returning. Otherwise,
125 * we'll have a double-free situation: the per-tuple context will probably
126 * be reset before we're called again, and then the tuple slot will think
127 * it still needs to free the tuple.
131 * If the LHS is all non-null, probe for an exact match in the main hash
132 * table. If we find one, the result is TRUE. Otherwise, scan the
133 * partly-null table to see if there are any rows that aren't provably
134 * unequal to the LHS; if so, the result is UNKNOWN. (We skip that part
135 * if we don't care about UNKNOWN.) Otherwise, the result is FALSE.
137 * Note: the reason we can avoid a full scan of the main hash table is
138 * that the combining operators are assumed never to yield NULL when both
139 * inputs are non-null. If they were to do so, we might need to produce
140 * UNKNOWN instead of FALSE because of an UNKNOWN result in comparing the
141 * LHS to some main-table entry --- which is a comparison we will not even
142 * make, unless there's a chance match of hash keys.
144 if (slotNoNulls(slot))
146 if (node->havehashrows &&
147 FindTupleHashEntry(node->hashtable,
150 node->lhs_hash_funcs) != NULL)
152 ExecClearTuple(slot);
153 return BoolGetDatum(true);
155 if (node->havenullrows &&
156 findPartialMatch(node->hashnulls, slot, node->cur_eq_funcs))
158 ExecClearTuple(slot);
160 return BoolGetDatum(false);
162 ExecClearTuple(slot);
163 return BoolGetDatum(false);
167 * When the LHS is partly or wholly NULL, we can never return TRUE. If we
168 * don't care about UNKNOWN, just return FALSE. Otherwise, if the LHS is
169 * wholly NULL, immediately return UNKNOWN. (Since the combining
170 * operators are strict, the result could only be FALSE if the sub-select
171 * were empty, but we already handled that case.) Otherwise, we must scan
172 * both the main and partly-null tables to see if there are any rows that
173 * aren't provably unequal to the LHS; if so, the result is UNKNOWN.
174 * Otherwise, the result is FALSE.
176 if (node->hashnulls == NULL)
178 ExecClearTuple(slot);
179 return BoolGetDatum(false);
181 if (slotAllNulls(slot))
183 ExecClearTuple(slot);
185 return BoolGetDatum(false);
187 /* Scan partly-null table first, since more likely to get a match */
188 if (node->havenullrows &&
189 findPartialMatch(node->hashnulls, slot, node->cur_eq_funcs))
191 ExecClearTuple(slot);
193 return BoolGetDatum(false);
195 if (node->havehashrows &&
196 findPartialMatch(node->hashtable, slot, node->cur_eq_funcs))
198 ExecClearTuple(slot);
200 return BoolGetDatum(false);
202 ExecClearTuple(slot);
203 return BoolGetDatum(false);
207 * ExecScanSubPlan: default case where we have to rescan subplan each time
210 ExecScanSubPlan(SubPlanState *node,
211 ExprContext *econtext,
214 SubPlan *subplan = node->subplan;
215 PlanState *planstate = node->planstate;
216 SubLinkType subLinkType = subplan->subLinkType;
217 MemoryContext oldcontext;
218 TupleTableSlot *slot;
220 bool found = false; /* TRUE if got at least one subplan tuple */
223 ArrayBuildStateAny *astate = NULL;
226 * MULTIEXPR subplans, when "executed", just return NULL; but first we
227 * mark the subplan's output parameters as needing recalculation. (This
228 * is a bit of a hack: it relies on the subplan appearing later in its
229 * targetlist than any of the referencing Params, so that all the Params
230 * have been evaluated before we re-mark them for the next evaluation
231 * cycle. But in general resjunk tlist items appear after non-resjunk
232 * ones, so this should be safe.) Unlike ExecReScanSetParamPlan, we do
233 * *not* set bits in the parent plan node's chgParam, because we don't
234 * want to cause a rescan of the parent.
236 if (subLinkType == MULTIEXPR_SUBLINK)
238 EState *estate = node->parent->state;
240 foreach(l, subplan->setParam)
242 int paramid = lfirst_int(l);
243 ParamExecData *prm = &(estate->es_param_exec_vals[paramid]);
245 prm->execPlan = node;
251 /* Initialize ArrayBuildStateAny in caller's context, if needed */
252 if (subLinkType == ARRAY_SUBLINK)
253 astate = initArrayResultAny(subplan->firstColType,
254 CurrentMemoryContext, true);
257 * We are probably in a short-lived expression-evaluation context. Switch
258 * to the per-query context for manipulating the child plan's chgParam,
259 * calling ExecProcNode on it, etc.
261 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
264 * Set Params of this plan from parent plan correlation values. (Any
265 * calculation we have to do is done in the parent econtext, since the
266 * Param values don't need to have per-query lifetime.)
268 Assert(list_length(subplan->parParam) == list_length(node->args));
270 forboth(l, subplan->parParam, pvar, node->args)
272 int paramid = lfirst_int(l);
273 ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
275 prm->value = ExecEvalExprSwitchContext((ExprState *) lfirst(pvar),
278 planstate->chgParam = bms_add_member(planstate->chgParam, paramid);
282 * Now that we've set up its parameters, we can reset the subplan.
284 ExecReScan(planstate);
287 * For all sublink types except EXPR_SUBLINK and ARRAY_SUBLINK, the result
288 * is boolean as are the results of the combining operators. We combine
289 * results across tuples (if the subplan produces more than one) using OR
290 * semantics for ANY_SUBLINK or AND semantics for ALL_SUBLINK.
291 * (ROWCOMPARE_SUBLINK doesn't allow multiple tuples from the subplan.)
292 * NULL results from the combining operators are handled according to the
293 * usual SQL semantics for OR and AND. The result for no input tuples is
294 * FALSE for ANY_SUBLINK, TRUE for ALL_SUBLINK, NULL for
295 * ROWCOMPARE_SUBLINK.
297 * For EXPR_SUBLINK we require the subplan to produce no more than one
298 * tuple, else an error is raised. If zero tuples are produced, we return
299 * NULL. Assuming we get a tuple, we just use its first column (there can
300 * be only one non-junk column in this case).
302 * For ARRAY_SUBLINK we allow the subplan to produce any number of tuples,
303 * and form an array of the first column's values. Note in particular
304 * that we produce a zero-element array if no tuples are produced (this is
305 * a change from pre-8.3 behavior of returning NULL).
307 result = BoolGetDatum(subLinkType == ALL_SUBLINK);
310 for (slot = ExecProcNode(planstate);
312 slot = ExecProcNode(planstate))
314 TupleDesc tdesc = slot->tts_tupleDescriptor;
320 if (subLinkType == EXISTS_SUBLINK)
323 result = BoolGetDatum(true);
327 if (subLinkType == EXPR_SUBLINK)
329 /* cannot allow multiple input tuples for EXPR sublink */
332 (errcode(ERRCODE_CARDINALITY_VIOLATION),
333 errmsg("more than one row returned by a subquery used as an expression")));
337 * We need to copy the subplan's tuple in case the result is of
338 * pass-by-ref type --- our return value will point into this
339 * copied tuple! Can't use the subplan's instance of the tuple
340 * since it won't still be valid after next ExecProcNode() call.
341 * node->curTuple keeps track of the copied tuple for eventual
345 heap_freetuple(node->curTuple);
346 node->curTuple = ExecCopySlotTuple(slot);
348 result = heap_getattr(node->curTuple, 1, tdesc, isNull);
349 /* keep scanning subplan to make sure there's only one tuple */
353 if (subLinkType == ARRAY_SUBLINK)
359 /* stash away current value */
360 Assert(subplan->firstColType == tdesc->attrs[0]->atttypid);
361 dvalue = slot_getattr(slot, 1, &disnull);
362 astate = accumArrayResultAny(astate, dvalue, disnull,
363 subplan->firstColType, oldcontext);
364 /* keep scanning subplan to collect all values */
368 /* cannot allow multiple input tuples for ROWCOMPARE sublink either */
369 if (subLinkType == ROWCOMPARE_SUBLINK && found)
371 (errcode(ERRCODE_CARDINALITY_VIOLATION),
372 errmsg("more than one row returned by a subquery used as an expression")));
377 * For ALL, ANY, and ROWCOMPARE sublinks, load up the Params
378 * representing the columns of the sub-select, and then evaluate the
379 * combining expression.
382 foreach(plst, subplan->paramIds)
384 int paramid = lfirst_int(plst);
385 ParamExecData *prmdata;
387 prmdata = &(econtext->ecxt_param_exec_vals[paramid]);
388 Assert(prmdata->execPlan == NULL);
389 prmdata->value = slot_getattr(slot, col, &(prmdata->isnull));
393 rowresult = ExecEvalExprSwitchContext(node->testexpr, econtext,
396 if (subLinkType == ANY_SUBLINK)
398 /* combine across rows per OR semantics */
401 else if (DatumGetBool(rowresult))
403 result = BoolGetDatum(true);
405 break; /* needn't look at any more rows */
408 else if (subLinkType == ALL_SUBLINK)
410 /* combine across rows per AND semantics */
413 else if (!DatumGetBool(rowresult))
415 result = BoolGetDatum(false);
417 break; /* needn't look at any more rows */
422 /* must be ROWCOMPARE_SUBLINK */
428 MemoryContextSwitchTo(oldcontext);
430 if (subLinkType == ARRAY_SUBLINK)
432 /* We return the result in the caller's context */
433 result = makeArrayResultAny(astate, oldcontext, true);
438 * deal with empty subplan result. result/isNull were previously
439 * initialized correctly for all sublink types except EXPR and
440 * ROWCOMPARE; for those, return NULL.
442 if (subLinkType == EXPR_SUBLINK ||
443 subLinkType == ROWCOMPARE_SUBLINK)
454 * buildSubPlanHash: load hash table by scanning subplan output.
457 buildSubPlanHash(SubPlanState *node, ExprContext *econtext)
459 SubPlan *subplan = node->subplan;
460 PlanState *planstate = node->planstate;
461 int ncols = list_length(subplan->paramIds);
462 ExprContext *innerecontext = node->innerecontext;
463 MemoryContext oldcontext;
465 TupleTableSlot *slot;
467 Assert(subplan->subLinkType == ANY_SUBLINK);
470 * If we already had any hash tables, destroy 'em; then create empty hash
473 * If we need to distinguish accurately between FALSE and UNKNOWN (i.e.,
474 * NULL) results of the IN operation, then we have to store subplan output
475 * rows that are partly or wholly NULL. We store such rows in a separate
476 * hash table that we expect will be much smaller than the main table. (We
477 * can use hashing to eliminate partly-null rows that are not distinct. We
478 * keep them separate to minimize the cost of the inevitable full-table
479 * searches; see findPartialMatch.)
481 * If it's not necessary to distinguish FALSE and UNKNOWN, then we don't
482 * need to store subplan output rows that contain NULL.
484 MemoryContextReset(node->hashtablecxt);
485 node->hashtable = NULL;
486 node->hashnulls = NULL;
487 node->havehashrows = false;
488 node->havenullrows = false;
490 nbuckets = (long) Min(planstate->plan->plan_rows, (double) LONG_MAX);
494 node->hashtable = BuildTupleHashTable(ncols,
497 node->tab_hash_funcs,
504 if (!subplan->unknownEqFalse)
507 nbuckets = 1; /* there can only be one entry */
514 node->hashnulls = BuildTupleHashTable(ncols,
517 node->tab_hash_funcs,
526 * We are probably in a short-lived expression-evaluation context. Switch
527 * to the per-query context for manipulating the child plan.
529 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
532 * Reset subplan to start.
534 ExecReScan(planstate);
537 * Scan the subplan and load the hash table(s). Note that when there are
538 * duplicate rows coming out of the sub-select, only one copy is stored.
540 for (slot = ExecProcNode(planstate);
542 slot = ExecProcNode(planstate))
549 * Load up the Params representing the raw sub-select outputs, then
550 * form the projection tuple to store in the hashtable.
552 foreach(plst, subplan->paramIds)
554 int paramid = lfirst_int(plst);
555 ParamExecData *prmdata;
557 prmdata = &(innerecontext->ecxt_param_exec_vals[paramid]);
558 Assert(prmdata->execPlan == NULL);
559 prmdata->value = slot_getattr(slot, col,
563 slot = ExecProject(node->projRight);
566 * If result contains any nulls, store separately or not at all.
568 if (slotNoNulls(slot))
570 (void) LookupTupleHashEntry(node->hashtable, slot, &isnew);
571 node->havehashrows = true;
573 else if (node->hashnulls)
575 (void) LookupTupleHashEntry(node->hashnulls, slot, &isnew);
576 node->havenullrows = true;
580 * Reset innerecontext after each inner tuple to free any memory used
581 * during ExecProject.
583 ResetExprContext(innerecontext);
587 * Since the projected tuples are in the sub-query's context and not the
588 * main context, we'd better clear the tuple slot before there's any
589 * chance of a reset of the sub-query's context. Else we will have the
590 * potential for a double free attempt. (XXX possibly no longer needed,
593 ExecClearTuple(node->projRight->pi_state.resultslot);
595 MemoryContextSwitchTo(oldcontext);
599 * findPartialMatch: does the hashtable contain an entry that is not
600 * provably distinct from the tuple?
602 * We have to scan the whole hashtable; we can't usefully use hashkeys
603 * to guide probing, since we might get partial matches on tuples with
604 * hashkeys quite unrelated to what we'd get from the given tuple.
606 * Caller must provide the equality functions to use, since in cross-type
607 * cases these are different from the hashtable's internal functions.
610 findPartialMatch(TupleHashTable hashtable, TupleTableSlot *slot,
611 FmgrInfo *eqfunctions)
613 int numCols = hashtable->numCols;
614 AttrNumber *keyColIdx = hashtable->keyColIdx;
615 TupleHashIterator hashiter;
616 TupleHashEntry entry;
618 InitTupleHashIterator(hashtable, &hashiter);
619 while ((entry = ScanTupleHashTable(hashtable, &hashiter)) != NULL)
621 ExecStoreMinimalTuple(entry->firstTuple, hashtable->tableslot, false);
622 if (!execTuplesUnequal(slot, hashtable->tableslot,
627 TermTupleHashIterator(&hashiter);
631 /* No TermTupleHashIterator call needed here */
636 * slotAllNulls: is the slot completely NULL?
638 * This does not test for dropped columns, which is OK because we only
639 * use it on projected tuples.
642 slotAllNulls(TupleTableSlot *slot)
644 int ncols = slot->tts_tupleDescriptor->natts;
647 for (i = 1; i <= ncols; i++)
649 if (!slot_attisnull(slot, i))
656 * slotNoNulls: is the slot entirely not NULL?
658 * This does not test for dropped columns, which is OK because we only
659 * use it on projected tuples.
662 slotNoNulls(TupleTableSlot *slot)
664 int ncols = slot->tts_tupleDescriptor->natts;
667 for (i = 1; i <= ncols; i++)
669 if (slot_attisnull(slot, i))
675 /* ----------------------------------------------------------------
678 * Create a SubPlanState for a SubPlan; this is the SubPlan-specific part
679 * of ExecInitExpr(). We split it out so that it can be used for InitPlans
680 * as well as regular SubPlans. Note that we don't link the SubPlan into
681 * the parent's subPlan list, because that shouldn't happen for InitPlans.
682 * Instead, ExecInitExpr() does that one part.
683 * ----------------------------------------------------------------
686 ExecInitSubPlan(SubPlan *subplan, PlanState *parent)
688 SubPlanState *sstate = makeNode(SubPlanState);
689 EState *estate = parent->state;
691 sstate->subplan = subplan;
693 /* Link the SubPlanState to already-initialized subplan */
694 sstate->planstate = (PlanState *) list_nth(estate->es_subplanstates,
695 subplan->plan_id - 1);
697 /* ... and to its parent's state */
698 sstate->parent = parent;
700 /* Initialize subexpressions */
701 sstate->testexpr = ExecInitExpr((Expr *) subplan->testexpr, parent);
702 sstate->args = ExecInitExprList(subplan->args, parent);
705 * initialize my state
707 sstate->curTuple = NULL;
708 sstate->curArray = PointerGetDatum(NULL);
709 sstate->projLeft = NULL;
710 sstate->projRight = NULL;
711 sstate->hashtable = NULL;
712 sstate->hashnulls = NULL;
713 sstate->hashtablecxt = NULL;
714 sstate->hashtempcxt = NULL;
715 sstate->innerecontext = NULL;
716 sstate->keyColIdx = NULL;
717 sstate->tab_hash_funcs = NULL;
718 sstate->tab_eq_funcs = NULL;
719 sstate->lhs_hash_funcs = NULL;
720 sstate->cur_eq_funcs = NULL;
723 * If this is an initplan or MULTIEXPR subplan, it has output parameters
724 * that the parent plan will use, so mark those parameters as needing
725 * evaluation. We don't actually run the subplan until we first need one
728 * A CTE subplan's output parameter is never to be evaluated in the normal
729 * way, so skip this in that case.
731 * Note that we don't set parent->chgParam here: the parent plan hasn't
732 * been run yet, so no need to force it to re-run.
734 if (subplan->setParam != NIL && subplan->subLinkType != CTE_SUBLINK)
738 foreach(lst, subplan->setParam)
740 int paramid = lfirst_int(lst);
741 ParamExecData *prm = &(estate->es_param_exec_vals[paramid]);
743 prm->execPlan = sstate;
748 * If we are going to hash the subquery output, initialize relevant stuff.
749 * (We don't create the hashtable until needed, though.)
751 if (subplan->useHashTable)
756 TupleTableSlot *slot;
762 /* We need a memory context to hold the hash table(s) */
763 sstate->hashtablecxt =
764 AllocSetContextCreate(CurrentMemoryContext,
765 "Subplan HashTable Context",
766 ALLOCSET_DEFAULT_SIZES);
767 /* and a small one for the hash tables to use as temp storage */
768 sstate->hashtempcxt =
769 AllocSetContextCreate(CurrentMemoryContext,
770 "Subplan HashTable Temp Context",
771 ALLOCSET_SMALL_SIZES);
772 /* and a short-lived exprcontext for function evaluation */
773 sstate->innerecontext = CreateExprContext(estate);
774 /* Silly little array of column numbers 1..n */
775 ncols = list_length(subplan->paramIds);
776 sstate->keyColIdx = (AttrNumber *) palloc(ncols * sizeof(AttrNumber));
777 for (i = 0; i < ncols; i++)
778 sstate->keyColIdx[i] = i + 1;
781 * We use ExecProject to evaluate the lefthand and righthand
782 * expression lists and form tuples. (You might think that we could
783 * use the sub-select's output tuples directly, but that is not the
784 * case if we had to insert any run-time coercions of the sub-select's
785 * output datatypes; anyway this avoids storing any resjunk columns
786 * that might be in the sub-select's output.) Run through the
787 * combining expressions to build tlists for the lefthand and
790 * We also extract the combining operators themselves to initialize
791 * the equality and hashing functions for the hash tables.
793 if (IsA(subplan->testexpr, OpExpr))
795 /* single combining operator */
796 oplist = list_make1(subplan->testexpr);
798 else if (and_clause((Node *) subplan->testexpr))
800 /* multiple combining operators */
801 oplist = castNode(BoolExpr, subplan->testexpr)->args;
805 /* shouldn't see anything else in a hashable subplan */
806 elog(ERROR, "unrecognized testexpr type: %d",
807 (int) nodeTag(subplan->testexpr));
808 oplist = NIL; /* keep compiler quiet */
810 Assert(list_length(oplist) == ncols);
812 lefttlist = righttlist = NIL;
813 sstate->tab_hash_funcs = (FmgrInfo *) palloc(ncols * sizeof(FmgrInfo));
814 sstate->tab_eq_funcs = (FmgrInfo *) palloc(ncols * sizeof(FmgrInfo));
815 sstate->lhs_hash_funcs = (FmgrInfo *) palloc(ncols * sizeof(FmgrInfo));
816 sstate->cur_eq_funcs = (FmgrInfo *) palloc(ncols * sizeof(FmgrInfo));
820 OpExpr *opexpr = lfirst_node(OpExpr, l);
827 Assert(list_length(opexpr->args) == 2);
829 /* Process lefthand argument */
830 expr = (Expr *) linitial(opexpr->args);
831 tle = makeTargetEntry(expr,
835 lefttlist = lappend(lefttlist, tle);
837 /* Process righthand argument */
838 expr = (Expr *) lsecond(opexpr->args);
839 tle = makeTargetEntry(expr,
843 righttlist = lappend(righttlist, tle);
845 /* Lookup the equality function (potentially cross-type) */
846 fmgr_info(opexpr->opfuncid, &sstate->cur_eq_funcs[i - 1]);
847 fmgr_info_set_expr((Node *) opexpr, &sstate->cur_eq_funcs[i - 1]);
849 /* Look up the equality function for the RHS type */
850 if (!get_compatible_hash_operators(opexpr->opno,
852 elog(ERROR, "could not find compatible hash operator for operator %u",
854 fmgr_info(get_opcode(rhs_eq_oper), &sstate->tab_eq_funcs[i - 1]);
856 /* Lookup the associated hash functions */
857 if (!get_op_hash_functions(opexpr->opno,
858 &left_hashfn, &right_hashfn))
859 elog(ERROR, "could not find hash function for hash operator %u",
861 fmgr_info(left_hashfn, &sstate->lhs_hash_funcs[i - 1]);
862 fmgr_info(right_hashfn, &sstate->tab_hash_funcs[i - 1]);
868 * Construct tupdescs, slots and projection nodes for left and right
869 * sides. The lefthand expressions will be evaluated in the parent
870 * plan node's exprcontext, which we don't have access to here.
871 * Fortunately we can just pass NULL for now and fill it in later
872 * (hack alert!). The righthand expressions will be evaluated in our
875 tupDesc = ExecTypeFromTL(lefttlist, false);
876 slot = ExecInitExtraTupleSlot(estate);
877 ExecSetSlotDescriptor(slot, tupDesc);
878 sstate->projLeft = ExecBuildProjectionInfo(lefttlist,
884 tupDesc = ExecTypeFromTL(righttlist, false);
885 slot = ExecInitExtraTupleSlot(estate);
886 ExecSetSlotDescriptor(slot, tupDesc);
887 sstate->projRight = ExecBuildProjectionInfo(righttlist,
888 sstate->innerecontext,
897 /* ----------------------------------------------------------------
900 * Executes a subplan and sets its output parameters.
902 * This is called from ExecEvalParamExec() when the value of a PARAM_EXEC
903 * parameter is requested and the param's execPlan field is set (indicating
904 * that the param has not yet been evaluated). This allows lazy evaluation
905 * of initplans: we don't run the subplan until/unless we need its output.
906 * Note that this routine MUST clear the execPlan fields of the plan's
907 * output parameters after evaluating them!
908 * ----------------------------------------------------------------
911 ExecSetParamPlan(SubPlanState *node, ExprContext *econtext)
913 SubPlan *subplan = node->subplan;
914 PlanState *planstate = node->planstate;
915 SubLinkType subLinkType = subplan->subLinkType;
916 MemoryContext oldcontext;
917 TupleTableSlot *slot;
921 ArrayBuildStateAny *astate = NULL;
923 if (subLinkType == ANY_SUBLINK ||
924 subLinkType == ALL_SUBLINK)
925 elog(ERROR, "ANY/ALL subselect unsupported as initplan");
926 if (subLinkType == CTE_SUBLINK)
927 elog(ERROR, "CTE subplans should not be executed via ExecSetParamPlan");
929 /* Initialize ArrayBuildStateAny in caller's context, if needed */
930 if (subLinkType == ARRAY_SUBLINK)
931 astate = initArrayResultAny(subplan->firstColType,
932 CurrentMemoryContext, true);
935 * Must switch to per-query memory context.
937 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
940 * Set Params of this plan from parent plan correlation values. (Any
941 * calculation we have to do is done in the parent econtext, since the
942 * Param values don't need to have per-query lifetime.) Currently, we
943 * expect only MULTIEXPR_SUBLINK plans to have any correlation values.
945 Assert(subplan->parParam == NIL || subLinkType == MULTIEXPR_SUBLINK);
946 Assert(list_length(subplan->parParam) == list_length(node->args));
948 forboth(l, subplan->parParam, pvar, node->args)
950 int paramid = lfirst_int(l);
951 ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
953 prm->value = ExecEvalExprSwitchContext((ExprState *) lfirst(pvar),
956 planstate->chgParam = bms_add_member(planstate->chgParam, paramid);
960 * Run the plan. (If it needs to be rescanned, the first ExecProcNode
961 * call will take care of that.)
963 for (slot = ExecProcNode(planstate);
965 slot = ExecProcNode(planstate))
967 TupleDesc tdesc = slot->tts_tupleDescriptor;
970 if (subLinkType == EXISTS_SUBLINK)
972 /* There can be only one setParam... */
973 int paramid = linitial_int(subplan->setParam);
974 ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
976 prm->execPlan = NULL;
977 prm->value = BoolGetDatum(true);
983 if (subLinkType == ARRAY_SUBLINK)
989 /* stash away current value */
990 Assert(subplan->firstColType == tdesc->attrs[0]->atttypid);
991 dvalue = slot_getattr(slot, 1, &disnull);
992 astate = accumArrayResultAny(astate, dvalue, disnull,
993 subplan->firstColType, oldcontext);
994 /* keep scanning subplan to collect all values */
999 (subLinkType == EXPR_SUBLINK ||
1000 subLinkType == MULTIEXPR_SUBLINK ||
1001 subLinkType == ROWCOMPARE_SUBLINK))
1003 (errcode(ERRCODE_CARDINALITY_VIOLATION),
1004 errmsg("more than one row returned by a subquery used as an expression")));
1009 * We need to copy the subplan's tuple into our own context, in case
1010 * any of the params are pass-by-ref type --- the pointers stored in
1011 * the param structs will point at this copied tuple! node->curTuple
1012 * keeps track of the copied tuple for eventual freeing.
1015 heap_freetuple(node->curTuple);
1016 node->curTuple = ExecCopySlotTuple(slot);
1019 * Now set all the setParam params from the columns of the tuple
1021 foreach(l, subplan->setParam)
1023 int paramid = lfirst_int(l);
1024 ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
1026 prm->execPlan = NULL;
1027 prm->value = heap_getattr(node->curTuple, i, tdesc,
1033 if (subLinkType == ARRAY_SUBLINK)
1035 /* There can be only one setParam... */
1036 int paramid = linitial_int(subplan->setParam);
1037 ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
1040 * We build the result array in query context so it won't disappear;
1041 * to avoid leaking memory across repeated calls, we have to remember
1042 * the latest value, much as for curTuple above.
1044 if (node->curArray != PointerGetDatum(NULL))
1045 pfree(DatumGetPointer(node->curArray));
1046 node->curArray = makeArrayResultAny(astate,
1047 econtext->ecxt_per_query_memory,
1049 prm->execPlan = NULL;
1050 prm->value = node->curArray;
1051 prm->isnull = false;
1055 if (subLinkType == EXISTS_SUBLINK)
1057 /* There can be only one setParam... */
1058 int paramid = linitial_int(subplan->setParam);
1059 ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
1061 prm->execPlan = NULL;
1062 prm->value = BoolGetDatum(false);
1063 prm->isnull = false;
1067 /* For other sublink types, set all the output params to NULL */
1068 foreach(l, subplan->setParam)
1070 int paramid = lfirst_int(l);
1071 ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
1073 prm->execPlan = NULL;
1074 prm->value = (Datum) 0;
1080 MemoryContextSwitchTo(oldcontext);
1084 * Mark an initplan as needing recalculation
1087 ExecReScanSetParamPlan(SubPlanState *node, PlanState *parent)
1089 PlanState *planstate = node->planstate;
1090 SubPlan *subplan = node->subplan;
1091 EState *estate = parent->state;
1095 if (subplan->parParam != NIL)
1096 elog(ERROR, "direct correlated subquery unsupported as initplan");
1097 if (subplan->setParam == NIL)
1098 elog(ERROR, "setParam list of initplan is empty");
1099 if (bms_is_empty(planstate->plan->extParam))
1100 elog(ERROR, "extParam set of initplan is empty");
1103 * Don't actually re-scan: it'll happen inside ExecSetParamPlan if needed.
1107 * Mark this subplan's output parameters as needing recalculation.
1109 * CTE subplans are never executed via parameter recalculation; instead
1110 * they get run when called by nodeCtescan.c. So don't mark the output
1111 * parameter of a CTE subplan as dirty, but do set the chgParam bit for it
1112 * so that dependent plan nodes will get told to rescan.
1114 foreach(l, subplan->setParam)
1116 int paramid = lfirst_int(l);
1117 ParamExecData *prm = &(estate->es_param_exec_vals[paramid]);
1119 if (subplan->subLinkType != CTE_SUBLINK)
1120 prm->execPlan = node;
1122 parent->chgParam = bms_add_member(parent->chgParam, paramid);
1128 * ExecInitAlternativeSubPlan
1130 * Initialize for execution of one of a set of alternative subplans.
1132 AlternativeSubPlanState *
1133 ExecInitAlternativeSubPlan(AlternativeSubPlan *asplan, PlanState *parent)
1135 AlternativeSubPlanState *asstate = makeNode(AlternativeSubPlanState);
1143 asstate->subplan = asplan;
1146 * Initialize subplans. (Can we get away with only initializing the one
1147 * we're going to use?)
1149 foreach(lc, asplan->subplans)
1151 SubPlan *sp = lfirst_node(SubPlan, lc);
1152 SubPlanState *sps = ExecInitSubPlan(sp, parent);
1154 asstate->subplans = lappend(asstate->subplans, sps);
1155 parent->subPlan = lappend(parent->subPlan, sps);
1159 * Select the one to be used. For this, we need an estimate of the number
1160 * of executions of the subplan. We use the number of output rows
1161 * expected from the parent plan node. This is a good estimate if we are
1162 * in the parent's targetlist, and an underestimate (but probably not by
1163 * more than a factor of 2) if we are in the qual.
1165 num_calls = parent->plan->plan_rows;
1168 * The planner saved enough info so that we don't have to work very hard
1169 * to estimate the total cost, given the number-of-calls estimate.
1171 Assert(list_length(asplan->subplans) == 2);
1172 subplan1 = (SubPlan *) linitial(asplan->subplans);
1173 subplan2 = (SubPlan *) lsecond(asplan->subplans);
1175 cost1 = subplan1->startup_cost + num_calls * subplan1->per_call_cost;
1176 cost2 = subplan2->startup_cost + num_calls * subplan2->per_call_cost;
1179 asstate->active = 0;
1181 asstate->active = 1;
1187 * ExecAlternativeSubPlan
1189 * Execute one of a set of alternative subplans.
1191 * Note: in future we might consider changing to different subplans on the
1192 * fly, in case the original rowcount estimate turns out to be way off.
1195 ExecAlternativeSubPlan(AlternativeSubPlanState *node,
1196 ExprContext *econtext,
1199 /* Just pass control to the active subplan */
1200 SubPlanState *activesp = list_nth_node(SubPlanState,
1201 node->subplans, node->active);
1203 return ExecSubPlan(activesp, econtext, isNull);