1 /*-------------------------------------------------------------------------
4 * routines to support subselects
6 * Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
10 * src/backend/executor/nodeSubplan.c
12 *-------------------------------------------------------------------------
16 * ExecSubPlan - process a subselect
17 * ExecInitSubPlan - initialize a subselect
23 #include "executor/executor.h"
24 #include "executor/nodeSubplan.h"
25 #include "nodes/makefuncs.h"
26 #include "optimizer/clauses.h"
27 #include "utils/array.h"
28 #include "utils/lsyscache.h"
29 #include "utils/memutils.h"
32 static Datum ExecSubPlan(SubPlanState *node,
33 ExprContext *econtext,
35 ExprDoneCond *isDone);
36 static Datum ExecAlternativeSubPlan(AlternativeSubPlanState *node,
37 ExprContext *econtext,
39 ExprDoneCond *isDone);
40 static Datum ExecHashSubPlan(SubPlanState *node,
41 ExprContext *econtext,
43 static Datum ExecScanSubPlan(SubPlanState *node,
44 ExprContext *econtext,
46 static void buildSubPlanHash(SubPlanState *node, ExprContext *econtext);
47 static bool findPartialMatch(TupleHashTable hashtable, TupleTableSlot *slot);
48 static bool slotAllNulls(TupleTableSlot *slot);
49 static bool slotNoNulls(TupleTableSlot *slot);
52 /* ----------------------------------------------------------------
54 * ----------------------------------------------------------------
57 ExecSubPlan(SubPlanState *node,
58 ExprContext *econtext,
62 SubPlan *subplan = (SubPlan *) node->xprstate.expr;
64 /* Set default values for result flags: non-null, not a set result */
67 *isDone = ExprSingleResult;
70 if (subplan->subLinkType == CTE_SUBLINK)
71 elog(ERROR, "CTE subplans should not be executed via ExecSubPlan");
72 if (subplan->setParam != NIL)
73 elog(ERROR, "cannot set parent params from subquery");
75 /* Select appropriate evaluation strategy */
76 if (subplan->useHashTable)
77 return ExecHashSubPlan(node, econtext, isNull);
79 return ExecScanSubPlan(node, econtext, isNull);
83 * ExecHashSubPlan: store subselect result in an in-memory hash table
86 ExecHashSubPlan(SubPlanState *node,
87 ExprContext *econtext,
90 SubPlan *subplan = (SubPlan *) node->xprstate.expr;
91 PlanState *planstate = node->planstate;
94 /* Shouldn't have any direct correlation Vars */
95 if (subplan->parParam != NIL || node->args != NIL)
96 elog(ERROR, "hashed subplan with direct correlation not supported");
99 * If first time through or we need to rescan the subplan, build the hash
102 if (node->hashtable == NULL || planstate->chgParam != NULL)
103 buildSubPlanHash(node, econtext);
106 * The result for an empty subplan is always FALSE; no need to evaluate
110 if (!node->havehashrows && !node->havenullrows)
111 return BoolGetDatum(false);
114 * Evaluate lefthand expressions and form a projection tuple. First we
115 * have to set the econtext to use (hack alert!).
117 node->projLeft->pi_exprContext = econtext;
118 slot = ExecProject(node->projLeft, NULL);
121 * Note: because we are typically called in a per-tuple context, we have
122 * to explicitly clear the projected tuple before returning. Otherwise,
123 * we'll have a double-free situation: the per-tuple context will probably
124 * be reset before we're called again, and then the tuple slot will think
125 * it still needs to free the tuple.
129 * If the LHS is all non-null, probe for an exact match in the main hash
130 * table. If we find one, the result is TRUE. Otherwise, scan the
131 * partly-null table to see if there are any rows that aren't provably
132 * unequal to the LHS; if so, the result is UNKNOWN. (We skip that part
133 * if we don't care about UNKNOWN.) Otherwise, the result is FALSE.
135 * Note: the reason we can avoid a full scan of the main hash table is
136 * that the combining operators are assumed never to yield NULL when both
137 * inputs are non-null. If they were to do so, we might need to produce
138 * UNKNOWN instead of FALSE because of an UNKNOWN result in comparing the
139 * LHS to some main-table entry --- which is a comparison we will not even
140 * make, unless there's a chance match of hash keys.
142 if (slotNoNulls(slot))
144 if (node->havehashrows &&
145 FindTupleHashEntry(node->hashtable,
148 node->lhs_hash_funcs) != NULL)
150 ExecClearTuple(slot);
151 return BoolGetDatum(true);
153 if (node->havenullrows &&
154 findPartialMatch(node->hashnulls, slot))
156 ExecClearTuple(slot);
158 return BoolGetDatum(false);
160 ExecClearTuple(slot);
161 return BoolGetDatum(false);
165 * When the LHS is partly or wholly NULL, we can never return TRUE. If we
166 * don't care about UNKNOWN, just return FALSE. Otherwise, if the LHS is
167 * wholly NULL, immediately return UNKNOWN. (Since the combining
168 * operators are strict, the result could only be FALSE if the sub-select
169 * were empty, but we already handled that case.) Otherwise, we must scan
170 * both the main and partly-null tables to see if there are any rows that
171 * aren't provably unequal to the LHS; if so, the result is UNKNOWN.
172 * Otherwise, the result is FALSE.
174 if (node->hashnulls == NULL)
176 ExecClearTuple(slot);
177 return BoolGetDatum(false);
179 if (slotAllNulls(slot))
181 ExecClearTuple(slot);
183 return BoolGetDatum(false);
185 /* Scan partly-null table first, since more likely to get a match */
186 if (node->havenullrows &&
187 findPartialMatch(node->hashnulls, slot))
189 ExecClearTuple(slot);
191 return BoolGetDatum(false);
193 if (node->havehashrows &&
194 findPartialMatch(node->hashtable, slot))
196 ExecClearTuple(slot);
198 return BoolGetDatum(false);
200 ExecClearTuple(slot);
201 return BoolGetDatum(false);
205 * ExecScanSubPlan: default case where we have to rescan subplan each time
208 ExecScanSubPlan(SubPlanState *node,
209 ExprContext *econtext,
212 SubPlan *subplan = (SubPlan *) node->xprstate.expr;
213 PlanState *planstate = node->planstate;
214 SubLinkType subLinkType = subplan->subLinkType;
215 MemoryContext oldcontext;
216 TupleTableSlot *slot;
218 bool found = false; /* TRUE if got at least one subplan tuple */
221 ArrayBuildState *astate = NULL;
224 * We are probably in a short-lived expression-evaluation context. Switch
225 * to the per-query context for manipulating the child plan's chgParam,
226 * calling ExecProcNode on it, etc.
228 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
231 * Set Params of this plan from parent plan correlation values. (Any
232 * calculation we have to do is done in the parent econtext, since the
233 * Param values don't need to have per-query lifetime.)
235 Assert(list_length(subplan->parParam) == list_length(node->args));
237 forboth(l, subplan->parParam, pvar, node->args)
239 int paramid = lfirst_int(l);
240 ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
242 prm->value = ExecEvalExprSwitchContext((ExprState *) lfirst(pvar),
246 planstate->chgParam = bms_add_member(planstate->chgParam, paramid);
250 * Now that we've set up its parameters, we can reset the subplan.
252 ExecReScan(planstate);
255 * For all sublink types except EXPR_SUBLINK and ARRAY_SUBLINK, the result
256 * is boolean as are the results of the combining operators. We combine
257 * results across tuples (if the subplan produces more than one) using OR
258 * semantics for ANY_SUBLINK or AND semantics for ALL_SUBLINK.
259 * (ROWCOMPARE_SUBLINK doesn't allow multiple tuples from the subplan.)
260 * NULL results from the combining operators are handled according to the
261 * usual SQL semantics for OR and AND. The result for no input tuples is
262 * FALSE for ANY_SUBLINK, TRUE for ALL_SUBLINK, NULL for
263 * ROWCOMPARE_SUBLINK.
265 * For EXPR_SUBLINK we require the subplan to produce no more than one
266 * tuple, else an error is raised. If zero tuples are produced, we return
267 * NULL. Assuming we get a tuple, we just use its first column (there can
268 * be only one non-junk column in this case).
270 * For ARRAY_SUBLINK we allow the subplan to produce any number of tuples,
271 * and form an array of the first column's values. Note in particular
272 * that we produce a zero-element array if no tuples are produced (this is
273 * a change from pre-8.3 behavior of returning NULL).
275 result = BoolGetDatum(subLinkType == ALL_SUBLINK);
278 for (slot = ExecProcNode(planstate);
280 slot = ExecProcNode(planstate))
282 TupleDesc tdesc = slot->tts_tupleDescriptor;
288 if (subLinkType == EXISTS_SUBLINK)
291 result = BoolGetDatum(true);
295 if (subLinkType == EXPR_SUBLINK)
297 /* cannot allow multiple input tuples for EXPR sublink */
300 (errcode(ERRCODE_CARDINALITY_VIOLATION),
301 errmsg("more than one row returned by a subquery used as an expression")));
305 * We need to copy the subplan's tuple in case the result is of
306 * pass-by-ref type --- our return value will point into this
307 * copied tuple! Can't use the subplan's instance of the tuple
308 * since it won't still be valid after next ExecProcNode() call.
309 * node->curTuple keeps track of the copied tuple for eventual
313 heap_freetuple(node->curTuple);
314 node->curTuple = ExecCopySlotTuple(slot);
316 result = heap_getattr(node->curTuple, 1, tdesc, isNull);
317 /* keep scanning subplan to make sure there's only one tuple */
321 if (subLinkType == ARRAY_SUBLINK)
327 /* stash away current value */
328 Assert(subplan->firstColType == tdesc->attrs[0]->atttypid);
329 dvalue = slot_getattr(slot, 1, &disnull);
330 astate = accumArrayResult(astate, dvalue, disnull,
331 subplan->firstColType, oldcontext);
332 /* keep scanning subplan to collect all values */
336 /* cannot allow multiple input tuples for ROWCOMPARE sublink either */
337 if (subLinkType == ROWCOMPARE_SUBLINK && found)
339 (errcode(ERRCODE_CARDINALITY_VIOLATION),
340 errmsg("more than one row returned by a subquery used as an expression")));
345 * For ALL, ANY, and ROWCOMPARE sublinks, load up the Params
346 * representing the columns of the sub-select, and then evaluate the
347 * combining expression.
350 foreach(plst, subplan->paramIds)
352 int paramid = lfirst_int(plst);
353 ParamExecData *prmdata;
355 prmdata = &(econtext->ecxt_param_exec_vals[paramid]);
356 Assert(prmdata->execPlan == NULL);
357 prmdata->value = slot_getattr(slot, col, &(prmdata->isnull));
361 rowresult = ExecEvalExprSwitchContext(node->testexpr, econtext,
364 if (subLinkType == ANY_SUBLINK)
366 /* combine across rows per OR semantics */
369 else if (DatumGetBool(rowresult))
371 result = BoolGetDatum(true);
373 break; /* needn't look at any more rows */
376 else if (subLinkType == ALL_SUBLINK)
378 /* combine across rows per AND semantics */
381 else if (!DatumGetBool(rowresult))
383 result = BoolGetDatum(false);
385 break; /* needn't look at any more rows */
390 /* must be ROWCOMPARE_SUBLINK */
396 MemoryContextSwitchTo(oldcontext);
398 if (subLinkType == ARRAY_SUBLINK)
400 /* We return the result in the caller's context */
402 result = makeArrayResult(astate, oldcontext);
404 result = PointerGetDatum(construct_empty_array(subplan->firstColType));
409 * deal with empty subplan result. result/isNull were previously
410 * initialized correctly for all sublink types except EXPR and
411 * ROWCOMPARE; for those, return NULL.
413 if (subLinkType == EXPR_SUBLINK ||
414 subLinkType == ROWCOMPARE_SUBLINK)
425 * buildSubPlanHash: load hash table by scanning subplan output.
428 buildSubPlanHash(SubPlanState *node, ExprContext *econtext)
430 SubPlan *subplan = (SubPlan *) node->xprstate.expr;
431 PlanState *planstate = node->planstate;
432 int ncols = list_length(subplan->paramIds);
433 ExprContext *innerecontext = node->innerecontext;
434 MemoryContext oldcontext;
436 TupleTableSlot *slot;
438 Assert(subplan->subLinkType == ANY_SUBLINK);
441 * If we already had any hash tables, destroy 'em; then create empty hash
444 * If we need to distinguish accurately between FALSE and UNKNOWN (i.e.,
445 * NULL) results of the IN operation, then we have to store subplan output
446 * rows that are partly or wholly NULL. We store such rows in a separate
447 * hash table that we expect will be much smaller than the main table. (We
448 * can use hashing to eliminate partly-null rows that are not distinct. We
449 * keep them separate to minimize the cost of the inevitable full-table
450 * searches; see findPartialMatch.)
452 * If it's not necessary to distinguish FALSE and UNKNOWN, then we don't
453 * need to store subplan output rows that contain NULL.
455 MemoryContextReset(node->hashtablecxt);
456 node->hashtable = NULL;
457 node->hashnulls = NULL;
458 node->havehashrows = false;
459 node->havenullrows = false;
461 nbuckets = (long) Min(planstate->plan->plan_rows, (double) LONG_MAX);
465 node->hashtable = BuildTupleHashTable(ncols,
468 node->tab_hash_funcs,
470 sizeof(TupleHashEntryData),
474 if (!subplan->unknownEqFalse)
477 nbuckets = 1; /* there can only be one entry */
484 node->hashnulls = BuildTupleHashTable(ncols,
487 node->tab_hash_funcs,
489 sizeof(TupleHashEntryData),
495 * We are probably in a short-lived expression-evaluation context. Switch
496 * to the per-query context for manipulating the child plan.
498 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
501 * Reset subplan to start.
503 ExecReScan(planstate);
506 * Scan the subplan and load the hash table(s). Note that when there are
507 * duplicate rows coming out of the sub-select, only one copy is stored.
509 for (slot = ExecProcNode(planstate);
511 slot = ExecProcNode(planstate))
518 * Load up the Params representing the raw sub-select outputs, then
519 * form the projection tuple to store in the hashtable.
521 foreach(plst, subplan->paramIds)
523 int paramid = lfirst_int(plst);
524 ParamExecData *prmdata;
526 prmdata = &(innerecontext->ecxt_param_exec_vals[paramid]);
527 Assert(prmdata->execPlan == NULL);
528 prmdata->value = slot_getattr(slot, col,
532 slot = ExecProject(node->projRight, NULL);
535 * If result contains any nulls, store separately or not at all.
537 if (slotNoNulls(slot))
539 (void) LookupTupleHashEntry(node->hashtable, slot, &isnew);
540 node->havehashrows = true;
542 else if (node->hashnulls)
544 (void) LookupTupleHashEntry(node->hashnulls, slot, &isnew);
545 node->havenullrows = true;
549 * Reset innerecontext after each inner tuple to free any memory used
550 * during ExecProject.
552 ResetExprContext(innerecontext);
556 * Since the projected tuples are in the sub-query's context and not the
557 * main context, we'd better clear the tuple slot before there's any
558 * chance of a reset of the sub-query's context. Else we will have the
559 * potential for a double free attempt. (XXX possibly no longer needed,
562 ExecClearTuple(node->projRight->pi_slot);
564 MemoryContextSwitchTo(oldcontext);
568 * findPartialMatch: does the hashtable contain an entry that is not
569 * provably distinct from the tuple?
571 * We have to scan the whole hashtable; we can't usefully use hashkeys
572 * to guide probing, since we might get partial matches on tuples with
573 * hashkeys quite unrelated to what we'd get from the given tuple.
576 findPartialMatch(TupleHashTable hashtable, TupleTableSlot *slot)
578 int numCols = hashtable->numCols;
579 AttrNumber *keyColIdx = hashtable->keyColIdx;
580 TupleHashIterator hashiter;
581 TupleHashEntry entry;
583 InitTupleHashIterator(hashtable, &hashiter);
584 while ((entry = ScanTupleHashTable(&hashiter)) != NULL)
586 ExecStoreMinimalTuple(entry->firstTuple, hashtable->tableslot, false);
587 if (!execTuplesUnequal(slot, hashtable->tableslot,
589 hashtable->cur_eq_funcs,
592 TermTupleHashIterator(&hashiter);
596 /* No TermTupleHashIterator call needed here */
601 * slotAllNulls: is the slot completely NULL?
603 * This does not test for dropped columns, which is OK because we only
604 * use it on projected tuples.
607 slotAllNulls(TupleTableSlot *slot)
609 int ncols = slot->tts_tupleDescriptor->natts;
612 for (i = 1; i <= ncols; i++)
614 if (!slot_attisnull(slot, i))
621 * slotNoNulls: is the slot entirely not NULL?
623 * This does not test for dropped columns, which is OK because we only
624 * use it on projected tuples.
627 slotNoNulls(TupleTableSlot *slot)
629 int ncols = slot->tts_tupleDescriptor->natts;
632 for (i = 1; i <= ncols; i++)
634 if (slot_attisnull(slot, i))
640 /* ----------------------------------------------------------------
643 * Create a SubPlanState for a SubPlan; this is the SubPlan-specific part
644 * of ExecInitExpr(). We split it out so that it can be used for InitPlans
645 * as well as regular SubPlans. Note that we don't link the SubPlan into
646 * the parent's subPlan list, because that shouldn't happen for InitPlans.
647 * Instead, ExecInitExpr() does that one part.
648 * ----------------------------------------------------------------
651 ExecInitSubPlan(SubPlan *subplan, PlanState *parent)
653 SubPlanState *sstate = makeNode(SubPlanState);
654 EState *estate = parent->state;
656 sstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecSubPlan;
657 sstate->xprstate.expr = (Expr *) subplan;
659 /* Link the SubPlanState to already-initialized subplan */
660 sstate->planstate = (PlanState *) list_nth(estate->es_subplanstates,
661 subplan->plan_id - 1);
663 /* Initialize subexpressions */
664 sstate->testexpr = ExecInitExpr((Expr *) subplan->testexpr, parent);
665 sstate->args = (List *) ExecInitExpr((Expr *) subplan->args, parent);
668 * initialize my state
670 sstate->curTuple = NULL;
671 sstate->curArray = PointerGetDatum(NULL);
672 sstate->projLeft = NULL;
673 sstate->projRight = NULL;
674 sstate->hashtable = NULL;
675 sstate->hashnulls = NULL;
676 sstate->hashtablecxt = NULL;
677 sstate->hashtempcxt = NULL;
678 sstate->innerecontext = NULL;
679 sstate->keyColIdx = NULL;
680 sstate->tab_hash_funcs = NULL;
681 sstate->tab_eq_funcs = NULL;
682 sstate->lhs_hash_funcs = NULL;
683 sstate->cur_eq_funcs = NULL;
686 * If this plan is un-correlated or undirect correlated one and want to
687 * set params for parent plan then mark parameters as needing evaluation.
689 * A CTE subplan's output parameter is never to be evaluated in the normal
690 * way, so skip this in that case.
692 * Note that in the case of un-correlated subqueries we don't care about
693 * setting parent->chgParam here: indices take care about it, for others -
694 * it doesn't matter...
696 if (subplan->setParam != NIL && subplan->subLinkType != CTE_SUBLINK)
700 foreach(lst, subplan->setParam)
702 int paramid = lfirst_int(lst);
703 ParamExecData *prm = &(estate->es_param_exec_vals[paramid]);
705 prm->execPlan = sstate;
710 * If we are going to hash the subquery output, initialize relevant stuff.
711 * (We don't create the hashtable until needed, though.)
713 if (subplan->useHashTable)
718 TupleTableSlot *slot;
726 /* We need a memory context to hold the hash table(s) */
727 sstate->hashtablecxt =
728 AllocSetContextCreate(CurrentMemoryContext,
729 "Subplan HashTable Context",
730 ALLOCSET_DEFAULT_MINSIZE,
731 ALLOCSET_DEFAULT_INITSIZE,
732 ALLOCSET_DEFAULT_MAXSIZE);
733 /* and a small one for the hash tables to use as temp storage */
734 sstate->hashtempcxt =
735 AllocSetContextCreate(CurrentMemoryContext,
736 "Subplan HashTable Temp Context",
737 ALLOCSET_SMALL_MINSIZE,
738 ALLOCSET_SMALL_INITSIZE,
739 ALLOCSET_SMALL_MAXSIZE);
740 /* and a short-lived exprcontext for function evaluation */
741 sstate->innerecontext = CreateExprContext(estate);
742 /* Silly little array of column numbers 1..n */
743 ncols = list_length(subplan->paramIds);
744 sstate->keyColIdx = (AttrNumber *) palloc(ncols * sizeof(AttrNumber));
745 for (i = 0; i < ncols; i++)
746 sstate->keyColIdx[i] = i + 1;
749 * We use ExecProject to evaluate the lefthand and righthand
750 * expression lists and form tuples. (You might think that we could
751 * use the sub-select's output tuples directly, but that is not the
752 * case if we had to insert any run-time coercions of the sub-select's
753 * output datatypes; anyway this avoids storing any resjunk columns
754 * that might be in the sub-select's output.) Run through the
755 * combining expressions to build tlists for the lefthand and
756 * righthand sides. We need both the ExprState list (for ExecProject)
757 * and the underlying parse Exprs (for ExecTypeFromTL).
759 * We also extract the combining operators themselves to initialize
760 * the equality and hashing functions for the hash tables.
762 if (IsA(sstate->testexpr->expr, OpExpr))
764 /* single combining operator */
765 oplist = list_make1(sstate->testexpr);
767 else if (and_clause((Node *) sstate->testexpr->expr))
769 /* multiple combining operators */
770 Assert(IsA(sstate->testexpr, BoolExprState));
771 oplist = ((BoolExprState *) sstate->testexpr)->args;
775 /* shouldn't see anything else in a hashable subplan */
776 elog(ERROR, "unrecognized testexpr type: %d",
777 (int) nodeTag(sstate->testexpr->expr));
778 oplist = NIL; /* keep compiler quiet */
780 Assert(list_length(oplist) == ncols);
782 lefttlist = righttlist = NIL;
783 leftptlist = rightptlist = NIL;
784 sstate->tab_hash_funcs = (FmgrInfo *) palloc(ncols * sizeof(FmgrInfo));
785 sstate->tab_eq_funcs = (FmgrInfo *) palloc(ncols * sizeof(FmgrInfo));
786 sstate->lhs_hash_funcs = (FmgrInfo *) palloc(ncols * sizeof(FmgrInfo));
787 sstate->cur_eq_funcs = (FmgrInfo *) palloc(ncols * sizeof(FmgrInfo));
791 FuncExprState *fstate = (FuncExprState *) lfirst(l);
792 OpExpr *opexpr = (OpExpr *) fstate->xprstate.expr;
796 GenericExprState *tlestate;
801 Assert(IsA(fstate, FuncExprState));
802 Assert(IsA(opexpr, OpExpr));
803 Assert(list_length(fstate->args) == 2);
805 /* Process lefthand argument */
806 exstate = (ExprState *) linitial(fstate->args);
807 expr = exstate->expr;
808 tle = makeTargetEntry(expr,
812 tlestate = makeNode(GenericExprState);
813 tlestate->xprstate.expr = (Expr *) tle;
814 tlestate->xprstate.evalfunc = NULL;
815 tlestate->arg = exstate;
816 lefttlist = lappend(lefttlist, tlestate);
817 leftptlist = lappend(leftptlist, tle);
819 /* Process righthand argument */
820 exstate = (ExprState *) lsecond(fstate->args);
821 expr = exstate->expr;
822 tle = makeTargetEntry(expr,
826 tlestate = makeNode(GenericExprState);
827 tlestate->xprstate.expr = (Expr *) tle;
828 tlestate->xprstate.evalfunc = NULL;
829 tlestate->arg = exstate;
830 righttlist = lappend(righttlist, tlestate);
831 rightptlist = lappend(rightptlist, tle);
833 /* Lookup the equality function (potentially cross-type) */
834 fmgr_info(opexpr->opfuncid, &sstate->cur_eq_funcs[i - 1]);
835 fmgr_info_set_expr((Node *) opexpr, &sstate->cur_eq_funcs[i - 1]);
837 /* Look up the equality function for the RHS type */
838 if (!get_compatible_hash_operators(opexpr->opno,
840 elog(ERROR, "could not find compatible hash operator for operator %u",
842 fmgr_info(get_opcode(rhs_eq_oper), &sstate->tab_eq_funcs[i - 1]);
844 /* Lookup the associated hash functions */
845 if (!get_op_hash_functions(opexpr->opno,
846 &left_hashfn, &right_hashfn))
847 elog(ERROR, "could not find hash function for hash operator %u",
849 fmgr_info(left_hashfn, &sstate->lhs_hash_funcs[i - 1]);
850 fmgr_info(right_hashfn, &sstate->tab_hash_funcs[i - 1]);
856 * Construct tupdescs, slots and projection nodes for left and right
857 * sides. The lefthand expressions will be evaluated in the parent
858 * plan node's exprcontext, which we don't have access to here.
859 * Fortunately we can just pass NULL for now and fill it in later
860 * (hack alert!). The righthand expressions will be evaluated in our
863 tupDesc = ExecTypeFromTL(leftptlist, false);
864 slot = ExecInitExtraTupleSlot(estate);
865 ExecSetSlotDescriptor(slot, tupDesc);
866 sstate->projLeft = ExecBuildProjectionInfo(lefttlist,
871 tupDesc = ExecTypeFromTL(rightptlist, false);
872 slot = ExecInitExtraTupleSlot(estate);
873 ExecSetSlotDescriptor(slot, tupDesc);
874 sstate->projRight = ExecBuildProjectionInfo(righttlist,
875 sstate->innerecontext,
883 /* ----------------------------------------------------------------
886 * Executes an InitPlan subplan and sets its output parameters.
888 * This is called from ExecEvalParamExec() when the value of a PARAM_EXEC
889 * parameter is requested and the param's execPlan field is set (indicating
890 * that the param has not yet been evaluated). This allows lazy evaluation
891 * of initplans: we don't run the subplan until/unless we need its output.
892 * Note that this routine MUST clear the execPlan fields of the plan's
893 * output parameters after evaluating them!
894 * ----------------------------------------------------------------
897 ExecSetParamPlan(SubPlanState *node, ExprContext *econtext)
899 SubPlan *subplan = (SubPlan *) node->xprstate.expr;
900 PlanState *planstate = node->planstate;
901 SubLinkType subLinkType = subplan->subLinkType;
902 MemoryContext oldcontext;
903 TupleTableSlot *slot;
906 ArrayBuildState *astate = NULL;
908 if (subLinkType == ANY_SUBLINK ||
909 subLinkType == ALL_SUBLINK)
910 elog(ERROR, "ANY/ALL subselect unsupported as initplan");
911 if (subLinkType == CTE_SUBLINK)
912 elog(ERROR, "CTE subplans should not be executed via ExecSetParamPlan");
915 * Must switch to per-query memory context.
917 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
920 * Run the plan. (If it needs to be rescanned, the first ExecProcNode
921 * call will take care of that.)
923 for (slot = ExecProcNode(planstate);
925 slot = ExecProcNode(planstate))
927 TupleDesc tdesc = slot->tts_tupleDescriptor;
930 if (subLinkType == EXISTS_SUBLINK)
932 /* There can be only one setParam... */
933 int paramid = linitial_int(subplan->setParam);
934 ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
936 prm->execPlan = NULL;
937 prm->value = BoolGetDatum(true);
943 if (subLinkType == ARRAY_SUBLINK)
949 /* stash away current value */
950 Assert(subplan->firstColType == tdesc->attrs[0]->atttypid);
951 dvalue = slot_getattr(slot, 1, &disnull);
952 astate = accumArrayResult(astate, dvalue, disnull,
953 subplan->firstColType, oldcontext);
954 /* keep scanning subplan to collect all values */
959 (subLinkType == EXPR_SUBLINK ||
960 subLinkType == ROWCOMPARE_SUBLINK))
962 (errcode(ERRCODE_CARDINALITY_VIOLATION),
963 errmsg("more than one row returned by a subquery used as an expression")));
968 * We need to copy the subplan's tuple into our own context, in case
969 * any of the params are pass-by-ref type --- the pointers stored in
970 * the param structs will point at this copied tuple! node->curTuple
971 * keeps track of the copied tuple for eventual freeing.
974 heap_freetuple(node->curTuple);
975 node->curTuple = ExecCopySlotTuple(slot);
978 * Now set all the setParam params from the columns of the tuple
980 foreach(l, subplan->setParam)
982 int paramid = lfirst_int(l);
983 ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
985 prm->execPlan = NULL;
986 prm->value = heap_getattr(node->curTuple, i, tdesc,
992 if (subLinkType == ARRAY_SUBLINK)
994 /* There can be only one setParam... */
995 int paramid = linitial_int(subplan->setParam);
996 ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
999 * We build the result array in query context so it won't disappear;
1000 * to avoid leaking memory across repeated calls, we have to remember
1001 * the latest value, much as for curTuple above.
1003 if (node->curArray != PointerGetDatum(NULL))
1004 pfree(DatumGetPointer(node->curArray));
1006 node->curArray = makeArrayResult(astate,
1007 econtext->ecxt_per_query_memory);
1010 MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1011 node->curArray = PointerGetDatum(construct_empty_array(subplan->firstColType));
1013 prm->execPlan = NULL;
1014 prm->value = node->curArray;
1015 prm->isnull = false;
1019 if (subLinkType == EXISTS_SUBLINK)
1021 /* There can be only one setParam... */
1022 int paramid = linitial_int(subplan->setParam);
1023 ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
1025 prm->execPlan = NULL;
1026 prm->value = BoolGetDatum(false);
1027 prm->isnull = false;
1031 foreach(l, subplan->setParam)
1033 int paramid = lfirst_int(l);
1034 ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
1036 prm->execPlan = NULL;
1037 prm->value = (Datum) 0;
1043 MemoryContextSwitchTo(oldcontext);
1047 * Mark an initplan as needing recalculation
1050 ExecReScanSetParamPlan(SubPlanState *node, PlanState *parent)
1052 PlanState *planstate = node->planstate;
1053 SubPlan *subplan = (SubPlan *) node->xprstate.expr;
1054 EState *estate = parent->state;
1058 if (subplan->parParam != NIL)
1059 elog(ERROR, "direct correlated subquery unsupported as initplan");
1060 if (subplan->setParam == NIL)
1061 elog(ERROR, "setParam list of initplan is empty");
1062 if (bms_is_empty(planstate->plan->extParam))
1063 elog(ERROR, "extParam set of initplan is empty");
1066 * Don't actually re-scan: it'll happen inside ExecSetParamPlan if needed.
1070 * Mark this subplan's output parameters as needing recalculation.
1072 * CTE subplans are never executed via parameter recalculation; instead
1073 * they get run when called by nodeCtescan.c. So don't mark the output
1074 * parameter of a CTE subplan as dirty, but do set the chgParam bit for it
1075 * so that dependent plan nodes will get told to rescan.
1077 foreach(l, subplan->setParam)
1079 int paramid = lfirst_int(l);
1080 ParamExecData *prm = &(estate->es_param_exec_vals[paramid]);
1082 if (subplan->subLinkType != CTE_SUBLINK)
1083 prm->execPlan = node;
1085 parent->chgParam = bms_add_member(parent->chgParam, paramid);
1091 * ExecInitAlternativeSubPlan
1093 * Initialize for execution of one of a set of alternative subplans.
1095 AlternativeSubPlanState *
1096 ExecInitAlternativeSubPlan(AlternativeSubPlan *asplan, PlanState *parent)
1098 AlternativeSubPlanState *asstate = makeNode(AlternativeSubPlanState);
1105 asstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecAlternativeSubPlan;
1106 asstate->xprstate.expr = (Expr *) asplan;
1109 * Initialize subplans. (Can we get away with only initializing the one
1110 * we're going to use?)
1112 asstate->subplans = (List *) ExecInitExpr((Expr *) asplan->subplans,
1116 * Select the one to be used. For this, we need an estimate of the number
1117 * of executions of the subplan. We use the number of output rows
1118 * expected from the parent plan node. This is a good estimate if we are
1119 * in the parent's targetlist, and an underestimate (but probably not by
1120 * more than a factor of 2) if we are in the qual.
1122 num_calls = parent->plan->plan_rows;
1125 * The planner saved enough info so that we don't have to work very hard
1126 * to estimate the total cost, given the number-of-calls estimate.
1128 Assert(list_length(asplan->subplans) == 2);
1129 subplan1 = (SubPlan *) linitial(asplan->subplans);
1130 subplan2 = (SubPlan *) lsecond(asplan->subplans);
1132 cost1 = subplan1->startup_cost + num_calls * subplan1->per_call_cost;
1133 cost2 = subplan2->startup_cost + num_calls * subplan2->per_call_cost;
1136 asstate->active = 0;
1138 asstate->active = 1;
1144 * ExecAlternativeSubPlan
1146 * Execute one of a set of alternative subplans.
1148 * Note: in future we might consider changing to different subplans on the
1149 * fly, in case the original rowcount estimate turns out to be way off.
1152 ExecAlternativeSubPlan(AlternativeSubPlanState *node,
1153 ExprContext *econtext,
1155 ExprDoneCond *isDone)
1157 /* Just pass control to the active subplan */
1158 SubPlanState *activesp = (SubPlanState *) list_nth(node->subplans,
1161 Assert(IsA(activesp, SubPlanState));
1163 return ExecSubPlan(activesp,