1 /*-------------------------------------------------------------------------
4 * Routines to evaluate qualification and targetlist expressions
6 * Portions Copyright (c) 1996-2003, 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.150 2003/10/13 22:47:15 momjian 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 (%d) 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 (%d) 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.
318 * ---------------------------------------------------------------- */
320 ExecEvalVar(Var *variable, ExprContext *econtext, bool *isNull)
323 TupleTableSlot *slot;
326 TupleDesc tuple_type;
329 * get the slot we want
331 switch (variable->varno)
333 case INNER: /* get the tuple from the inner node */
334 slot = econtext->ecxt_innertuple;
337 case OUTER: /* get the tuple from the outer node */
338 slot = econtext->ecxt_outertuple;
341 default: /* get the tuple from the relation being
343 slot = econtext->ecxt_scantuple;
348 * extract tuple information from the slot
350 heapTuple = slot->val;
351 tuple_type = slot->ttc_tupleDescriptor;
353 attnum = variable->varattno;
356 * Some checks that are only applied for user attribute numbers
357 * (bogus system attnums will be caught inside heap_getattr).
362 * This assert checks that the attnum is valid.
364 Assert(attnum <= tuple_type->natts &&
365 tuple_type->attrs[attnum - 1] != NULL);
368 * If the attribute's column has been dropped, we force a NULL result.
369 * This case should not happen in normal use, but it could happen if
370 * we are executing a plan cached before the column was dropped.
372 if (tuple_type->attrs[attnum - 1]->attisdropped)
379 * This assert checks that the datatype the plan expects to get (as
380 * told by our "variable" argument) is in fact the datatype of the
381 * attribute being fetched (as seen in the current context, identified
382 * by our "econtext" argument). Otherwise crashes are likely.
384 * Note that we can't check dropped columns, since their atttypid
387 Assert(variable->vartype == tuple_type->attrs[attnum - 1]->atttypid);
391 * If the attribute number is invalid, then we are supposed to return
392 * the entire tuple; we give back a whole slot so that callers know
393 * what the tuple looks like.
395 * XXX this is a horrid crock: since the pointer to the slot might live
396 * longer than the current evaluation context, we are forced to copy
397 * the tuple and slot into a long-lived context --- we use the
398 * econtext's per-query memory which should be safe enough. This
399 * represents a serious memory leak if many such tuples are processed
400 * in one command, however. We ought to redesign the representation
401 * of whole-tuple datums so that this is not necessary.
403 * We assume it's OK to point to the existing tupleDescriptor, rather
404 * than copy that too.
406 if (attnum == InvalidAttrNumber)
408 MemoryContext oldContext;
409 TupleTableSlot *tempSlot;
412 oldContext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
413 tempSlot = MakeTupleTableSlot();
414 tup = heap_copytuple(heapTuple);
415 ExecStoreTuple(tup, tempSlot, InvalidBuffer, true);
416 ExecSetSlotDescriptor(tempSlot, tuple_type, false);
417 MemoryContextSwitchTo(oldContext);
418 return PointerGetDatum(tempSlot);
421 result = heap_getattr(heapTuple, /* tuple containing attribute */
422 attnum, /* attribute number of desired
424 tuple_type, /* tuple descriptor of tuple */
425 isNull); /* return: is attribute null? */
430 /* ----------------------------------------------------------------
433 * Returns the value of a parameter. A param node contains
434 * something like ($.name) and the expression context contains
435 * the current parameter bindings (name = "sam") (age = 34)...
436 * so our job is to find and return the appropriate datum ("sam").
438 * Q: if we have a parameter ($.foo) without a binding, i.e.
439 * there is no (foo = xxx) in the parameter list info,
440 * is this a fatal error or should this be a "not available"
441 * (in which case we could return NULL)? -cim 10/13/89
442 * ----------------------------------------------------------------
445 ExecEvalParam(Param *expression, ExprContext *econtext, bool *isNull)
447 int thisParamKind = expression->paramkind;
448 AttrNumber thisParamId = expression->paramid;
450 if (thisParamKind == PARAM_EXEC)
453 * PARAM_EXEC params (internal executor parameters) are stored in
454 * the ecxt_param_exec_vals array, and can be accessed by array
459 prm = &(econtext->ecxt_param_exec_vals[thisParamId]);
460 if (prm->execPlan != NULL)
462 /* Parameter not evaluated yet, so go do it */
463 ExecSetParamPlan(prm->execPlan, econtext);
464 /* ExecSetParamPlan should have processed this param... */
465 Assert(prm->execPlan == NULL);
467 *isNull = prm->isnull;
473 * All other parameter types must be sought in
474 * ecxt_param_list_info. NOTE: The last entry in the param array
475 * is always an entry with kind == PARAM_INVALID.
477 ParamListInfo paramList = econtext->ecxt_param_list_info;
478 char *thisParamName = expression->paramname;
479 bool matchFound = false;
481 if (paramList != NULL)
483 while (paramList->kind != PARAM_INVALID && !matchFound)
485 if (thisParamKind == paramList->kind)
487 switch (thisParamKind)
490 if (strcmp(paramList->name, thisParamName) == 0)
494 if (paramList->id == thisParamId)
498 elog(ERROR, "unrecognized paramkind: %d",
509 if (thisParamKind == PARAM_NAMED)
511 (errcode(ERRCODE_UNDEFINED_OBJECT),
512 errmsg("no value found for parameter \"%s\"",
516 (errcode(ERRCODE_UNDEFINED_OBJECT),
517 errmsg("no value found for parameter %d",
521 *isNull = paramList->isnull;
522 return paramList->value;
527 /* ----------------------------------------------------------------
528 * ExecEvalOper / ExecEvalFunc support routines
529 * ----------------------------------------------------------------
536 * These are functions which return the value of the
537 * named attribute out of the tuple from the arg slot. User defined
538 * C functions which take a tuple as an argument are expected
539 * to use this. Ex: overpaid(EMP) might call GetAttributeByNum().
542 GetAttributeByNum(TupleTableSlot *slot,
548 if (!AttributeNumberIsValid(attrno))
549 elog(ERROR, "invalid attribute number %d", attrno);
551 if (isNull == (bool *) NULL)
552 elog(ERROR, "a NULL isNull pointer was passed");
560 retval = heap_getattr(slot->val,
562 slot->ttc_tupleDescriptor,
571 GetAttributeByName(TupleTableSlot *slot, char *attname, bool *isNull)
580 elog(ERROR, "invalid attribute name");
582 if (isNull == (bool *) NULL)
583 elog(ERROR, "a NULL isNull pointer was passed");
591 tupdesc = slot->ttc_tupleDescriptor;
592 natts = slot->val->t_data->t_natts;
594 attrno = InvalidAttrNumber;
595 for (i = 0; i < tupdesc->natts; i++)
597 if (namestrcmp(&(tupdesc->attrs[i]->attname), attname) == 0)
599 attrno = tupdesc->attrs[i]->attnum;
604 if (attrno == InvalidAttrNumber)
605 elog(ERROR, "attribute \"%s\" does not exist", attname);
607 retval = heap_getattr(slot->val,
618 * init_fcache - initialize a FuncExprState node during first use
621 init_fcache(Oid foid, FuncExprState *fcache, MemoryContext fcacheCxt)
625 /* Check permission to call function */
626 aclresult = pg_proc_aclcheck(foid, GetUserId(), ACL_EXECUTE);
627 if (aclresult != ACLCHECK_OK)
628 aclcheck_error(aclresult, ACL_KIND_PROC, get_func_name(foid));
630 /* Safety check (should never fail, as parser should check sooner) */
631 if (length(fcache->args) > FUNC_MAX_ARGS)
632 elog(ERROR, "too many arguments");
634 /* Set up the primary fmgr lookup information */
635 fmgr_info_cxt(foid, &(fcache->func), fcacheCxt);
637 /* Initialize additional info */
638 fcache->setArgsValid = false;
639 fcache->func.fn_expr = (Node *) fcache->xprstate.expr;
643 * Evaluate arguments for a function.
646 ExecEvalFuncArgs(FunctionCallInfo fcinfo,
648 ExprContext *econtext)
650 ExprDoneCond argIsDone;
654 argIsDone = ExprSingleResult; /* default assumption */
657 foreach(arg, argList)
659 ExprDoneCond thisArgIsDone;
661 fcinfo->arg[i] = ExecEvalExpr((ExprState *) lfirst(arg),
666 if (thisArgIsDone != ExprSingleResult)
669 * We allow only one argument to have a set value; we'd need
670 * much more complexity to keep track of multiple set
671 * arguments (cf. ExecTargetList) and it doesn't seem worth
674 if (argIsDone != ExprSingleResult)
676 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
677 errmsg("functions and operators can take at most one set argument")));
678 argIsDone = thisArgIsDone;
689 * ExecMakeFunctionResult
691 * Evaluate the arguments to a function and then the function itself.
694 ExecMakeFunctionResult(FuncExprState *fcache,
695 ExprContext *econtext,
697 ExprDoneCond *isDone)
699 List *arguments = fcache->args;
701 FunctionCallInfoData fcinfo;
702 ReturnSetInfo rsinfo; /* for functions returning sets */
703 ExprDoneCond argDone;
708 * arguments is a list of expressions to evaluate before passing to
709 * the function manager. We skip the evaluation if it was already
710 * done in the previous call (ie, we are continuing the evaluation of
711 * a set-valued function). Otherwise, collect the current argument
712 * values into fcinfo.
714 if (!fcache->setArgsValid)
716 /* Need to prep callinfo structure */
717 MemSet(&fcinfo, 0, sizeof(fcinfo));
718 fcinfo.flinfo = &(fcache->func);
719 argDone = ExecEvalFuncArgs(&fcinfo, arguments, econtext);
720 if (argDone == ExprEndResult)
722 /* input is an empty set, so return an empty set. */
725 *isDone = ExprEndResult;
728 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
729 errmsg("set-valued function called in context that cannot accept a set")));
732 hasSetArg = (argDone != ExprSingleResult);
736 /* Copy callinfo from previous evaluation */
737 memcpy(&fcinfo, &fcache->setArgs, sizeof(fcinfo));
738 hasSetArg = fcache->setHasSetArg;
739 /* Reset flag (we may set it again below) */
740 fcache->setArgsValid = false;
744 * If function returns set, prepare a resultinfo node for
747 if (fcache->func.fn_retset)
749 fcinfo.resultinfo = (Node *) &rsinfo;
750 rsinfo.type = T_ReturnSetInfo;
751 rsinfo.econtext = econtext;
752 rsinfo.expectedDesc = NULL;
753 rsinfo.allowedModes = (int) SFRM_ValuePerCall;
754 rsinfo.returnMode = SFRM_ValuePerCall;
755 /* isDone is filled below */
756 rsinfo.setResult = NULL;
757 rsinfo.setDesc = NULL;
761 * now return the value gotten by calling the function manager,
762 * passing the function the evaluated parameter values.
764 if (fcache->func.fn_retset || hasSetArg)
767 * We need to return a set result. Complain if caller not ready
772 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
773 errmsg("set-valued function called in context that cannot accept a set")));
776 * This loop handles the situation where we have both a set
777 * argument and a set-valued function. Once we have exhausted the
778 * function's value(s) for a particular argument value, we have to
779 * get the next argument value and start the function over again.
780 * We might have to do it more than once, if the function produces
781 * an empty result set for a particular input value.
786 * If function is strict, and there are any NULL arguments,
787 * skip calling the function (at least for this set of args).
791 if (fcache->func.fn_strict)
793 for (i = 0; i < fcinfo.nargs; i++)
795 if (fcinfo.argnull[i])
805 fcinfo.isnull = false;
806 rsinfo.isDone = ExprSingleResult;
807 result = FunctionCallInvoke(&fcinfo);
808 *isNull = fcinfo.isnull;
809 *isDone = rsinfo.isDone;
815 *isDone = ExprEndResult;
818 if (*isDone != ExprEndResult)
821 * Got a result from current argument. If function itself
822 * returns set, save the current argument values to re-use
825 if (fcache->func.fn_retset)
827 memcpy(&fcache->setArgs, &fcinfo, sizeof(fcinfo));
828 fcache->setHasSetArg = hasSetArg;
829 fcache->setArgsValid = true;
833 * Make sure we say we are returning a set, even if the
834 * function itself doesn't return sets.
836 *isDone = ExprMultipleResult;
840 /* Else, done with this argument */
842 break; /* input not a set, so done */
844 /* Re-eval args to get the next element of the input set */
845 argDone = ExecEvalFuncArgs(&fcinfo, arguments, econtext);
847 if (argDone != ExprMultipleResult)
849 /* End of argument set, so we're done. */
851 *isDone = ExprEndResult;
857 * If we reach here, loop around to run the function on the
865 * Non-set case: much easier.
867 * If function is strict, and there are any NULL arguments, skip
868 * calling the function and return NULL.
870 if (fcache->func.fn_strict)
872 for (i = 0; i < fcinfo.nargs; i++)
874 if (fcinfo.argnull[i])
881 fcinfo.isnull = false;
882 result = FunctionCallInvoke(&fcinfo);
883 *isNull = fcinfo.isnull;
891 * ExecMakeTableFunctionResult
893 * Evaluate a table function, producing a materialized result in a Tuplestore
894 * object. (If function returns an empty set, we just return NULL instead.)
897 ExecMakeTableFunctionResult(ExprState *funcexpr,
898 ExprContext *econtext,
899 TupleDesc expectedDesc,
900 TupleDesc *returnDesc)
902 Tuplestorestate *tupstore = NULL;
903 TupleDesc tupdesc = NULL;
905 FunctionCallInfoData fcinfo;
906 ReturnSetInfo rsinfo;
907 MemoryContext callerContext;
908 MemoryContext oldcontext;
909 TupleTableSlot *slot;
910 bool direct_function_call;
911 bool first_time = true;
912 bool returnsTuple = false;
915 * Normally the passed expression tree will be a FuncExprState, since
916 * the grammar only allows a function call at the top level of a table
917 * function reference. However, if the function doesn't return set
918 * then the planner might have replaced the function call via
919 * constant-folding or inlining. So if we see any other kind of
920 * expression node, execute it via the general ExecEvalExpr() code;
921 * the only difference is that we don't get a chance to pass a special
922 * ReturnSetInfo to any functions buried in the expression.
924 if (funcexpr && IsA(funcexpr, FuncExprState) &&
925 IsA(funcexpr->expr, FuncExpr))
927 FuncExprState *fcache = (FuncExprState *) funcexpr;
928 ExprDoneCond argDone;
931 * This path is similar to ExecMakeFunctionResult.
933 direct_function_call = true;
936 * Initialize function cache if first time through
938 if (fcache->func.fn_oid == InvalidOid)
940 FuncExpr *func = (FuncExpr *) fcache->xprstate.expr;
942 init_fcache(func->funcid, fcache, econtext->ecxt_per_query_memory);
946 * Evaluate the function's argument list.
948 * Note: ideally, we'd do this in the per-tuple context, but then the
949 * argument values would disappear when we reset the context in
950 * the inner loop. So do it in caller context. Perhaps we should
951 * make a separate context just to hold the evaluated arguments?
953 MemSet(&fcinfo, 0, sizeof(fcinfo));
954 fcinfo.flinfo = &(fcache->func);
955 argDone = ExecEvalFuncArgs(&fcinfo, fcache->args, econtext);
956 /* We don't allow sets in the arguments of the table function */
957 if (argDone != ExprSingleResult)
959 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
960 errmsg("set-valued function called in context that cannot accept a set")));
963 * If function is strict, and there are any NULL arguments, skip
964 * calling the function and return NULL (actually an empty set).
966 if (fcache->func.fn_strict)
970 for (i = 0; i < fcinfo.nargs; i++)
972 if (fcinfo.argnull[i])
982 /* Treat funcexpr as a generic expression */
983 direct_function_call = false;
986 funcrettype = exprType((Node *) funcexpr->expr);
989 * Prepare a resultinfo node for communication. We always do this
990 * even if not expecting a set result, so that we can pass
991 * expectedDesc. In the generic-expression case, the expression
992 * doesn't actually get to see the resultinfo, but set it up anyway
993 * because we use some of the fields as our own state variables.
995 fcinfo.resultinfo = (Node *) &rsinfo;
996 rsinfo.type = T_ReturnSetInfo;
997 rsinfo.econtext = econtext;
998 rsinfo.expectedDesc = expectedDesc;
999 rsinfo.allowedModes = (int) (SFRM_ValuePerCall | SFRM_Materialize);
1000 rsinfo.returnMode = SFRM_ValuePerCall;
1001 /* isDone is filled below */
1002 rsinfo.setResult = NULL;
1003 rsinfo.setDesc = NULL;
1006 * Switch to short-lived context for calling the function or
1009 callerContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
1012 * Loop to handle the ValuePerCall protocol (which is also the same
1013 * behavior needed in the generic ExecEvalExpr path).
1021 * reset per-tuple memory context before each call of the function
1022 * or expression. This cleans up any local memory the function may
1025 ResetExprContext(econtext);
1027 /* Call the function or expression one time */
1028 if (direct_function_call)
1030 fcinfo.isnull = false;
1031 rsinfo.isDone = ExprSingleResult;
1032 result = FunctionCallInvoke(&fcinfo);
1036 result = ExecEvalExpr(funcexpr, econtext,
1037 &fcinfo.isnull, &rsinfo.isDone);
1040 /* Which protocol does function want to use? */
1041 if (rsinfo.returnMode == SFRM_ValuePerCall)
1044 * Check for end of result set.
1046 * Note: if function returns an empty set, we don't build a
1047 * tupdesc or tuplestore (since we can't get a tupdesc in the
1048 * function-returning-tuple case)
1050 if (rsinfo.isDone == ExprEndResult)
1054 * If first time through, build tupdesc and tuplestore for
1059 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1060 if (funcrettype == RECORDOID ||
1061 get_typtype(funcrettype) == 'c')
1064 * Composite type, so function should have returned a
1065 * TupleTableSlot; use its descriptor
1067 slot = (TupleTableSlot *) DatumGetPointer(result);
1068 if (fcinfo.isnull || !slot)
1070 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1071 errmsg("function returning row cannot return null value")));
1072 if (!IsA(slot, TupleTableSlot) ||
1073 !slot->ttc_tupleDescriptor)
1075 (errcode(ERRCODE_DATATYPE_MISMATCH),
1076 errmsg("function returning row did not return a valid tuple slot")));
1077 tupdesc = CreateTupleDescCopy(slot->ttc_tupleDescriptor);
1078 returnsTuple = true;
1083 * Scalar type, so make a single-column descriptor
1085 tupdesc = CreateTemplateTupleDesc(1, false);
1086 TupleDescInitEntry(tupdesc,
1094 tupstore = tuplestore_begin_heap(true, false, SortMem);
1095 MemoryContextSwitchTo(oldcontext);
1096 rsinfo.setResult = tupstore;
1097 rsinfo.setDesc = tupdesc;
1101 * Store current resultset item.
1105 slot = (TupleTableSlot *) DatumGetPointer(result);
1106 if (fcinfo.isnull ||
1108 !IsA(slot, TupleTableSlot) ||
1111 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1112 errmsg("function returning row cannot return null value")));
1119 nullflag = fcinfo.isnull ? 'n' : ' ';
1120 tuple = heap_formtuple(tupdesc, &result, &nullflag);
1123 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1124 tuplestore_puttuple(tupstore, tuple);
1125 MemoryContextSwitchTo(oldcontext);
1130 if (rsinfo.isDone != ExprMultipleResult)
1133 else if (rsinfo.returnMode == SFRM_Materialize)
1135 /* check we're on the same page as the function author */
1136 if (!first_time || rsinfo.isDone != ExprSingleResult)
1138 (errcode(ERRCODE_E_R_I_E_SRF_PROTOCOL_VIOLATED),
1139 errmsg("table-function protocol for materialize mode was not followed")));
1140 /* Done evaluating the set result */
1145 (errcode(ERRCODE_E_R_I_E_SRF_PROTOCOL_VIOLATED),
1146 errmsg("unrecognized table-function returnMode: %d",
1147 (int) rsinfo.returnMode)));
1152 MemoryContextSwitchTo(callerContext);
1154 /* The returned pointers are those in rsinfo */
1155 *returnDesc = rsinfo.setDesc;
1156 return rsinfo.setResult;
1160 /* ----------------------------------------------------------------
1164 * Evaluate the functional result of a list of arguments by calling the
1166 * ----------------------------------------------------------------
1169 /* ----------------------------------------------------------------
1171 * ----------------------------------------------------------------
1174 ExecEvalFunc(FuncExprState *fcache,
1175 ExprContext *econtext,
1177 ExprDoneCond *isDone)
1180 * Initialize function cache if first time through
1182 if (fcache->func.fn_oid == InvalidOid)
1184 FuncExpr *func = (FuncExpr *) fcache->xprstate.expr;
1186 init_fcache(func->funcid, fcache, econtext->ecxt_per_query_memory);
1189 return ExecMakeFunctionResult(fcache, econtext, isNull, isDone);
1192 /* ----------------------------------------------------------------
1194 * ----------------------------------------------------------------
1197 ExecEvalOper(FuncExprState *fcache,
1198 ExprContext *econtext,
1200 ExprDoneCond *isDone)
1203 * Initialize function cache if first time through
1205 if (fcache->func.fn_oid == InvalidOid)
1207 OpExpr *op = (OpExpr *) fcache->xprstate.expr;
1209 init_fcache(op->opfuncid, fcache, econtext->ecxt_per_query_memory);
1212 return ExecMakeFunctionResult(fcache, econtext, isNull, isDone);
1215 /* ----------------------------------------------------------------
1218 * IS DISTINCT FROM must evaluate arguments to determine whether
1219 * they are NULL; if either is NULL then the result is already
1220 * known. If neither is NULL, then proceed to evaluate the
1221 * function. Note that this is *always* derived from the equals
1222 * operator, but since we need special processing of the arguments
1223 * we can not simply reuse ExecEvalOper() or ExecEvalFunc().
1224 * ----------------------------------------------------------------
1227 ExecEvalDistinct(FuncExprState *fcache,
1228 ExprContext *econtext,
1232 FunctionCallInfoData fcinfo;
1233 ExprDoneCond argDone;
1237 * Initialize function cache if first time through
1239 if (fcache->func.fn_oid == InvalidOid)
1241 DistinctExpr *op = (DistinctExpr *) fcache->xprstate.expr;
1243 init_fcache(op->opfuncid, fcache, econtext->ecxt_per_query_memory);
1244 Assert(!fcache->func.fn_retset);
1248 * extract info from fcache
1250 argList = fcache->args;
1252 /* Need to prep callinfo structure */
1253 MemSet(&fcinfo, 0, sizeof(fcinfo));
1254 fcinfo.flinfo = &(fcache->func);
1255 argDone = ExecEvalFuncArgs(&fcinfo, argList, econtext);
1256 if (argDone != ExprSingleResult)
1258 (errcode(ERRCODE_DATATYPE_MISMATCH),
1259 errmsg("IS DISTINCT FROM does not support set arguments")));
1260 Assert(fcinfo.nargs == 2);
1262 if (fcinfo.argnull[0] && fcinfo.argnull[1])
1264 /* Both NULL? Then is not distinct... */
1265 result = BoolGetDatum(FALSE);
1267 else if (fcinfo.argnull[0] || fcinfo.argnull[1])
1269 /* Only one is NULL? Then is distinct... */
1270 result = BoolGetDatum(TRUE);
1274 fcinfo.isnull = false;
1275 result = FunctionCallInvoke(&fcinfo);
1276 *isNull = fcinfo.isnull;
1277 /* Must invert result of "=" */
1278 result = BoolGetDatum(!DatumGetBool(result));
1285 * ExecEvalScalarArrayOp
1287 * Evaluate "scalar op ANY/ALL (array)". The operator always yields boolean,
1288 * and we combine the results across all array elements using OR and AND
1289 * (for ANY and ALL respectively). Of course we short-circuit as soon as
1290 * the result is known.
1293 ExecEvalScalarArrayOp(ScalarArrayOpExprState *sstate,
1294 ExprContext *econtext, bool *isNull)
1296 ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) sstate->fxprstate.xprstate.expr;
1297 bool useOr = opexpr->useOr;
1302 FunctionCallInfoData fcinfo;
1303 ExprDoneCond argDone;
1311 * Initialize function cache if first time through
1313 if (sstate->fxprstate.func.fn_oid == InvalidOid)
1315 init_fcache(opexpr->opfuncid, &sstate->fxprstate,
1316 econtext->ecxt_per_query_memory);
1317 Assert(!sstate->fxprstate.func.fn_retset);
1320 /* Need to prep callinfo structure */
1321 MemSet(&fcinfo, 0, sizeof(fcinfo));
1322 fcinfo.flinfo = &(sstate->fxprstate.func);
1323 argDone = ExecEvalFuncArgs(&fcinfo, sstate->fxprstate.args, econtext);
1324 if (argDone != ExprSingleResult)
1326 (errcode(ERRCODE_DATATYPE_MISMATCH),
1327 errmsg("op ANY/ALL (array) does not support set arguments")));
1328 Assert(fcinfo.nargs == 2);
1331 * If the array is NULL then we return NULL --- it's not very
1332 * meaningful to do anything else, even if the operator isn't strict.
1334 if (fcinfo.argnull[1])
1339 /* Else okay to fetch and detoast the array */
1340 arr = DatumGetArrayTypeP(fcinfo.arg[1]);
1343 * If the array is empty, we return either FALSE or TRUE per the useOr
1344 * flag. This is correct even if the scalar is NULL; since we would
1345 * evaluate the operator zero times, it matters not whether it would
1346 * want to return NULL.
1348 nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr));
1350 return BoolGetDatum(!useOr);
1353 * If the scalar is NULL, and the function is strict, return NULL.
1354 * This is just to avoid having to test for strictness inside the
1355 * loop. (XXX but if arrays could have null elements, we'd need a
1358 if (fcinfo.argnull[0] && sstate->fxprstate.func.fn_strict)
1365 * We arrange to look up info about the element type only once per
1366 * series of calls, assuming the element type doesn't change
1369 if (sstate->element_type != ARR_ELEMTYPE(arr))
1371 get_typlenbyvalalign(ARR_ELEMTYPE(arr),
1375 sstate->element_type = ARR_ELEMTYPE(arr);
1377 typlen = sstate->typlen;
1378 typbyval = sstate->typbyval;
1379 typalign = sstate->typalign;
1381 result = BoolGetDatum(!useOr);
1384 /* Loop over the array elements */
1385 s = (char *) ARR_DATA_PTR(arr);
1386 for (i = 0; i < nitems; i++)
1391 /* Get array element */
1392 elt = fetch_att(s, typbyval, typlen);
1394 s = att_addlength(s, typlen, PointerGetDatum(s));
1395 s = (char *) att_align(s, typalign);
1397 /* Call comparison function */
1398 fcinfo.arg[1] = elt;
1399 fcinfo.argnull[1] = false;
1400 fcinfo.isnull = false;
1401 thisresult = FunctionCallInvoke(&fcinfo);
1403 /* Combine results per OR or AND semantics */
1408 if (DatumGetBool(thisresult))
1410 result = BoolGetDatum(true);
1412 break; /* needn't look at any more elements */
1417 if (!DatumGetBool(thisresult))
1419 result = BoolGetDatum(false);
1421 break; /* needn't look at any more elements */
1426 *isNull = resultnull;
1430 /* ----------------------------------------------------------------
1435 * Evaluate boolean expressions, with appropriate short-circuiting.
1437 * The query planner reformulates clause expressions in the
1438 * qualification to conjunctive normal form. If we ever get
1439 * an AND to evaluate, we can be sure that it's not a top-level
1440 * clause in the qualification, but appears lower (as a function
1441 * argument, for example), or in the target list. Not that you
1442 * need to know this, mind you...
1443 * ----------------------------------------------------------------
1446 ExecEvalNot(BoolExprState *notclause, ExprContext *econtext, bool *isNull)
1451 clause = lfirst(notclause->args);
1453 expr_value = ExecEvalExpr(clause, econtext, isNull, NULL);
1456 * if the expression evaluates to null, then we just cascade the null
1457 * back to whoever called us.
1463 * evaluation of 'not' is simple.. expr is false, then return 'true'
1466 return BoolGetDatum(!DatumGetBool(expr_value));
1469 /* ----------------------------------------------------------------
1471 * ----------------------------------------------------------------
1474 ExecEvalOr(BoolExprState *orExpr, ExprContext *econtext, bool *isNull)
1481 clauses = orExpr->args;
1485 * If any of the clauses is TRUE, the OR result is TRUE regardless of
1486 * the states of the rest of the clauses, so we can stop evaluating
1487 * and return TRUE immediately. If none are TRUE and one or more is
1488 * NULL, we return NULL; otherwise we return FALSE. This makes sense
1489 * when you interpret NULL as "don't know": if we have a TRUE then the
1490 * OR is TRUE even if we aren't sure about some of the other inputs.
1491 * If all the known inputs are FALSE, but we have one or more "don't
1492 * knows", then we have to report that we "don't know" what the OR's
1493 * result should be --- perhaps one of the "don't knows" would have
1494 * been TRUE if we'd known its value. Only when all the inputs are
1495 * known to be FALSE can we state confidently that the OR's result is
1498 foreach(clause, clauses)
1500 clause_value = ExecEvalExpr((ExprState *) lfirst(clause),
1501 econtext, isNull, NULL);
1504 * if we have a non-null true result, then return it.
1507 AnyNull = true; /* remember we got a null */
1508 else if (DatumGetBool(clause_value))
1509 return clause_value;
1512 /* AnyNull is true if at least one clause evaluated to NULL */
1514 return BoolGetDatum(false);
1517 /* ----------------------------------------------------------------
1519 * ----------------------------------------------------------------
1522 ExecEvalAnd(BoolExprState *andExpr, ExprContext *econtext, bool *isNull)
1529 clauses = andExpr->args;
1533 * If any of the clauses is FALSE, the AND result is FALSE regardless
1534 * of the states of the rest of the clauses, so we can stop evaluating
1535 * and return FALSE immediately. If none are FALSE and one or more is
1536 * NULL, we return NULL; otherwise we return TRUE. This makes sense
1537 * when you interpret NULL as "don't know", using the same sort of
1538 * reasoning as for OR, above.
1540 foreach(clause, clauses)
1542 clause_value = ExecEvalExpr((ExprState *) lfirst(clause),
1543 econtext, isNull, NULL);
1546 * if we have a non-null false result, then return it.
1549 AnyNull = true; /* remember we got a null */
1550 else if (!DatumGetBool(clause_value))
1551 return clause_value;
1554 /* AnyNull is true if at least one clause evaluated to NULL */
1556 return BoolGetDatum(!AnyNull);
1560 /* ----------------------------------------------------------------
1563 * Evaluate a CASE clause. Will have boolean expressions
1564 * inside the WHEN clauses, and will have expressions
1566 * - thomas 1998-11-09
1567 * ----------------------------------------------------------------
1570 ExecEvalCase(CaseExprState *caseExpr, ExprContext *econtext,
1571 bool *isNull, ExprDoneCond *isDone)
1577 clauses = caseExpr->args;
1580 * we evaluate each of the WHEN clauses in turn, as soon as one is
1581 * true we return the corresponding result. If none are true then we
1582 * return the value of the default clause, or NULL if there is none.
1584 foreach(clause, clauses)
1586 CaseWhenState *wclause = lfirst(clause);
1588 clause_value = ExecEvalExpr(wclause->expr,
1594 * if we have a true test, then we return the result, since the
1595 * case statement is satisfied. A NULL result from the test is
1596 * not considered true.
1598 if (DatumGetBool(clause_value) && !*isNull)
1600 return ExecEvalExpr(wclause->result,
1607 if (caseExpr->defresult)
1609 return ExecEvalExpr(caseExpr->defresult,
1619 /* ----------------------------------------------------------------
1620 * ExecEvalArray - ARRAY[] expressions
1622 * NOTE: currently, if any input value is NULL then we return a NULL array,
1623 * so the ARRAY[] construct can be considered strict. Eventually this will
1624 * change; when it does, be sure to fix contain_nonstrict_functions().
1625 * ----------------------------------------------------------------
1628 ExecEvalArray(ArrayExprState *astate, ExprContext *econtext,
1631 ArrayExpr *arrayExpr = (ArrayExpr *) astate->xprstate.expr;
1634 Oid element_type = arrayExpr->element_typeid;
1639 if (!arrayExpr->multidims)
1641 /* Elements are presumably of scalar type */
1647 nelems = length(astate->elements);
1649 /* Shouldn't happen here, but if length is 0, return NULL */
1656 dvalues = (Datum *) palloc(nelems * sizeof(Datum));
1658 /* loop through and build array of datums */
1659 foreach(element, astate->elements)
1661 ExprState *e = (ExprState *) lfirst(element);
1664 dvalues[i++] = ExecEvalExpr(e, econtext, &eisnull, NULL);
1672 /* setup for 1-D array of the given length */
1676 result = construct_md_array(dvalues, ndims, dims, lbs,
1684 /* Must be nested array expressions */
1686 Size ndatabytes = 0;
1688 int outer_nelems = length(astate->elements);
1690 int *elem_dims = NULL;
1691 int *elem_lbs = NULL;
1692 bool firstone = true;
1695 /* loop through and get data area from each element */
1696 foreach(element, astate->elements)
1698 ExprState *e = (ExprState *) lfirst(element);
1702 int elem_ndatabytes;
1704 arraydatum = ExecEvalExpr(e, econtext, &eisnull, NULL);
1711 array = DatumGetArrayTypeP(arraydatum);
1713 /* run-time double-check on element type */
1714 if (element_type != ARR_ELEMTYPE(array))
1716 (errcode(ERRCODE_DATATYPE_MISMATCH),
1717 errmsg("cannot merge incompatible arrays"),
1718 errdetail("Array with element type %s cannot be "
1719 "included in ARRAY construct with element type %s.",
1720 format_type_be(ARR_ELEMTYPE(array)),
1721 format_type_be(element_type))));
1725 /* Get sub-array details from first member */
1726 elem_ndims = ARR_NDIM(array);
1727 ndims = elem_ndims + 1;
1728 if (ndims <= 0 || ndims > MAXDIM)
1730 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1731 errmsg("number of array dimensions (%d) exceeds " \
1732 "the maximum allowed (%d)", ndims, MAXDIM)));
1734 elem_dims = (int *) palloc(elem_ndims * sizeof(int));
1735 memcpy(elem_dims, ARR_DIMS(array), elem_ndims * sizeof(int));
1736 elem_lbs = (int *) palloc(elem_ndims * sizeof(int));
1737 memcpy(elem_lbs, ARR_LBOUND(array), elem_ndims * sizeof(int));
1743 /* Check other sub-arrays are compatible */
1744 if (elem_ndims != ARR_NDIM(array) ||
1745 memcmp(elem_dims, ARR_DIMS(array),
1746 elem_ndims * sizeof(int)) != 0 ||
1747 memcmp(elem_lbs, ARR_LBOUND(array),
1748 elem_ndims * sizeof(int)) != 0)
1750 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1751 errmsg("multidimensional arrays must have array "
1752 "expressions with matching dimensions")));
1755 elem_ndatabytes = ARR_SIZE(array) - ARR_OVERHEAD(elem_ndims);
1756 ndatabytes += elem_ndatabytes;
1758 dat = (char *) palloc(ndatabytes);
1760 dat = (char *) repalloc(dat, ndatabytes);
1762 memcpy(dat + (ndatabytes - elem_ndatabytes),
1763 ARR_DATA_PTR(array),
1767 /* setup for multi-D array */
1768 dims[0] = outer_nelems;
1770 for (i = 1; i < ndims; i++)
1772 dims[i] = elem_dims[i - 1];
1773 lbs[i] = elem_lbs[i - 1];
1776 nbytes = ndatabytes + ARR_OVERHEAD(ndims);
1777 result = (ArrayType *) palloc(nbytes);
1779 result->size = nbytes;
1780 result->ndim = ndims;
1782 result->elemtype = element_type;
1783 memcpy(ARR_DIMS(result), dims, ndims * sizeof(int));
1784 memcpy(ARR_LBOUND(result), lbs, ndims * sizeof(int));
1786 memcpy(ARR_DATA_PTR(result), dat, ndatabytes);
1792 return PointerGetDatum(result);
1795 /* ----------------------------------------------------------------
1797 * ----------------------------------------------------------------
1800 ExecEvalCoalesce(CoalesceExprState *coalesceExpr, ExprContext *econtext,
1805 /* Simply loop through until something NOT NULL is found */
1806 foreach(arg, coalesceExpr->args)
1808 ExprState *e = (ExprState *) lfirst(arg);
1811 value = ExecEvalExpr(e, econtext, isNull, NULL);
1816 /* Else return NULL */
1821 /* ----------------------------------------------------------------
1824 * Note that this is *always* derived from the equals operator,
1825 * but since we need special processing of the arguments
1826 * we can not simply reuse ExecEvalOper() or ExecEvalFunc().
1827 * ----------------------------------------------------------------
1830 ExecEvalNullIf(FuncExprState *fcache, ExprContext *econtext,
1834 FunctionCallInfoData fcinfo;
1835 ExprDoneCond argDone;
1839 * Initialize function cache if first time through
1841 if (fcache->func.fn_oid == InvalidOid)
1843 NullIfExpr *op = (NullIfExpr *) fcache->xprstate.expr;
1845 init_fcache(op->opfuncid, fcache, econtext->ecxt_per_query_memory);
1846 Assert(!fcache->func.fn_retset);
1850 * extract info from fcache
1852 argList = fcache->args;
1854 /* Need to prep callinfo structure */
1855 MemSet(&fcinfo, 0, sizeof(fcinfo));
1856 fcinfo.flinfo = &(fcache->func);
1857 argDone = ExecEvalFuncArgs(&fcinfo, argList, econtext);
1858 if (argDone != ExprSingleResult)
1860 (errcode(ERRCODE_DATATYPE_MISMATCH),
1861 errmsg("NULLIF does not support set arguments")));
1862 Assert(fcinfo.nargs == 2);
1864 /* if either argument is NULL they can't be equal */
1865 if (!fcinfo.argnull[0] && !fcinfo.argnull[1])
1867 fcinfo.isnull = false;
1868 result = FunctionCallInvoke(&fcinfo);
1869 /* if the arguments are equal return null */
1870 if (!fcinfo.isnull && DatumGetBool(result))
1877 /* else return first argument */
1878 *isNull = fcinfo.argnull[0];
1879 return fcinfo.arg[0];
1882 /* ----------------------------------------------------------------
1885 * Evaluate a NullTest node.
1886 * ----------------------------------------------------------------
1889 ExecEvalNullTest(GenericExprState *nstate,
1890 ExprContext *econtext,
1892 ExprDoneCond *isDone)
1894 NullTest *ntest = (NullTest *) nstate->xprstate.expr;
1897 result = ExecEvalExpr(nstate->arg, econtext, isNull, isDone);
1899 if (isDone && *isDone == ExprEndResult)
1900 return result; /* nothing to check */
1902 switch (ntest->nulltesttype)
1908 return BoolGetDatum(true);
1911 return BoolGetDatum(false);
1916 return BoolGetDatum(false);
1919 return BoolGetDatum(true);
1921 elog(ERROR, "unrecognized nulltesttype: %d",
1922 (int) ntest->nulltesttype);
1923 return (Datum) 0; /* keep compiler quiet */
1927 /* ----------------------------------------------------------------
1928 * ExecEvalBooleanTest
1930 * Evaluate a BooleanTest node.
1931 * ----------------------------------------------------------------
1934 ExecEvalBooleanTest(GenericExprState *bstate,
1935 ExprContext *econtext,
1937 ExprDoneCond *isDone)
1939 BooleanTest *btest = (BooleanTest *) bstate->xprstate.expr;
1942 result = ExecEvalExpr(bstate->arg, econtext, isNull, isDone);
1944 if (isDone && *isDone == ExprEndResult)
1945 return result; /* nothing to check */
1947 switch (btest->booltesttype)
1953 return BoolGetDatum(false);
1955 else if (DatumGetBool(result))
1956 return BoolGetDatum(true);
1958 return BoolGetDatum(false);
1963 return BoolGetDatum(true);
1965 else if (DatumGetBool(result))
1966 return BoolGetDatum(false);
1968 return BoolGetDatum(true);
1973 return BoolGetDatum(false);
1975 else if (DatumGetBool(result))
1976 return BoolGetDatum(false);
1978 return BoolGetDatum(true);
1983 return BoolGetDatum(true);
1985 else if (DatumGetBool(result))
1986 return BoolGetDatum(true);
1988 return BoolGetDatum(false);
1993 return BoolGetDatum(true);
1996 return BoolGetDatum(false);
1997 case IS_NOT_UNKNOWN:
2001 return BoolGetDatum(false);
2004 return BoolGetDatum(true);
2006 elog(ERROR, "unrecognized booltesttype: %d",
2007 (int) btest->booltesttype);
2008 return (Datum) 0; /* keep compiler quiet */
2013 * ExecEvalCoerceToDomain
2015 * Test the provided data against the domain constraint(s). If the data
2016 * passes the constraint specifications, pass it through (return the
2017 * datum) otherwise throw an error.
2020 ExecEvalCoerceToDomain(CoerceToDomainState *cstate, ExprContext *econtext,
2021 bool *isNull, ExprDoneCond *isDone)
2023 CoerceToDomain *ctest = (CoerceToDomain *) cstate->xprstate.expr;
2027 result = ExecEvalExpr(cstate->arg, econtext, isNull, isDone);
2029 if (isDone && *isDone == ExprEndResult)
2030 return result; /* nothing to check */
2032 foreach(l, cstate->constraints)
2034 DomainConstraintState *con = (DomainConstraintState *) lfirst(l);
2036 switch (con->constrainttype)
2038 case DOM_CONSTRAINT_NOTNULL:
2041 (errcode(ERRCODE_NOT_NULL_VIOLATION),
2042 errmsg("domain %s does not allow null values",
2043 format_type_be(ctest->resulttype))));
2045 case DOM_CONSTRAINT_CHECK:
2053 * Set up value to be returned by CoerceToDomainValue
2054 * nodes. We must save and restore prior setting of
2055 * econtext's domainValue fields, in case this node is
2056 * itself within a check expression for another
2059 save_datum = econtext->domainValue_datum;
2060 save_isNull = econtext->domainValue_isNull;
2062 econtext->domainValue_datum = result;
2063 econtext->domainValue_isNull = *isNull;
2065 conResult = ExecEvalExpr(con->check_expr,
2066 econtext, &conIsNull, NULL);
2069 !DatumGetBool(conResult))
2071 (errcode(ERRCODE_CHECK_VIOLATION),
2072 errmsg("value for domain %s violates check constraint \"%s\"",
2073 format_type_be(ctest->resulttype),
2075 econtext->domainValue_datum = save_datum;
2076 econtext->domainValue_isNull = save_isNull;
2081 elog(ERROR, "unrecognized constraint type: %d",
2082 (int) con->constrainttype);
2087 /* If all has gone well (constraints did not fail) return the datum */
2092 * ExecEvalCoerceToDomainValue
2094 * Return the value stored by CoerceToDomain.
2097 ExecEvalCoerceToDomainValue(CoerceToDomainValue *conVal,
2098 ExprContext *econtext, bool *isNull)
2100 *isNull = econtext->domainValue_isNull;
2101 return econtext->domainValue_datum;
2104 /* ----------------------------------------------------------------
2105 * ExecEvalFieldSelect
2107 * Evaluate a FieldSelect node.
2108 * ----------------------------------------------------------------
2111 ExecEvalFieldSelect(GenericExprState *fstate,
2112 ExprContext *econtext,
2114 ExprDoneCond *isDone)
2116 FieldSelect *fselect = (FieldSelect *) fstate->xprstate.expr;
2118 TupleTableSlot *resSlot;
2120 result = ExecEvalExpr(fstate->arg, econtext, isNull, isDone);
2122 /* this test covers the isDone exception too: */
2126 resSlot = (TupleTableSlot *) DatumGetPointer(result);
2127 Assert(resSlot != NULL && IsA(resSlot, TupleTableSlot));
2128 result = heap_getattr(resSlot->val,
2130 resSlot->ttc_tupleDescriptor,
2135 /* ----------------------------------------------------------------
2138 * Recursively evaluate a targetlist or qualification expression.
2141 * expression: the expression state tree to evaluate
2142 * econtext: evaluation context information
2145 * return value: Datum value of result
2146 * *isNull: set to TRUE if result is NULL (actual return value is
2147 * meaningless if so); set to FALSE if non-null result
2148 * *isDone: set to indicator of set-result status
2150 * A caller that can only accept a singleton (non-set) result should pass
2151 * NULL for isDone; if the expression computes a set result then an error
2152 * will be reported via ereport. If the caller does pass an isDone pointer
2153 * then *isDone is set to one of these three states:
2154 * ExprSingleResult singleton result (not a set)
2155 * ExprMultipleResult return value is one element of a set
2156 * ExprEndResult there are no more elements in the set
2157 * When ExprMultipleResult is returned, the caller should invoke
2158 * ExecEvalExpr() repeatedly until ExprEndResult is returned. ExprEndResult
2159 * is returned after the last real set element. For convenience isNull will
2160 * always be set TRUE when ExprEndResult is returned, but this should not be
2161 * taken as indicating a NULL element of the set. Note that these return
2162 * conventions allow us to distinguish among a singleton NULL, a NULL element
2163 * of a set, and an empty set.
2165 * The caller should already have switched into the temporary memory
2166 * context econtext->ecxt_per_tuple_memory. The convenience entry point
2167 * ExecEvalExprSwitchContext() is provided for callers who don't prefer to
2168 * do the switch in an outer loop. We do not do the switch here because
2169 * it'd be a waste of cycles during recursive entries to ExecEvalExpr().
2171 * This routine is an inner loop routine and must be as fast as possible.
2172 * ----------------------------------------------------------------
2175 ExecEvalExpr(ExprState *expression,
2176 ExprContext *econtext,
2178 ExprDoneCond *isDone)
2183 /* Set default values for result flags: non-null, not a set result */
2186 *isDone = ExprSingleResult;
2188 /* Is this still necessary? Doubtful... */
2189 if (expression == NULL)
2196 * here we dispatch the work to the appropriate type of function given
2197 * the type of our expression.
2199 expr = expression->expr;
2200 switch (nodeTag(expr))
2203 retDatum = ExecEvalVar((Var *) expr, econtext, isNull);
2207 Const *con = (Const *) expr;
2209 retDatum = con->constvalue;
2210 *isNull = con->constisnull;
2214 retDatum = ExecEvalParam((Param *) expr, econtext, isNull);
2217 retDatum = ExecEvalAggref((AggrefExprState *) expression,
2222 retDatum = ExecEvalArrayRef((ArrayRefExprState *) expression,
2228 retDatum = ExecEvalFunc((FuncExprState *) expression, econtext,
2232 retDatum = ExecEvalOper((FuncExprState *) expression, econtext,
2235 case T_DistinctExpr:
2236 retDatum = ExecEvalDistinct((FuncExprState *) expression, econtext,
2239 case T_ScalarArrayOpExpr:
2240 retDatum = ExecEvalScalarArrayOp((ScalarArrayOpExprState *) expression,
2245 BoolExprState *state = (BoolExprState *) expression;
2247 switch (((BoolExpr *) expr)->boolop)
2250 retDatum = ExecEvalAnd(state, econtext, isNull);
2253 retDatum = ExecEvalOr(state, econtext, isNull);
2256 retDatum = ExecEvalNot(state, econtext, isNull);
2259 elog(ERROR, "unrecognized boolop: %d",
2260 (int) ((BoolExpr *) expr)->boolop);
2261 retDatum = 0; /* keep compiler quiet */
2267 retDatum = ExecSubPlan((SubPlanState *) expression,
2272 retDatum = ExecEvalFieldSelect((GenericExprState *) expression,
2278 retDatum = ExecEvalExpr(((GenericExprState *) expression)->arg,
2284 retDatum = ExecEvalCase((CaseExprState *) expression,
2290 retDatum = ExecEvalArray((ArrayExprState *) expression,
2294 case T_CoalesceExpr:
2295 retDatum = ExecEvalCoalesce((CoalesceExprState *) expression,
2300 retDatum = ExecEvalNullIf((FuncExprState *) expression,
2305 retDatum = ExecEvalNullTest((GenericExprState *) expression,
2311 retDatum = ExecEvalBooleanTest((GenericExprState *) expression,
2316 case T_CoerceToDomain:
2317 retDatum = ExecEvalCoerceToDomain((CoerceToDomainState *) expression,
2322 case T_CoerceToDomainValue:
2323 retDatum = ExecEvalCoerceToDomainValue((CoerceToDomainValue *) expr,
2328 elog(ERROR, "unrecognized node type: %d",
2329 (int) nodeTag(expression));
2330 retDatum = 0; /* keep compiler quiet */
2335 } /* ExecEvalExpr() */
2339 * Same as above, but get into the right allocation context explicitly.
2342 ExecEvalExprSwitchContext(ExprState *expression,
2343 ExprContext *econtext,
2345 ExprDoneCond *isDone)
2348 MemoryContext oldContext;
2350 oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
2351 retDatum = ExecEvalExpr(expression, econtext, isNull, isDone);
2352 MemoryContextSwitchTo(oldContext);
2358 * ExecInitExpr: prepare an expression tree for execution
2360 * This function builds and returns an ExprState tree paralleling the given
2361 * Expr node tree. The ExprState tree can then be handed to ExecEvalExpr
2362 * for execution. Because the Expr tree itself is read-only as far as
2363 * ExecInitExpr and ExecEvalExpr are concerned, several different executions
2364 * of the same plan tree can occur concurrently.
2366 * This must be called in a memory context that will last as long as repeated
2367 * executions of the expression are needed. Typically the context will be
2368 * the same as the per-query context of the associated ExprContext.
2370 * Any Aggref and SubPlan nodes found in the tree are added to the lists
2371 * of such nodes held by the parent PlanState. Otherwise, we do very little
2372 * initialization here other than building the state-node tree. Any nontrivial
2373 * work associated with initializing runtime info for a node should happen
2374 * during the first actual evaluation of that node. (This policy lets us
2375 * avoid work if the node is never actually evaluated.)
2377 * Note: there is no ExecEndExpr function; we assume that any resource
2378 * cleanup needed will be handled by just releasing the memory context
2379 * in which the state tree is built. Functions that require additional
2380 * cleanup work can register a shutdown callback in the ExprContext.
2382 * 'node' is the root of the expression tree to examine
2383 * 'parent' is the PlanState node that owns the expression.
2385 * 'parent' may be NULL if we are preparing an expression that is not
2386 * associated with a plan tree. (If so, it can't have aggs or subplans.)
2387 * This case should usually come through ExecPrepareExpr, not directly here.
2390 ExecInitExpr(Expr *node, PlanState *parent)
2396 switch (nodeTag(node))
2401 case T_CoerceToDomainValue:
2402 /* No special setup needed for these node types */
2403 state = (ExprState *) makeNode(ExprState);
2407 Aggref *aggref = (Aggref *) node;
2408 AggrefExprState *astate = makeNode(AggrefExprState);
2410 if (parent && IsA(parent, AggState))
2412 AggState *aggstate = (AggState *) parent;
2415 aggstate->aggs = lcons(astate, aggstate->aggs);
2416 naggs = ++aggstate->numaggs;
2418 astate->target = ExecInitExpr(aggref->target, parent);
2421 * Complain if the aggregate's argument contains any
2422 * aggregates; nested agg functions are semantically
2423 * nonsensical. (This should have been caught
2424 * earlier, but we defend against it here anyway.)
2426 if (naggs != aggstate->numaggs)
2428 (errcode(ERRCODE_GROUPING_ERROR),
2429 errmsg("aggregate function calls may not be nested")));
2433 /* planner messed up */
2434 elog(ERROR, "aggref found in non-Agg plan node");
2436 state = (ExprState *) astate;
2441 ArrayRef *aref = (ArrayRef *) node;
2442 ArrayRefExprState *astate = makeNode(ArrayRefExprState);
2444 astate->refupperindexpr = (List *)
2445 ExecInitExpr((Expr *) aref->refupperindexpr, parent);
2446 astate->reflowerindexpr = (List *)
2447 ExecInitExpr((Expr *) aref->reflowerindexpr, parent);
2448 astate->refexpr = ExecInitExpr(aref->refexpr, parent);
2449 astate->refassgnexpr = ExecInitExpr(aref->refassgnexpr,
2451 /* do one-time catalog lookups for type info */
2452 astate->refattrlength = get_typlen(aref->refarraytype);
2453 get_typlenbyvalalign(aref->refelemtype,
2454 &astate->refelemlength,
2455 &astate->refelembyval,
2456 &astate->refelemalign);
2457 state = (ExprState *) astate;
2462 FuncExpr *funcexpr = (FuncExpr *) node;
2463 FuncExprState *fstate = makeNode(FuncExprState);
2465 fstate->args = (List *)
2466 ExecInitExpr((Expr *) funcexpr->args, parent);
2467 fstate->func.fn_oid = InvalidOid; /* not initialized */
2468 state = (ExprState *) fstate;
2473 OpExpr *opexpr = (OpExpr *) node;
2474 FuncExprState *fstate = makeNode(FuncExprState);
2476 fstate->args = (List *)
2477 ExecInitExpr((Expr *) opexpr->args, parent);
2478 fstate->func.fn_oid = InvalidOid; /* not initialized */
2479 state = (ExprState *) fstate;
2482 case T_DistinctExpr:
2484 DistinctExpr *distinctexpr = (DistinctExpr *) node;
2485 FuncExprState *fstate = makeNode(FuncExprState);
2487 fstate->args = (List *)
2488 ExecInitExpr((Expr *) distinctexpr->args, parent);
2489 fstate->func.fn_oid = InvalidOid; /* not initialized */
2490 state = (ExprState *) fstate;
2493 case T_ScalarArrayOpExpr:
2495 ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) node;
2496 ScalarArrayOpExprState *sstate = makeNode(ScalarArrayOpExprState);
2498 sstate->fxprstate.args = (List *)
2499 ExecInitExpr((Expr *) opexpr->args, parent);
2500 sstate->fxprstate.func.fn_oid = InvalidOid; /* not initialized */
2501 sstate->element_type = InvalidOid; /* ditto */
2502 state = (ExprState *) sstate;
2507 BoolExpr *boolexpr = (BoolExpr *) node;
2508 BoolExprState *bstate = makeNode(BoolExprState);
2510 bstate->args = (List *)
2511 ExecInitExpr((Expr *) boolexpr->args, parent);
2512 state = (ExprState *) bstate;
2517 /* Keep this in sync with ExecInitExprInitPlan, below */
2518 SubPlan *subplan = (SubPlan *) node;
2519 SubPlanState *sstate = makeNode(SubPlanState);
2522 elog(ERROR, "SubPlan found with no parent plan");
2525 * Here we just add the SubPlanState nodes to
2526 * parent->subPlan. The subplans will be initialized
2529 parent->subPlan = lcons(sstate, parent->subPlan);
2530 sstate->sub_estate = NULL;
2531 sstate->planstate = NULL;
2533 sstate->exprs = (List *)
2534 ExecInitExpr((Expr *) subplan->exprs, parent);
2535 sstate->args = (List *)
2536 ExecInitExpr((Expr *) subplan->args, parent);
2538 state = (ExprState *) sstate;
2543 FieldSelect *fselect = (FieldSelect *) node;
2544 GenericExprState *gstate = makeNode(GenericExprState);
2546 gstate->arg = ExecInitExpr(fselect->arg, parent);
2547 state = (ExprState *) gstate;
2552 RelabelType *relabel = (RelabelType *) node;
2553 GenericExprState *gstate = makeNode(GenericExprState);
2555 gstate->arg = ExecInitExpr(relabel->arg, parent);
2556 state = (ExprState *) gstate;
2561 CaseExpr *caseexpr = (CaseExpr *) node;
2562 CaseExprState *cstate = makeNode(CaseExprState);
2566 FastListInit(&outlist);
2567 foreach(inlist, caseexpr->args)
2569 CaseWhen *when = (CaseWhen *) lfirst(inlist);
2570 CaseWhenState *wstate = makeNode(CaseWhenState);
2572 Assert(IsA(when, CaseWhen));
2573 wstate->xprstate.expr = (Expr *) when;
2574 wstate->expr = ExecInitExpr(when->expr, parent);
2575 wstate->result = ExecInitExpr(when->result, parent);
2576 FastAppend(&outlist, wstate);
2578 cstate->args = FastListValue(&outlist);
2579 /* caseexpr->arg should be null by now */
2580 Assert(caseexpr->arg == NULL);
2581 cstate->defresult = ExecInitExpr(caseexpr->defresult, parent);
2582 state = (ExprState *) cstate;
2587 ArrayExpr *arrayexpr = (ArrayExpr *) node;
2588 ArrayExprState *astate = makeNode(ArrayExprState);
2592 FastListInit(&outlist);
2593 foreach(inlist, arrayexpr->elements)
2595 Expr *e = (Expr *) lfirst(inlist);
2598 estate = ExecInitExpr(e, parent);
2599 FastAppend(&outlist, estate);
2601 astate->elements = FastListValue(&outlist);
2602 /* do one-time catalog lookup for type info */
2603 get_typlenbyvalalign(arrayexpr->element_typeid,
2604 &astate->elemlength,
2606 &astate->elemalign);
2607 state = (ExprState *) astate;
2610 case T_CoalesceExpr:
2612 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
2613 CoalesceExprState *cstate = makeNode(CoalesceExprState);
2617 FastListInit(&outlist);
2618 foreach(inlist, coalesceexpr->args)
2620 Expr *e = (Expr *) lfirst(inlist);
2623 estate = ExecInitExpr(e, parent);
2624 FastAppend(&outlist, estate);
2626 cstate->args = FastListValue(&outlist);
2627 state = (ExprState *) cstate;
2632 NullIfExpr *nullifexpr = (NullIfExpr *) node;
2633 FuncExprState *fstate = makeNode(FuncExprState);
2635 fstate->args = (List *)
2636 ExecInitExpr((Expr *) nullifexpr->args, parent);
2637 fstate->func.fn_oid = InvalidOid; /* not initialized */
2638 state = (ExprState *) fstate;
2643 NullTest *ntest = (NullTest *) node;
2644 GenericExprState *gstate = makeNode(GenericExprState);
2646 gstate->arg = ExecInitExpr(ntest->arg, parent);
2647 state = (ExprState *) gstate;
2652 BooleanTest *btest = (BooleanTest *) node;
2653 GenericExprState *gstate = makeNode(GenericExprState);
2655 gstate->arg = ExecInitExpr(btest->arg, parent);
2656 state = (ExprState *) gstate;
2659 case T_CoerceToDomain:
2661 CoerceToDomain *ctest = (CoerceToDomain *) node;
2662 CoerceToDomainState *cstate = makeNode(CoerceToDomainState);
2664 cstate->arg = ExecInitExpr(ctest->arg, parent);
2665 cstate->constraints = GetDomainConstraints(ctest->resulttype);
2666 state = (ExprState *) cstate;
2671 TargetEntry *tle = (TargetEntry *) node;
2672 GenericExprState *gstate = makeNode(GenericExprState);
2674 gstate->arg = ExecInitExpr(tle->expr, parent);
2675 state = (ExprState *) gstate;
2683 FastListInit(&outlist);
2684 foreach(inlist, (List *) node)
2686 FastAppend(&outlist,
2687 ExecInitExpr((Expr *) lfirst(inlist),
2690 /* Don't fall through to the "common" code below */
2691 return (ExprState *) FastListValue(&outlist);
2694 elog(ERROR, "unrecognized node type: %d",
2695 (int) nodeTag(node));
2696 state = NULL; /* keep compiler quiet */
2700 /* Common code for all state-node types */
2707 * ExecInitExprInitPlan --- initialize a subplan expr that's being handled
2708 * as an InitPlan. This is identical to ExecInitExpr's handling of a regular
2709 * subplan expr, except we do NOT want to add the node to the parent's
2713 ExecInitExprInitPlan(SubPlan *node, PlanState *parent)
2715 SubPlanState *sstate = makeNode(SubPlanState);
2718 elog(ERROR, "SubPlan found with no parent plan");
2720 /* The subplan's state will be initialized later */
2721 sstate->sub_estate = NULL;
2722 sstate->planstate = NULL;
2724 sstate->exprs = (List *) ExecInitExpr((Expr *) node->exprs, parent);
2725 sstate->args = (List *) ExecInitExpr((Expr *) node->args, parent);
2727 sstate->xprstate.expr = (Expr *) node;
2733 * ExecPrepareExpr --- initialize for expression execution outside a normal
2734 * Plan tree context.
2736 * This differs from ExecInitExpr in that we don't assume the caller is
2737 * already running in the EState's per-query context. Also, we apply
2738 * fix_opfuncids() to the passed expression tree to be sure it is ready
2739 * to run. (In ordinary Plan trees the planner will have fixed opfuncids,
2740 * but callers outside the executor will not have done this.)
2743 ExecPrepareExpr(Expr *node, EState *estate)
2746 MemoryContext oldcontext;
2748 fix_opfuncids((Node *) node);
2750 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2752 result = ExecInitExpr(node, NULL);
2754 MemoryContextSwitchTo(oldcontext);
2760 /* ----------------------------------------------------------------
2761 * ExecQual / ExecTargetList / ExecProject
2762 * ----------------------------------------------------------------
2765 /* ----------------------------------------------------------------
2768 * Evaluates a conjunctive boolean expression (qual list) and
2769 * returns true iff none of the subexpressions are false.
2770 * (We also return true if the list is empty.)
2772 * If some of the subexpressions yield NULL but none yield FALSE,
2773 * then the result of the conjunction is NULL (ie, unknown)
2774 * according to three-valued boolean logic. In this case,
2775 * we return the value specified by the "resultForNull" parameter.
2777 * Callers evaluating WHERE clauses should pass resultForNull=FALSE,
2778 * since SQL specifies that tuples with null WHERE results do not
2779 * get selected. On the other hand, callers evaluating constraint
2780 * conditions should pass resultForNull=TRUE, since SQL also specifies
2781 * that NULL constraint conditions are not failures.
2783 * NOTE: it would not be correct to use this routine to evaluate an
2784 * AND subclause of a boolean expression; for that purpose, a NULL
2785 * result must be returned as NULL so that it can be properly treated
2786 * in the next higher operator (cf. ExecEvalAnd and ExecEvalOr).
2787 * This routine is only used in contexts where a complete expression
2788 * is being evaluated and we know that NULL can be treated the same
2789 * as one boolean result or the other.
2791 * ----------------------------------------------------------------
2794 ExecQual(List *qual, ExprContext *econtext, bool resultForNull)
2797 MemoryContext oldContext;
2803 EV_printf("ExecQual: qual is ");
2804 EV_nodeDisplay(qual);
2810 * Run in short-lived per-tuple context while computing expressions.
2812 oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
2815 * Evaluate the qual conditions one at a time. If we find a FALSE
2816 * result, we can stop evaluating and return FALSE --- the AND result
2817 * must be FALSE. Also, if we find a NULL result when resultForNull
2818 * is FALSE, we can stop and return FALSE --- the AND result must be
2819 * FALSE or NULL in that case, and the caller doesn't care which.
2821 * If we get to the end of the list, we can return TRUE. This will
2822 * happen when the AND result is indeed TRUE, or when the AND result
2823 * is NULL (one or more NULL subresult, with all the rest TRUE) and
2824 * the caller has specified resultForNull = TRUE.
2828 foreach(qlist, qual)
2830 ExprState *clause = (ExprState *) lfirst(qlist);
2834 expr_value = ExecEvalExpr(clause, econtext, &isNull, NULL);
2838 if (resultForNull == false)
2840 result = false; /* treat NULL as FALSE */
2846 if (!DatumGetBool(expr_value))
2848 result = false; /* definitely FALSE */
2854 MemoryContextSwitchTo(oldContext);
2860 * Number of items in a tlist (including any resjunk items!)
2863 ExecTargetListLength(List *targetlist)
2865 /* This used to be more complex, but fjoins are dead */
2866 return length(targetlist);
2870 * Number of items in a tlist, not including any resjunk items
2873 ExecCleanTargetListLength(List *targetlist)
2878 foreach(tl, targetlist)
2880 TargetEntry *curTle = (TargetEntry *) lfirst(tl);
2882 Assert(IsA(curTle, TargetEntry));
2883 if (!curTle->resdom->resjunk)
2889 /* ----------------------------------------------------------------
2892 * Evaluates a targetlist with respect to the given
2893 * expression context and returns a tuple.
2895 * The caller must pass workspace for the values and nulls arrays
2896 * as well as the itemIsDone array. This convention saves palloc'ing
2897 * workspace on each call, and some callers may find it useful to examine
2898 * the values array directly.
2900 * As with ExecEvalExpr, the caller should pass isDone = NULL if not
2901 * prepared to deal with sets of result tuples. Otherwise, a return
2902 * of *isDone = ExprMultipleResult signifies a set element, and a return
2903 * of *isDone = ExprEndResult signifies end of the set of tuple.
2904 * ----------------------------------------------------------------
2907 ExecTargetList(List *targetlist,
2908 TupleDesc targettype,
2909 ExprContext *econtext,
2912 ExprDoneCond *itemIsDone,
2913 ExprDoneCond *isDone)
2915 MemoryContext oldContext;
2919 static struct tupleDesc NullTupleDesc; /* we assume this inits to
2925 EV_printf("ExecTargetList: tl is ");
2926 EV_nodeDisplay(targetlist);
2930 * Run in short-lived per-tuple context while computing expressions.
2932 oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
2935 * There used to be some klugy and demonstrably broken code here that
2936 * special-cased the situation where targetlist == NIL. Now we just
2937 * fall through and return an empty-but-valid tuple. We do, however,
2938 * have to cope with the possibility that targettype is NULL ---
2939 * heap_formtuple won't like that, so pass a dummy descriptor with
2940 * natts = 0 to deal with it.
2942 if (targettype == NULL)
2943 targettype = &NullTupleDesc;
2946 * evaluate all the expressions in the target list
2949 *isDone = ExprSingleResult; /* until proven otherwise */
2951 haveDoneSets = false; /* any exhausted set exprs in tlist? */
2953 foreach(tl, targetlist)
2955 GenericExprState *gstate = (GenericExprState *) lfirst(tl);
2956 TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr;
2957 AttrNumber resind = tle->resdom->resno - 1;
2959 values[resind] = ExecEvalExpr(gstate->arg,
2962 &itemIsDone[resind]);
2963 nulls[resind] = isNull ? 'n' : ' ';
2965 if (itemIsDone[resind] != ExprSingleResult)
2967 /* We have a set-valued expression in the tlist */
2970 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2971 errmsg("set-valued function called in context that cannot accept a set")));
2972 if (itemIsDone[resind] == ExprMultipleResult)
2974 /* we have undone sets in the tlist, set flag */
2975 *isDone = ExprMultipleResult;
2979 /* we have done sets in the tlist, set flag for that */
2980 haveDoneSets = true;
2988 * note: can't get here unless we verified isDone != NULL
2990 if (*isDone == ExprSingleResult)
2993 * all sets are done, so report that tlist expansion is
2996 *isDone = ExprEndResult;
2997 MemoryContextSwitchTo(oldContext);
3003 * We have some done and some undone sets. Restart the done
3004 * ones so that we can deliver a tuple (if possible).
3006 foreach(tl, targetlist)
3008 GenericExprState *gstate = (GenericExprState *) lfirst(tl);
3009 TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr;
3010 AttrNumber resind = tle->resdom->resno - 1;
3012 if (itemIsDone[resind] == ExprEndResult)
3014 values[resind] = ExecEvalExpr(gstate->arg,
3017 &itemIsDone[resind]);
3018 nulls[resind] = isNull ? 'n' : ' ';
3020 if (itemIsDone[resind] == ExprEndResult)
3023 * Oh dear, this item is returning an empty set.
3024 * Guess we can't make a tuple after all.
3026 *isDone = ExprEndResult;
3033 * If we cannot make a tuple because some sets are empty, we
3034 * still have to cycle the nonempty sets to completion, else
3035 * resources will not be released from subplans etc.
3037 * XXX is that still necessary?
3039 if (*isDone == ExprEndResult)
3041 foreach(tl, targetlist)
3043 GenericExprState *gstate = (GenericExprState *) lfirst(tl);
3044 TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr;
3045 AttrNumber resind = tle->resdom->resno - 1;
3047 while (itemIsDone[resind] == ExprMultipleResult)
3049 (void) ExecEvalExpr(gstate->arg,
3052 &itemIsDone[resind]);
3056 MemoryContextSwitchTo(oldContext);
3063 * form the new result tuple (in the caller's memory context!)
3065 MemoryContextSwitchTo(oldContext);
3067 return heap_formtuple(targettype, values, nulls);
3070 /* ----------------------------------------------------------------
3073 * projects a tuple based on projection info and stores
3074 * it in the specified tuple table slot.
3076 * Note: someday soon the executor can be extended to eliminate
3077 * redundant projections by storing pointers to datums
3078 * in the tuple table and then passing these around when
3079 * possible. this should make things much quicker.
3081 * ----------------------------------------------------------------
3084 ExecProject(ProjectionInfo *projInfo, ExprDoneCond *isDone)
3086 TupleTableSlot *slot;
3093 if (projInfo == NULL)
3094 return (TupleTableSlot *) NULL;
3097 * get the projection info we want
3099 slot = projInfo->pi_slot;
3100 tupType = slot->ttc_tupleDescriptor;
3103 * form a new result tuple (if possible --- result can be NULL)
3105 newTuple = ExecTargetList(projInfo->pi_targetlist,
3107 projInfo->pi_exprContext,
3108 projInfo->pi_tupValues,
3109 projInfo->pi_tupNulls,
3110 projInfo->pi_itemIsDone,
3114 * store the tuple in the projection slot and return the slot.
3116 return ExecStoreTuple(newTuple, /* tuple to store */
3117 slot, /* slot to store in */
3118 InvalidBuffer, /* tuple has no buffer */