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-2018, 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 "miscadmin.h"
37 #include "optimizer/clauses.h"
38 #include "utils/array.h"
39 #include "utils/lsyscache.h"
40 #include "utils/memutils.h"
43 static Datum ExecHashSubPlan(SubPlanState *node,
44 ExprContext *econtext,
46 static Datum ExecScanSubPlan(SubPlanState *node,
47 ExprContext *econtext,
49 static void buildSubPlanHash(SubPlanState *node, ExprContext *econtext);
50 static bool findPartialMatch(TupleHashTable hashtable, TupleTableSlot *slot,
51 FmgrInfo *eqfunctions);
52 static bool slotAllNulls(TupleTableSlot *slot);
53 static bool slotNoNulls(TupleTableSlot *slot);
56 /* ----------------------------------------------------------------
59 * This is the main entry point for execution of a regular SubPlan.
60 * ----------------------------------------------------------------
63 ExecSubPlan(SubPlanState *node,
64 ExprContext *econtext,
67 SubPlan *subplan = node->subplan;
68 EState *estate = node->planstate->state;
69 ScanDirection dir = estate->es_direction;
72 CHECK_FOR_INTERRUPTS();
74 /* Set non-null as default */
78 if (subplan->subLinkType == CTE_SUBLINK)
79 elog(ERROR, "CTE subplans should not be executed via ExecSubPlan");
80 if (subplan->setParam != NIL && subplan->subLinkType != MULTIEXPR_SUBLINK)
81 elog(ERROR, "cannot set parent params from subquery");
83 /* Force forward-scan mode for evaluation */
84 estate->es_direction = ForwardScanDirection;
86 /* Select appropriate evaluation strategy */
87 if (subplan->useHashTable)
88 retval = ExecHashSubPlan(node, econtext, isNull);
90 retval = ExecScanSubPlan(node, econtext, isNull);
92 /* restore scan direction */
93 estate->es_direction = dir;
99 * ExecHashSubPlan: store subselect result in an in-memory hash table
102 ExecHashSubPlan(SubPlanState *node,
103 ExprContext *econtext,
106 SubPlan *subplan = node->subplan;
107 PlanState *planstate = node->planstate;
108 TupleTableSlot *slot;
110 /* Shouldn't have any direct correlation Vars */
111 if (subplan->parParam != NIL || node->args != NIL)
112 elog(ERROR, "hashed subplan with direct correlation not supported");
115 * If first time through or we need to rescan the subplan, build the hash
118 if (node->hashtable == NULL || planstate->chgParam != NULL)
119 buildSubPlanHash(node, econtext);
122 * The result for an empty subplan is always FALSE; no need to evaluate
126 if (!node->havehashrows && !node->havenullrows)
127 return BoolGetDatum(false);
130 * Evaluate lefthand expressions and form a projection tuple. First we
131 * have to set the econtext to use (hack alert!).
133 node->projLeft->pi_exprContext = econtext;
134 slot = ExecProject(node->projLeft);
137 * Note: because we are typically called in a per-tuple context, we have
138 * to explicitly clear the projected tuple before returning. Otherwise,
139 * we'll have a double-free situation: the per-tuple context will probably
140 * be reset before we're called again, and then the tuple slot will think
141 * it still needs to free the tuple.
145 * If the LHS is all non-null, probe for an exact match in the main hash
146 * table. If we find one, the result is TRUE. Otherwise, scan the
147 * partly-null table to see if there are any rows that aren't provably
148 * unequal to the LHS; if so, the result is UNKNOWN. (We skip that part
149 * if we don't care about UNKNOWN.) Otherwise, the result is FALSE.
151 * Note: the reason we can avoid a full scan of the main hash table is
152 * that the combining operators are assumed never to yield NULL when both
153 * inputs are non-null. If they were to do so, we might need to produce
154 * UNKNOWN instead of FALSE because of an UNKNOWN result in comparing the
155 * LHS to some main-table entry --- which is a comparison we will not even
156 * make, unless there's a chance match of hash keys.
158 if (slotNoNulls(slot))
160 if (node->havehashrows &&
161 FindTupleHashEntry(node->hashtable,
164 node->lhs_hash_funcs) != NULL)
166 ExecClearTuple(slot);
167 return BoolGetDatum(true);
169 if (node->havenullrows &&
170 findPartialMatch(node->hashnulls, slot, node->cur_eq_funcs))
172 ExecClearTuple(slot);
174 return BoolGetDatum(false);
176 ExecClearTuple(slot);
177 return BoolGetDatum(false);
181 * When the LHS is partly or wholly NULL, we can never return TRUE. If we
182 * don't care about UNKNOWN, just return FALSE. Otherwise, if the LHS is
183 * wholly NULL, immediately return UNKNOWN. (Since the combining
184 * operators are strict, the result could only be FALSE if the sub-select
185 * were empty, but we already handled that case.) Otherwise, we must scan
186 * both the main and partly-null tables to see if there are any rows that
187 * aren't provably unequal to the LHS; if so, the result is UNKNOWN.
188 * Otherwise, the result is FALSE.
190 if (node->hashnulls == NULL)
192 ExecClearTuple(slot);
193 return BoolGetDatum(false);
195 if (slotAllNulls(slot))
197 ExecClearTuple(slot);
199 return BoolGetDatum(false);
201 /* Scan partly-null table first, since more likely to get a match */
202 if (node->havenullrows &&
203 findPartialMatch(node->hashnulls, slot, node->cur_eq_funcs))
205 ExecClearTuple(slot);
207 return BoolGetDatum(false);
209 if (node->havehashrows &&
210 findPartialMatch(node->hashtable, slot, node->cur_eq_funcs))
212 ExecClearTuple(slot);
214 return BoolGetDatum(false);
216 ExecClearTuple(slot);
217 return BoolGetDatum(false);
221 * ExecScanSubPlan: default case where we have to rescan subplan each time
224 ExecScanSubPlan(SubPlanState *node,
225 ExprContext *econtext,
228 SubPlan *subplan = node->subplan;
229 PlanState *planstate = node->planstate;
230 SubLinkType subLinkType = subplan->subLinkType;
231 MemoryContext oldcontext;
232 TupleTableSlot *slot;
234 bool found = false; /* true if got at least one subplan tuple */
237 ArrayBuildStateAny *astate = NULL;
240 * MULTIEXPR subplans, when "executed", just return NULL; but first we
241 * mark the subplan's output parameters as needing recalculation. (This
242 * is a bit of a hack: it relies on the subplan appearing later in its
243 * targetlist than any of the referencing Params, so that all the Params
244 * have been evaluated before we re-mark them for the next evaluation
245 * cycle. But in general resjunk tlist items appear after non-resjunk
246 * ones, so this should be safe.) Unlike ExecReScanSetParamPlan, we do
247 * *not* set bits in the parent plan node's chgParam, because we don't
248 * want to cause a rescan of the parent.
250 if (subLinkType == MULTIEXPR_SUBLINK)
252 EState *estate = node->parent->state;
254 foreach(l, subplan->setParam)
256 int paramid = lfirst_int(l);
257 ParamExecData *prm = &(estate->es_param_exec_vals[paramid]);
259 prm->execPlan = node;
265 /* Initialize ArrayBuildStateAny in caller's context, if needed */
266 if (subLinkType == ARRAY_SUBLINK)
267 astate = initArrayResultAny(subplan->firstColType,
268 CurrentMemoryContext, true);
271 * We are probably in a short-lived expression-evaluation context. Switch
272 * to the per-query context for manipulating the child plan's chgParam,
273 * calling ExecProcNode on it, etc.
275 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
278 * Set Params of this plan from parent plan correlation values. (Any
279 * calculation we have to do is done in the parent econtext, since the
280 * Param values don't need to have per-query lifetime.)
282 Assert(list_length(subplan->parParam) == list_length(node->args));
284 forboth(l, subplan->parParam, pvar, node->args)
286 int paramid = lfirst_int(l);
287 ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
289 prm->value = ExecEvalExprSwitchContext((ExprState *) lfirst(pvar),
292 planstate->chgParam = bms_add_member(planstate->chgParam, paramid);
296 * Now that we've set up its parameters, we can reset the subplan.
298 ExecReScan(planstate);
301 * For all sublink types except EXPR_SUBLINK and ARRAY_SUBLINK, the result
302 * is boolean as are the results of the combining operators. We combine
303 * results across tuples (if the subplan produces more than one) using OR
304 * semantics for ANY_SUBLINK or AND semantics for ALL_SUBLINK.
305 * (ROWCOMPARE_SUBLINK doesn't allow multiple tuples from the subplan.)
306 * NULL results from the combining operators are handled according to the
307 * usual SQL semantics for OR and AND. The result for no input tuples is
308 * FALSE for ANY_SUBLINK, TRUE for ALL_SUBLINK, NULL for
309 * ROWCOMPARE_SUBLINK.
311 * For EXPR_SUBLINK we require the subplan to produce no more than one
312 * tuple, else an error is raised. If zero tuples are produced, we return
313 * NULL. Assuming we get a tuple, we just use its first column (there can
314 * be only one non-junk column in this case).
316 * For ARRAY_SUBLINK we allow the subplan to produce any number of tuples,
317 * and form an array of the first column's values. Note in particular
318 * that we produce a zero-element array if no tuples are produced (this is
319 * a change from pre-8.3 behavior of returning NULL).
321 result = BoolGetDatum(subLinkType == ALL_SUBLINK);
324 for (slot = ExecProcNode(planstate);
326 slot = ExecProcNode(planstate))
328 TupleDesc tdesc = slot->tts_tupleDescriptor;
334 if (subLinkType == EXISTS_SUBLINK)
337 result = BoolGetDatum(true);
341 if (subLinkType == EXPR_SUBLINK)
343 /* cannot allow multiple input tuples for EXPR sublink */
346 (errcode(ERRCODE_CARDINALITY_VIOLATION),
347 errmsg("more than one row returned by a subquery used as an expression")));
351 * We need to copy the subplan's tuple in case the result is of
352 * pass-by-ref type --- our return value will point into this
353 * copied tuple! Can't use the subplan's instance of the tuple
354 * since it won't still be valid after next ExecProcNode() call.
355 * node->curTuple keeps track of the copied tuple for eventual
359 heap_freetuple(node->curTuple);
360 node->curTuple = ExecCopySlotHeapTuple(slot);
362 result = heap_getattr(node->curTuple, 1, tdesc, isNull);
363 /* keep scanning subplan to make sure there's only one tuple */
367 if (subLinkType == ARRAY_SUBLINK)
373 /* stash away current value */
374 Assert(subplan->firstColType == TupleDescAttr(tdesc, 0)->atttypid);
375 dvalue = slot_getattr(slot, 1, &disnull);
376 astate = accumArrayResultAny(astate, dvalue, disnull,
377 subplan->firstColType, oldcontext);
378 /* keep scanning subplan to collect all values */
382 /* cannot allow multiple input tuples for ROWCOMPARE sublink either */
383 if (subLinkType == ROWCOMPARE_SUBLINK && found)
385 (errcode(ERRCODE_CARDINALITY_VIOLATION),
386 errmsg("more than one row returned by a subquery used as an expression")));
391 * For ALL, ANY, and ROWCOMPARE sublinks, load up the Params
392 * representing the columns of the sub-select, and then evaluate the
393 * combining expression.
396 foreach(plst, subplan->paramIds)
398 int paramid = lfirst_int(plst);
399 ParamExecData *prmdata;
401 prmdata = &(econtext->ecxt_param_exec_vals[paramid]);
402 Assert(prmdata->execPlan == NULL);
403 prmdata->value = slot_getattr(slot, col, &(prmdata->isnull));
407 rowresult = ExecEvalExprSwitchContext(node->testexpr, econtext,
410 if (subLinkType == ANY_SUBLINK)
412 /* combine across rows per OR semantics */
415 else if (DatumGetBool(rowresult))
417 result = BoolGetDatum(true);
419 break; /* needn't look at any more rows */
422 else if (subLinkType == ALL_SUBLINK)
424 /* combine across rows per AND semantics */
427 else if (!DatumGetBool(rowresult))
429 result = BoolGetDatum(false);
431 break; /* needn't look at any more rows */
436 /* must be ROWCOMPARE_SUBLINK */
442 MemoryContextSwitchTo(oldcontext);
444 if (subLinkType == ARRAY_SUBLINK)
446 /* We return the result in the caller's context */
447 result = makeArrayResultAny(astate, oldcontext, true);
452 * deal with empty subplan result. result/isNull were previously
453 * initialized correctly for all sublink types except EXPR and
454 * ROWCOMPARE; for those, return NULL.
456 if (subLinkType == EXPR_SUBLINK ||
457 subLinkType == ROWCOMPARE_SUBLINK)
468 * buildSubPlanHash: load hash table by scanning subplan output.
471 buildSubPlanHash(SubPlanState *node, ExprContext *econtext)
473 SubPlan *subplan = node->subplan;
474 PlanState *planstate = node->planstate;
475 int ncols = list_length(subplan->paramIds);
476 ExprContext *innerecontext = node->innerecontext;
477 MemoryContext oldcontext;
479 TupleTableSlot *slot;
481 Assert(subplan->subLinkType == ANY_SUBLINK);
484 * If we already had any hash tables, destroy 'em; then create empty hash
487 * If we need to distinguish accurately between FALSE and UNKNOWN (i.e.,
488 * NULL) results of the IN operation, then we have to store subplan output
489 * rows that are partly or wholly NULL. We store such rows in a separate
490 * hash table that we expect will be much smaller than the main table. (We
491 * can use hashing to eliminate partly-null rows that are not distinct. We
492 * keep them separate to minimize the cost of the inevitable full-table
493 * searches; see findPartialMatch.)
495 * If it's not necessary to distinguish FALSE and UNKNOWN, then we don't
496 * need to store subplan output rows that contain NULL.
498 MemoryContextReset(node->hashtablecxt);
499 node->hashtable = NULL;
500 node->hashnulls = NULL;
501 node->havehashrows = false;
502 node->havenullrows = false;
504 nbuckets = (long) Min(planstate->plan->plan_rows, (double) LONG_MAX);
508 node->hashtable = BuildTupleHashTable(node->parent,
512 node->tab_eq_funcoids,
513 node->tab_hash_funcs,
520 if (!subplan->unknownEqFalse)
523 nbuckets = 1; /* there can only be one entry */
530 node->hashnulls = BuildTupleHashTable(node->parent,
534 node->tab_eq_funcoids,
535 node->tab_hash_funcs,
544 * We are probably in a short-lived expression-evaluation context. Switch
545 * to the per-query context for manipulating the child plan.
547 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
550 * Reset subplan to start.
552 ExecReScan(planstate);
555 * Scan the subplan and load the hash table(s). Note that when there are
556 * duplicate rows coming out of the sub-select, only one copy is stored.
558 for (slot = ExecProcNode(planstate);
560 slot = ExecProcNode(planstate))
567 * Load up the Params representing the raw sub-select outputs, then
568 * form the projection tuple to store in the hashtable.
570 foreach(plst, subplan->paramIds)
572 int paramid = lfirst_int(plst);
573 ParamExecData *prmdata;
575 prmdata = &(innerecontext->ecxt_param_exec_vals[paramid]);
576 Assert(prmdata->execPlan == NULL);
577 prmdata->value = slot_getattr(slot, col,
581 slot = ExecProject(node->projRight);
584 * If result contains any nulls, store separately or not at all.
586 if (slotNoNulls(slot))
588 (void) LookupTupleHashEntry(node->hashtable, slot, &isnew);
589 node->havehashrows = true;
591 else if (node->hashnulls)
593 (void) LookupTupleHashEntry(node->hashnulls, slot, &isnew);
594 node->havenullrows = true;
598 * Reset innerecontext after each inner tuple to free any memory used
599 * during ExecProject.
601 ResetExprContext(innerecontext);
605 * Since the projected tuples are in the sub-query's context and not the
606 * main context, we'd better clear the tuple slot before there's any
607 * chance of a reset of the sub-query's context. Else we will have the
608 * potential for a double free attempt. (XXX possibly no longer needed,
611 ExecClearTuple(node->projRight->pi_state.resultslot);
613 MemoryContextSwitchTo(oldcontext);
618 * Return true if two tuples are definitely unequal in the indicated
621 * Nulls are neither equal nor unequal to anything else. A true result
622 * is obtained only if there are non-null fields that compare not-equal.
624 * slot1, slot2: the tuples to compare (must have same columns!)
625 * numCols: the number of attributes to be examined
626 * matchColIdx: array of attribute column numbers
627 * eqFunctions: array of fmgr lookup info for the equality functions to use
628 * evalContext: short-term memory context for executing the functions
631 execTuplesUnequal(TupleTableSlot *slot1,
632 TupleTableSlot *slot2,
634 AttrNumber *matchColIdx,
635 FmgrInfo *eqfunctions,
636 MemoryContext evalContext)
638 MemoryContext oldContext;
642 /* Reset and switch into the temp context. */
643 MemoryContextReset(evalContext);
644 oldContext = MemoryContextSwitchTo(evalContext);
647 * We cannot report a match without checking all the fields, but we can
648 * report a non-match as soon as we find unequal fields. So, start
649 * comparing at the last field (least significant sort key). That's the
650 * most likely to be different if we are dealing with sorted input.
654 for (i = numCols; --i >= 0;)
656 AttrNumber att = matchColIdx[i];
662 attr1 = slot_getattr(slot1, att, &isNull1);
665 continue; /* can't prove anything here */
667 attr2 = slot_getattr(slot2, att, &isNull2);
670 continue; /* can't prove anything here */
672 /* Apply the type-specific equality function */
674 if (!DatumGetBool(FunctionCall2(&eqfunctions[i],
677 result = true; /* they are unequal */
682 MemoryContextSwitchTo(oldContext);
688 * findPartialMatch: does the hashtable contain an entry that is not
689 * provably distinct from the tuple?
691 * We have to scan the whole hashtable; we can't usefully use hashkeys
692 * to guide probing, since we might get partial matches on tuples with
693 * hashkeys quite unrelated to what we'd get from the given tuple.
695 * Caller must provide the equality functions to use, since in cross-type
696 * cases these are different from the hashtable's internal functions.
699 findPartialMatch(TupleHashTable hashtable, TupleTableSlot *slot,
700 FmgrInfo *eqfunctions)
702 int numCols = hashtable->numCols;
703 AttrNumber *keyColIdx = hashtable->keyColIdx;
704 TupleHashIterator hashiter;
705 TupleHashEntry entry;
707 InitTupleHashIterator(hashtable, &hashiter);
708 while ((entry = ScanTupleHashTable(hashtable, &hashiter)) != NULL)
710 CHECK_FOR_INTERRUPTS();
712 ExecStoreMinimalTuple(entry->firstTuple, hashtable->tableslot, false);
713 if (!execTuplesUnequal(slot, hashtable->tableslot,
718 TermTupleHashIterator(&hashiter);
722 /* No TermTupleHashIterator call needed here */
727 * slotAllNulls: is the slot completely NULL?
729 * This does not test for dropped columns, which is OK because we only
730 * use it on projected tuples.
733 slotAllNulls(TupleTableSlot *slot)
735 int ncols = slot->tts_tupleDescriptor->natts;
738 for (i = 1; i <= ncols; i++)
740 if (!slot_attisnull(slot, i))
747 * slotNoNulls: is the slot entirely not NULL?
749 * This does not test for dropped columns, which is OK because we only
750 * use it on projected tuples.
753 slotNoNulls(TupleTableSlot *slot)
755 int ncols = slot->tts_tupleDescriptor->natts;
758 for (i = 1; i <= ncols; i++)
760 if (slot_attisnull(slot, i))
766 /* ----------------------------------------------------------------
769 * Create a SubPlanState for a SubPlan; this is the SubPlan-specific part
770 * of ExecInitExpr(). We split it out so that it can be used for InitPlans
771 * as well as regular SubPlans. Note that we don't link the SubPlan into
772 * the parent's subPlan list, because that shouldn't happen for InitPlans.
773 * Instead, ExecInitExpr() does that one part.
774 * ----------------------------------------------------------------
777 ExecInitSubPlan(SubPlan *subplan, PlanState *parent)
779 SubPlanState *sstate = makeNode(SubPlanState);
780 EState *estate = parent->state;
782 sstate->subplan = subplan;
784 /* Link the SubPlanState to already-initialized subplan */
785 sstate->planstate = (PlanState *) list_nth(estate->es_subplanstates,
786 subplan->plan_id - 1);
788 /* ... and to its parent's state */
789 sstate->parent = parent;
791 /* Initialize subexpressions */
792 sstate->testexpr = ExecInitExpr((Expr *) subplan->testexpr, parent);
793 sstate->args = ExecInitExprList(subplan->args, parent);
796 * initialize my state
798 sstate->curTuple = NULL;
799 sstate->curArray = PointerGetDatum(NULL);
800 sstate->projLeft = NULL;
801 sstate->projRight = NULL;
802 sstate->hashtable = NULL;
803 sstate->hashnulls = NULL;
804 sstate->hashtablecxt = NULL;
805 sstate->hashtempcxt = NULL;
806 sstate->innerecontext = NULL;
807 sstate->keyColIdx = NULL;
808 sstate->tab_eq_funcoids = NULL;
809 sstate->tab_hash_funcs = NULL;
810 sstate->tab_eq_funcs = NULL;
811 sstate->lhs_hash_funcs = NULL;
812 sstate->cur_eq_funcs = NULL;
815 * If this is an initplan or MULTIEXPR subplan, it has output parameters
816 * that the parent plan will use, so mark those parameters as needing
817 * evaluation. We don't actually run the subplan until we first need one
820 * A CTE subplan's output parameter is never to be evaluated in the normal
821 * way, so skip this in that case.
823 * Note that we don't set parent->chgParam here: the parent plan hasn't
824 * been run yet, so no need to force it to re-run.
826 if (subplan->setParam != NIL && subplan->subLinkType != CTE_SUBLINK)
830 foreach(lst, subplan->setParam)
832 int paramid = lfirst_int(lst);
833 ParamExecData *prm = &(estate->es_param_exec_vals[paramid]);
835 prm->execPlan = sstate;
840 * If we are going to hash the subquery output, initialize relevant stuff.
841 * (We don't create the hashtable until needed, though.)
843 if (subplan->useHashTable)
847 TupleDesc tupDescLeft;
848 TupleDesc tupDescRight;
849 TupleTableSlot *slot;
855 /* We need a memory context to hold the hash table(s) */
856 sstate->hashtablecxt =
857 AllocSetContextCreate(CurrentMemoryContext,
858 "Subplan HashTable Context",
859 ALLOCSET_DEFAULT_SIZES);
860 /* and a small one for the hash tables to use as temp storage */
861 sstate->hashtempcxt =
862 AllocSetContextCreate(CurrentMemoryContext,
863 "Subplan HashTable Temp Context",
864 ALLOCSET_SMALL_SIZES);
865 /* and a short-lived exprcontext for function evaluation */
866 sstate->innerecontext = CreateExprContext(estate);
867 /* Silly little array of column numbers 1..n */
868 ncols = list_length(subplan->paramIds);
869 sstate->keyColIdx = (AttrNumber *) palloc(ncols * sizeof(AttrNumber));
870 for (i = 0; i < ncols; i++)
871 sstate->keyColIdx[i] = i + 1;
874 * We use ExecProject to evaluate the lefthand and righthand
875 * expression lists and form tuples. (You might think that we could
876 * use the sub-select's output tuples directly, but that is not the
877 * case if we had to insert any run-time coercions of the sub-select's
878 * output datatypes; anyway this avoids storing any resjunk columns
879 * that might be in the sub-select's output.) Run through the
880 * combining expressions to build tlists for the lefthand and
883 * We also extract the combining operators themselves to initialize
884 * the equality and hashing functions for the hash tables.
886 if (IsA(subplan->testexpr, OpExpr))
888 /* single combining operator */
889 oplist = list_make1(subplan->testexpr);
891 else if (and_clause((Node *) subplan->testexpr))
893 /* multiple combining operators */
894 oplist = castNode(BoolExpr, subplan->testexpr)->args;
898 /* shouldn't see anything else in a hashable subplan */
899 elog(ERROR, "unrecognized testexpr type: %d",
900 (int) nodeTag(subplan->testexpr));
901 oplist = NIL; /* keep compiler quiet */
903 Assert(list_length(oplist) == ncols);
905 lefttlist = righttlist = NIL;
906 sstate->tab_eq_funcoids = (Oid *) palloc(ncols * sizeof(Oid));
907 sstate->tab_hash_funcs = (FmgrInfo *) palloc(ncols * sizeof(FmgrInfo));
908 sstate->tab_eq_funcs = (FmgrInfo *) palloc(ncols * sizeof(FmgrInfo));
909 sstate->lhs_hash_funcs = (FmgrInfo *) palloc(ncols * sizeof(FmgrInfo));
910 sstate->cur_eq_funcs = (FmgrInfo *) palloc(ncols * sizeof(FmgrInfo));
914 OpExpr *opexpr = lfirst_node(OpExpr, l);
921 Assert(list_length(opexpr->args) == 2);
923 /* Process lefthand argument */
924 expr = (Expr *) linitial(opexpr->args);
925 tle = makeTargetEntry(expr,
929 lefttlist = lappend(lefttlist, tle);
931 /* Process righthand argument */
932 expr = (Expr *) lsecond(opexpr->args);
933 tle = makeTargetEntry(expr,
937 righttlist = lappend(righttlist, tle);
939 /* Lookup the equality function (potentially cross-type) */
940 sstate->tab_eq_funcoids[i - 1] = opexpr->opfuncid;
941 fmgr_info(opexpr->opfuncid, &sstate->cur_eq_funcs[i - 1]);
942 fmgr_info_set_expr((Node *) opexpr, &sstate->cur_eq_funcs[i - 1]);
944 /* Look up the equality function for the RHS type */
945 if (!get_compatible_hash_operators(opexpr->opno,
947 elog(ERROR, "could not find compatible hash operator for operator %u",
949 fmgr_info(get_opcode(rhs_eq_oper), &sstate->tab_eq_funcs[i - 1]);
951 /* Lookup the associated hash functions */
952 if (!get_op_hash_functions(opexpr->opno,
953 &left_hashfn, &right_hashfn))
954 elog(ERROR, "could not find hash function for hash operator %u",
956 fmgr_info(left_hashfn, &sstate->lhs_hash_funcs[i - 1]);
957 fmgr_info(right_hashfn, &sstate->tab_hash_funcs[i - 1]);
963 * Construct tupdescs, slots and projection nodes for left and right
964 * sides. The lefthand expressions will be evaluated in the parent
965 * plan node's exprcontext, which we don't have access to here.
966 * Fortunately we can just pass NULL for now and fill it in later
967 * (hack alert!). The righthand expressions will be evaluated in our
970 tupDescLeft = ExecTypeFromTL(lefttlist, false);
971 slot = ExecInitExtraTupleSlot(estate, tupDescLeft, &TTSOpsVirtual);
972 sstate->projLeft = ExecBuildProjectionInfo(lefttlist,
978 sstate->descRight = tupDescRight = ExecTypeFromTL(righttlist, false);
979 slot = ExecInitExtraTupleSlot(estate, tupDescRight, &TTSOpsVirtual);
980 sstate->projRight = ExecBuildProjectionInfo(righttlist,
981 sstate->innerecontext,
987 * Create comparator for lookups of rows in the table (potentially
988 * across-type comparison).
990 sstate->cur_eq_comp = ExecBuildGroupingEqual(tupDescLeft, tupDescRight,
991 &TTSOpsVirtual, &TTSOpsMinimalTuple,
994 sstate->tab_eq_funcoids,
1002 /* ----------------------------------------------------------------
1005 * Executes a subplan and sets its output parameters.
1007 * This is called from ExecEvalParamExec() when the value of a PARAM_EXEC
1008 * parameter is requested and the param's execPlan field is set (indicating
1009 * that the param has not yet been evaluated). This allows lazy evaluation
1010 * of initplans: we don't run the subplan until/unless we need its output.
1011 * Note that this routine MUST clear the execPlan fields of the plan's
1012 * output parameters after evaluating them!
1014 * The results of this function are stored in the EState associated with the
1015 * ExprContext (particularly, its ecxt_param_exec_vals); any pass-by-ref
1016 * result Datums are allocated in the EState's per-query memory. The passed
1017 * econtext can be any ExprContext belonging to that EState; which one is
1018 * important only to the extent that the ExprContext's per-tuple memory
1019 * context is used to evaluate any parameters passed down to the subplan.
1020 * (Thus in principle, the shorter-lived the ExprContext the better, since
1021 * that data isn't needed after we return. In practice, because initplan
1022 * parameters are never more complex than Vars, Aggrefs, etc, evaluating them
1023 * currently never leaks any memory anyway.)
1024 * ----------------------------------------------------------------
1027 ExecSetParamPlan(SubPlanState *node, ExprContext *econtext)
1029 SubPlan *subplan = node->subplan;
1030 PlanState *planstate = node->planstate;
1031 SubLinkType subLinkType = subplan->subLinkType;
1032 EState *estate = planstate->state;
1033 ScanDirection dir = estate->es_direction;
1034 MemoryContext oldcontext;
1035 TupleTableSlot *slot;
1039 ArrayBuildStateAny *astate = NULL;
1041 if (subLinkType == ANY_SUBLINK ||
1042 subLinkType == ALL_SUBLINK)
1043 elog(ERROR, "ANY/ALL subselect unsupported as initplan");
1044 if (subLinkType == CTE_SUBLINK)
1045 elog(ERROR, "CTE subplans should not be executed via ExecSetParamPlan");
1048 * Enforce forward scan direction regardless of caller. It's hard but not
1049 * impossible to get here in backward scan, so make it work anyway.
1051 estate->es_direction = ForwardScanDirection;
1053 /* Initialize ArrayBuildStateAny in caller's context, if needed */
1054 if (subLinkType == ARRAY_SUBLINK)
1055 astate = initArrayResultAny(subplan->firstColType,
1056 CurrentMemoryContext, true);
1059 * Must switch to per-query memory context.
1061 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1064 * Set Params of this plan from parent plan correlation values. (Any
1065 * calculation we have to do is done in the parent econtext, since the
1066 * Param values don't need to have per-query lifetime.) Currently, we
1067 * expect only MULTIEXPR_SUBLINK plans to have any correlation values.
1069 Assert(subplan->parParam == NIL || subLinkType == MULTIEXPR_SUBLINK);
1070 Assert(list_length(subplan->parParam) == list_length(node->args));
1072 forboth(l, subplan->parParam, pvar, node->args)
1074 int paramid = lfirst_int(l);
1075 ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
1077 prm->value = ExecEvalExprSwitchContext((ExprState *) lfirst(pvar),
1080 planstate->chgParam = bms_add_member(planstate->chgParam, paramid);
1084 * Run the plan. (If it needs to be rescanned, the first ExecProcNode
1085 * call will take care of that.)
1087 for (slot = ExecProcNode(planstate);
1089 slot = ExecProcNode(planstate))
1091 TupleDesc tdesc = slot->tts_tupleDescriptor;
1094 if (subLinkType == EXISTS_SUBLINK)
1096 /* There can be only one setParam... */
1097 int paramid = linitial_int(subplan->setParam);
1098 ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
1100 prm->execPlan = NULL;
1101 prm->value = BoolGetDatum(true);
1102 prm->isnull = false;
1107 if (subLinkType == ARRAY_SUBLINK)
1113 /* stash away current value */
1114 Assert(subplan->firstColType == TupleDescAttr(tdesc, 0)->atttypid);
1115 dvalue = slot_getattr(slot, 1, &disnull);
1116 astate = accumArrayResultAny(astate, dvalue, disnull,
1117 subplan->firstColType, oldcontext);
1118 /* keep scanning subplan to collect all values */
1123 (subLinkType == EXPR_SUBLINK ||
1124 subLinkType == MULTIEXPR_SUBLINK ||
1125 subLinkType == ROWCOMPARE_SUBLINK))
1127 (errcode(ERRCODE_CARDINALITY_VIOLATION),
1128 errmsg("more than one row returned by a subquery used as an expression")));
1133 * We need to copy the subplan's tuple into our own context, in case
1134 * any of the params are pass-by-ref type --- the pointers stored in
1135 * the param structs will point at this copied tuple! node->curTuple
1136 * keeps track of the copied tuple for eventual freeing.
1139 heap_freetuple(node->curTuple);
1140 node->curTuple = ExecCopySlotHeapTuple(slot);
1143 * Now set all the setParam params from the columns of the tuple
1145 foreach(l, subplan->setParam)
1147 int paramid = lfirst_int(l);
1148 ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
1150 prm->execPlan = NULL;
1151 prm->value = heap_getattr(node->curTuple, i, tdesc,
1157 if (subLinkType == ARRAY_SUBLINK)
1159 /* There can be only one setParam... */
1160 int paramid = linitial_int(subplan->setParam);
1161 ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
1164 * We build the result array in query context so it won't disappear;
1165 * to avoid leaking memory across repeated calls, we have to remember
1166 * the latest value, much as for curTuple above.
1168 if (node->curArray != PointerGetDatum(NULL))
1169 pfree(DatumGetPointer(node->curArray));
1170 node->curArray = makeArrayResultAny(astate,
1171 econtext->ecxt_per_query_memory,
1173 prm->execPlan = NULL;
1174 prm->value = node->curArray;
1175 prm->isnull = false;
1179 if (subLinkType == EXISTS_SUBLINK)
1181 /* There can be only one setParam... */
1182 int paramid = linitial_int(subplan->setParam);
1183 ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
1185 prm->execPlan = NULL;
1186 prm->value = BoolGetDatum(false);
1187 prm->isnull = false;
1191 /* For other sublink types, set all the output params to NULL */
1192 foreach(l, subplan->setParam)
1194 int paramid = lfirst_int(l);
1195 ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
1197 prm->execPlan = NULL;
1198 prm->value = (Datum) 0;
1204 MemoryContextSwitchTo(oldcontext);
1206 /* restore scan direction */
1207 estate->es_direction = dir;
1211 * ExecSetParamPlanMulti
1213 * Apply ExecSetParamPlan to evaluate any not-yet-evaluated initplan output
1214 * parameters whose ParamIDs are listed in "params". Any listed params that
1215 * are not initplan outputs are ignored.
1217 * As with ExecSetParamPlan, any ExprContext belonging to the current EState
1218 * can be used, but in principle a shorter-lived ExprContext is better than a
1222 ExecSetParamPlanMulti(const Bitmapset *params, ExprContext *econtext)
1227 while ((paramid = bms_next_member(params, paramid)) >= 0)
1229 ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
1231 if (prm->execPlan != NULL)
1233 /* Parameter not evaluated yet, so go do it */
1234 ExecSetParamPlan(prm->execPlan, econtext);
1235 /* ExecSetParamPlan should have processed this param... */
1236 Assert(prm->execPlan == NULL);
1242 * Mark an initplan as needing recalculation
1245 ExecReScanSetParamPlan(SubPlanState *node, PlanState *parent)
1247 PlanState *planstate = node->planstate;
1248 SubPlan *subplan = node->subplan;
1249 EState *estate = parent->state;
1253 if (subplan->parParam != NIL)
1254 elog(ERROR, "direct correlated subquery unsupported as initplan");
1255 if (subplan->setParam == NIL)
1256 elog(ERROR, "setParam list of initplan is empty");
1257 if (bms_is_empty(planstate->plan->extParam))
1258 elog(ERROR, "extParam set of initplan is empty");
1261 * Don't actually re-scan: it'll happen inside ExecSetParamPlan if needed.
1265 * Mark this subplan's output parameters as needing recalculation.
1267 * CTE subplans are never executed via parameter recalculation; instead
1268 * they get run when called by nodeCtescan.c. So don't mark the output
1269 * parameter of a CTE subplan as dirty, but do set the chgParam bit for it
1270 * so that dependent plan nodes will get told to rescan.
1272 foreach(l, subplan->setParam)
1274 int paramid = lfirst_int(l);
1275 ParamExecData *prm = &(estate->es_param_exec_vals[paramid]);
1277 if (subplan->subLinkType != CTE_SUBLINK)
1278 prm->execPlan = node;
1280 parent->chgParam = bms_add_member(parent->chgParam, paramid);
1286 * ExecInitAlternativeSubPlan
1288 * Initialize for execution of one of a set of alternative subplans.
1290 AlternativeSubPlanState *
1291 ExecInitAlternativeSubPlan(AlternativeSubPlan *asplan, PlanState *parent)
1293 AlternativeSubPlanState *asstate = makeNode(AlternativeSubPlanState);
1301 asstate->subplan = asplan;
1304 * Initialize subplans. (Can we get away with only initializing the one
1305 * we're going to use?)
1307 foreach(lc, asplan->subplans)
1309 SubPlan *sp = lfirst_node(SubPlan, lc);
1310 SubPlanState *sps = ExecInitSubPlan(sp, parent);
1312 asstate->subplans = lappend(asstate->subplans, sps);
1313 parent->subPlan = lappend(parent->subPlan, sps);
1317 * Select the one to be used. For this, we need an estimate of the number
1318 * of executions of the subplan. We use the number of output rows
1319 * expected from the parent plan node. This is a good estimate if we are
1320 * in the parent's targetlist, and an underestimate (but probably not by
1321 * more than a factor of 2) if we are in the qual.
1323 num_calls = parent->plan->plan_rows;
1326 * The planner saved enough info so that we don't have to work very hard
1327 * to estimate the total cost, given the number-of-calls estimate.
1329 Assert(list_length(asplan->subplans) == 2);
1330 subplan1 = (SubPlan *) linitial(asplan->subplans);
1331 subplan2 = (SubPlan *) lsecond(asplan->subplans);
1333 cost1 = subplan1->startup_cost + num_calls * subplan1->per_call_cost;
1334 cost2 = subplan2->startup_cost + num_calls * subplan2->per_call_cost;
1337 asstate->active = 0;
1339 asstate->active = 1;
1345 * ExecAlternativeSubPlan
1347 * Execute one of a set of alternative subplans.
1349 * Note: in future we might consider changing to different subplans on the
1350 * fly, in case the original rowcount estimate turns out to be way off.
1353 ExecAlternativeSubPlan(AlternativeSubPlanState *node,
1354 ExprContext *econtext,
1357 /* Just pass control to the active subplan */
1358 SubPlanState *activesp = list_nth_node(SubPlanState,
1359 node->subplans, node->active);
1361 return ExecSubPlan(activesp, econtext, isNull);