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.126 2003/03/09 02:19:13 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 ExprDoneCond ExecEvalFuncArgs(FunctionCallInfo fcinfo,
69 List *argList, ExprContext *econtext);
70 static Datum ExecEvalNot(BoolExprState *notclause, ExprContext *econtext,
72 static Datum ExecEvalOr(BoolExprState *orExpr, ExprContext *econtext,
74 static Datum ExecEvalAnd(BoolExprState *andExpr, ExprContext *econtext,
76 static Datum ExecEvalCase(CaseExprState *caseExpr, ExprContext *econtext,
77 bool *isNull, ExprDoneCond *isDone);
78 static Datum ExecEvalCoalesce(CoalesceExprState *coalesceExpr,
79 ExprContext *econtext,
81 static Datum ExecEvalNullIf(FuncExprState *nullIfExpr, ExprContext *econtext,
83 static Datum ExecEvalNullTest(GenericExprState *nstate,
84 ExprContext *econtext,
85 bool *isNull, ExprDoneCond *isDone);
86 static Datum ExecEvalBooleanTest(GenericExprState *bstate,
87 ExprContext *econtext,
88 bool *isNull, ExprDoneCond *isDone);
89 static Datum ExecEvalCoerceToDomain(CoerceToDomainState *cstate,
90 ExprContext *econtext,
91 bool *isNull, ExprDoneCond *isDone);
92 static Datum ExecEvalCoerceToDomainValue(CoerceToDomainValue *conVal,
93 ExprContext *econtext, bool *isNull);
94 static Datum ExecEvalFieldSelect(GenericExprState *fstate,
95 ExprContext *econtext,
96 bool *isNull, ExprDoneCond *isDone);
102 * This function takes an ArrayRef and returns the extracted Datum
103 * if it's a simple reference, or the modified array value if it's
104 * an array assignment (i.e., array element or slice insertion).
106 * NOTE: if we get a NULL result from a subexpression, we return NULL when
107 * it's an array reference, or the unmodified source array when it's an
108 * array assignment. This may seem peculiar, but if we return NULL (as was
109 * done in versions up through 7.0) then an assignment like
110 * UPDATE table SET arrayfield[4] = NULL
111 * will result in setting the whole array to NULL, which is certainly not
112 * very desirable. By returning the source array we make the assignment
113 * into a no-op, instead. (Eventually we need to redesign arrays so that
114 * individual elements can be NULL, but for now, let's try to protect users
115 * from shooting themselves in the foot.)
117 * NOTE: we deliberately refrain from applying DatumGetArrayTypeP() here,
118 * even though that might seem natural, because this code needs to support
119 * both varlena arrays and fixed-length array types. DatumGetArrayTypeP()
120 * only works for the varlena kind. The routines we call in arrayfuncs.c
121 * have to know the difference (that's what they need refattrlength for).
125 ExecEvalArrayRef(ArrayRefExprState *astate,
126 ExprContext *econtext,
128 ExprDoneCond *isDone)
130 ArrayRef *arrayRef = (ArrayRef *) astate->xprstate.expr;
131 ArrayType *array_source;
132 ArrayType *resultArray;
133 bool isAssignment = (arrayRef->refassgnexpr != NULL);
141 if (arrayRef->refexpr != NULL)
143 array_source = (ArrayType *)
144 DatumGetPointer(ExecEvalExpr(astate->refexpr,
150 * If refexpr yields NULL, result is always NULL, for now anyway.
151 * (This means you cannot assign to an element or slice of an
152 * array that's NULL; it'll just stay NULL.)
160 * Empty refexpr indicates we are doing an INSERT into an array
161 * column. For now, we just take the refassgnexpr (which the
162 * parser will have ensured is an array value) and return it
163 * as-is, ignoring any subscripts that may have been supplied in
164 * the INSERT column list. This is a kluge, but it's not real
165 * clear what the semantics ought to be...
170 foreach(elt, astate->refupperindexpr)
173 elog(ERROR, "ExecEvalArrayRef: can only handle %d dimensions",
176 upper.indx[i++] = DatumGetInt32(ExecEvalExpr((ExprState *) lfirst(elt),
180 /* If any index expr yields NULL, result is NULL or source array */
183 if (!isAssignment || array_source == NULL)
186 return PointerGetDatum(array_source);
190 if (astate->reflowerindexpr != NIL)
192 foreach(elt, astate->reflowerindexpr)
195 elog(ERROR, "ExecEvalArrayRef: can only handle %d dimensions",
198 lower.indx[j++] = DatumGetInt32(ExecEvalExpr((ExprState *) lfirst(elt),
204 * If any index expr yields NULL, result is NULL or source
209 if (!isAssignment || array_source == NULL)
212 return PointerGetDatum(array_source);
217 "ExecEvalArrayRef: upper and lower indices mismatch");
225 Datum sourceData = ExecEvalExpr(astate->refassgnexpr,
231 * For now, can't cope with inserting NULL into an array, so make
232 * it a no-op per discussion above...
236 if (array_source == NULL)
239 return PointerGetDatum(array_source);
242 if (array_source == NULL)
243 return sourceData; /* XXX do something else? */
246 resultArray = array_set(array_source, i,
249 arrayRef->refattrlength,
250 arrayRef->refelemlength,
251 arrayRef->refelembyval,
252 arrayRef->refelemalign,
255 resultArray = array_set_slice(array_source, i,
256 upper.indx, lower.indx,
257 (ArrayType *) DatumGetPointer(sourceData),
258 arrayRef->refattrlength,
259 arrayRef->refelemlength,
260 arrayRef->refelembyval,
261 arrayRef->refelemalign,
263 return PointerGetDatum(resultArray);
267 return array_ref(array_source, i, upper.indx,
268 arrayRef->refattrlength,
269 arrayRef->refelemlength,
270 arrayRef->refelembyval,
271 arrayRef->refelemalign,
275 resultArray = array_get_slice(array_source, i,
276 upper.indx, lower.indx,
277 arrayRef->refattrlength,
278 arrayRef->refelemlength,
279 arrayRef->refelembyval,
280 arrayRef->refelemalign,
282 return PointerGetDatum(resultArray);
287 /* ----------------------------------------------------------------
290 * Returns a Datum whose value is the value of the precomputed
291 * aggregate found in the given expression context.
292 * ----------------------------------------------------------------
295 ExecEvalAggref(AggrefExprState *aggref, ExprContext *econtext, bool *isNull)
297 if (econtext->ecxt_aggvalues == NULL) /* safety check */
298 elog(ERROR, "ExecEvalAggref: no aggregates in this expression context");
300 *isNull = econtext->ecxt_aggnulls[aggref->aggno];
301 return econtext->ecxt_aggvalues[aggref->aggno];
304 /* ----------------------------------------------------------------
307 * Returns a Datum whose value is the value of a range
308 * variable with respect to given expression context.
311 * As an entry condition, we expect that the datatype the
312 * plan expects to get (as told by our "variable" argument) is in
313 * fact the datatype of the attribute the plan says to fetch (as
314 * seen in the current context, identified by our "econtext"
317 * If we fetch a Type A attribute and Caller treats it as if it
318 * were Type B, there will be undefined results (e.g. crash).
319 * One way these might mismatch now is that we're accessing a
320 * catalog class and the type information in the pg_attribute
321 * class does not match the hardcoded pg_attribute information
322 * (in pg_attribute.h) for the class in question.
324 * We have an Assert to make sure this entry condition is met.
326 * ---------------------------------------------------------------- */
328 ExecEvalVar(Var *variable, ExprContext *econtext, bool *isNull)
331 TupleTableSlot *slot;
334 TupleDesc tuple_type;
337 * get the slot we want
339 switch (variable->varno)
341 case INNER: /* get the tuple from the inner node */
342 slot = econtext->ecxt_innertuple;
345 case OUTER: /* get the tuple from the outer node */
346 slot = econtext->ecxt_outertuple;
349 default: /* get the tuple from the relation being
351 slot = econtext->ecxt_scantuple;
356 * extract tuple information from the slot
358 heapTuple = slot->val;
359 tuple_type = slot->ttc_tupleDescriptor;
361 attnum = variable->varattno;
363 /* (See prolog for explanation of this Assert) */
364 Assert(attnum <= 0 ||
365 (attnum - 1 <= tuple_type->natts - 1 &&
366 tuple_type->attrs[attnum - 1] != NULL &&
367 variable->vartype == tuple_type->attrs[attnum - 1]->atttypid));
370 * If the attribute number is invalid, then we are supposed to return
371 * the entire tuple; we give back a whole slot so that callers know
372 * what the tuple looks like.
374 * XXX this is a horrid crock: since the pointer to the slot might live
375 * longer than the current evaluation context, we are forced to copy
376 * the tuple and slot into a long-lived context --- we use
377 * TransactionCommandContext which should be safe enough. This
378 * represents a serious memory leak if many such tuples are processed
379 * in one command, however. We ought to redesign the representation
380 * of whole-tuple datums so that this is not necessary.
382 * We assume it's OK to point to the existing tupleDescriptor, rather
383 * than copy that too.
385 if (attnum == InvalidAttrNumber)
387 MemoryContext oldContext;
388 TupleTableSlot *tempSlot;
391 oldContext = MemoryContextSwitchTo(TransactionCommandContext);
392 tempSlot = MakeTupleTableSlot();
393 tup = heap_copytuple(heapTuple);
394 ExecStoreTuple(tup, tempSlot, InvalidBuffer, true);
395 ExecSetSlotDescriptor(tempSlot, tuple_type, false);
396 MemoryContextSwitchTo(oldContext);
397 return PointerGetDatum(tempSlot);
400 result = heap_getattr(heapTuple, /* tuple containing attribute */
401 attnum, /* attribute number of desired
403 tuple_type, /* tuple descriptor of tuple */
404 isNull); /* return: is attribute null? */
409 /* ----------------------------------------------------------------
412 * Returns the value of a parameter. A param node contains
413 * something like ($.name) and the expression context contains
414 * the current parameter bindings (name = "sam") (age = 34)...
415 * so our job is to find and return the appropriate datum ("sam").
417 * Q: if we have a parameter ($.foo) without a binding, i.e.
418 * there is no (foo = xxx) in the parameter list info,
419 * is this a fatal error or should this be a "not available"
420 * (in which case we could return NULL)? -cim 10/13/89
421 * ----------------------------------------------------------------
424 ExecEvalParam(Param *expression, ExprContext *econtext, bool *isNull)
426 int thisParamKind = expression->paramkind;
427 AttrNumber thisParamId = expression->paramid;
429 if (thisParamKind == PARAM_EXEC)
432 * PARAM_EXEC params (internal executor parameters) are stored in
433 * the ecxt_param_exec_vals array, and can be accessed by array index.
437 prm = &(econtext->ecxt_param_exec_vals[thisParamId]);
438 if (prm->execPlan != NULL)
440 /* Parameter not evaluated yet, so go do it */
441 ExecSetParamPlan(prm->execPlan, econtext);
442 /* ExecSetParamPlan should have processed this param... */
443 Assert(prm->execPlan == NULL);
445 *isNull = prm->isnull;
451 * All other parameter types must be sought in ecxt_param_list_info.
452 * NOTE: The last entry in the param array is always an
453 * entry with kind == PARAM_INVALID.
455 ParamListInfo paramList = econtext->ecxt_param_list_info;
456 char *thisParamName = expression->paramname;
457 bool matchFound = false;
459 if (paramList != NULL)
461 while (paramList->kind != PARAM_INVALID && !matchFound)
463 if (thisParamKind == paramList->kind)
465 switch (thisParamKind)
468 if (strcmp(paramList->name, thisParamName) == 0)
472 if (paramList->id == thisParamId)
476 elog(ERROR, "ExecEvalParam: invalid paramkind %d",
487 if (thisParamKind == PARAM_NAMED)
488 elog(ERROR, "ExecEvalParam: Unknown value for parameter %s",
491 elog(ERROR, "ExecEvalParam: Unknown value for parameter %d",
495 *isNull = paramList->isnull;
496 return paramList->value;
501 /* ----------------------------------------------------------------
502 * ExecEvalOper / ExecEvalFunc support routines
503 * ----------------------------------------------------------------
510 * These are functions which return the value of the
511 * named attribute out of the tuple from the arg slot. User defined
512 * C functions which take a tuple as an argument are expected
513 * to use this. Ex: overpaid(EMP) might call GetAttributeByNum().
516 GetAttributeByNum(TupleTableSlot *slot,
522 if (!AttributeNumberIsValid(attrno))
523 elog(ERROR, "GetAttributeByNum: Invalid attribute number");
525 if (!AttrNumberIsForUserDefinedAttr(attrno))
526 elog(ERROR, "GetAttributeByNum: cannot access system attributes here");
528 if (isNull == (bool *) NULL)
529 elog(ERROR, "GetAttributeByNum: a NULL isNull flag was passed");
537 retval = heap_getattr(slot->val,
539 slot->ttc_tupleDescriptor,
548 GetAttributeByName(TupleTableSlot *slot, char *attname, bool *isNull)
557 elog(ERROR, "GetAttributeByName: Invalid attribute name");
559 if (isNull == (bool *) NULL)
560 elog(ERROR, "GetAttributeByName: a NULL isNull flag was passed");
568 tupdesc = slot->ttc_tupleDescriptor;
569 natts = slot->val->t_data->t_natts;
571 attrno = InvalidAttrNumber;
572 for (i = 0; i < tupdesc->natts; i++)
574 if (namestrcmp(&(tupdesc->attrs[i]->attname), attname) == 0)
576 attrno = tupdesc->attrs[i]->attnum;
581 if (attrno == InvalidAttrNumber)
582 elog(ERROR, "GetAttributeByName: attribute %s not found", attname);
584 retval = heap_getattr(slot->val,
595 * init_fcache - initialize a FuncExprState node during first use
598 init_fcache(Oid foid, FuncExprState *fcache, MemoryContext fcacheCxt)
602 /* Check permission to call function */
603 aclresult = pg_proc_aclcheck(foid, GetUserId(), ACL_EXECUTE);
604 if (aclresult != ACLCHECK_OK)
605 aclcheck_error(aclresult, get_func_name(foid));
607 /* Safety check (should never fail, as parser should check sooner) */
608 if (length(fcache->args) > FUNC_MAX_ARGS)
609 elog(ERROR, "init_fcache: too many arguments");
611 /* Set up the primary fmgr lookup information */
612 fmgr_info_cxt(foid, &(fcache->func), fcacheCxt);
614 /* Initialize additional info */
615 fcache->setArgsValid = false;
619 * Evaluate arguments for a function.
622 ExecEvalFuncArgs(FunctionCallInfo fcinfo,
624 ExprContext *econtext)
626 ExprDoneCond argIsDone;
630 argIsDone = ExprSingleResult; /* default assumption */
633 foreach(arg, argList)
635 ExprDoneCond thisArgIsDone;
637 fcinfo->arg[i] = ExecEvalExpr((ExprState *) lfirst(arg),
642 if (thisArgIsDone != ExprSingleResult)
645 * We allow only one argument to have a set value; we'd need
646 * much more complexity to keep track of multiple set
647 * arguments (cf. ExecTargetList) and it doesn't seem worth
650 if (argIsDone != ExprSingleResult)
651 elog(ERROR, "Functions and operators can take only one set argument");
652 argIsDone = thisArgIsDone;
663 * ExecMakeFunctionResult
665 * Evaluate the arguments to a function and then the function itself.
668 ExecMakeFunctionResult(FuncExprState *fcache,
669 ExprContext *econtext,
671 ExprDoneCond *isDone)
673 List *arguments = fcache->args;
675 FunctionCallInfoData fcinfo;
676 ReturnSetInfo rsinfo; /* for functions returning sets */
677 ExprDoneCond argDone;
682 * arguments is a list of expressions to evaluate before passing to
683 * the function manager. We skip the evaluation if it was already
684 * done in the previous call (ie, we are continuing the evaluation of
685 * a set-valued function). Otherwise, collect the current argument
686 * values into fcinfo.
688 if (!fcache->setArgsValid)
690 /* Need to prep callinfo structure */
691 MemSet(&fcinfo, 0, sizeof(fcinfo));
692 fcinfo.flinfo = &(fcache->func);
693 argDone = ExecEvalFuncArgs(&fcinfo, arguments, econtext);
694 if (argDone == ExprEndResult)
696 /* input is an empty set, so return an empty set. */
699 *isDone = ExprEndResult;
701 elog(ERROR, "Set-valued function called in context that cannot accept a set");
704 hasSetArg = (argDone != ExprSingleResult);
708 /* Copy callinfo from previous evaluation */
709 memcpy(&fcinfo, &fcache->setArgs, sizeof(fcinfo));
710 hasSetArg = fcache->setHasSetArg;
711 /* Reset flag (we may set it again below) */
712 fcache->setArgsValid = false;
716 * If function returns set, prepare a resultinfo node for
719 if (fcache->func.fn_retset)
721 fcinfo.resultinfo = (Node *) &rsinfo;
722 rsinfo.type = T_ReturnSetInfo;
723 rsinfo.econtext = econtext;
724 rsinfo.expectedDesc = NULL;
725 rsinfo.allowedModes = (int) SFRM_ValuePerCall;
726 rsinfo.returnMode = SFRM_ValuePerCall;
727 /* isDone is filled below */
728 rsinfo.setResult = NULL;
729 rsinfo.setDesc = NULL;
733 * now return the value gotten by calling the function manager,
734 * passing the function the evaluated parameter values.
736 if (fcache->func.fn_retset || hasSetArg)
739 * We need to return a set result. Complain if caller not ready
743 elog(ERROR, "Set-valued function called in context that cannot accept a set");
746 * This loop handles the situation where we have both a set
747 * argument and a set-valued function. Once we have exhausted the
748 * function's value(s) for a particular argument value, we have to
749 * get the next argument value and start the function over again.
750 * We might have to do it more than once, if the function produces
751 * an empty result set for a particular input value.
756 * If function is strict, and there are any NULL arguments,
757 * skip calling the function (at least for this set of args).
761 if (fcache->func.fn_strict)
763 for (i = 0; i < fcinfo.nargs; i++)
765 if (fcinfo.argnull[i])
775 fcinfo.isnull = false;
776 rsinfo.isDone = ExprSingleResult;
777 result = FunctionCallInvoke(&fcinfo);
778 *isNull = fcinfo.isnull;
779 *isDone = rsinfo.isDone;
785 *isDone = ExprEndResult;
788 if (*isDone != ExprEndResult)
791 * Got a result from current argument. If function itself
792 * returns set, save the current argument values to re-use
795 if (fcache->func.fn_retset)
797 memcpy(&fcache->setArgs, &fcinfo, sizeof(fcinfo));
798 fcache->setHasSetArg = hasSetArg;
799 fcache->setArgsValid = true;
803 * Make sure we say we are returning a set, even if the
804 * function itself doesn't return sets.
806 *isDone = ExprMultipleResult;
810 /* Else, done with this argument */
812 break; /* input not a set, so done */
814 /* Re-eval args to get the next element of the input set */
815 argDone = ExecEvalFuncArgs(&fcinfo, arguments, econtext);
817 if (argDone != ExprMultipleResult)
819 /* End of argument set, so we're done. */
821 *isDone = ExprEndResult;
827 * If we reach here, loop around to run the function on the
835 * Non-set case: much easier.
837 * If function is strict, and there are any NULL arguments, skip
838 * calling the function and return NULL.
840 if (fcache->func.fn_strict)
842 for (i = 0; i < fcinfo.nargs; i++)
844 if (fcinfo.argnull[i])
851 fcinfo.isnull = false;
852 result = FunctionCallInvoke(&fcinfo);
853 *isNull = fcinfo.isnull;
861 * ExecMakeTableFunctionResult
863 * Evaluate a table function, producing a materialized result in a Tuplestore
864 * object. (If function returns an empty set, we just return NULL instead.)
867 ExecMakeTableFunctionResult(ExprState *funcexpr,
868 ExprContext *econtext,
869 TupleDesc expectedDesc,
870 TupleDesc *returnDesc)
872 Tuplestorestate *tupstore = NULL;
873 TupleDesc tupdesc = NULL;
875 FunctionCallInfoData fcinfo;
876 ReturnSetInfo rsinfo;
877 MemoryContext callerContext;
878 MemoryContext oldcontext;
879 TupleTableSlot *slot;
880 bool direct_function_call;
881 bool first_time = true;
882 bool returnsTuple = false;
885 * Normally the passed expression tree will be a FuncExprState, since the
886 * grammar only allows a function call at the top level of a table
887 * function reference. However, if the function doesn't return set then
888 * the planner might have replaced the function call via constant-folding
889 * or inlining. So if we see any other kind of expression node, execute
890 * it via the general ExecEvalExpr() code; the only difference is that
891 * we don't get a chance to pass a special ReturnSetInfo to any functions
892 * buried in the expression.
894 if (funcexpr && IsA(funcexpr, FuncExprState) &&
895 IsA(funcexpr->expr, FuncExpr))
897 FuncExprState *fcache = (FuncExprState *) funcexpr;
898 ExprDoneCond argDone;
901 * This path is similar to ExecMakeFunctionResult.
903 direct_function_call = true;
906 * Initialize function cache if first time through
908 if (fcache->func.fn_oid == InvalidOid)
910 FuncExpr *func = (FuncExpr *) fcache->xprstate.expr;
912 init_fcache(func->funcid, fcache, econtext->ecxt_per_query_memory);
916 * Evaluate the function's argument list.
918 * Note: ideally, we'd do this in the per-tuple context, but then the
919 * argument values would disappear when we reset the context in the
920 * inner loop. So do it in caller context. Perhaps we should make a
921 * separate context just to hold the evaluated arguments?
923 MemSet(&fcinfo, 0, sizeof(fcinfo));
924 fcinfo.flinfo = &(fcache->func);
925 argDone = ExecEvalFuncArgs(&fcinfo, fcache->args, econtext);
926 /* We don't allow sets in the arguments of the table function */
927 if (argDone != ExprSingleResult)
928 elog(ERROR, "Set-valued function called in context that cannot accept a set");
931 * If function is strict, and there are any NULL arguments, skip
932 * calling the function and return NULL (actually an empty set).
934 if (fcache->func.fn_strict)
938 for (i = 0; i < fcinfo.nargs; i++)
940 if (fcinfo.argnull[i])
950 /* Treat funcexpr as a generic expression */
951 direct_function_call = false;
954 funcrettype = exprType((Node *) funcexpr->expr);
957 * Prepare a resultinfo node for communication. We always do this
958 * even if not expecting a set result, so that we can pass
959 * expectedDesc. In the generic-expression case, the expression
960 * doesn't actually get to see the resultinfo, but set it up anyway
961 * because we use some of the fields as our own state variables.
963 fcinfo.resultinfo = (Node *) &rsinfo;
964 rsinfo.type = T_ReturnSetInfo;
965 rsinfo.econtext = econtext;
966 rsinfo.expectedDesc = expectedDesc;
967 rsinfo.allowedModes = (int) (SFRM_ValuePerCall | SFRM_Materialize);
968 rsinfo.returnMode = SFRM_ValuePerCall;
969 /* isDone is filled below */
970 rsinfo.setResult = NULL;
971 rsinfo.setDesc = NULL;
974 * Switch to short-lived context for calling the function or expression.
976 callerContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
979 * Loop to handle the ValuePerCall protocol (which is also the same
980 * behavior needed in the generic ExecEvalExpr path).
988 * reset per-tuple memory context before each call of the
989 * function or expression. This cleans up any local memory the
990 * function may leak when called.
992 ResetExprContext(econtext);
994 /* Call the function or expression one time */
995 if (direct_function_call)
997 fcinfo.isnull = false;
998 rsinfo.isDone = ExprSingleResult;
999 result = FunctionCallInvoke(&fcinfo);
1003 result = ExecEvalExpr(funcexpr, econtext,
1004 &fcinfo.isnull, &rsinfo.isDone);
1007 /* Which protocol does function want to use? */
1008 if (rsinfo.returnMode == SFRM_ValuePerCall)
1011 * Check for end of result set.
1013 * Note: if function returns an empty set, we don't build a
1014 * tupdesc or tuplestore (since we can't get a tupdesc in the
1015 * function-returning-tuple case)
1017 if (rsinfo.isDone == ExprEndResult)
1021 * If first time through, build tupdesc and tuplestore for
1026 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1027 if (funcrettype == RECORDOID ||
1028 get_typtype(funcrettype) == 'c')
1031 * Composite type, so function should have returned a
1032 * TupleTableSlot; use its descriptor
1034 slot = (TupleTableSlot *) DatumGetPointer(result);
1035 if (fcinfo.isnull ||
1037 !IsA(slot, TupleTableSlot) ||
1038 !slot->ttc_tupleDescriptor)
1039 elog(ERROR, "ExecMakeTableFunctionResult: Invalid result from function returning tuple");
1040 tupdesc = CreateTupleDescCopy(slot->ttc_tupleDescriptor);
1041 returnsTuple = true;
1046 * Scalar type, so make a single-column descriptor
1048 tupdesc = CreateTemplateTupleDesc(1, false);
1049 TupleDescInitEntry(tupdesc,
1057 tupstore = tuplestore_begin_heap(true, /* randomAccess */
1059 MemoryContextSwitchTo(oldcontext);
1060 rsinfo.setResult = tupstore;
1061 rsinfo.setDesc = tupdesc;
1065 * Store current resultset item.
1069 slot = (TupleTableSlot *) DatumGetPointer(result);
1070 if (fcinfo.isnull ||
1072 !IsA(slot, TupleTableSlot) ||
1074 elog(ERROR, "ExecMakeTableFunctionResult: Invalid result from function returning tuple");
1081 nullflag = fcinfo.isnull ? 'n' : ' ';
1082 tuple = heap_formtuple(tupdesc, &result, &nullflag);
1085 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1086 tuplestore_puttuple(tupstore, tuple);
1087 MemoryContextSwitchTo(oldcontext);
1092 if (rsinfo.isDone != ExprMultipleResult)
1095 else if (rsinfo.returnMode == SFRM_Materialize)
1097 /* check we're on the same page as the function author */
1098 if (!first_time || rsinfo.isDone != ExprSingleResult)
1099 elog(ERROR, "ExecMakeTableFunctionResult: Materialize-mode protocol not followed");
1100 /* Done evaluating the set result */
1104 elog(ERROR, "ExecMakeTableFunctionResult: unknown returnMode %d",
1105 (int) rsinfo.returnMode);
1110 MemoryContextSwitchTo(callerContext);
1112 /* The returned pointers are those in rsinfo */
1113 *returnDesc = rsinfo.setDesc;
1114 return rsinfo.setResult;
1118 /* ----------------------------------------------------------------
1123 * Evaluate the functional result of a list of arguments by calling the
1125 * ----------------------------------------------------------------
1128 /* ----------------------------------------------------------------
1130 * ----------------------------------------------------------------
1133 ExecEvalFunc(FuncExprState *fcache,
1134 ExprContext *econtext,
1136 ExprDoneCond *isDone)
1139 * Initialize function cache if first time through
1141 if (fcache->func.fn_oid == InvalidOid)
1143 FuncExpr *func = (FuncExpr *) fcache->xprstate.expr;
1145 init_fcache(func->funcid, fcache, econtext->ecxt_per_query_memory);
1148 return ExecMakeFunctionResult(fcache, econtext, isNull, isDone);
1151 /* ----------------------------------------------------------------
1153 * ----------------------------------------------------------------
1156 ExecEvalOper(FuncExprState *fcache,
1157 ExprContext *econtext,
1159 ExprDoneCond *isDone)
1162 * Initialize function cache if first time through
1164 if (fcache->func.fn_oid == InvalidOid)
1166 OpExpr *op = (OpExpr *) fcache->xprstate.expr;
1168 init_fcache(op->opfuncid, fcache, econtext->ecxt_per_query_memory);
1171 return ExecMakeFunctionResult(fcache, econtext, isNull, isDone);
1174 /* ----------------------------------------------------------------
1177 * IS DISTINCT FROM must evaluate arguments to determine whether
1178 * they are NULL; if either is NULL then the result is already
1179 * known. If neither is NULL, then proceed to evaluate the
1180 * function. Note that this is *always* derived from the equals
1181 * operator, but since we need special processing of the arguments
1182 * we can not simply reuse ExecEvalOper() or ExecEvalFunc().
1183 * ----------------------------------------------------------------
1186 ExecEvalDistinct(FuncExprState *fcache,
1187 ExprContext *econtext,
1191 FunctionCallInfoData fcinfo;
1192 ExprDoneCond argDone;
1196 * Initialize function cache if first time through
1198 if (fcache->func.fn_oid == InvalidOid)
1200 DistinctExpr *op = (DistinctExpr *) fcache->xprstate.expr;
1202 init_fcache(op->opfuncid, fcache, econtext->ecxt_per_query_memory);
1203 Assert(!fcache->func.fn_retset);
1207 * extract info from fcache
1209 argList = fcache->args;
1211 /* Need to prep callinfo structure */
1212 MemSet(&fcinfo, 0, sizeof(fcinfo));
1213 fcinfo.flinfo = &(fcache->func);
1214 argDone = ExecEvalFuncArgs(&fcinfo, argList, econtext);
1215 if (argDone != ExprSingleResult)
1216 elog(ERROR, "IS DISTINCT FROM does not support set arguments");
1217 Assert(fcinfo.nargs == 2);
1219 if (fcinfo.argnull[0] && fcinfo.argnull[1])
1221 /* Both NULL? Then is not distinct... */
1222 result = BoolGetDatum(FALSE);
1224 else if (fcinfo.argnull[0] || fcinfo.argnull[1])
1226 /* Only one is NULL? Then is distinct... */
1227 result = BoolGetDatum(TRUE);
1231 fcinfo.isnull = false;
1232 result = FunctionCallInvoke(&fcinfo);
1233 *isNull = fcinfo.isnull;
1234 /* Must invert result of "=" */
1235 result = BoolGetDatum(!DatumGetBool(result));
1241 /* ----------------------------------------------------------------
1246 * Evaluate boolean expressions, with appropriate short-circuiting.
1248 * The query planner reformulates clause expressions in the
1249 * qualification to conjunctive normal form. If we ever get
1250 * an AND to evaluate, we can be sure that it's not a top-level
1251 * clause in the qualification, but appears lower (as a function
1252 * argument, for example), or in the target list. Not that you
1253 * need to know this, mind you...
1254 * ----------------------------------------------------------------
1257 ExecEvalNot(BoolExprState *notclause, ExprContext *econtext, bool *isNull)
1262 clause = lfirst(notclause->args);
1264 expr_value = ExecEvalExpr(clause, econtext, isNull, NULL);
1267 * if the expression evaluates to null, then we just cascade the null
1268 * back to whoever called us.
1274 * evaluation of 'not' is simple.. expr is false, then return 'true'
1277 return BoolGetDatum(!DatumGetBool(expr_value));
1280 /* ----------------------------------------------------------------
1282 * ----------------------------------------------------------------
1285 ExecEvalOr(BoolExprState *orExpr, ExprContext *econtext, bool *isNull)
1292 clauses = orExpr->args;
1296 * If any of the clauses is TRUE, the OR result is TRUE regardless of
1297 * the states of the rest of the clauses, so we can stop evaluating
1298 * and return TRUE immediately. If none are TRUE and one or more is
1299 * NULL, we return NULL; otherwise we return FALSE. This makes sense
1300 * when you interpret NULL as "don't know": if we have a TRUE then the
1301 * OR is TRUE even if we aren't sure about some of the other inputs.
1302 * If all the known inputs are FALSE, but we have one or more "don't
1303 * knows", then we have to report that we "don't know" what the OR's
1304 * result should be --- perhaps one of the "don't knows" would have
1305 * been TRUE if we'd known its value. Only when all the inputs are
1306 * known to be FALSE can we state confidently that the OR's result is
1309 foreach(clause, clauses)
1311 clause_value = ExecEvalExpr((ExprState *) lfirst(clause),
1312 econtext, isNull, NULL);
1315 * if we have a non-null true result, then return it.
1318 AnyNull = true; /* remember we got a null */
1319 else if (DatumGetBool(clause_value))
1320 return clause_value;
1323 /* AnyNull is true if at least one clause evaluated to NULL */
1325 return BoolGetDatum(false);
1328 /* ----------------------------------------------------------------
1330 * ----------------------------------------------------------------
1333 ExecEvalAnd(BoolExprState *andExpr, ExprContext *econtext, bool *isNull)
1340 clauses = andExpr->args;
1344 * If any of the clauses is FALSE, the AND result is FALSE regardless
1345 * of the states of the rest of the clauses, so we can stop evaluating
1346 * and return FALSE immediately. If none are FALSE and one or more is
1347 * NULL, we return NULL; otherwise we return TRUE. This makes sense
1348 * when you interpret NULL as "don't know", using the same sort of
1349 * reasoning as for OR, above.
1351 foreach(clause, clauses)
1353 clause_value = ExecEvalExpr((ExprState *) lfirst(clause),
1354 econtext, isNull, NULL);
1357 * if we have a non-null false result, then return it.
1360 AnyNull = true; /* remember we got a null */
1361 else if (!DatumGetBool(clause_value))
1362 return clause_value;
1365 /* AnyNull is true if at least one clause evaluated to NULL */
1367 return BoolGetDatum(!AnyNull);
1371 /* ----------------------------------------------------------------
1374 * Evaluate a CASE clause. Will have boolean expressions
1375 * inside the WHEN clauses, and will have expressions
1377 * - thomas 1998-11-09
1378 * ----------------------------------------------------------------
1381 ExecEvalCase(CaseExprState *caseExpr, ExprContext *econtext,
1382 bool *isNull, ExprDoneCond *isDone)
1388 clauses = caseExpr->args;
1391 * we evaluate each of the WHEN clauses in turn, as soon as one is
1392 * true we return the corresponding result. If none are true then we
1393 * return the value of the default clause, or NULL if there is none.
1395 foreach(clause, clauses)
1397 CaseWhenState *wclause = lfirst(clause);
1399 clause_value = ExecEvalExpr(wclause->expr,
1405 * if we have a true test, then we return the result, since the
1406 * case statement is satisfied. A NULL result from the test is
1407 * not considered true.
1409 if (DatumGetBool(clause_value) && !*isNull)
1411 return ExecEvalExpr(wclause->result,
1418 if (caseExpr->defresult)
1420 return ExecEvalExpr(caseExpr->defresult,
1430 /* ----------------------------------------------------------------
1432 * ----------------------------------------------------------------
1435 ExecEvalCoalesce(CoalesceExprState *coalesceExpr, ExprContext *econtext,
1440 /* Simply loop through until something NOT NULL is found */
1441 foreach(arg, coalesceExpr->args)
1443 ExprState *e = (ExprState *) lfirst(arg);
1446 value = ExecEvalExpr(e, econtext, isNull, NULL);
1451 /* Else return NULL */
1456 /* ----------------------------------------------------------------
1459 * Note that this is *always* derived from the equals operator,
1460 * but since we need special processing of the arguments
1461 * we can not simply reuse ExecEvalOper() or ExecEvalFunc().
1462 * ----------------------------------------------------------------
1465 ExecEvalNullIf(FuncExprState *fcache, ExprContext *econtext,
1469 FunctionCallInfoData fcinfo;
1470 ExprDoneCond argDone;
1474 * Initialize function cache if first time through
1476 if (fcache->func.fn_oid == InvalidOid)
1478 NullIfExpr *op = (NullIfExpr *) fcache->xprstate.expr;
1480 init_fcache(op->opfuncid, fcache, econtext->ecxt_per_query_memory);
1481 Assert(!fcache->func.fn_retset);
1485 * extract info from fcache
1487 argList = fcache->args;
1489 /* Need to prep callinfo structure */
1490 MemSet(&fcinfo, 0, sizeof(fcinfo));
1491 fcinfo.flinfo = &(fcache->func);
1492 argDone = ExecEvalFuncArgs(&fcinfo, argList, econtext);
1493 if (argDone != ExprSingleResult)
1494 elog(ERROR, "NULLIF does not support set arguments");
1495 Assert(fcinfo.nargs == 2);
1497 /* if either argument is NULL they can't be equal */
1498 if (!fcinfo.argnull[0] && !fcinfo.argnull[1])
1500 fcinfo.isnull = false;
1501 result = FunctionCallInvoke(&fcinfo);
1502 /* if the arguments are equal return null */
1503 if (!fcinfo.isnull && DatumGetBool(result))
1510 /* else return first argument */
1511 *isNull = fcinfo.argnull[0];
1512 return fcinfo.arg[0];
1515 /* ----------------------------------------------------------------
1518 * Evaluate a NullTest node.
1519 * ----------------------------------------------------------------
1522 ExecEvalNullTest(GenericExprState *nstate,
1523 ExprContext *econtext,
1525 ExprDoneCond *isDone)
1527 NullTest *ntest = (NullTest *) nstate->xprstate.expr;
1530 result = ExecEvalExpr(nstate->arg, econtext, isNull, isDone);
1532 if (isDone && *isDone == ExprEndResult)
1533 return result; /* nothing to check */
1535 switch (ntest->nulltesttype)
1541 return BoolGetDatum(true);
1544 return BoolGetDatum(false);
1549 return BoolGetDatum(false);
1552 return BoolGetDatum(true);
1554 elog(ERROR, "ExecEvalNullTest: unexpected nulltesttype %d",
1555 (int) ntest->nulltesttype);
1556 return (Datum) 0; /* keep compiler quiet */
1560 /* ----------------------------------------------------------------
1561 * ExecEvalBooleanTest
1563 * Evaluate a BooleanTest node.
1564 * ----------------------------------------------------------------
1567 ExecEvalBooleanTest(GenericExprState *bstate,
1568 ExprContext *econtext,
1570 ExprDoneCond *isDone)
1572 BooleanTest *btest = (BooleanTest *) bstate->xprstate.expr;
1575 result = ExecEvalExpr(bstate->arg, econtext, isNull, isDone);
1577 if (isDone && *isDone == ExprEndResult)
1578 return result; /* nothing to check */
1580 switch (btest->booltesttype)
1586 return BoolGetDatum(false);
1588 else if (DatumGetBool(result))
1589 return BoolGetDatum(true);
1591 return BoolGetDatum(false);
1596 return BoolGetDatum(true);
1598 else if (DatumGetBool(result))
1599 return BoolGetDatum(false);
1601 return BoolGetDatum(true);
1606 return BoolGetDatum(false);
1608 else if (DatumGetBool(result))
1609 return BoolGetDatum(false);
1611 return BoolGetDatum(true);
1616 return BoolGetDatum(true);
1618 else if (DatumGetBool(result))
1619 return BoolGetDatum(true);
1621 return BoolGetDatum(false);
1626 return BoolGetDatum(true);
1629 return BoolGetDatum(false);
1630 case IS_NOT_UNKNOWN:
1634 return BoolGetDatum(false);
1637 return BoolGetDatum(true);
1639 elog(ERROR, "ExecEvalBooleanTest: unexpected booltesttype %d",
1640 (int) btest->booltesttype);
1641 return (Datum) 0; /* keep compiler quiet */
1646 * ExecEvalCoerceToDomain
1648 * Test the provided data against the domain constraint(s). If the data
1649 * passes the constraint specifications, pass it through (return the
1650 * datum) otherwise throw an error.
1653 ExecEvalCoerceToDomain(CoerceToDomainState *cstate, ExprContext *econtext,
1654 bool *isNull, ExprDoneCond *isDone)
1656 CoerceToDomain *ctest = (CoerceToDomain *) cstate->xprstate.expr;
1660 result = ExecEvalExpr(cstate->arg, econtext, isNull, isDone);
1662 if (isDone && *isDone == ExprEndResult)
1663 return result; /* nothing to check */
1665 foreach(l, cstate->constraints)
1667 DomainConstraintState *con = (DomainConstraintState *) lfirst(l);
1669 switch (con->constrainttype)
1671 case DOM_CONSTRAINT_NOTNULL:
1673 elog(ERROR, "Domain %s does not allow NULL values",
1674 format_type_be(ctest->resulttype));
1676 case DOM_CONSTRAINT_CHECK:
1684 * Set up value to be returned by CoerceToDomainValue nodes.
1685 * We must save and restore prior setting of econtext's
1686 * domainValue fields, in case this node is itself within
1687 * a check expression for another domain.
1689 save_datum = econtext->domainValue_datum;
1690 save_isNull = econtext->domainValue_isNull;
1692 econtext->domainValue_datum = result;
1693 econtext->domainValue_isNull = *isNull;
1695 conResult = ExecEvalExpr(con->check_expr,
1696 econtext, &conIsNull, NULL);
1699 !DatumGetBool(conResult))
1700 elog(ERROR, "ExecEvalCoerceToDomain: Domain %s constraint %s failed",
1701 format_type_be(ctest->resulttype), con->name);
1703 econtext->domainValue_datum = save_datum;
1704 econtext->domainValue_isNull = save_isNull;
1709 elog(ERROR, "ExecEvalCoerceToDomain: Constraint type unknown");
1714 /* If all has gone well (constraints did not fail) return the datum */
1719 * ExecEvalCoerceToDomainValue
1721 * Return the value stored by CoerceToDomain.
1724 ExecEvalCoerceToDomainValue(CoerceToDomainValue *conVal,
1725 ExprContext *econtext, bool *isNull)
1727 *isNull = econtext->domainValue_isNull;
1728 return econtext->domainValue_datum;
1731 /* ----------------------------------------------------------------
1732 * ExecEvalFieldSelect
1734 * Evaluate a FieldSelect node.
1735 * ----------------------------------------------------------------
1738 ExecEvalFieldSelect(GenericExprState *fstate,
1739 ExprContext *econtext,
1741 ExprDoneCond *isDone)
1743 FieldSelect *fselect = (FieldSelect *) fstate->xprstate.expr;
1745 TupleTableSlot *resSlot;
1747 result = ExecEvalExpr(fstate->arg, econtext, isNull, isDone);
1749 /* this test covers the isDone exception too: */
1753 resSlot = (TupleTableSlot *) DatumGetPointer(result);
1754 Assert(resSlot != NULL && IsA(resSlot, TupleTableSlot));
1755 result = heap_getattr(resSlot->val,
1757 resSlot->ttc_tupleDescriptor,
1762 /* ----------------------------------------------------------------
1765 * Recursively evaluate a targetlist or qualification expression.
1768 * expression: the expression state tree to evaluate
1769 * econtext: evaluation context information
1772 * return value: Datum value of result
1773 * *isNull: set to TRUE if result is NULL (actual return value is
1774 * meaningless if so); set to FALSE if non-null result
1775 * *isDone: set to indicator of set-result status
1777 * A caller that can only accept a singleton (non-set) result should pass
1778 * NULL for isDone; if the expression computes a set result then an elog()
1779 * error will be reported. If the caller does pass an isDone pointer then
1780 * *isDone is set to one of these three states:
1781 * ExprSingleResult singleton result (not a set)
1782 * ExprMultipleResult return value is one element of a set
1783 * ExprEndResult there are no more elements in the set
1784 * When ExprMultipleResult is returned, the caller should invoke
1785 * ExecEvalExpr() repeatedly until ExprEndResult is returned. ExprEndResult
1786 * is returned after the last real set element. For convenience isNull will
1787 * always be set TRUE when ExprEndResult is returned, but this should not be
1788 * taken as indicating a NULL element of the set. Note that these return
1789 * conventions allow us to distinguish among a singleton NULL, a NULL element
1790 * of a set, and an empty set.
1792 * The caller should already have switched into the temporary memory
1793 * context econtext->ecxt_per_tuple_memory. The convenience entry point
1794 * ExecEvalExprSwitchContext() is provided for callers who don't prefer to
1795 * do the switch in an outer loop. We do not do the switch here because
1796 * it'd be a waste of cycles during recursive entries to ExecEvalExpr().
1798 * This routine is an inner loop routine and must be as fast as possible.
1799 * ----------------------------------------------------------------
1802 ExecEvalExpr(ExprState *expression,
1803 ExprContext *econtext,
1805 ExprDoneCond *isDone)
1810 /* Set default values for result flags: non-null, not a set result */
1813 *isDone = ExprSingleResult;
1815 /* Is this still necessary? Doubtful... */
1816 if (expression == NULL)
1823 * here we dispatch the work to the appropriate type of function given
1824 * the type of our expression.
1826 expr = expression->expr;
1827 switch (nodeTag(expr))
1830 retDatum = ExecEvalVar((Var *) expr, econtext, isNull);
1834 Const *con = (Const *) expr;
1836 retDatum = con->constvalue;
1837 *isNull = con->constisnull;
1841 retDatum = ExecEvalParam((Param *) expr, econtext, isNull);
1844 retDatum = ExecEvalAggref((AggrefExprState *) expression,
1849 retDatum = ExecEvalArrayRef((ArrayRefExprState *) expression,
1855 retDatum = ExecEvalFunc((FuncExprState *) expression, econtext,
1859 retDatum = ExecEvalOper((FuncExprState *) expression, econtext,
1862 case T_DistinctExpr:
1863 retDatum = ExecEvalDistinct((FuncExprState *) expression, econtext,
1868 BoolExprState *state = (BoolExprState *) expression;
1870 switch (((BoolExpr *) expr)->boolop)
1873 retDatum = ExecEvalAnd(state, econtext, isNull);
1876 retDatum = ExecEvalOr(state, econtext, isNull);
1879 retDatum = ExecEvalNot(state, econtext, isNull);
1882 elog(ERROR, "ExecEvalExpr: unknown boolop %d",
1883 ((BoolExpr *) expr)->boolop);
1884 retDatum = 0; /* keep compiler quiet */
1890 retDatum = ExecSubPlan((SubPlanState *) expression,
1895 retDatum = ExecEvalFieldSelect((GenericExprState *) expression,
1901 retDatum = ExecEvalExpr(((GenericExprState *) expression)->arg,
1907 retDatum = ExecEvalCase((CaseExprState *) expression,
1912 case T_CoalesceExpr:
1913 retDatum = ExecEvalCoalesce((CoalesceExprState *) expression,
1918 retDatum = ExecEvalNullIf((FuncExprState *) expression,
1923 retDatum = ExecEvalNullTest((GenericExprState *) expression,
1929 retDatum = ExecEvalBooleanTest((GenericExprState *) expression,
1934 case T_CoerceToDomain:
1935 retDatum = ExecEvalCoerceToDomain((CoerceToDomainState *) expression,
1940 case T_CoerceToDomainValue:
1941 retDatum = ExecEvalCoerceToDomainValue((CoerceToDomainValue *) expr,
1946 elog(ERROR, "ExecEvalExpr: unknown expression type %d",
1947 nodeTag(expression));
1948 retDatum = 0; /* keep compiler quiet */
1953 } /* ExecEvalExpr() */
1957 * Same as above, but get into the right allocation context explicitly.
1960 ExecEvalExprSwitchContext(ExprState *expression,
1961 ExprContext *econtext,
1963 ExprDoneCond *isDone)
1966 MemoryContext oldContext;
1968 oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
1969 retDatum = ExecEvalExpr(expression, econtext, isNull, isDone);
1970 MemoryContextSwitchTo(oldContext);
1976 * ExecInitExpr: prepare an expression tree for execution
1978 * This function builds and returns an ExprState tree paralleling the given
1979 * Expr node tree. The ExprState tree can then be handed to ExecEvalExpr
1980 * for execution. Because the Expr tree itself is read-only as far as
1981 * ExecInitExpr and ExecEvalExpr are concerned, several different executions
1982 * of the same plan tree can occur concurrently.
1984 * This must be called in a memory context that will last as long as repeated
1985 * executions of the expression are needed. Typically the context will be
1986 * the same as the per-query context of the associated ExprContext.
1988 * Any Aggref and SubPlan nodes found in the tree are added to the lists
1989 * of such nodes held by the parent PlanState. Otherwise, we do very little
1990 * initialization here other than building the state-node tree. Any nontrivial
1991 * work associated with initializing runtime info for a node should happen
1992 * during the first actual evaluation of that node. (This policy lets us
1993 * avoid work if the node is never actually evaluated.)
1995 * Note: there is no ExecEndExpr function; we assume that any resource
1996 * cleanup needed will be handled by just releasing the memory context
1997 * in which the state tree is built. Functions that require additional
1998 * cleanup work can register a shutdown callback in the ExprContext.
2000 * 'node' is the root of the expression tree to examine
2001 * 'parent' is the PlanState node that owns the expression.
2003 * 'parent' may be NULL if we are preparing an expression that is not
2004 * associated with a plan tree. (If so, it can't have aggs or subplans.)
2005 * This case should usually come through ExecPrepareExpr, not directly here.
2008 ExecInitExpr(Expr *node, PlanState *parent)
2014 switch (nodeTag(node))
2019 case T_CoerceToDomainValue:
2020 /* No special setup needed for these node types */
2021 state = (ExprState *) makeNode(ExprState);
2025 Aggref *aggref = (Aggref *) node;
2026 AggrefExprState *astate = makeNode(AggrefExprState);
2028 if (parent && IsA(parent, AggState))
2030 AggState *aggstate = (AggState *) parent;
2033 aggstate->aggs = lcons(astate, aggstate->aggs);
2034 naggs = ++aggstate->numaggs;
2036 astate->target = ExecInitExpr(aggref->target, parent);
2039 * Complain if the aggregate's argument contains any
2040 * aggregates; nested agg functions are semantically
2041 * nonsensical. (This probably was caught earlier,
2042 * but we defend against it here anyway.)
2044 if (naggs != aggstate->numaggs)
2045 elog(ERROR, "Aggregate function calls may not be nested");
2048 elog(ERROR, "ExecInitExpr: Aggref not expected here");
2049 state = (ExprState *) astate;
2054 ArrayRef *aref = (ArrayRef *) node;
2055 ArrayRefExprState *astate = makeNode(ArrayRefExprState);
2057 astate->refupperindexpr = (List *)
2058 ExecInitExpr((Expr *) aref->refupperindexpr, parent);
2059 astate->reflowerindexpr = (List *)
2060 ExecInitExpr((Expr *) aref->reflowerindexpr, parent);
2061 astate->refexpr = ExecInitExpr(aref->refexpr, parent);
2062 astate->refassgnexpr = ExecInitExpr(aref->refassgnexpr,
2064 state = (ExprState *) astate;
2069 FuncExpr *funcexpr = (FuncExpr *) node;
2070 FuncExprState *fstate = makeNode(FuncExprState);
2072 fstate->args = (List *)
2073 ExecInitExpr((Expr *) funcexpr->args, parent);
2074 fstate->func.fn_oid = InvalidOid; /* not initialized */
2075 state = (ExprState *) fstate;
2080 OpExpr *opexpr = (OpExpr *) node;
2081 FuncExprState *fstate = makeNode(FuncExprState);
2083 fstate->args = (List *)
2084 ExecInitExpr((Expr *) opexpr->args, parent);
2085 fstate->func.fn_oid = InvalidOid; /* not initialized */
2086 state = (ExprState *) fstate;
2089 case T_DistinctExpr:
2091 DistinctExpr *distinctexpr = (DistinctExpr *) node;
2092 FuncExprState *fstate = makeNode(FuncExprState);
2094 fstate->args = (List *)
2095 ExecInitExpr((Expr *) distinctexpr->args, parent);
2096 fstate->func.fn_oid = InvalidOid; /* not initialized */
2097 state = (ExprState *) fstate;
2102 BoolExpr *boolexpr = (BoolExpr *) node;
2103 BoolExprState *bstate = makeNode(BoolExprState);
2105 bstate->args = (List *)
2106 ExecInitExpr((Expr *) boolexpr->args, parent);
2107 state = (ExprState *) bstate;
2112 /* Keep this in sync with ExecInitExprInitPlan, below */
2113 SubPlan *subplan = (SubPlan *) node;
2114 SubPlanState *sstate = makeNode(SubPlanState);
2117 elog(ERROR, "ExecInitExpr: SubPlan not expected here");
2120 * Here we just add the SubPlanState nodes to
2121 * parent->subPlan. The subplans will be initialized later.
2123 parent->subPlan = lcons(sstate, parent->subPlan);
2124 sstate->sub_estate = NULL;
2125 sstate->planstate = NULL;
2127 sstate->exprs = (List *)
2128 ExecInitExpr((Expr *) subplan->exprs, parent);
2129 sstate->args = (List *)
2130 ExecInitExpr((Expr *) subplan->args, parent);
2132 state = (ExprState *) sstate;
2137 FieldSelect *fselect = (FieldSelect *) node;
2138 GenericExprState *gstate = makeNode(GenericExprState);
2140 gstate->arg = ExecInitExpr(fselect->arg, parent);
2141 state = (ExprState *) gstate;
2146 RelabelType *relabel = (RelabelType *) node;
2147 GenericExprState *gstate = makeNode(GenericExprState);
2149 gstate->arg = ExecInitExpr(relabel->arg, parent);
2150 state = (ExprState *) gstate;
2155 CaseExpr *caseexpr = (CaseExpr *) node;
2156 CaseExprState *cstate = makeNode(CaseExprState);
2157 List *outlist = NIL;
2160 foreach(inlist, caseexpr->args)
2162 CaseWhen *when = (CaseWhen *) lfirst(inlist);
2163 CaseWhenState *wstate = makeNode(CaseWhenState);
2165 Assert(IsA(when, CaseWhen));
2166 wstate->xprstate.expr = (Expr *) when;
2167 wstate->expr = ExecInitExpr(when->expr, parent);
2168 wstate->result = ExecInitExpr(when->result, parent);
2169 outlist = lappend(outlist, wstate);
2171 cstate->args = outlist;
2172 /* caseexpr->arg should be null by now */
2173 Assert(caseexpr->arg == NULL);
2174 cstate->defresult = ExecInitExpr(caseexpr->defresult, parent);
2175 state = (ExprState *) cstate;
2178 case T_CoalesceExpr:
2180 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
2181 CoalesceExprState *cstate = makeNode(CoalesceExprState);
2182 List *outlist = NIL;
2185 foreach(inlist, coalesceexpr->args)
2187 Expr *e = (Expr *) lfirst(inlist);
2190 estate = ExecInitExpr(e, parent);
2191 outlist = lappend(outlist, estate);
2193 cstate->args = outlist;
2194 state = (ExprState *) cstate;
2199 NullIfExpr *nullifexpr = (NullIfExpr *) node;
2200 FuncExprState *fstate = makeNode(FuncExprState);
2202 fstate->args = (List *)
2203 ExecInitExpr((Expr *) nullifexpr->args, parent);
2204 fstate->func.fn_oid = InvalidOid; /* not initialized */
2205 state = (ExprState *) fstate;
2210 NullTest *ntest = (NullTest *) node;
2211 GenericExprState *gstate = makeNode(GenericExprState);
2213 gstate->arg = ExecInitExpr(ntest->arg, parent);
2214 state = (ExprState *) gstate;
2219 BooleanTest *btest = (BooleanTest *) node;
2220 GenericExprState *gstate = makeNode(GenericExprState);
2222 gstate->arg = ExecInitExpr(btest->arg, parent);
2223 state = (ExprState *) gstate;
2226 case T_CoerceToDomain:
2228 CoerceToDomain *ctest = (CoerceToDomain *) node;
2229 CoerceToDomainState *cstate = makeNode(CoerceToDomainState);
2231 cstate->arg = ExecInitExpr(ctest->arg, parent);
2232 cstate->constraints = GetDomainConstraints(ctest->resulttype);
2233 state = (ExprState *) cstate;
2238 TargetEntry *tle = (TargetEntry *) node;
2239 GenericExprState *gstate = makeNode(GenericExprState);
2241 gstate->arg = ExecInitExpr(tle->expr, parent);
2242 state = (ExprState *) gstate;
2247 List *outlist = NIL;
2250 foreach(inlist, (List *) node)
2252 outlist = lappend(outlist,
2253 ExecInitExpr((Expr *) lfirst(inlist),
2256 /* Don't fall through to the "common" code below */
2257 return (ExprState *) outlist;
2260 elog(ERROR, "ExecInitExpr: unknown expression type %d",
2262 state = NULL; /* keep compiler quiet */
2266 /* Common code for all state-node types */
2273 * ExecInitExprInitPlan --- initialize a subplan expr that's being handled
2274 * as an InitPlan. This is identical to ExecInitExpr's handling of a regular
2275 * subplan expr, except we do NOT want to add the node to the parent's
2279 ExecInitExprInitPlan(SubPlan *node, PlanState *parent)
2281 SubPlanState *sstate = makeNode(SubPlanState);
2284 elog(ERROR, "ExecInitExpr: SubPlan not expected here");
2286 /* The subplan's state will be initialized later */
2287 sstate->sub_estate = NULL;
2288 sstate->planstate = NULL;
2290 sstate->exprs = (List *) ExecInitExpr((Expr *) node->exprs, parent);
2291 sstate->args = (List *) ExecInitExpr((Expr *) node->args, parent);
2293 sstate->xprstate.expr = (Expr *) node;
2299 * ExecPrepareExpr --- initialize for expression execution outside a normal
2300 * Plan tree context.
2302 * This differs from ExecInitExpr in that we don't assume the caller is
2303 * already running in the EState's per-query context. Also, we apply
2304 * fix_opfuncids() to the passed expression tree to be sure it is ready
2305 * to run. (In ordinary Plan trees the planner will have fixed opfuncids,
2306 * but callers outside the executor will not have done this.)
2309 ExecPrepareExpr(Expr *node, EState *estate)
2312 MemoryContext oldcontext;
2314 fix_opfuncids((Node *) node);
2316 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2318 result = ExecInitExpr(node, NULL);
2320 MemoryContextSwitchTo(oldcontext);
2326 /* ----------------------------------------------------------------
2327 * ExecQual / ExecTargetList / ExecProject
2328 * ----------------------------------------------------------------
2331 /* ----------------------------------------------------------------
2334 * Evaluates a conjunctive boolean expression (qual list) and
2335 * returns true iff none of the subexpressions are false.
2336 * (We also return true if the list is empty.)
2338 * If some of the subexpressions yield NULL but none yield FALSE,
2339 * then the result of the conjunction is NULL (ie, unknown)
2340 * according to three-valued boolean logic. In this case,
2341 * we return the value specified by the "resultForNull" parameter.
2343 * Callers evaluating WHERE clauses should pass resultForNull=FALSE,
2344 * since SQL specifies that tuples with null WHERE results do not
2345 * get selected. On the other hand, callers evaluating constraint
2346 * conditions should pass resultForNull=TRUE, since SQL also specifies
2347 * that NULL constraint conditions are not failures.
2349 * NOTE: it would not be correct to use this routine to evaluate an
2350 * AND subclause of a boolean expression; for that purpose, a NULL
2351 * result must be returned as NULL so that it can be properly treated
2352 * in the next higher operator (cf. ExecEvalAnd and ExecEvalOr).
2353 * This routine is only used in contexts where a complete expression
2354 * is being evaluated and we know that NULL can be treated the same
2355 * as one boolean result or the other.
2357 * ----------------------------------------------------------------
2360 ExecQual(List *qual, ExprContext *econtext, bool resultForNull)
2363 MemoryContext oldContext;
2369 EV_printf("ExecQual: qual is ");
2370 EV_nodeDisplay(qual);
2376 * Run in short-lived per-tuple context while computing expressions.
2378 oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
2381 * Evaluate the qual conditions one at a time. If we find a FALSE
2382 * result, we can stop evaluating and return FALSE --- the AND result
2383 * must be FALSE. Also, if we find a NULL result when resultForNull
2384 * is FALSE, we can stop and return FALSE --- the AND result must be
2385 * FALSE or NULL in that case, and the caller doesn't care which.
2387 * If we get to the end of the list, we can return TRUE. This will
2388 * happen when the AND result is indeed TRUE, or when the AND result
2389 * is NULL (one or more NULL subresult, with all the rest TRUE) and
2390 * the caller has specified resultForNull = TRUE.
2394 foreach(qlist, qual)
2396 ExprState *clause = (ExprState *) lfirst(qlist);
2400 expr_value = ExecEvalExpr(clause, econtext, &isNull, NULL);
2404 if (resultForNull == false)
2406 result = false; /* treat NULL as FALSE */
2412 if (!DatumGetBool(expr_value))
2414 result = false; /* definitely FALSE */
2420 MemoryContextSwitchTo(oldContext);
2426 * Number of items in a tlist (including any resjunk items!)
2429 ExecTargetListLength(List *targetlist)
2431 /* This used to be more complex, but fjoins are dead */
2432 return length(targetlist);
2436 * Number of items in a tlist, not including any resjunk items
2439 ExecCleanTargetListLength(List *targetlist)
2444 foreach(tl, targetlist)
2446 TargetEntry *curTle = (TargetEntry *) lfirst(tl);
2448 Assert(IsA(curTle, TargetEntry));
2449 if (!curTle->resdom->resjunk)
2455 /* ----------------------------------------------------------------
2458 * Evaluates a targetlist with respect to the given
2459 * expression context and returns a tuple.
2461 * The caller must pass workspace for the values and nulls arrays
2462 * as well as the itemIsDone array. This convention saves palloc'ing
2463 * workspace on each call, and some callers may find it useful to examine
2464 * the values array directly.
2466 * As with ExecEvalExpr, the caller should pass isDone = NULL if not
2467 * prepared to deal with sets of result tuples. Otherwise, a return
2468 * of *isDone = ExprMultipleResult signifies a set element, and a return
2469 * of *isDone = ExprEndResult signifies end of the set of tuple.
2470 * ----------------------------------------------------------------
2473 ExecTargetList(List *targetlist,
2474 TupleDesc targettype,
2475 ExprContext *econtext,
2478 ExprDoneCond *itemIsDone,
2479 ExprDoneCond *isDone)
2481 MemoryContext oldContext;
2485 static struct tupleDesc NullTupleDesc; /* we assume this inits to
2491 EV_printf("ExecTargetList: tl is ");
2492 EV_nodeDisplay(targetlist);
2496 * Run in short-lived per-tuple context while computing expressions.
2498 oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
2501 * There used to be some klugy and demonstrably broken code here that
2502 * special-cased the situation where targetlist == NIL. Now we just
2503 * fall through and return an empty-but-valid tuple. We do, however,
2504 * have to cope with the possibility that targettype is NULL ---
2505 * heap_formtuple won't like that, so pass a dummy descriptor with
2506 * natts = 0 to deal with it.
2508 if (targettype == NULL)
2509 targettype = &NullTupleDesc;
2512 * evaluate all the expressions in the target list
2515 *isDone = ExprSingleResult; /* until proven otherwise */
2517 haveDoneSets = false; /* any exhausted set exprs in tlist? */
2519 foreach(tl, targetlist)
2521 GenericExprState *gstate = (GenericExprState *) lfirst(tl);
2522 TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr;
2523 AttrNumber resind = tle->resdom->resno - 1;
2525 values[resind] = ExecEvalExpr(gstate->arg,
2528 &itemIsDone[resind]);
2529 nulls[resind] = isNull ? 'n' : ' ';
2531 if (itemIsDone[resind] != ExprSingleResult)
2533 /* We have a set-valued expression in the tlist */
2535 elog(ERROR, "Set-valued function called in context that cannot accept a set");
2536 if (itemIsDone[resind] == ExprMultipleResult)
2538 /* we have undone sets in the tlist, set flag */
2539 *isDone = ExprMultipleResult;
2543 /* we have done sets in the tlist, set flag for that */
2544 haveDoneSets = true;
2552 * note: can't get here unless we verified isDone != NULL
2554 if (*isDone == ExprSingleResult)
2557 * all sets are done, so report that tlist expansion is
2560 *isDone = ExprEndResult;
2561 MemoryContextSwitchTo(oldContext);
2567 * We have some done and some undone sets. Restart the done
2568 * ones so that we can deliver a tuple (if possible).
2570 foreach(tl, targetlist)
2572 GenericExprState *gstate = (GenericExprState *) lfirst(tl);
2573 TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr;
2574 AttrNumber resind = tle->resdom->resno - 1;
2576 if (itemIsDone[resind] == ExprEndResult)
2578 values[resind] = ExecEvalExpr(gstate->arg,
2581 &itemIsDone[resind]);
2582 nulls[resind] = isNull ? 'n' : ' ';
2584 if (itemIsDone[resind] == ExprEndResult)
2587 * Oh dear, this item is returning an empty
2588 * set. Guess we can't make a tuple after all.
2590 *isDone = ExprEndResult;
2597 * If we cannot make a tuple because some sets are empty, we
2598 * still have to cycle the nonempty sets to completion, else
2599 * resources will not be released from subplans etc.
2601 * XXX is that still necessary?
2603 if (*isDone == ExprEndResult)
2605 foreach(tl, targetlist)
2607 GenericExprState *gstate = (GenericExprState *) lfirst(tl);
2608 TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr;
2609 AttrNumber resind = tle->resdom->resno - 1;
2611 while (itemIsDone[resind] == ExprMultipleResult)
2613 (void) ExecEvalExpr(gstate->arg,
2616 &itemIsDone[resind]);
2620 MemoryContextSwitchTo(oldContext);
2627 * form the new result tuple (in the caller's memory context!)
2629 MemoryContextSwitchTo(oldContext);
2631 return heap_formtuple(targettype, values, nulls);
2634 /* ----------------------------------------------------------------
2637 * projects a tuple based on projection info and stores
2638 * it in the specified tuple table slot.
2640 * Note: someday soon the executor can be extended to eliminate
2641 * redundant projections by storing pointers to datums
2642 * in the tuple table and then passing these around when
2643 * possible. this should make things much quicker.
2645 * ----------------------------------------------------------------
2648 ExecProject(ProjectionInfo *projInfo, ExprDoneCond *isDone)
2650 TupleTableSlot *slot;
2657 if (projInfo == NULL)
2658 return (TupleTableSlot *) NULL;
2661 * get the projection info we want
2663 slot = projInfo->pi_slot;
2664 tupType = slot->ttc_tupleDescriptor;
2667 * form a new result tuple (if possible --- result can be NULL)
2669 newTuple = ExecTargetList(projInfo->pi_targetlist,
2671 projInfo->pi_exprContext,
2672 projInfo->pi_tupValues,
2673 projInfo->pi_tupNulls,
2674 projInfo->pi_itemIsDone,
2678 * store the tuple in the projection slot and return the slot.
2680 return ExecStoreTuple(newTuple, /* tuple to store */
2681 slot, /* slot to store in */
2682 InvalidBuffer, /* tuple has no buffer */