1 /*-------------------------------------------------------------------------
4 * routines to support subselects
6 * Portions Copyright (c) 1996-2007, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
10 * $PostgreSQL: pgsql/src/backend/executor/nodeSubplan.c,v 1.88 2007/04/26 23:24:44 tgl Exp $
12 *-------------------------------------------------------------------------
16 * ExecSubPlan - process a subselect
17 * ExecInitSubPlan - initialize a subselect
23 #include "access/heapam.h"
24 #include "executor/executor.h"
25 #include "executor/nodeSubplan.h"
26 #include "nodes/makefuncs.h"
27 #include "optimizer/clauses.h"
28 #include "utils/array.h"
29 #include "utils/lsyscache.h"
30 #include "utils/memutils.h"
33 static Datum ExecHashSubPlan(SubPlanState *node,
34 ExprContext *econtext,
36 static Datum ExecScanSubPlan(SubPlanState *node,
37 ExprContext *econtext,
39 static void buildSubPlanHash(SubPlanState *node, ExprContext *econtext);
40 static bool findPartialMatch(TupleHashTable hashtable, TupleTableSlot *slot);
41 static bool slotAllNulls(TupleTableSlot *slot);
42 static bool slotNoNulls(TupleTableSlot *slot);
45 /* ----------------------------------------------------------------
47 * ----------------------------------------------------------------
50 ExecSubPlan(SubPlanState *node,
51 ExprContext *econtext,
55 SubPlan *subplan = (SubPlan *) node->xprstate.expr;
57 /* Set default values for result flags: non-null, not a set result */
60 *isDone = ExprSingleResult;
62 if (subplan->setParam != NIL)
63 elog(ERROR, "cannot set parent params from subquery");
65 if (subplan->useHashTable)
66 return ExecHashSubPlan(node, econtext, isNull);
68 return ExecScanSubPlan(node, econtext, isNull);
72 * ExecHashSubPlan: store subselect result in an in-memory hash table
75 ExecHashSubPlan(SubPlanState *node,
76 ExprContext *econtext,
79 SubPlan *subplan = (SubPlan *) node->xprstate.expr;
80 PlanState *planstate = node->planstate;
81 ExprContext *innerecontext = node->innerecontext;
84 /* Shouldn't have any direct correlation Vars */
85 if (subplan->parParam != NIL || node->args != NIL)
86 elog(ERROR, "hashed subplan with direct correlation not supported");
89 * If first time through or we need to rescan the subplan, build the hash
92 if (node->hashtable == NULL || planstate->chgParam != NULL)
93 buildSubPlanHash(node, econtext);
96 * The result for an empty subplan is always FALSE; no need to evaluate
100 if (!node->havehashrows && !node->havenullrows)
101 return BoolGetDatum(false);
104 * Evaluate lefthand expressions and form a projection tuple. First we
105 * have to set the econtext to use (hack alert!).
107 node->projLeft->pi_exprContext = econtext;
108 slot = ExecProject(node->projLeft, NULL);
111 * Note: because we are typically called in a per-tuple context, we have
112 * to explicitly clear the projected tuple before returning. Otherwise,
113 * we'll have a double-free situation: the per-tuple context will probably
114 * be reset before we're called again, and then the tuple slot will think
115 * it still needs to free the tuple.
119 * Since the hashtable routines will use innerecontext's per-tuple memory
120 * as working memory, be sure to reset it for each tuple.
122 ResetExprContext(innerecontext);
125 * If the LHS is all non-null, probe for an exact match in the main hash
126 * table. If we find one, the result is TRUE. Otherwise, scan the
127 * partly-null table to see if there are any rows that aren't provably
128 * unequal to the LHS; if so, the result is UNKNOWN. (We skip that part
129 * if we don't care about UNKNOWN.) Otherwise, the result is FALSE.
131 * Note: the reason we can avoid a full scan of the main hash table is
132 * that the combining operators are assumed never to yield NULL when both
133 * inputs are non-null. If they were to do so, we might need to produce
134 * UNKNOWN instead of FALSE because of an UNKNOWN result in comparing the
135 * LHS to some main-table entry --- which is a comparison we will not even
136 * make, unless there's a chance match of hash keys.
138 if (slotNoNulls(slot))
140 if (node->havehashrows &&
141 FindTupleHashEntry(node->hashtable,
144 node->lhs_hash_funcs) != NULL)
146 ExecClearTuple(slot);
147 return BoolGetDatum(true);
149 if (node->havenullrows &&
150 findPartialMatch(node->hashnulls, slot))
152 ExecClearTuple(slot);
154 return BoolGetDatum(false);
156 ExecClearTuple(slot);
157 return BoolGetDatum(false);
161 * When the LHS is partly or wholly NULL, we can never return TRUE. If we
162 * don't care about UNKNOWN, just return FALSE. Otherwise, if the LHS is
163 * wholly NULL, immediately return UNKNOWN. (Since the combining
164 * operators are strict, the result could only be FALSE if the sub-select
165 * were empty, but we already handled that case.) Otherwise, we must scan
166 * both the main and partly-null tables to see if there are any rows that
167 * aren't provably unequal to the LHS; if so, the result is UNKNOWN.
168 * Otherwise, the result is FALSE.
170 if (node->hashnulls == NULL)
172 ExecClearTuple(slot);
173 return BoolGetDatum(false);
175 if (slotAllNulls(slot))
177 ExecClearTuple(slot);
179 return BoolGetDatum(false);
181 /* Scan partly-null table first, since more likely to get a match */
182 if (node->havenullrows &&
183 findPartialMatch(node->hashnulls, slot))
185 ExecClearTuple(slot);
187 return BoolGetDatum(false);
189 if (node->havehashrows &&
190 findPartialMatch(node->hashtable, slot))
192 ExecClearTuple(slot);
194 return BoolGetDatum(false);
196 ExecClearTuple(slot);
197 return BoolGetDatum(false);
201 * ExecScanSubPlan: default case where we have to rescan subplan each time
204 ExecScanSubPlan(SubPlanState *node,
205 ExprContext *econtext,
208 SubPlan *subplan = (SubPlan *) node->xprstate.expr;
209 PlanState *planstate = node->planstate;
210 SubLinkType subLinkType = subplan->subLinkType;
211 MemoryContext oldcontext;
212 TupleTableSlot *slot;
214 bool found = false; /* TRUE if got at least one subplan tuple */
217 ArrayBuildState *astate = NULL;
220 * We are probably in a short-lived expression-evaluation context. Switch
221 * to the per-query context for manipulating the child plan's chgParam,
222 * calling ExecProcNode on it, etc.
224 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
227 * Set Params of this plan from parent plan correlation values. (Any
228 * calculation we have to do is done in the parent econtext, since the
229 * Param values don't need to have per-query lifetime.)
231 Assert(list_length(subplan->parParam) == list_length(node->args));
233 forboth(l, subplan->parParam, pvar, node->args)
235 int paramid = lfirst_int(l);
236 ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
238 prm->value = ExecEvalExprSwitchContext((ExprState *) lfirst(pvar),
242 planstate->chgParam = bms_add_member(planstate->chgParam, paramid);
245 ExecReScan(planstate, NULL);
248 * For all sublink types except EXPR_SUBLINK and ARRAY_SUBLINK, the result
249 * is boolean as are the results of the combining operators. We combine
250 * results across tuples (if the subplan produces more than one) using OR
251 * semantics for ANY_SUBLINK or AND semantics for ALL_SUBLINK.
252 * (ROWCOMPARE_SUBLINK doesn't allow multiple tuples from the subplan.)
253 * NULL results from the combining operators are handled according to the
254 * usual SQL semantics for OR and AND. The result for no input tuples is
255 * FALSE for ANY_SUBLINK, TRUE for ALL_SUBLINK, NULL for
256 * ROWCOMPARE_SUBLINK.
258 * For EXPR_SUBLINK we require the subplan to produce no more than one
259 * tuple, else an error is raised. For ARRAY_SUBLINK we allow the subplan
260 * to produce more than one tuple. In either case, if zero tuples are
261 * produced, we return NULL. Assuming we get a tuple, we just use its
262 * first column (there can be only one non-junk column in this case).
264 result = BoolGetDatum(subLinkType == ALL_SUBLINK);
267 for (slot = ExecProcNode(planstate);
269 slot = ExecProcNode(planstate))
271 TupleDesc tdesc = slot->tts_tupleDescriptor;
277 if (subLinkType == EXISTS_SUBLINK)
280 result = BoolGetDatum(true);
284 if (subLinkType == EXPR_SUBLINK)
286 /* cannot allow multiple input tuples for EXPR sublink */
289 (errcode(ERRCODE_CARDINALITY_VIOLATION),
290 errmsg("more than one row returned by a subquery used as an expression")));
294 * We need to copy the subplan's tuple in case the result is of
295 * pass-by-ref type --- our return value will point into this
296 * copied tuple! Can't use the subplan's instance of the tuple
297 * since it won't still be valid after next ExecProcNode() call.
298 * node->curTuple keeps track of the copied tuple for eventual
302 heap_freetuple(node->curTuple);
303 node->curTuple = ExecCopySlotTuple(slot);
305 result = heap_getattr(node->curTuple, 1, tdesc, isNull);
306 /* keep scanning subplan to make sure there's only one tuple */
310 if (subLinkType == ARRAY_SUBLINK)
316 /* stash away current value */
317 dvalue = slot_getattr(slot, 1, &disnull);
318 astate = accumArrayResult(astate, dvalue, disnull,
319 tdesc->attrs[0]->atttypid,
321 /* keep scanning subplan to collect all values */
325 /* cannot allow multiple input tuples for ROWCOMPARE sublink either */
326 if (subLinkType == ROWCOMPARE_SUBLINK && found)
328 (errcode(ERRCODE_CARDINALITY_VIOLATION),
329 errmsg("more than one row returned by a subquery used as an expression")));
334 * For ALL, ANY, and ROWCOMPARE sublinks, load up the Params
335 * representing the columns of the sub-select, and then evaluate the
336 * combining expression.
339 foreach(plst, subplan->paramIds)
341 int paramid = lfirst_int(plst);
342 ParamExecData *prmdata;
344 prmdata = &(econtext->ecxt_param_exec_vals[paramid]);
345 Assert(prmdata->execPlan == NULL);
346 prmdata->value = slot_getattr(slot, col, &(prmdata->isnull));
350 rowresult = ExecEvalExprSwitchContext(node->testexpr, econtext,
353 if (subLinkType == ANY_SUBLINK)
355 /* combine across rows per OR semantics */
358 else if (DatumGetBool(rowresult))
360 result = BoolGetDatum(true);
362 break; /* needn't look at any more rows */
365 else if (subLinkType == ALL_SUBLINK)
367 /* combine across rows per AND semantics */
370 else if (!DatumGetBool(rowresult))
372 result = BoolGetDatum(false);
374 break; /* needn't look at any more rows */
379 /* must be ROWCOMPARE_SUBLINK */
388 * deal with empty subplan result. result/isNull were previously
389 * initialized correctly for all sublink types except EXPR, ARRAY, and
390 * ROWCOMPARE; for those, return NULL.
392 if (subLinkType == EXPR_SUBLINK ||
393 subLinkType == ARRAY_SUBLINK ||
394 subLinkType == ROWCOMPARE_SUBLINK)
400 else if (subLinkType == ARRAY_SUBLINK)
402 Assert(astate != NULL);
403 /* We return the result in the caller's context */
404 result = makeArrayResult(astate, oldcontext);
407 MemoryContextSwitchTo(oldcontext);
413 * buildSubPlanHash: load hash table by scanning subplan output.
416 buildSubPlanHash(SubPlanState *node, ExprContext *econtext)
418 SubPlan *subplan = (SubPlan *) node->xprstate.expr;
419 PlanState *planstate = node->planstate;
420 int ncols = list_length(subplan->paramIds);
421 ExprContext *innerecontext = node->innerecontext;
422 MemoryContext tempcxt = innerecontext->ecxt_per_tuple_memory;
423 MemoryContext oldcontext;
425 TupleTableSlot *slot;
427 Assert(subplan->subLinkType == ANY_SUBLINK);
430 * If we already had any hash tables, destroy 'em; then create empty hash
433 * If we need to distinguish accurately between FALSE and UNKNOWN (i.e.,
434 * NULL) results of the IN operation, then we have to store subplan output
435 * rows that are partly or wholly NULL. We store such rows in a separate
436 * hash table that we expect will be much smaller than the main table. (We
437 * can use hashing to eliminate partly-null rows that are not distinct. We
438 * keep them separate to minimize the cost of the inevitable full-table
439 * searches; see findPartialMatch.)
441 * If it's not necessary to distinguish FALSE and UNKNOWN, then we don't
442 * need to store subplan output rows that contain NULL.
444 MemoryContextReset(node->tablecxt);
445 node->hashtable = NULL;
446 node->hashnulls = NULL;
447 node->havehashrows = false;
448 node->havenullrows = false;
450 nbuckets = (int) ceil(planstate->plan->plan_rows);
454 node->hashtable = BuildTupleHashTable(ncols,
457 node->tab_hash_funcs,
459 sizeof(TupleHashEntryData),
463 if (!subplan->unknownEqFalse)
466 nbuckets = 1; /* there can only be one entry */
473 node->hashnulls = BuildTupleHashTable(ncols,
476 node->tab_hash_funcs,
478 sizeof(TupleHashEntryData),
484 * We are probably in a short-lived expression-evaluation context. Switch
485 * to the per-query context for manipulating the child plan.
487 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
490 * Reset subplan to start.
492 ExecReScan(planstate, NULL);
495 * Scan the subplan and load the hash table(s). Note that when there are
496 * duplicate rows coming out of the sub-select, only one copy is stored.
498 for (slot = ExecProcNode(planstate);
500 slot = ExecProcNode(planstate))
507 * Load up the Params representing the raw sub-select outputs, then
508 * form the projection tuple to store in the hashtable.
510 foreach(plst, subplan->paramIds)
512 int paramid = lfirst_int(plst);
513 ParamExecData *prmdata;
515 prmdata = &(innerecontext->ecxt_param_exec_vals[paramid]);
516 Assert(prmdata->execPlan == NULL);
517 prmdata->value = slot_getattr(slot, col,
521 slot = ExecProject(node->projRight, NULL);
524 * If result contains any nulls, store separately or not at all.
526 if (slotNoNulls(slot))
528 (void) LookupTupleHashEntry(node->hashtable, slot, &isnew);
529 node->havehashrows = true;
531 else if (node->hashnulls)
533 (void) LookupTupleHashEntry(node->hashnulls, slot, &isnew);
534 node->havenullrows = true;
538 * Reset innerecontext after each inner tuple to free any memory used
539 * in hash computation or comparison routines.
541 ResetExprContext(innerecontext);
545 * Since the projected tuples are in the sub-query's context and not the
546 * main context, we'd better clear the tuple slot before there's any
547 * chance of a reset of the sub-query's context. Else we will have the
548 * potential for a double free attempt. (XXX possibly no longer needed,
551 ExecClearTuple(node->projRight->pi_slot);
553 MemoryContextSwitchTo(oldcontext);
557 * findPartialMatch: does the hashtable contain an entry that is not
558 * provably distinct from the tuple?
560 * We have to scan the whole hashtable; we can't usefully use hashkeys
561 * to guide probing, since we might get partial matches on tuples with
562 * hashkeys quite unrelated to what we'd get from the given tuple.
565 findPartialMatch(TupleHashTable hashtable, TupleTableSlot *slot)
567 int numCols = hashtable->numCols;
568 AttrNumber *keyColIdx = hashtable->keyColIdx;
569 TupleHashIterator hashiter;
570 TupleHashEntry entry;
572 InitTupleHashIterator(hashtable, &hashiter);
573 while ((entry = ScanTupleHashTable(&hashiter)) != NULL)
575 ExecStoreMinimalTuple(entry->firstTuple, hashtable->tableslot, false);
576 if (!execTuplesUnequal(slot, hashtable->tableslot,
578 hashtable->cur_eq_funcs,
581 TermTupleHashIterator(&hashiter);
585 /* No TermTupleHashIterator call needed here */
590 * slotAllNulls: is the slot completely NULL?
592 * This does not test for dropped columns, which is OK because we only
593 * use it on projected tuples.
596 slotAllNulls(TupleTableSlot *slot)
598 int ncols = slot->tts_tupleDescriptor->natts;
601 for (i = 1; i <= ncols; i++)
603 if (!slot_attisnull(slot, i))
610 * slotNoNulls: is the slot entirely not NULL?
612 * This does not test for dropped columns, which is OK because we only
613 * use it on projected tuples.
616 slotNoNulls(TupleTableSlot *slot)
618 int ncols = slot->tts_tupleDescriptor->natts;
621 for (i = 1; i <= ncols; i++)
623 if (slot_attisnull(slot, i))
629 /* ----------------------------------------------------------------
632 * Create a SubPlanState for a SubPlan; this is the SubPlan-specific part
633 * of ExecInitExpr(). We split it out so that it can be used for InitPlans
634 * as well as regular SubPlans. Note that we don't link the SubPlan into
635 * the parent's subPlan list, because that shouldn't happen for InitPlans.
636 * Instead, ExecInitExpr() does that one part.
637 * ----------------------------------------------------------------
640 ExecInitSubPlan(SubPlan *subplan, PlanState *parent)
642 SubPlanState *sstate = makeNode(SubPlanState);
643 EState *estate = parent->state;
645 sstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecSubPlan;
646 sstate->xprstate.expr = (Expr *) subplan;
648 /* Link the SubPlanState to already-initialized subplan */
649 sstate->planstate = (PlanState *) list_nth(estate->es_subplanstates,
650 subplan->plan_id - 1);
652 /* Initialize subexpressions */
653 sstate->testexpr = ExecInitExpr((Expr *) subplan->testexpr, parent);
654 sstate->args = (List *) ExecInitExpr((Expr *) subplan->args, parent);
657 * initialize my state
659 sstate->curTuple = NULL;
660 sstate->projLeft = NULL;
661 sstate->projRight = NULL;
662 sstate->hashtable = NULL;
663 sstate->hashnulls = NULL;
664 sstate->tablecxt = NULL;
665 sstate->innerecontext = NULL;
666 sstate->keyColIdx = NULL;
667 sstate->tab_hash_funcs = NULL;
668 sstate->tab_eq_funcs = NULL;
669 sstate->lhs_hash_funcs = NULL;
670 sstate->cur_eq_funcs = NULL;
673 * If this plan is un-correlated or undirect correlated one and want to
674 * set params for parent plan then mark parameters as needing evaluation.
676 * Note that in the case of un-correlated subqueries we don't care about
677 * setting parent->chgParam here: indices take care about it, for others -
678 * it doesn't matter...
680 if (subplan->setParam != NIL)
684 foreach(lst, subplan->setParam)
686 int paramid = lfirst_int(lst);
687 ParamExecData *prm = &(estate->es_param_exec_vals[paramid]);
689 prm->execPlan = sstate;
694 * If we are going to hash the subquery output, initialize relevant stuff.
695 * (We don't create the hashtable until needed, though.)
697 if (subplan->useHashTable)
703 TupleTableSlot *slot;
711 /* We need a memory context to hold the hash table(s) */
713 AllocSetContextCreate(CurrentMemoryContext,
714 "Subplan HashTable Context",
715 ALLOCSET_DEFAULT_MINSIZE,
716 ALLOCSET_DEFAULT_INITSIZE,
717 ALLOCSET_DEFAULT_MAXSIZE);
718 /* and a short-lived exprcontext for function evaluation */
719 sstate->innerecontext = CreateExprContext(estate);
720 /* Silly little array of column numbers 1..n */
721 ncols = list_length(subplan->paramIds);
722 sstate->keyColIdx = (AttrNumber *) palloc(ncols * sizeof(AttrNumber));
723 for (i = 0; i < ncols; i++)
724 sstate->keyColIdx[i] = i + 1;
727 * We use ExecProject to evaluate the lefthand and righthand
728 * expression lists and form tuples. (You might think that we could
729 * use the sub-select's output tuples directly, but that is not the
730 * case if we had to insert any run-time coercions of the sub-select's
731 * output datatypes; anyway this avoids storing any resjunk columns
732 * that might be in the sub-select's output.) Run through the
733 * combining expressions to build tlists for the lefthand and
734 * righthand sides. We need both the ExprState list (for ExecProject)
735 * and the underlying parse Exprs (for ExecTypeFromTL).
737 * We also extract the combining operators themselves to initialize
738 * the equality and hashing functions for the hash tables.
740 if (IsA(sstate->testexpr->expr, OpExpr))
742 /* single combining operator */
743 oplist = list_make1(sstate->testexpr);
745 else if (and_clause((Node *) sstate->testexpr->expr))
747 /* multiple combining operators */
748 Assert(IsA(sstate->testexpr, BoolExprState));
749 oplist = ((BoolExprState *) sstate->testexpr)->args;
753 /* shouldn't see anything else in a hashable subplan */
754 elog(ERROR, "unrecognized testexpr type: %d",
755 (int) nodeTag(sstate->testexpr->expr));
756 oplist = NIL; /* keep compiler quiet */
758 Assert(list_length(oplist) == ncols);
760 lefttlist = righttlist = NIL;
761 leftptlist = rightptlist = NIL;
762 sstate->tab_hash_funcs = (FmgrInfo *) palloc(ncols * sizeof(FmgrInfo));
763 sstate->tab_eq_funcs = (FmgrInfo *) palloc(ncols * sizeof(FmgrInfo));
764 sstate->lhs_hash_funcs = (FmgrInfo *) palloc(ncols * sizeof(FmgrInfo));
765 sstate->cur_eq_funcs = (FmgrInfo *) palloc(ncols * sizeof(FmgrInfo));
769 FuncExprState *fstate = (FuncExprState *) lfirst(l);
770 OpExpr *opexpr = (OpExpr *) fstate->xprstate.expr;
774 GenericExprState *tlestate;
779 Assert(IsA(fstate, FuncExprState));
780 Assert(IsA(opexpr, OpExpr));
781 Assert(list_length(fstate->args) == 2);
783 /* Process lefthand argument */
784 exstate = (ExprState *) linitial(fstate->args);
785 expr = exstate->expr;
786 tle = makeTargetEntry(expr,
790 tlestate = makeNode(GenericExprState);
791 tlestate->xprstate.expr = (Expr *) tle;
792 tlestate->xprstate.evalfunc = NULL;
793 tlestate->arg = exstate;
794 lefttlist = lappend(lefttlist, tlestate);
795 leftptlist = lappend(leftptlist, tle);
797 /* Process righthand argument */
798 exstate = (ExprState *) lsecond(fstate->args);
799 expr = exstate->expr;
800 tle = makeTargetEntry(expr,
804 tlestate = makeNode(GenericExprState);
805 tlestate->xprstate.expr = (Expr *) tle;
806 tlestate->xprstate.evalfunc = NULL;
807 tlestate->arg = exstate;
808 righttlist = lappend(righttlist, tlestate);
809 rightptlist = lappend(rightptlist, tle);
811 /* Lookup the equality function (potentially cross-type) */
812 fmgr_info(opexpr->opfuncid, &sstate->cur_eq_funcs[i - 1]);
813 sstate->cur_eq_funcs[i - 1].fn_expr = (Node *) opexpr;
815 /* Look up the equality function for the RHS type */
816 if (!get_compatible_hash_operators(opexpr->opno,
818 elog(ERROR, "could not find compatible hash operator for operator %u",
820 fmgr_info(get_opcode(rhs_eq_oper), &sstate->tab_eq_funcs[i - 1]);
822 /* Lookup the associated hash functions */
823 if (!get_op_hash_functions(opexpr->opno,
824 &left_hashfn, &right_hashfn))
825 elog(ERROR, "could not find hash function for hash operator %u",
827 fmgr_info(left_hashfn, &sstate->lhs_hash_funcs[i - 1]);
828 fmgr_info(right_hashfn, &sstate->tab_hash_funcs[i - 1]);
834 * Create a tupletable to hold these tuples. (Note: we never bother
835 * to free the tupletable explicitly; that's okay because it will
836 * never store raw disk tuples that might have associated buffer pins.
837 * The only resource involved is memory, which will be cleaned up by
838 * freeing the query context.)
840 tupTable = ExecCreateTupleTable(2);
843 * Construct tupdescs, slots and projection nodes for left and right
844 * sides. The lefthand expressions will be evaluated in the parent
845 * plan node's exprcontext, which we don't have access to here.
846 * Fortunately we can just pass NULL for now and fill it in later
847 * (hack alert!). The righthand expressions will be evaluated in our
850 tupDesc = ExecTypeFromTL(leftptlist, false);
851 slot = ExecAllocTableSlot(tupTable);
852 ExecSetSlotDescriptor(slot, tupDesc);
853 sstate->projLeft = ExecBuildProjectionInfo(lefttlist,
858 tupDesc = ExecTypeFromTL(rightptlist, false);
859 slot = ExecAllocTableSlot(tupTable);
860 ExecSetSlotDescriptor(slot, tupDesc);
861 sstate->projRight = ExecBuildProjectionInfo(righttlist,
862 sstate->innerecontext,
870 /* ----------------------------------------------------------------
873 * Executes an InitPlan subplan and sets its output parameters.
875 * This is called from ExecEvalParam() when the value of a PARAM_EXEC
876 * parameter is requested and the param's execPlan field is set (indicating
877 * that the param has not yet been evaluated). This allows lazy evaluation
878 * of initplans: we don't run the subplan until/unless we need its output.
879 * Note that this routine MUST clear the execPlan fields of the plan's
880 * output parameters after evaluating them!
881 * ----------------------------------------------------------------
884 ExecSetParamPlan(SubPlanState *node, ExprContext *econtext)
886 SubPlan *subplan = (SubPlan *) node->xprstate.expr;
887 PlanState *planstate = node->planstate;
888 SubLinkType subLinkType = subplan->subLinkType;
889 MemoryContext oldcontext;
890 TupleTableSlot *slot;
893 ArrayBuildState *astate = NULL;
896 * Must switch to per-query memory context.
898 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
900 if (subLinkType == ANY_SUBLINK ||
901 subLinkType == ALL_SUBLINK)
902 elog(ERROR, "ANY/ALL subselect unsupported as initplan");
904 if (planstate->chgParam != NULL)
905 ExecReScan(planstate, NULL);
907 for (slot = ExecProcNode(planstate);
909 slot = ExecProcNode(planstate))
911 TupleDesc tdesc = slot->tts_tupleDescriptor;
914 if (subLinkType == EXISTS_SUBLINK)
916 /* There can be only one param... */
917 int paramid = linitial_int(subplan->setParam);
918 ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
920 prm->execPlan = NULL;
921 prm->value = BoolGetDatum(true);
927 if (subLinkType == ARRAY_SUBLINK)
933 /* stash away current value */
934 dvalue = slot_getattr(slot, 1, &disnull);
935 astate = accumArrayResult(astate, dvalue, disnull,
936 tdesc->attrs[0]->atttypid,
938 /* keep scanning subplan to collect all values */
943 (subLinkType == EXPR_SUBLINK ||
944 subLinkType == ROWCOMPARE_SUBLINK))
946 (errcode(ERRCODE_CARDINALITY_VIOLATION),
947 errmsg("more than one row returned by a subquery used as an expression")));
952 * We need to copy the subplan's tuple into our own context, in case
953 * any of the params are pass-by-ref type --- the pointers stored in
954 * the param structs will point at this copied tuple! node->curTuple
955 * keeps track of the copied tuple for eventual freeing.
958 heap_freetuple(node->curTuple);
959 node->curTuple = ExecCopySlotTuple(slot);
962 * Now set all the setParam params from the columns of the tuple
964 foreach(l, subplan->setParam)
966 int paramid = lfirst_int(l);
967 ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
969 prm->execPlan = NULL;
970 prm->value = heap_getattr(node->curTuple, i, tdesc,
978 if (subLinkType == EXISTS_SUBLINK)
980 /* There can be only one param... */
981 int paramid = linitial_int(subplan->setParam);
982 ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
984 prm->execPlan = NULL;
985 prm->value = BoolGetDatum(false);
990 foreach(l, subplan->setParam)
992 int paramid = lfirst_int(l);
993 ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
995 prm->execPlan = NULL;
996 prm->value = (Datum) 0;
1001 else if (subLinkType == ARRAY_SUBLINK)
1003 /* There can be only one param... */
1004 int paramid = linitial_int(subplan->setParam);
1005 ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
1007 Assert(astate != NULL);
1008 prm->execPlan = NULL;
1009 /* We build the result in query context so it won't disappear */
1010 prm->value = makeArrayResult(astate, econtext->ecxt_per_query_memory);
1011 prm->isnull = false;
1014 MemoryContextSwitchTo(oldcontext);
1018 * Mark an initplan as needing recalculation
1021 ExecReScanSetParamPlan(SubPlanState *node, PlanState *parent)
1023 PlanState *planstate = node->planstate;
1024 SubPlan *subplan = (SubPlan *) node->xprstate.expr;
1025 EState *estate = parent->state;
1029 if (subplan->parParam != NIL)
1030 elog(ERROR, "direct correlated subquery unsupported as initplan");
1031 if (subplan->setParam == NIL)
1032 elog(ERROR, "setParam list of initplan is empty");
1033 if (bms_is_empty(planstate->plan->extParam))
1034 elog(ERROR, "extParam set of initplan is empty");
1037 * Don't actually re-scan: ExecSetParamPlan does it if needed.
1041 * Mark this subplan's output parameters as needing recalculation
1043 foreach(l, subplan->setParam)
1045 int paramid = lfirst_int(l);
1046 ParamExecData *prm = &(estate->es_param_exec_vals[paramid]);
1048 prm->execPlan = node;
1049 parent->chgParam = bms_add_member(parent->chgParam, paramid);