1 /*-------------------------------------------------------------------------
4 * Routines to evaluate qualification and targetlist expressions
6 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $Header: /cvsroot/pgsql/src/backend/executor/execQual.c,v 1.137 2003/07/30 19:02:18 tgl Exp $
13 *-------------------------------------------------------------------------
17 * ExecEvalExpr - evaluate an expression and return a datum
18 * ExecEvalExprSwitchContext - same, but switch into eval memory context
19 * ExecQual - return true/false if qualification is satisfied
20 * ExecProject - form a new tuple by projecting the given tuple
23 * ExecEvalExpr() and ExecEvalVar() are hotspots. making these faster
24 * will speed up the entire system. Unfortunately they are currently
25 * implemented recursively. Eliminating the recursion is bound to
26 * improve the speed of the executor.
28 * ExecProject() is used to make tuple projections. Rather then
29 * trying to speed it up, the execution plan should be pre-processed
30 * to facilitate attribute sharing between nodes wherever possible,
31 * instead of doing needless copying. -cim 5/31/91
37 #include "access/heapam.h"
38 #include "catalog/pg_type.h"
39 #include "commands/typecmds.h"
40 #include "executor/execdebug.h"
41 #include "executor/functions.h"
42 #include "executor/nodeSubplan.h"
43 #include "miscadmin.h"
44 #include "optimizer/planmain.h"
45 #include "parser/parse_expr.h"
46 #include "utils/acl.h"
47 #include "utils/array.h"
48 #include "utils/builtins.h"
49 #include "utils/lsyscache.h"
52 /* static function decls */
53 static Datum ExecEvalAggref(AggrefExprState *aggref,
54 ExprContext *econtext,
56 static Datum ExecEvalArrayRef(ArrayRefExprState *astate,
57 ExprContext *econtext,
58 bool *isNull, ExprDoneCond *isDone);
59 static Datum ExecEvalVar(Var *variable, ExprContext *econtext, bool *isNull);
60 static Datum ExecEvalParam(Param *expression, ExprContext *econtext,
62 static Datum ExecEvalFunc(FuncExprState *fcache, ExprContext *econtext,
63 bool *isNull, ExprDoneCond *isDone);
64 static Datum ExecEvalOper(FuncExprState *fcache, ExprContext *econtext,
65 bool *isNull, ExprDoneCond *isDone);
66 static Datum ExecEvalDistinct(FuncExprState *fcache, ExprContext *econtext,
68 static Datum ExecEvalScalarArrayOp(ScalarArrayOpExprState *sstate,
69 ExprContext *econtext, bool *isNull);
70 static ExprDoneCond ExecEvalFuncArgs(FunctionCallInfo fcinfo,
71 List *argList, ExprContext *econtext);
72 static Datum ExecEvalNot(BoolExprState *notclause, ExprContext *econtext,
74 static Datum ExecEvalOr(BoolExprState *orExpr, ExprContext *econtext,
76 static Datum ExecEvalAnd(BoolExprState *andExpr, ExprContext *econtext,
78 static Datum ExecEvalCase(CaseExprState *caseExpr, ExprContext *econtext,
79 bool *isNull, ExprDoneCond *isDone);
80 static Datum ExecEvalArray(ArrayExprState *astate,
81 ExprContext *econtext,
83 static Datum ExecEvalCoalesce(CoalesceExprState *coalesceExpr,
84 ExprContext *econtext,
86 static Datum ExecEvalNullIf(FuncExprState *nullIfExpr, ExprContext *econtext,
88 static Datum ExecEvalNullTest(GenericExprState *nstate,
89 ExprContext *econtext,
90 bool *isNull, ExprDoneCond *isDone);
91 static Datum ExecEvalBooleanTest(GenericExprState *bstate,
92 ExprContext *econtext,
93 bool *isNull, ExprDoneCond *isDone);
94 static Datum ExecEvalCoerceToDomain(CoerceToDomainState *cstate,
95 ExprContext *econtext,
96 bool *isNull, ExprDoneCond *isDone);
97 static Datum ExecEvalCoerceToDomainValue(CoerceToDomainValue *conVal,
98 ExprContext *econtext, bool *isNull);
99 static Datum ExecEvalFieldSelect(GenericExprState *fstate,
100 ExprContext *econtext,
101 bool *isNull, ExprDoneCond *isDone);
107 * This function takes an ArrayRef and returns the extracted Datum
108 * if it's a simple reference, or the modified array value if it's
109 * an array assignment (i.e., array element or slice insertion).
111 * NOTE: if we get a NULL result from a subexpression, we return NULL when
112 * it's an array reference, or the unmodified source array when it's an
113 * array assignment. This may seem peculiar, but if we return NULL (as was
114 * done in versions up through 7.0) then an assignment like
115 * UPDATE table SET arrayfield[4] = NULL
116 * will result in setting the whole array to NULL, which is certainly not
117 * very desirable. By returning the source array we make the assignment
118 * into a no-op, instead. (Eventually we need to redesign arrays so that
119 * individual elements can be NULL, but for now, let's try to protect users
120 * from shooting themselves in the foot.)
122 * NOTE: we deliberately refrain from applying DatumGetArrayTypeP() here,
123 * even though that might seem natural, because this code needs to support
124 * both varlena arrays and fixed-length array types. DatumGetArrayTypeP()
125 * only works for the varlena kind. The routines we call in arrayfuncs.c
126 * have to know the difference (that's what they need refattrlength for).
130 ExecEvalArrayRef(ArrayRefExprState *astate,
131 ExprContext *econtext,
133 ExprDoneCond *isDone)
135 ArrayRef *arrayRef = (ArrayRef *) astate->xprstate.expr;
136 ArrayType *array_source;
137 ArrayType *resultArray;
138 bool isAssignment = (arrayRef->refassgnexpr != NULL);
146 if (arrayRef->refexpr != NULL)
148 array_source = (ArrayType *)
149 DatumGetPointer(ExecEvalExpr(astate->refexpr,
155 * If refexpr yields NULL, result is always NULL, for now anyway.
156 * (This means you cannot assign to an element or slice of an
157 * array that's NULL; it'll just stay NULL.)
165 * Empty refexpr indicates we are doing an INSERT into an array
166 * column. For now, we just take the refassgnexpr (which the
167 * parser will have ensured is an array value) and return it
168 * as-is, ignoring any subscripts that may have been supplied in
169 * the INSERT column list. This is a kluge, but it's not real
170 * clear what the semantics ought to be...
175 foreach(elt, astate->refupperindexpr)
179 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
180 errmsg("number of array dimensions exceeds the maximum allowed, %d",
183 upper.indx[i++] = DatumGetInt32(ExecEvalExpr((ExprState *) lfirst(elt),
187 /* If any index expr yields NULL, result is NULL or source array */
190 if (!isAssignment || array_source == NULL)
193 return PointerGetDatum(array_source);
197 if (astate->reflowerindexpr != NIL)
199 foreach(elt, astate->reflowerindexpr)
203 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
204 errmsg("number of array dimensions exceeds the maximum allowed, %d",
207 lower.indx[j++] = DatumGetInt32(ExecEvalExpr((ExprState *) lfirst(elt),
213 * If any index expr yields NULL, result is NULL or source
218 if (!isAssignment || array_source == NULL)
221 return PointerGetDatum(array_source);
224 /* this can't happen unless parser messed up */
226 elog(ERROR, "upper and lower index lists are not same length");
234 Datum sourceData = ExecEvalExpr(astate->refassgnexpr,
240 * For now, can't cope with inserting NULL into an array, so make
241 * it a no-op per discussion above...
245 if (array_source == NULL)
248 return PointerGetDatum(array_source);
251 if (array_source == NULL)
252 return sourceData; /* XXX do something else? */
255 resultArray = array_set(array_source, i,
258 astate->refattrlength,
259 astate->refelemlength,
260 astate->refelembyval,
261 astate->refelemalign,
264 resultArray = array_set_slice(array_source, i,
265 upper.indx, lower.indx,
266 (ArrayType *) DatumGetPointer(sourceData),
267 astate->refattrlength,
268 astate->refelemlength,
269 astate->refelembyval,
270 astate->refelemalign,
272 return PointerGetDatum(resultArray);
276 return array_ref(array_source, i, upper.indx,
277 astate->refattrlength,
278 astate->refelemlength,
279 astate->refelembyval,
280 astate->refelemalign,
284 resultArray = array_get_slice(array_source, i,
285 upper.indx, lower.indx,
286 astate->refattrlength,
287 astate->refelemlength,
288 astate->refelembyval,
289 astate->refelemalign,
291 return PointerGetDatum(resultArray);
296 /* ----------------------------------------------------------------
299 * Returns a Datum whose value is the value of the precomputed
300 * aggregate found in the given expression context.
301 * ----------------------------------------------------------------
304 ExecEvalAggref(AggrefExprState *aggref, ExprContext *econtext, bool *isNull)
306 if (econtext->ecxt_aggvalues == NULL) /* safety check */
307 elog(ERROR, "no aggregates in this expression context");
309 *isNull = econtext->ecxt_aggnulls[aggref->aggno];
310 return econtext->ecxt_aggvalues[aggref->aggno];
313 /* ----------------------------------------------------------------
316 * Returns a Datum whose value is the value of a range
317 * variable with respect to given expression context.
320 * As an entry condition, we expect that the datatype the
321 * plan expects to get (as told by our "variable" argument) is in
322 * fact the datatype of the attribute the plan says to fetch (as
323 * seen in the current context, identified by our "econtext"
326 * If we fetch a Type A attribute and Caller treats it as if it
327 * were Type B, there will be undefined results (e.g. crash).
328 * One way these might mismatch now is that we're accessing a
329 * catalog class and the type information in the pg_attribute
330 * class does not match the hardcoded pg_attribute information
331 * (in pg_attribute.h) for the class in question.
333 * We have an Assert to make sure this entry condition is met.
335 * ---------------------------------------------------------------- */
337 ExecEvalVar(Var *variable, ExprContext *econtext, bool *isNull)
340 TupleTableSlot *slot;
343 TupleDesc tuple_type;
346 * get the slot we want
348 switch (variable->varno)
350 case INNER: /* get the tuple from the inner node */
351 slot = econtext->ecxt_innertuple;
354 case OUTER: /* get the tuple from the outer node */
355 slot = econtext->ecxt_outertuple;
358 default: /* get the tuple from the relation being
360 slot = econtext->ecxt_scantuple;
365 * extract tuple information from the slot
367 heapTuple = slot->val;
368 tuple_type = slot->ttc_tupleDescriptor;
370 attnum = variable->varattno;
372 /* (See prolog for explanation of this Assert) */
373 Assert(attnum <= 0 ||
374 (attnum - 1 <= tuple_type->natts - 1 &&
375 tuple_type->attrs[attnum - 1] != NULL &&
376 variable->vartype == tuple_type->attrs[attnum - 1]->atttypid));
379 * If the attribute number is invalid, then we are supposed to return
380 * the entire tuple; we give back a whole slot so that callers know
381 * what the tuple looks like.
383 * XXX this is a horrid crock: since the pointer to the slot might live
384 * longer than the current evaluation context, we are forced to copy
385 * the tuple and slot into a long-lived context --- we use
386 * the econtext's per-query memory which should be safe enough. This
387 * represents a serious memory leak if many such tuples are processed
388 * in one command, however. We ought to redesign the representation
389 * of whole-tuple datums so that this is not necessary.
391 * We assume it's OK to point to the existing tupleDescriptor, rather
392 * than copy that too.
394 if (attnum == InvalidAttrNumber)
396 MemoryContext oldContext;
397 TupleTableSlot *tempSlot;
400 oldContext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
401 tempSlot = MakeTupleTableSlot();
402 tup = heap_copytuple(heapTuple);
403 ExecStoreTuple(tup, tempSlot, InvalidBuffer, true);
404 ExecSetSlotDescriptor(tempSlot, tuple_type, false);
405 MemoryContextSwitchTo(oldContext);
406 return PointerGetDatum(tempSlot);
409 result = heap_getattr(heapTuple, /* tuple containing attribute */
410 attnum, /* attribute number of desired
412 tuple_type, /* tuple descriptor of tuple */
413 isNull); /* return: is attribute null? */
418 /* ----------------------------------------------------------------
421 * Returns the value of a parameter. A param node contains
422 * something like ($.name) and the expression context contains
423 * the current parameter bindings (name = "sam") (age = 34)...
424 * so our job is to find and return the appropriate datum ("sam").
426 * Q: if we have a parameter ($.foo) without a binding, i.e.
427 * there is no (foo = xxx) in the parameter list info,
428 * is this a fatal error or should this be a "not available"
429 * (in which case we could return NULL)? -cim 10/13/89
430 * ----------------------------------------------------------------
433 ExecEvalParam(Param *expression, ExprContext *econtext, bool *isNull)
435 int thisParamKind = expression->paramkind;
436 AttrNumber thisParamId = expression->paramid;
438 if (thisParamKind == PARAM_EXEC)
441 * PARAM_EXEC params (internal executor parameters) are stored in
442 * the ecxt_param_exec_vals array, and can be accessed by array index.
446 prm = &(econtext->ecxt_param_exec_vals[thisParamId]);
447 if (prm->execPlan != NULL)
449 /* Parameter not evaluated yet, so go do it */
450 ExecSetParamPlan(prm->execPlan, econtext);
451 /* ExecSetParamPlan should have processed this param... */
452 Assert(prm->execPlan == NULL);
454 *isNull = prm->isnull;
460 * All other parameter types must be sought in ecxt_param_list_info.
461 * NOTE: The last entry in the param array is always an
462 * entry with kind == PARAM_INVALID.
464 ParamListInfo paramList = econtext->ecxt_param_list_info;
465 char *thisParamName = expression->paramname;
466 bool matchFound = false;
468 if (paramList != NULL)
470 while (paramList->kind != PARAM_INVALID && !matchFound)
472 if (thisParamKind == paramList->kind)
474 switch (thisParamKind)
477 if (strcmp(paramList->name, thisParamName) == 0)
481 if (paramList->id == thisParamId)
485 elog(ERROR, "unrecognized paramkind: %d",
496 if (thisParamKind == PARAM_NAMED)
498 (errcode(ERRCODE_UNDEFINED_OBJECT),
499 errmsg("no value found for parameter \"%s\"",
503 (errcode(ERRCODE_UNDEFINED_OBJECT),
504 errmsg("no value found for parameter %d",
508 *isNull = paramList->isnull;
509 return paramList->value;
514 /* ----------------------------------------------------------------
515 * ExecEvalOper / ExecEvalFunc support routines
516 * ----------------------------------------------------------------
523 * These are functions which return the value of the
524 * named attribute out of the tuple from the arg slot. User defined
525 * C functions which take a tuple as an argument are expected
526 * to use this. Ex: overpaid(EMP) might call GetAttributeByNum().
529 GetAttributeByNum(TupleTableSlot *slot,
535 if (!AttributeNumberIsValid(attrno))
536 elog(ERROR, "invalid attribute number %d", attrno);
538 if (isNull == (bool *) NULL)
539 elog(ERROR, "a NULL isNull pointer was passed");
547 retval = heap_getattr(slot->val,
549 slot->ttc_tupleDescriptor,
558 GetAttributeByName(TupleTableSlot *slot, char *attname, bool *isNull)
567 elog(ERROR, "invalid attribute name");
569 if (isNull == (bool *) NULL)
570 elog(ERROR, "a NULL isNull pointer was passed");
578 tupdesc = slot->ttc_tupleDescriptor;
579 natts = slot->val->t_data->t_natts;
581 attrno = InvalidAttrNumber;
582 for (i = 0; i < tupdesc->natts; i++)
584 if (namestrcmp(&(tupdesc->attrs[i]->attname), attname) == 0)
586 attrno = tupdesc->attrs[i]->attnum;
591 if (attrno == InvalidAttrNumber)
592 elog(ERROR, "attribute \"%s\" does not exist", attname);
594 retval = heap_getattr(slot->val,
605 * init_fcache - initialize a FuncExprState node during first use
608 init_fcache(Oid foid, FuncExprState *fcache, MemoryContext fcacheCxt)
612 /* Check permission to call function */
613 aclresult = pg_proc_aclcheck(foid, GetUserId(), ACL_EXECUTE);
614 if (aclresult != ACLCHECK_OK)
615 aclcheck_error(aclresult, get_func_name(foid));
617 /* Safety check (should never fail, as parser should check sooner) */
618 if (length(fcache->args) > FUNC_MAX_ARGS)
619 elog(ERROR, "too many arguments");
621 /* Set up the primary fmgr lookup information */
622 fmgr_info_cxt(foid, &(fcache->func), fcacheCxt);
624 /* Initialize additional info */
625 fcache->setArgsValid = false;
626 fcache->func.fn_expr = (Node *) fcache->xprstate.expr;
630 * Evaluate arguments for a function.
633 ExecEvalFuncArgs(FunctionCallInfo fcinfo,
635 ExprContext *econtext)
637 ExprDoneCond argIsDone;
641 argIsDone = ExprSingleResult; /* default assumption */
644 foreach(arg, argList)
646 ExprDoneCond thisArgIsDone;
648 fcinfo->arg[i] = ExecEvalExpr((ExprState *) lfirst(arg),
653 if (thisArgIsDone != ExprSingleResult)
656 * We allow only one argument to have a set value; we'd need
657 * much more complexity to keep track of multiple set
658 * arguments (cf. ExecTargetList) and it doesn't seem worth
661 if (argIsDone != ExprSingleResult)
663 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
664 errmsg("functions and operators can take at most one set argument")));
665 argIsDone = thisArgIsDone;
676 * ExecMakeFunctionResult
678 * Evaluate the arguments to a function and then the function itself.
681 ExecMakeFunctionResult(FuncExprState *fcache,
682 ExprContext *econtext,
684 ExprDoneCond *isDone)
686 List *arguments = fcache->args;
688 FunctionCallInfoData fcinfo;
689 ReturnSetInfo rsinfo; /* for functions returning sets */
690 ExprDoneCond argDone;
695 * arguments is a list of expressions to evaluate before passing to
696 * the function manager. We skip the evaluation if it was already
697 * done in the previous call (ie, we are continuing the evaluation of
698 * a set-valued function). Otherwise, collect the current argument
699 * values into fcinfo.
701 if (!fcache->setArgsValid)
703 /* Need to prep callinfo structure */
704 MemSet(&fcinfo, 0, sizeof(fcinfo));
705 fcinfo.flinfo = &(fcache->func);
706 argDone = ExecEvalFuncArgs(&fcinfo, arguments, econtext);
707 if (argDone == ExprEndResult)
709 /* input is an empty set, so return an empty set. */
712 *isDone = ExprEndResult;
715 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
716 errmsg("set-valued function called in context that cannot accept a set")));
719 hasSetArg = (argDone != ExprSingleResult);
723 /* Copy callinfo from previous evaluation */
724 memcpy(&fcinfo, &fcache->setArgs, sizeof(fcinfo));
725 hasSetArg = fcache->setHasSetArg;
726 /* Reset flag (we may set it again below) */
727 fcache->setArgsValid = false;
731 * If function returns set, prepare a resultinfo node for
734 if (fcache->func.fn_retset)
736 fcinfo.resultinfo = (Node *) &rsinfo;
737 rsinfo.type = T_ReturnSetInfo;
738 rsinfo.econtext = econtext;
739 rsinfo.expectedDesc = NULL;
740 rsinfo.allowedModes = (int) SFRM_ValuePerCall;
741 rsinfo.returnMode = SFRM_ValuePerCall;
742 /* isDone is filled below */
743 rsinfo.setResult = NULL;
744 rsinfo.setDesc = NULL;
748 * now return the value gotten by calling the function manager,
749 * passing the function the evaluated parameter values.
751 if (fcache->func.fn_retset || hasSetArg)
754 * We need to return a set result. Complain if caller not ready
759 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
760 errmsg("set-valued function called in context that cannot accept a set")));
763 * This loop handles the situation where we have both a set
764 * argument and a set-valued function. Once we have exhausted the
765 * function's value(s) for a particular argument value, we have to
766 * get the next argument value and start the function over again.
767 * We might have to do it more than once, if the function produces
768 * an empty result set for a particular input value.
773 * If function is strict, and there are any NULL arguments,
774 * skip calling the function (at least for this set of args).
778 if (fcache->func.fn_strict)
780 for (i = 0; i < fcinfo.nargs; i++)
782 if (fcinfo.argnull[i])
792 fcinfo.isnull = false;
793 rsinfo.isDone = ExprSingleResult;
794 result = FunctionCallInvoke(&fcinfo);
795 *isNull = fcinfo.isnull;
796 *isDone = rsinfo.isDone;
802 *isDone = ExprEndResult;
805 if (*isDone != ExprEndResult)
808 * Got a result from current argument. If function itself
809 * returns set, save the current argument values to re-use
812 if (fcache->func.fn_retset)
814 memcpy(&fcache->setArgs, &fcinfo, sizeof(fcinfo));
815 fcache->setHasSetArg = hasSetArg;
816 fcache->setArgsValid = true;
820 * Make sure we say we are returning a set, even if the
821 * function itself doesn't return sets.
823 *isDone = ExprMultipleResult;
827 /* Else, done with this argument */
829 break; /* input not a set, so done */
831 /* Re-eval args to get the next element of the input set */
832 argDone = ExecEvalFuncArgs(&fcinfo, arguments, econtext);
834 if (argDone != ExprMultipleResult)
836 /* End of argument set, so we're done. */
838 *isDone = ExprEndResult;
844 * If we reach here, loop around to run the function on the
852 * Non-set case: much easier.
854 * If function is strict, and there are any NULL arguments, skip
855 * calling the function and return NULL.
857 if (fcache->func.fn_strict)
859 for (i = 0; i < fcinfo.nargs; i++)
861 if (fcinfo.argnull[i])
868 fcinfo.isnull = false;
869 result = FunctionCallInvoke(&fcinfo);
870 *isNull = fcinfo.isnull;
878 * ExecMakeTableFunctionResult
880 * Evaluate a table function, producing a materialized result in a Tuplestore
881 * object. (If function returns an empty set, we just return NULL instead.)
884 ExecMakeTableFunctionResult(ExprState *funcexpr,
885 ExprContext *econtext,
886 TupleDesc expectedDesc,
887 TupleDesc *returnDesc)
889 Tuplestorestate *tupstore = NULL;
890 TupleDesc tupdesc = NULL;
892 FunctionCallInfoData fcinfo;
893 ReturnSetInfo rsinfo;
894 MemoryContext callerContext;
895 MemoryContext oldcontext;
896 TupleTableSlot *slot;
897 bool direct_function_call;
898 bool first_time = true;
899 bool returnsTuple = false;
902 * Normally the passed expression tree will be a FuncExprState, since the
903 * grammar only allows a function call at the top level of a table
904 * function reference. However, if the function doesn't return set then
905 * the planner might have replaced the function call via constant-folding
906 * or inlining. So if we see any other kind of expression node, execute
907 * it via the general ExecEvalExpr() code; the only difference is that
908 * we don't get a chance to pass a special ReturnSetInfo to any functions
909 * buried in the expression.
911 if (funcexpr && IsA(funcexpr, FuncExprState) &&
912 IsA(funcexpr->expr, FuncExpr))
914 FuncExprState *fcache = (FuncExprState *) funcexpr;
915 ExprDoneCond argDone;
918 * This path is similar to ExecMakeFunctionResult.
920 direct_function_call = true;
923 * Initialize function cache if first time through
925 if (fcache->func.fn_oid == InvalidOid)
927 FuncExpr *func = (FuncExpr *) fcache->xprstate.expr;
929 init_fcache(func->funcid, fcache, econtext->ecxt_per_query_memory);
933 * Evaluate the function's argument list.
935 * Note: ideally, we'd do this in the per-tuple context, but then the
936 * argument values would disappear when we reset the context in the
937 * inner loop. So do it in caller context. Perhaps we should make a
938 * separate context just to hold the evaluated arguments?
940 MemSet(&fcinfo, 0, sizeof(fcinfo));
941 fcinfo.flinfo = &(fcache->func);
942 argDone = ExecEvalFuncArgs(&fcinfo, fcache->args, econtext);
943 /* We don't allow sets in the arguments of the table function */
944 if (argDone != ExprSingleResult)
946 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
947 errmsg("set-valued function called in context that cannot accept a set")));
950 * If function is strict, and there are any NULL arguments, skip
951 * calling the function and return NULL (actually an empty set).
953 if (fcache->func.fn_strict)
957 for (i = 0; i < fcinfo.nargs; i++)
959 if (fcinfo.argnull[i])
969 /* Treat funcexpr as a generic expression */
970 direct_function_call = false;
973 funcrettype = exprType((Node *) funcexpr->expr);
976 * Prepare a resultinfo node for communication. We always do this
977 * even if not expecting a set result, so that we can pass
978 * expectedDesc. In the generic-expression case, the expression
979 * doesn't actually get to see the resultinfo, but set it up anyway
980 * because we use some of the fields as our own state variables.
982 fcinfo.resultinfo = (Node *) &rsinfo;
983 rsinfo.type = T_ReturnSetInfo;
984 rsinfo.econtext = econtext;
985 rsinfo.expectedDesc = expectedDesc;
986 rsinfo.allowedModes = (int) (SFRM_ValuePerCall | SFRM_Materialize);
987 rsinfo.returnMode = SFRM_ValuePerCall;
988 /* isDone is filled below */
989 rsinfo.setResult = NULL;
990 rsinfo.setDesc = NULL;
993 * Switch to short-lived context for calling the function or expression.
995 callerContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
998 * Loop to handle the ValuePerCall protocol (which is also the same
999 * behavior needed in the generic ExecEvalExpr path).
1007 * reset per-tuple memory context before each call of the
1008 * function or expression. This cleans up any local memory the
1009 * function may leak when called.
1011 ResetExprContext(econtext);
1013 /* Call the function or expression one time */
1014 if (direct_function_call)
1016 fcinfo.isnull = false;
1017 rsinfo.isDone = ExprSingleResult;
1018 result = FunctionCallInvoke(&fcinfo);
1022 result = ExecEvalExpr(funcexpr, econtext,
1023 &fcinfo.isnull, &rsinfo.isDone);
1026 /* Which protocol does function want to use? */
1027 if (rsinfo.returnMode == SFRM_ValuePerCall)
1030 * Check for end of result set.
1032 * Note: if function returns an empty set, we don't build a
1033 * tupdesc or tuplestore (since we can't get a tupdesc in the
1034 * function-returning-tuple case)
1036 if (rsinfo.isDone == ExprEndResult)
1040 * If first time through, build tupdesc and tuplestore for
1045 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1046 if (funcrettype == RECORDOID ||
1047 get_typtype(funcrettype) == 'c')
1050 * Composite type, so function should have returned a
1051 * TupleTableSlot; use its descriptor
1053 slot = (TupleTableSlot *) DatumGetPointer(result);
1054 if (fcinfo.isnull || !slot)
1056 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1057 errmsg("function returning tuple cannot return NULL")));
1058 if (!IsA(slot, TupleTableSlot) ||
1059 !slot->ttc_tupleDescriptor)
1061 (errcode(ERRCODE_DATATYPE_MISMATCH),
1062 errmsg("function returning tuple did not return a valid tuple slot")));
1063 tupdesc = CreateTupleDescCopy(slot->ttc_tupleDescriptor);
1064 returnsTuple = true;
1069 * Scalar type, so make a single-column descriptor
1071 tupdesc = CreateTemplateTupleDesc(1, false);
1072 TupleDescInitEntry(tupdesc,
1080 tupstore = tuplestore_begin_heap(true, false, SortMem);
1081 MemoryContextSwitchTo(oldcontext);
1082 rsinfo.setResult = tupstore;
1083 rsinfo.setDesc = tupdesc;
1087 * Store current resultset item.
1091 slot = (TupleTableSlot *) DatumGetPointer(result);
1092 if (fcinfo.isnull ||
1094 !IsA(slot, TupleTableSlot) ||
1097 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1098 errmsg("function returning tuple cannot return NULL")));
1105 nullflag = fcinfo.isnull ? 'n' : ' ';
1106 tuple = heap_formtuple(tupdesc, &result, &nullflag);
1109 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1110 tuplestore_puttuple(tupstore, tuple);
1111 MemoryContextSwitchTo(oldcontext);
1116 if (rsinfo.isDone != ExprMultipleResult)
1119 else if (rsinfo.returnMode == SFRM_Materialize)
1121 /* check we're on the same page as the function author */
1122 if (!first_time || rsinfo.isDone != ExprSingleResult)
1124 (errcode(ERRCODE_E_R_I_E_SRF_PROTOCOL_VIOLATED),
1125 errmsg("table-function protocol for materialize mode was not followed")));
1126 /* Done evaluating the set result */
1131 (errcode(ERRCODE_E_R_I_E_SRF_PROTOCOL_VIOLATED),
1132 errmsg("unrecognized table-function returnMode: %d",
1133 (int) rsinfo.returnMode)));
1138 MemoryContextSwitchTo(callerContext);
1140 /* The returned pointers are those in rsinfo */
1141 *returnDesc = rsinfo.setDesc;
1142 return rsinfo.setResult;
1146 /* ----------------------------------------------------------------
1150 * Evaluate the functional result of a list of arguments by calling the
1152 * ----------------------------------------------------------------
1155 /* ----------------------------------------------------------------
1157 * ----------------------------------------------------------------
1160 ExecEvalFunc(FuncExprState *fcache,
1161 ExprContext *econtext,
1163 ExprDoneCond *isDone)
1166 * Initialize function cache if first time through
1168 if (fcache->func.fn_oid == InvalidOid)
1170 FuncExpr *func = (FuncExpr *) fcache->xprstate.expr;
1172 init_fcache(func->funcid, fcache, econtext->ecxt_per_query_memory);
1175 return ExecMakeFunctionResult(fcache, econtext, isNull, isDone);
1178 /* ----------------------------------------------------------------
1180 * ----------------------------------------------------------------
1183 ExecEvalOper(FuncExprState *fcache,
1184 ExprContext *econtext,
1186 ExprDoneCond *isDone)
1189 * Initialize function cache if first time through
1191 if (fcache->func.fn_oid == InvalidOid)
1193 OpExpr *op = (OpExpr *) fcache->xprstate.expr;
1195 init_fcache(op->opfuncid, fcache, econtext->ecxt_per_query_memory);
1198 return ExecMakeFunctionResult(fcache, econtext, isNull, isDone);
1201 /* ----------------------------------------------------------------
1204 * IS DISTINCT FROM must evaluate arguments to determine whether
1205 * they are NULL; if either is NULL then the result is already
1206 * known. If neither is NULL, then proceed to evaluate the
1207 * function. Note that this is *always* derived from the equals
1208 * operator, but since we need special processing of the arguments
1209 * we can not simply reuse ExecEvalOper() or ExecEvalFunc().
1210 * ----------------------------------------------------------------
1213 ExecEvalDistinct(FuncExprState *fcache,
1214 ExprContext *econtext,
1218 FunctionCallInfoData fcinfo;
1219 ExprDoneCond argDone;
1223 * Initialize function cache if first time through
1225 if (fcache->func.fn_oid == InvalidOid)
1227 DistinctExpr *op = (DistinctExpr *) fcache->xprstate.expr;
1229 init_fcache(op->opfuncid, fcache, econtext->ecxt_per_query_memory);
1230 Assert(!fcache->func.fn_retset);
1234 * extract info from fcache
1236 argList = fcache->args;
1238 /* Need to prep callinfo structure */
1239 MemSet(&fcinfo, 0, sizeof(fcinfo));
1240 fcinfo.flinfo = &(fcache->func);
1241 argDone = ExecEvalFuncArgs(&fcinfo, argList, econtext);
1242 if (argDone != ExprSingleResult)
1244 (errcode(ERRCODE_DATATYPE_MISMATCH),
1245 errmsg("IS DISTINCT FROM does not support set arguments")));
1246 Assert(fcinfo.nargs == 2);
1248 if (fcinfo.argnull[0] && fcinfo.argnull[1])
1250 /* Both NULL? Then is not distinct... */
1251 result = BoolGetDatum(FALSE);
1253 else if (fcinfo.argnull[0] || fcinfo.argnull[1])
1255 /* Only one is NULL? Then is distinct... */
1256 result = BoolGetDatum(TRUE);
1260 fcinfo.isnull = false;
1261 result = FunctionCallInvoke(&fcinfo);
1262 *isNull = fcinfo.isnull;
1263 /* Must invert result of "=" */
1264 result = BoolGetDatum(!DatumGetBool(result));
1271 * ExecEvalScalarArrayOp
1273 * Evaluate "scalar op ANY/ALL (array)". The operator always yields boolean,
1274 * and we combine the results across all array elements using OR and AND
1275 * (for ANY and ALL respectively). Of course we short-circuit as soon as
1276 * the result is known.
1279 ExecEvalScalarArrayOp(ScalarArrayOpExprState *sstate,
1280 ExprContext *econtext, bool *isNull)
1282 ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) sstate->fxprstate.xprstate.expr;
1283 bool useOr = opexpr->useOr;
1288 FunctionCallInfoData fcinfo;
1289 ExprDoneCond argDone;
1297 * Initialize function cache if first time through
1299 if (sstate->fxprstate.func.fn_oid == InvalidOid)
1301 init_fcache(opexpr->opfuncid, &sstate->fxprstate,
1302 econtext->ecxt_per_query_memory);
1303 Assert(!sstate->fxprstate.func.fn_retset);
1306 /* Need to prep callinfo structure */
1307 MemSet(&fcinfo, 0, sizeof(fcinfo));
1308 fcinfo.flinfo = &(sstate->fxprstate.func);
1309 argDone = ExecEvalFuncArgs(&fcinfo, sstate->fxprstate.args, econtext);
1310 if (argDone != ExprSingleResult)
1312 (errcode(ERRCODE_DATATYPE_MISMATCH),
1313 errmsg("op ANY/ALL (array) does not support set arguments")));
1314 Assert(fcinfo.nargs == 2);
1317 * If the array is NULL then we return NULL --- it's not very meaningful
1318 * to do anything else, even if the operator isn't strict.
1320 if (fcinfo.argnull[1])
1325 /* Else okay to fetch and detoast the array */
1326 arr = DatumGetArrayTypeP(fcinfo.arg[1]);
1329 * If the array is empty, we return either FALSE or TRUE per the useOr
1330 * flag. This is correct even if the scalar is NULL; since we would
1331 * evaluate the operator zero times, it matters not whether it would
1332 * want to return NULL.
1334 nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr));
1336 return BoolGetDatum(!useOr);
1338 * If the scalar is NULL, and the function is strict, return NULL.
1339 * This is just to avoid having to test for strictness inside the
1340 * loop. (XXX but if arrays could have null elements, we'd need a
1343 if (fcinfo.argnull[0] && sstate->fxprstate.func.fn_strict)
1350 * We arrange to look up info about the element type only
1351 * once per series of calls, assuming the element type doesn't change
1354 if (sstate->element_type != ARR_ELEMTYPE(arr))
1356 get_typlenbyvalalign(ARR_ELEMTYPE(arr),
1360 sstate->element_type = ARR_ELEMTYPE(arr);
1362 typlen = sstate->typlen;
1363 typbyval = sstate->typbyval;
1364 typalign = sstate->typalign;
1366 result = BoolGetDatum(!useOr);
1369 /* Loop over the array elements */
1370 s = (char *) ARR_DATA_PTR(arr);
1371 for (i = 0; i < nitems; i++)
1376 /* Get array element */
1377 elt = fetch_att(s, typbyval, typlen);
1379 s = att_addlength(s, typlen, PointerGetDatum(s));
1380 s = (char *) att_align(s, typalign);
1382 /* Call comparison function */
1383 fcinfo.arg[1] = elt;
1384 fcinfo.argnull[1] = false;
1385 fcinfo.isnull = false;
1386 thisresult = FunctionCallInvoke(&fcinfo);
1388 /* Combine results per OR or AND semantics */
1393 if (DatumGetBool(thisresult))
1395 result = BoolGetDatum(true);
1397 break; /* needn't look at any more elements */
1402 if (!DatumGetBool(thisresult))
1404 result = BoolGetDatum(false);
1406 break; /* needn't look at any more elements */
1411 *isNull = resultnull;
1415 /* ----------------------------------------------------------------
1420 * Evaluate boolean expressions, with appropriate short-circuiting.
1422 * The query planner reformulates clause expressions in the
1423 * qualification to conjunctive normal form. If we ever get
1424 * an AND to evaluate, we can be sure that it's not a top-level
1425 * clause in the qualification, but appears lower (as a function
1426 * argument, for example), or in the target list. Not that you
1427 * need to know this, mind you...
1428 * ----------------------------------------------------------------
1431 ExecEvalNot(BoolExprState *notclause, ExprContext *econtext, bool *isNull)
1436 clause = lfirst(notclause->args);
1438 expr_value = ExecEvalExpr(clause, econtext, isNull, NULL);
1441 * if the expression evaluates to null, then we just cascade the null
1442 * back to whoever called us.
1448 * evaluation of 'not' is simple.. expr is false, then return 'true'
1451 return BoolGetDatum(!DatumGetBool(expr_value));
1454 /* ----------------------------------------------------------------
1456 * ----------------------------------------------------------------
1459 ExecEvalOr(BoolExprState *orExpr, ExprContext *econtext, bool *isNull)
1466 clauses = orExpr->args;
1470 * If any of the clauses is TRUE, the OR result is TRUE regardless of
1471 * the states of the rest of the clauses, so we can stop evaluating
1472 * and return TRUE immediately. If none are TRUE and one or more is
1473 * NULL, we return NULL; otherwise we return FALSE. This makes sense
1474 * when you interpret NULL as "don't know": if we have a TRUE then the
1475 * OR is TRUE even if we aren't sure about some of the other inputs.
1476 * If all the known inputs are FALSE, but we have one or more "don't
1477 * knows", then we have to report that we "don't know" what the OR's
1478 * result should be --- perhaps one of the "don't knows" would have
1479 * been TRUE if we'd known its value. Only when all the inputs are
1480 * known to be FALSE can we state confidently that the OR's result is
1483 foreach(clause, clauses)
1485 clause_value = ExecEvalExpr((ExprState *) lfirst(clause),
1486 econtext, isNull, NULL);
1489 * if we have a non-null true result, then return it.
1492 AnyNull = true; /* remember we got a null */
1493 else if (DatumGetBool(clause_value))
1494 return clause_value;
1497 /* AnyNull is true if at least one clause evaluated to NULL */
1499 return BoolGetDatum(false);
1502 /* ----------------------------------------------------------------
1504 * ----------------------------------------------------------------
1507 ExecEvalAnd(BoolExprState *andExpr, ExprContext *econtext, bool *isNull)
1514 clauses = andExpr->args;
1518 * If any of the clauses is FALSE, the AND result is FALSE regardless
1519 * of the states of the rest of the clauses, so we can stop evaluating
1520 * and return FALSE immediately. If none are FALSE and one or more is
1521 * NULL, we return NULL; otherwise we return TRUE. This makes sense
1522 * when you interpret NULL as "don't know", using the same sort of
1523 * reasoning as for OR, above.
1525 foreach(clause, clauses)
1527 clause_value = ExecEvalExpr((ExprState *) lfirst(clause),
1528 econtext, isNull, NULL);
1531 * if we have a non-null false result, then return it.
1534 AnyNull = true; /* remember we got a null */
1535 else if (!DatumGetBool(clause_value))
1536 return clause_value;
1539 /* AnyNull is true if at least one clause evaluated to NULL */
1541 return BoolGetDatum(!AnyNull);
1545 /* ----------------------------------------------------------------
1548 * Evaluate a CASE clause. Will have boolean expressions
1549 * inside the WHEN clauses, and will have expressions
1551 * - thomas 1998-11-09
1552 * ----------------------------------------------------------------
1555 ExecEvalCase(CaseExprState *caseExpr, ExprContext *econtext,
1556 bool *isNull, ExprDoneCond *isDone)
1562 clauses = caseExpr->args;
1565 * we evaluate each of the WHEN clauses in turn, as soon as one is
1566 * true we return the corresponding result. If none are true then we
1567 * return the value of the default clause, or NULL if there is none.
1569 foreach(clause, clauses)
1571 CaseWhenState *wclause = lfirst(clause);
1573 clause_value = ExecEvalExpr(wclause->expr,
1579 * if we have a true test, then we return the result, since the
1580 * case statement is satisfied. A NULL result from the test is
1581 * not considered true.
1583 if (DatumGetBool(clause_value) && !*isNull)
1585 return ExecEvalExpr(wclause->result,
1592 if (caseExpr->defresult)
1594 return ExecEvalExpr(caseExpr->defresult,
1604 /* ----------------------------------------------------------------
1605 * ExecEvalArray - ARRAY[] expressions
1607 * NOTE: currently, if any input value is NULL then we return a NULL array,
1608 * so the ARRAY[] construct can be considered strict. Eventually this will
1609 * change; when it does, be sure to fix contain_nonstrict_functions().
1610 * ----------------------------------------------------------------
1613 ExecEvalArray(ArrayExprState *astate, ExprContext *econtext,
1616 ArrayExpr *arrayExpr = (ArrayExpr *) astate->xprstate.expr;
1619 Oid element_type = arrayExpr->element_typeid;
1620 int ndims = arrayExpr->ndims;
1630 nelems = length(astate->elements);
1632 /* Shouldn't happen here, but if length is 0, return NULL */
1639 dvalues = (Datum *) palloc(nelems * sizeof(Datum));
1641 /* loop through and build array of datums */
1642 foreach(element, astate->elements)
1644 ExprState *e = (ExprState *) lfirst(element);
1647 dvalues[i++] = ExecEvalExpr(e, econtext, &eisnull, NULL);
1655 /* setup for 1-D array of the given length */
1659 result = construct_md_array(dvalues, ndims, dims, lbs,
1668 Size ndatabytes = 0;
1670 int outer_nelems = length(astate->elements);
1672 int *elem_dims = NULL;
1673 int *elem_lbs = NULL;
1674 bool firstone = true;
1677 if (ndims <= 0 || ndims > MAXDIM)
1679 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1680 errmsg("number of array dimensions exceeds the maximum allowed, %d",
1683 /* loop through and get data area from each element */
1684 foreach(element, astate->elements)
1686 ExprState *e = (ExprState *) lfirst(element);
1690 int elem_ndatabytes;
1692 arraydatum = ExecEvalExpr(e, econtext, &eisnull, NULL);
1699 array = DatumGetArrayTypeP(arraydatum);
1703 /* Get sub-array details from first member */
1704 elem_ndims = ARR_NDIM(array);
1705 elem_dims = (int *) palloc(elem_ndims * sizeof(int));
1706 memcpy(elem_dims, ARR_DIMS(array), elem_ndims * sizeof(int));
1707 elem_lbs = (int *) palloc(elem_ndims * sizeof(int));
1708 memcpy(elem_lbs, ARR_LBOUND(array), elem_ndims * sizeof(int));
1713 /* Check other sub-arrays are compatible */
1714 if (elem_ndims != ARR_NDIM(array) ||
1715 memcmp(elem_dims, ARR_DIMS(array),
1716 elem_ndims * sizeof(int)) != 0 ||
1717 memcmp(elem_lbs, ARR_LBOUND(array),
1718 elem_ndims * sizeof(int)) != 0)
1720 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1721 errmsg("multidimensional arrays must have array "
1722 "expressions with matching dimensions")));
1725 elem_ndatabytes = ARR_SIZE(array) - ARR_OVERHEAD(elem_ndims);
1726 ndatabytes += elem_ndatabytes;
1728 dat = (char *) palloc(ndatabytes);
1730 dat = (char *) repalloc(dat, ndatabytes);
1732 memcpy(dat + (ndatabytes - elem_ndatabytes),
1733 ARR_DATA_PTR(array),
1737 /* setup for multi-D array */
1738 dims[0] = outer_nelems;
1740 for (i = 1; i < ndims; i++)
1742 dims[i] = elem_dims[i - 1];
1743 lbs[i] = elem_lbs[i - 1];
1746 nbytes = ndatabytes + ARR_OVERHEAD(ndims);
1747 result = (ArrayType *) palloc(nbytes);
1749 result->size = nbytes;
1750 result->ndim = ndims;
1752 result->elemtype = element_type;
1753 memcpy(ARR_DIMS(result), dims, ndims * sizeof(int));
1754 memcpy(ARR_LBOUND(result), lbs, ndims * sizeof(int));
1756 memcpy(ARR_DATA_PTR(result), dat, ndatabytes);
1762 return PointerGetDatum(result);
1765 /* ----------------------------------------------------------------
1767 * ----------------------------------------------------------------
1770 ExecEvalCoalesce(CoalesceExprState *coalesceExpr, ExprContext *econtext,
1775 /* Simply loop through until something NOT NULL is found */
1776 foreach(arg, coalesceExpr->args)
1778 ExprState *e = (ExprState *) lfirst(arg);
1781 value = ExecEvalExpr(e, econtext, isNull, NULL);
1786 /* Else return NULL */
1791 /* ----------------------------------------------------------------
1794 * Note that this is *always* derived from the equals operator,
1795 * but since we need special processing of the arguments
1796 * we can not simply reuse ExecEvalOper() or ExecEvalFunc().
1797 * ----------------------------------------------------------------
1800 ExecEvalNullIf(FuncExprState *fcache, ExprContext *econtext,
1804 FunctionCallInfoData fcinfo;
1805 ExprDoneCond argDone;
1809 * Initialize function cache if first time through
1811 if (fcache->func.fn_oid == InvalidOid)
1813 NullIfExpr *op = (NullIfExpr *) fcache->xprstate.expr;
1815 init_fcache(op->opfuncid, fcache, econtext->ecxt_per_query_memory);
1816 Assert(!fcache->func.fn_retset);
1820 * extract info from fcache
1822 argList = fcache->args;
1824 /* Need to prep callinfo structure */
1825 MemSet(&fcinfo, 0, sizeof(fcinfo));
1826 fcinfo.flinfo = &(fcache->func);
1827 argDone = ExecEvalFuncArgs(&fcinfo, argList, econtext);
1828 if (argDone != ExprSingleResult)
1830 (errcode(ERRCODE_DATATYPE_MISMATCH),
1831 errmsg("NULLIF does not support set arguments")));
1832 Assert(fcinfo.nargs == 2);
1834 /* if either argument is NULL they can't be equal */
1835 if (!fcinfo.argnull[0] && !fcinfo.argnull[1])
1837 fcinfo.isnull = false;
1838 result = FunctionCallInvoke(&fcinfo);
1839 /* if the arguments are equal return null */
1840 if (!fcinfo.isnull && DatumGetBool(result))
1847 /* else return first argument */
1848 *isNull = fcinfo.argnull[0];
1849 return fcinfo.arg[0];
1852 /* ----------------------------------------------------------------
1855 * Evaluate a NullTest node.
1856 * ----------------------------------------------------------------
1859 ExecEvalNullTest(GenericExprState *nstate,
1860 ExprContext *econtext,
1862 ExprDoneCond *isDone)
1864 NullTest *ntest = (NullTest *) nstate->xprstate.expr;
1867 result = ExecEvalExpr(nstate->arg, econtext, isNull, isDone);
1869 if (isDone && *isDone == ExprEndResult)
1870 return result; /* nothing to check */
1872 switch (ntest->nulltesttype)
1878 return BoolGetDatum(true);
1881 return BoolGetDatum(false);
1886 return BoolGetDatum(false);
1889 return BoolGetDatum(true);
1891 elog(ERROR, "unrecognized nulltesttype: %d",
1892 (int) ntest->nulltesttype);
1893 return (Datum) 0; /* keep compiler quiet */
1897 /* ----------------------------------------------------------------
1898 * ExecEvalBooleanTest
1900 * Evaluate a BooleanTest node.
1901 * ----------------------------------------------------------------
1904 ExecEvalBooleanTest(GenericExprState *bstate,
1905 ExprContext *econtext,
1907 ExprDoneCond *isDone)
1909 BooleanTest *btest = (BooleanTest *) bstate->xprstate.expr;
1912 result = ExecEvalExpr(bstate->arg, econtext, isNull, isDone);
1914 if (isDone && *isDone == ExprEndResult)
1915 return result; /* nothing to check */
1917 switch (btest->booltesttype)
1923 return BoolGetDatum(false);
1925 else if (DatumGetBool(result))
1926 return BoolGetDatum(true);
1928 return BoolGetDatum(false);
1933 return BoolGetDatum(true);
1935 else if (DatumGetBool(result))
1936 return BoolGetDatum(false);
1938 return BoolGetDatum(true);
1943 return BoolGetDatum(false);
1945 else if (DatumGetBool(result))
1946 return BoolGetDatum(false);
1948 return BoolGetDatum(true);
1953 return BoolGetDatum(true);
1955 else if (DatumGetBool(result))
1956 return BoolGetDatum(true);
1958 return BoolGetDatum(false);
1963 return BoolGetDatum(true);
1966 return BoolGetDatum(false);
1967 case IS_NOT_UNKNOWN:
1971 return BoolGetDatum(false);
1974 return BoolGetDatum(true);
1976 elog(ERROR, "unrecognized booltesttype: %d",
1977 (int) btest->booltesttype);
1978 return (Datum) 0; /* keep compiler quiet */
1983 * ExecEvalCoerceToDomain
1985 * Test the provided data against the domain constraint(s). If the data
1986 * passes the constraint specifications, pass it through (return the
1987 * datum) otherwise throw an error.
1990 ExecEvalCoerceToDomain(CoerceToDomainState *cstate, ExprContext *econtext,
1991 bool *isNull, ExprDoneCond *isDone)
1993 CoerceToDomain *ctest = (CoerceToDomain *) cstate->xprstate.expr;
1997 result = ExecEvalExpr(cstate->arg, econtext, isNull, isDone);
1999 if (isDone && *isDone == ExprEndResult)
2000 return result; /* nothing to check */
2002 foreach(l, cstate->constraints)
2004 DomainConstraintState *con = (DomainConstraintState *) lfirst(l);
2006 switch (con->constrainttype)
2008 case DOM_CONSTRAINT_NOTNULL:
2011 (errcode(ERRCODE_NOT_NULL_VIOLATION),
2012 errmsg("domain %s does not allow NULL values",
2013 format_type_be(ctest->resulttype))));
2015 case DOM_CONSTRAINT_CHECK:
2023 * Set up value to be returned by CoerceToDomainValue nodes.
2024 * We must save and restore prior setting of econtext's
2025 * domainValue fields, in case this node is itself within
2026 * a check expression for another domain.
2028 save_datum = econtext->domainValue_datum;
2029 save_isNull = econtext->domainValue_isNull;
2031 econtext->domainValue_datum = result;
2032 econtext->domainValue_isNull = *isNull;
2034 conResult = ExecEvalExpr(con->check_expr,
2035 econtext, &conIsNull, NULL);
2038 !DatumGetBool(conResult))
2040 (errcode(ERRCODE_CHECK_VIOLATION),
2041 errmsg("value for domain %s violates CHECK constraint \"%s\"",
2042 format_type_be(ctest->resulttype),
2044 econtext->domainValue_datum = save_datum;
2045 econtext->domainValue_isNull = save_isNull;
2050 elog(ERROR, "unrecognized constraint type: %d",
2051 (int) con->constrainttype);
2056 /* If all has gone well (constraints did not fail) return the datum */
2061 * ExecEvalCoerceToDomainValue
2063 * Return the value stored by CoerceToDomain.
2066 ExecEvalCoerceToDomainValue(CoerceToDomainValue *conVal,
2067 ExprContext *econtext, bool *isNull)
2069 *isNull = econtext->domainValue_isNull;
2070 return econtext->domainValue_datum;
2073 /* ----------------------------------------------------------------
2074 * ExecEvalFieldSelect
2076 * Evaluate a FieldSelect node.
2077 * ----------------------------------------------------------------
2080 ExecEvalFieldSelect(GenericExprState *fstate,
2081 ExprContext *econtext,
2083 ExprDoneCond *isDone)
2085 FieldSelect *fselect = (FieldSelect *) fstate->xprstate.expr;
2087 TupleTableSlot *resSlot;
2089 result = ExecEvalExpr(fstate->arg, econtext, isNull, isDone);
2091 /* this test covers the isDone exception too: */
2095 resSlot = (TupleTableSlot *) DatumGetPointer(result);
2096 Assert(resSlot != NULL && IsA(resSlot, TupleTableSlot));
2097 result = heap_getattr(resSlot->val,
2099 resSlot->ttc_tupleDescriptor,
2104 /* ----------------------------------------------------------------
2107 * Recursively evaluate a targetlist or qualification expression.
2110 * expression: the expression state tree to evaluate
2111 * econtext: evaluation context information
2114 * return value: Datum value of result
2115 * *isNull: set to TRUE if result is NULL (actual return value is
2116 * meaningless if so); set to FALSE if non-null result
2117 * *isDone: set to indicator of set-result status
2119 * A caller that can only accept a singleton (non-set) result should pass
2120 * NULL for isDone; if the expression computes a set result then an error
2121 * will be reported via ereport. If the caller does pass an isDone pointer
2122 * then *isDone is set to one of these three states:
2123 * ExprSingleResult singleton result (not a set)
2124 * ExprMultipleResult return value is one element of a set
2125 * ExprEndResult there are no more elements in the set
2126 * When ExprMultipleResult is returned, the caller should invoke
2127 * ExecEvalExpr() repeatedly until ExprEndResult is returned. ExprEndResult
2128 * is returned after the last real set element. For convenience isNull will
2129 * always be set TRUE when ExprEndResult is returned, but this should not be
2130 * taken as indicating a NULL element of the set. Note that these return
2131 * conventions allow us to distinguish among a singleton NULL, a NULL element
2132 * of a set, and an empty set.
2134 * The caller should already have switched into the temporary memory
2135 * context econtext->ecxt_per_tuple_memory. The convenience entry point
2136 * ExecEvalExprSwitchContext() is provided for callers who don't prefer to
2137 * do the switch in an outer loop. We do not do the switch here because
2138 * it'd be a waste of cycles during recursive entries to ExecEvalExpr().
2140 * This routine is an inner loop routine and must be as fast as possible.
2141 * ----------------------------------------------------------------
2144 ExecEvalExpr(ExprState *expression,
2145 ExprContext *econtext,
2147 ExprDoneCond *isDone)
2152 /* Set default values for result flags: non-null, not a set result */
2155 *isDone = ExprSingleResult;
2157 /* Is this still necessary? Doubtful... */
2158 if (expression == NULL)
2165 * here we dispatch the work to the appropriate type of function given
2166 * the type of our expression.
2168 expr = expression->expr;
2169 switch (nodeTag(expr))
2172 retDatum = ExecEvalVar((Var *) expr, econtext, isNull);
2176 Const *con = (Const *) expr;
2178 retDatum = con->constvalue;
2179 *isNull = con->constisnull;
2183 retDatum = ExecEvalParam((Param *) expr, econtext, isNull);
2186 retDatum = ExecEvalAggref((AggrefExprState *) expression,
2191 retDatum = ExecEvalArrayRef((ArrayRefExprState *) expression,
2197 retDatum = ExecEvalFunc((FuncExprState *) expression, econtext,
2201 retDatum = ExecEvalOper((FuncExprState *) expression, econtext,
2204 case T_DistinctExpr:
2205 retDatum = ExecEvalDistinct((FuncExprState *) expression, econtext,
2208 case T_ScalarArrayOpExpr:
2209 retDatum = ExecEvalScalarArrayOp((ScalarArrayOpExprState *) expression,
2214 BoolExprState *state = (BoolExprState *) expression;
2216 switch (((BoolExpr *) expr)->boolop)
2219 retDatum = ExecEvalAnd(state, econtext, isNull);
2222 retDatum = ExecEvalOr(state, econtext, isNull);
2225 retDatum = ExecEvalNot(state, econtext, isNull);
2228 elog(ERROR, "unrecognized boolop: %d",
2229 (int) ((BoolExpr *) expr)->boolop);
2230 retDatum = 0; /* keep compiler quiet */
2236 retDatum = ExecSubPlan((SubPlanState *) expression,
2241 retDatum = ExecEvalFieldSelect((GenericExprState *) expression,
2247 retDatum = ExecEvalExpr(((GenericExprState *) expression)->arg,
2253 retDatum = ExecEvalCase((CaseExprState *) expression,
2259 retDatum = ExecEvalArray((ArrayExprState *) expression,
2263 case T_CoalesceExpr:
2264 retDatum = ExecEvalCoalesce((CoalesceExprState *) expression,
2269 retDatum = ExecEvalNullIf((FuncExprState *) expression,
2274 retDatum = ExecEvalNullTest((GenericExprState *) expression,
2280 retDatum = ExecEvalBooleanTest((GenericExprState *) expression,
2285 case T_CoerceToDomain:
2286 retDatum = ExecEvalCoerceToDomain((CoerceToDomainState *) expression,
2291 case T_CoerceToDomainValue:
2292 retDatum = ExecEvalCoerceToDomainValue((CoerceToDomainValue *) expr,
2297 elog(ERROR, "unrecognized node type: %d",
2298 (int) nodeTag(expression));
2299 retDatum = 0; /* keep compiler quiet */
2304 } /* ExecEvalExpr() */
2308 * Same as above, but get into the right allocation context explicitly.
2311 ExecEvalExprSwitchContext(ExprState *expression,
2312 ExprContext *econtext,
2314 ExprDoneCond *isDone)
2317 MemoryContext oldContext;
2319 oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
2320 retDatum = ExecEvalExpr(expression, econtext, isNull, isDone);
2321 MemoryContextSwitchTo(oldContext);
2327 * ExecInitExpr: prepare an expression tree for execution
2329 * This function builds and returns an ExprState tree paralleling the given
2330 * Expr node tree. The ExprState tree can then be handed to ExecEvalExpr
2331 * for execution. Because the Expr tree itself is read-only as far as
2332 * ExecInitExpr and ExecEvalExpr are concerned, several different executions
2333 * of the same plan tree can occur concurrently.
2335 * This must be called in a memory context that will last as long as repeated
2336 * executions of the expression are needed. Typically the context will be
2337 * the same as the per-query context of the associated ExprContext.
2339 * Any Aggref and SubPlan nodes found in the tree are added to the lists
2340 * of such nodes held by the parent PlanState. Otherwise, we do very little
2341 * initialization here other than building the state-node tree. Any nontrivial
2342 * work associated with initializing runtime info for a node should happen
2343 * during the first actual evaluation of that node. (This policy lets us
2344 * avoid work if the node is never actually evaluated.)
2346 * Note: there is no ExecEndExpr function; we assume that any resource
2347 * cleanup needed will be handled by just releasing the memory context
2348 * in which the state tree is built. Functions that require additional
2349 * cleanup work can register a shutdown callback in the ExprContext.
2351 * 'node' is the root of the expression tree to examine
2352 * 'parent' is the PlanState node that owns the expression.
2354 * 'parent' may be NULL if we are preparing an expression that is not
2355 * associated with a plan tree. (If so, it can't have aggs or subplans.)
2356 * This case should usually come through ExecPrepareExpr, not directly here.
2359 ExecInitExpr(Expr *node, PlanState *parent)
2365 switch (nodeTag(node))
2370 case T_CoerceToDomainValue:
2371 /* No special setup needed for these node types */
2372 state = (ExprState *) makeNode(ExprState);
2376 Aggref *aggref = (Aggref *) node;
2377 AggrefExprState *astate = makeNode(AggrefExprState);
2379 if (parent && IsA(parent, AggState))
2381 AggState *aggstate = (AggState *) parent;
2384 aggstate->aggs = lcons(astate, aggstate->aggs);
2385 naggs = ++aggstate->numaggs;
2387 astate->target = ExecInitExpr(aggref->target, parent);
2390 * Complain if the aggregate's argument contains any
2391 * aggregates; nested agg functions are semantically
2392 * nonsensical. (This should have been caught earlier,
2393 * but we defend against it here anyway.)
2395 if (naggs != aggstate->numaggs)
2397 (errcode(ERRCODE_GROUPING_ERROR),
2398 errmsg("aggregate function calls may not be nested")));
2402 /* planner messed up */
2403 elog(ERROR, "aggref found in non-Agg plan node");
2405 state = (ExprState *) astate;
2410 ArrayRef *aref = (ArrayRef *) node;
2411 ArrayRefExprState *astate = makeNode(ArrayRefExprState);
2413 astate->refupperindexpr = (List *)
2414 ExecInitExpr((Expr *) aref->refupperindexpr, parent);
2415 astate->reflowerindexpr = (List *)
2416 ExecInitExpr((Expr *) aref->reflowerindexpr, parent);
2417 astate->refexpr = ExecInitExpr(aref->refexpr, parent);
2418 astate->refassgnexpr = ExecInitExpr(aref->refassgnexpr,
2420 /* do one-time catalog lookups for type info */
2421 astate->refattrlength = get_typlen(aref->refarraytype);
2422 get_typlenbyvalalign(aref->refelemtype,
2423 &astate->refelemlength,
2424 &astate->refelembyval,
2425 &astate->refelemalign);
2426 state = (ExprState *) astate;
2431 FuncExpr *funcexpr = (FuncExpr *) node;
2432 FuncExprState *fstate = makeNode(FuncExprState);
2434 fstate->args = (List *)
2435 ExecInitExpr((Expr *) funcexpr->args, parent);
2436 fstate->func.fn_oid = InvalidOid; /* not initialized */
2437 state = (ExprState *) fstate;
2442 OpExpr *opexpr = (OpExpr *) node;
2443 FuncExprState *fstate = makeNode(FuncExprState);
2445 fstate->args = (List *)
2446 ExecInitExpr((Expr *) opexpr->args, parent);
2447 fstate->func.fn_oid = InvalidOid; /* not initialized */
2448 state = (ExprState *) fstate;
2451 case T_DistinctExpr:
2453 DistinctExpr *distinctexpr = (DistinctExpr *) node;
2454 FuncExprState *fstate = makeNode(FuncExprState);
2456 fstate->args = (List *)
2457 ExecInitExpr((Expr *) distinctexpr->args, parent);
2458 fstate->func.fn_oid = InvalidOid; /* not initialized */
2459 state = (ExprState *) fstate;
2462 case T_ScalarArrayOpExpr:
2464 ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) node;
2465 ScalarArrayOpExprState *sstate = makeNode(ScalarArrayOpExprState);
2467 sstate->fxprstate.args = (List *)
2468 ExecInitExpr((Expr *) opexpr->args, parent);
2469 sstate->fxprstate.func.fn_oid = InvalidOid; /* not initialized */
2470 sstate->element_type = InvalidOid; /* ditto */
2471 state = (ExprState *) sstate;
2476 BoolExpr *boolexpr = (BoolExpr *) node;
2477 BoolExprState *bstate = makeNode(BoolExprState);
2479 bstate->args = (List *)
2480 ExecInitExpr((Expr *) boolexpr->args, parent);
2481 state = (ExprState *) bstate;
2486 /* Keep this in sync with ExecInitExprInitPlan, below */
2487 SubPlan *subplan = (SubPlan *) node;
2488 SubPlanState *sstate = makeNode(SubPlanState);
2491 elog(ERROR, "SubPlan found with no parent plan");
2494 * Here we just add the SubPlanState nodes to
2495 * parent->subPlan. The subplans will be initialized later.
2497 parent->subPlan = lcons(sstate, parent->subPlan);
2498 sstate->sub_estate = NULL;
2499 sstate->planstate = NULL;
2501 sstate->exprs = (List *)
2502 ExecInitExpr((Expr *) subplan->exprs, parent);
2503 sstate->args = (List *)
2504 ExecInitExpr((Expr *) subplan->args, parent);
2506 state = (ExprState *) sstate;
2511 FieldSelect *fselect = (FieldSelect *) node;
2512 GenericExprState *gstate = makeNode(GenericExprState);
2514 gstate->arg = ExecInitExpr(fselect->arg, parent);
2515 state = (ExprState *) gstate;
2520 RelabelType *relabel = (RelabelType *) node;
2521 GenericExprState *gstate = makeNode(GenericExprState);
2523 gstate->arg = ExecInitExpr(relabel->arg, parent);
2524 state = (ExprState *) gstate;
2529 CaseExpr *caseexpr = (CaseExpr *) node;
2530 CaseExprState *cstate = makeNode(CaseExprState);
2534 FastListInit(&outlist);
2535 foreach(inlist, caseexpr->args)
2537 CaseWhen *when = (CaseWhen *) lfirst(inlist);
2538 CaseWhenState *wstate = makeNode(CaseWhenState);
2540 Assert(IsA(when, CaseWhen));
2541 wstate->xprstate.expr = (Expr *) when;
2542 wstate->expr = ExecInitExpr(when->expr, parent);
2543 wstate->result = ExecInitExpr(when->result, parent);
2544 FastAppend(&outlist, wstate);
2546 cstate->args = FastListValue(&outlist);
2547 /* caseexpr->arg should be null by now */
2548 Assert(caseexpr->arg == NULL);
2549 cstate->defresult = ExecInitExpr(caseexpr->defresult, parent);
2550 state = (ExprState *) cstate;
2555 ArrayExpr *arrayexpr = (ArrayExpr *) node;
2556 ArrayExprState *astate = makeNode(ArrayExprState);
2560 FastListInit(&outlist);
2561 foreach(inlist, arrayexpr->elements)
2563 Expr *e = (Expr *) lfirst(inlist);
2566 estate = ExecInitExpr(e, parent);
2567 FastAppend(&outlist, estate);
2569 astate->elements = FastListValue(&outlist);
2570 /* do one-time catalog lookup for type info */
2571 get_typlenbyvalalign(arrayexpr->element_typeid,
2572 &astate->elemlength,
2574 &astate->elemalign);
2575 state = (ExprState *) astate;
2578 case T_CoalesceExpr:
2580 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
2581 CoalesceExprState *cstate = makeNode(CoalesceExprState);
2585 FastListInit(&outlist);
2586 foreach(inlist, coalesceexpr->args)
2588 Expr *e = (Expr *) lfirst(inlist);
2591 estate = ExecInitExpr(e, parent);
2592 FastAppend(&outlist, estate);
2594 cstate->args = FastListValue(&outlist);
2595 state = (ExprState *) cstate;
2600 NullIfExpr *nullifexpr = (NullIfExpr *) node;
2601 FuncExprState *fstate = makeNode(FuncExprState);
2603 fstate->args = (List *)
2604 ExecInitExpr((Expr *) nullifexpr->args, parent);
2605 fstate->func.fn_oid = InvalidOid; /* not initialized */
2606 state = (ExprState *) fstate;
2611 NullTest *ntest = (NullTest *) node;
2612 GenericExprState *gstate = makeNode(GenericExprState);
2614 gstate->arg = ExecInitExpr(ntest->arg, parent);
2615 state = (ExprState *) gstate;
2620 BooleanTest *btest = (BooleanTest *) node;
2621 GenericExprState *gstate = makeNode(GenericExprState);
2623 gstate->arg = ExecInitExpr(btest->arg, parent);
2624 state = (ExprState *) gstate;
2627 case T_CoerceToDomain:
2629 CoerceToDomain *ctest = (CoerceToDomain *) node;
2630 CoerceToDomainState *cstate = makeNode(CoerceToDomainState);
2632 cstate->arg = ExecInitExpr(ctest->arg, parent);
2633 cstate->constraints = GetDomainConstraints(ctest->resulttype);
2634 state = (ExprState *) cstate;
2639 TargetEntry *tle = (TargetEntry *) node;
2640 GenericExprState *gstate = makeNode(GenericExprState);
2642 gstate->arg = ExecInitExpr(tle->expr, parent);
2643 state = (ExprState *) gstate;
2651 FastListInit(&outlist);
2652 foreach(inlist, (List *) node)
2654 FastAppend(&outlist,
2655 ExecInitExpr((Expr *) lfirst(inlist),
2658 /* Don't fall through to the "common" code below */
2659 return (ExprState *) FastListValue(&outlist);
2662 elog(ERROR, "unrecognized node type: %d",
2663 (int) nodeTag(node));
2664 state = NULL; /* keep compiler quiet */
2668 /* Common code for all state-node types */
2675 * ExecInitExprInitPlan --- initialize a subplan expr that's being handled
2676 * as an InitPlan. This is identical to ExecInitExpr's handling of a regular
2677 * subplan expr, except we do NOT want to add the node to the parent's
2681 ExecInitExprInitPlan(SubPlan *node, PlanState *parent)
2683 SubPlanState *sstate = makeNode(SubPlanState);
2686 elog(ERROR, "SubPlan found with no parent plan");
2688 /* The subplan's state will be initialized later */
2689 sstate->sub_estate = NULL;
2690 sstate->planstate = NULL;
2692 sstate->exprs = (List *) ExecInitExpr((Expr *) node->exprs, parent);
2693 sstate->args = (List *) ExecInitExpr((Expr *) node->args, parent);
2695 sstate->xprstate.expr = (Expr *) node;
2701 * ExecPrepareExpr --- initialize for expression execution outside a normal
2702 * Plan tree context.
2704 * This differs from ExecInitExpr in that we don't assume the caller is
2705 * already running in the EState's per-query context. Also, we apply
2706 * fix_opfuncids() to the passed expression tree to be sure it is ready
2707 * to run. (In ordinary Plan trees the planner will have fixed opfuncids,
2708 * but callers outside the executor will not have done this.)
2711 ExecPrepareExpr(Expr *node, EState *estate)
2714 MemoryContext oldcontext;
2716 fix_opfuncids((Node *) node);
2718 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2720 result = ExecInitExpr(node, NULL);
2722 MemoryContextSwitchTo(oldcontext);
2728 /* ----------------------------------------------------------------
2729 * ExecQual / ExecTargetList / ExecProject
2730 * ----------------------------------------------------------------
2733 /* ----------------------------------------------------------------
2736 * Evaluates a conjunctive boolean expression (qual list) and
2737 * returns true iff none of the subexpressions are false.
2738 * (We also return true if the list is empty.)
2740 * If some of the subexpressions yield NULL but none yield FALSE,
2741 * then the result of the conjunction is NULL (ie, unknown)
2742 * according to three-valued boolean logic. In this case,
2743 * we return the value specified by the "resultForNull" parameter.
2745 * Callers evaluating WHERE clauses should pass resultForNull=FALSE,
2746 * since SQL specifies that tuples with null WHERE results do not
2747 * get selected. On the other hand, callers evaluating constraint
2748 * conditions should pass resultForNull=TRUE, since SQL also specifies
2749 * that NULL constraint conditions are not failures.
2751 * NOTE: it would not be correct to use this routine to evaluate an
2752 * AND subclause of a boolean expression; for that purpose, a NULL
2753 * result must be returned as NULL so that it can be properly treated
2754 * in the next higher operator (cf. ExecEvalAnd and ExecEvalOr).
2755 * This routine is only used in contexts where a complete expression
2756 * is being evaluated and we know that NULL can be treated the same
2757 * as one boolean result or the other.
2759 * ----------------------------------------------------------------
2762 ExecQual(List *qual, ExprContext *econtext, bool resultForNull)
2765 MemoryContext oldContext;
2771 EV_printf("ExecQual: qual is ");
2772 EV_nodeDisplay(qual);
2778 * Run in short-lived per-tuple context while computing expressions.
2780 oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
2783 * Evaluate the qual conditions one at a time. If we find a FALSE
2784 * result, we can stop evaluating and return FALSE --- the AND result
2785 * must be FALSE. Also, if we find a NULL result when resultForNull
2786 * is FALSE, we can stop and return FALSE --- the AND result must be
2787 * FALSE or NULL in that case, and the caller doesn't care which.
2789 * If we get to the end of the list, we can return TRUE. This will
2790 * happen when the AND result is indeed TRUE, or when the AND result
2791 * is NULL (one or more NULL subresult, with all the rest TRUE) and
2792 * the caller has specified resultForNull = TRUE.
2796 foreach(qlist, qual)
2798 ExprState *clause = (ExprState *) lfirst(qlist);
2802 expr_value = ExecEvalExpr(clause, econtext, &isNull, NULL);
2806 if (resultForNull == false)
2808 result = false; /* treat NULL as FALSE */
2814 if (!DatumGetBool(expr_value))
2816 result = false; /* definitely FALSE */
2822 MemoryContextSwitchTo(oldContext);
2828 * Number of items in a tlist (including any resjunk items!)
2831 ExecTargetListLength(List *targetlist)
2833 /* This used to be more complex, but fjoins are dead */
2834 return length(targetlist);
2838 * Number of items in a tlist, not including any resjunk items
2841 ExecCleanTargetListLength(List *targetlist)
2846 foreach(tl, targetlist)
2848 TargetEntry *curTle = (TargetEntry *) lfirst(tl);
2850 Assert(IsA(curTle, TargetEntry));
2851 if (!curTle->resdom->resjunk)
2857 /* ----------------------------------------------------------------
2860 * Evaluates a targetlist with respect to the given
2861 * expression context and returns a tuple.
2863 * The caller must pass workspace for the values and nulls arrays
2864 * as well as the itemIsDone array. This convention saves palloc'ing
2865 * workspace on each call, and some callers may find it useful to examine
2866 * the values array directly.
2868 * As with ExecEvalExpr, the caller should pass isDone = NULL if not
2869 * prepared to deal with sets of result tuples. Otherwise, a return
2870 * of *isDone = ExprMultipleResult signifies a set element, and a return
2871 * of *isDone = ExprEndResult signifies end of the set of tuple.
2872 * ----------------------------------------------------------------
2875 ExecTargetList(List *targetlist,
2876 TupleDesc targettype,
2877 ExprContext *econtext,
2880 ExprDoneCond *itemIsDone,
2881 ExprDoneCond *isDone)
2883 MemoryContext oldContext;
2887 static struct tupleDesc NullTupleDesc; /* we assume this inits to
2893 EV_printf("ExecTargetList: tl is ");
2894 EV_nodeDisplay(targetlist);
2898 * Run in short-lived per-tuple context while computing expressions.
2900 oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
2903 * There used to be some klugy and demonstrably broken code here that
2904 * special-cased the situation where targetlist == NIL. Now we just
2905 * fall through and return an empty-but-valid tuple. We do, however,
2906 * have to cope with the possibility that targettype is NULL ---
2907 * heap_formtuple won't like that, so pass a dummy descriptor with
2908 * natts = 0 to deal with it.
2910 if (targettype == NULL)
2911 targettype = &NullTupleDesc;
2914 * evaluate all the expressions in the target list
2917 *isDone = ExprSingleResult; /* until proven otherwise */
2919 haveDoneSets = false; /* any exhausted set exprs in tlist? */
2921 foreach(tl, targetlist)
2923 GenericExprState *gstate = (GenericExprState *) lfirst(tl);
2924 TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr;
2925 AttrNumber resind = tle->resdom->resno - 1;
2927 values[resind] = ExecEvalExpr(gstate->arg,
2930 &itemIsDone[resind]);
2931 nulls[resind] = isNull ? 'n' : ' ';
2933 if (itemIsDone[resind] != ExprSingleResult)
2935 /* We have a set-valued expression in the tlist */
2938 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2939 errmsg("set-valued function called in context that cannot accept a set")));
2940 if (itemIsDone[resind] == ExprMultipleResult)
2942 /* we have undone sets in the tlist, set flag */
2943 *isDone = ExprMultipleResult;
2947 /* we have done sets in the tlist, set flag for that */
2948 haveDoneSets = true;
2956 * note: can't get here unless we verified isDone != NULL
2958 if (*isDone == ExprSingleResult)
2961 * all sets are done, so report that tlist expansion is
2964 *isDone = ExprEndResult;
2965 MemoryContextSwitchTo(oldContext);
2971 * We have some done and some undone sets. Restart the done
2972 * ones so that we can deliver a tuple (if possible).
2974 foreach(tl, targetlist)
2976 GenericExprState *gstate = (GenericExprState *) lfirst(tl);
2977 TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr;
2978 AttrNumber resind = tle->resdom->resno - 1;
2980 if (itemIsDone[resind] == ExprEndResult)
2982 values[resind] = ExecEvalExpr(gstate->arg,
2985 &itemIsDone[resind]);
2986 nulls[resind] = isNull ? 'n' : ' ';
2988 if (itemIsDone[resind] == ExprEndResult)
2991 * Oh dear, this item is returning an empty
2992 * set. Guess we can't make a tuple after all.
2994 *isDone = ExprEndResult;
3001 * If we cannot make a tuple because some sets are empty, we
3002 * still have to cycle the nonempty sets to completion, else
3003 * resources will not be released from subplans etc.
3005 * XXX is that still necessary?
3007 if (*isDone == ExprEndResult)
3009 foreach(tl, targetlist)
3011 GenericExprState *gstate = (GenericExprState *) lfirst(tl);
3012 TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr;
3013 AttrNumber resind = tle->resdom->resno - 1;
3015 while (itemIsDone[resind] == ExprMultipleResult)
3017 (void) ExecEvalExpr(gstate->arg,
3020 &itemIsDone[resind]);
3024 MemoryContextSwitchTo(oldContext);
3031 * form the new result tuple (in the caller's memory context!)
3033 MemoryContextSwitchTo(oldContext);
3035 return heap_formtuple(targettype, values, nulls);
3038 /* ----------------------------------------------------------------
3041 * projects a tuple based on projection info and stores
3042 * it in the specified tuple table slot.
3044 * Note: someday soon the executor can be extended to eliminate
3045 * redundant projections by storing pointers to datums
3046 * in the tuple table and then passing these around when
3047 * possible. this should make things much quicker.
3049 * ----------------------------------------------------------------
3052 ExecProject(ProjectionInfo *projInfo, ExprDoneCond *isDone)
3054 TupleTableSlot *slot;
3061 if (projInfo == NULL)
3062 return (TupleTableSlot *) NULL;
3065 * get the projection info we want
3067 slot = projInfo->pi_slot;
3068 tupType = slot->ttc_tupleDescriptor;
3071 * form a new result tuple (if possible --- result can be NULL)
3073 newTuple = ExecTargetList(projInfo->pi_targetlist,
3075 projInfo->pi_exprContext,
3076 projInfo->pi_tupValues,
3077 projInfo->pi_tupNulls,
3078 projInfo->pi_itemIsDone,
3082 * store the tuple in the projection slot and return the slot.
3084 return ExecStoreTuple(newTuple, /* tuple to store */
3085 slot, /* slot to store in */
3086 InvalidBuffer, /* tuple has no buffer */