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.121 2002/12/15 16:17:45 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 "executor/execdebug.h"
40 #include "executor/functions.h"
41 #include "executor/nodeSubplan.h"
42 #include "miscadmin.h"
43 #include "optimizer/planmain.h"
44 #include "parser/parse_expr.h"
45 #include "utils/acl.h"
46 #include "utils/array.h"
47 #include "utils/builtins.h"
48 #include "utils/lsyscache.h"
51 /* static function decls */
52 static Datum ExecEvalAggref(AggrefExprState *aggref,
53 ExprContext *econtext,
55 static Datum ExecEvalArrayRef(ArrayRefExprState *astate,
56 ExprContext *econtext,
57 bool *isNull, ExprDoneCond *isDone);
58 static Datum ExecEvalVar(Var *variable, ExprContext *econtext, bool *isNull);
59 static Datum ExecEvalParam(Param *expression, ExprContext *econtext,
61 static Datum ExecEvalFunc(FuncExprState *fcache, ExprContext *econtext,
62 bool *isNull, ExprDoneCond *isDone);
63 static Datum ExecEvalOper(FuncExprState *fcache, ExprContext *econtext,
64 bool *isNull, ExprDoneCond *isDone);
65 static Datum ExecEvalDistinct(FuncExprState *fcache, ExprContext *econtext,
66 bool *isNull, ExprDoneCond *isDone);
67 static ExprDoneCond ExecEvalFuncArgs(FunctionCallInfo fcinfo,
68 List *argList, ExprContext *econtext);
69 static Datum ExecEvalNot(BoolExprState *notclause, ExprContext *econtext,
71 static Datum ExecEvalOr(BoolExprState *orExpr, ExprContext *econtext,
73 static Datum ExecEvalAnd(BoolExprState *andExpr, ExprContext *econtext,
75 static Datum ExecEvalCase(CaseExprState *caseExpr, ExprContext *econtext,
76 bool *isNull, ExprDoneCond *isDone);
77 static Datum ExecEvalNullTest(GenericExprState *nstate,
78 ExprContext *econtext,
79 bool *isNull, ExprDoneCond *isDone);
80 static Datum ExecEvalBooleanTest(GenericExprState *bstate,
81 ExprContext *econtext,
82 bool *isNull, ExprDoneCond *isDone);
83 static Datum ExecEvalConstraintTest(ConstraintTestState *cstate,
84 ExprContext *econtext,
85 bool *isNull, ExprDoneCond *isDone);
86 static Datum ExecEvalConstraintTestValue(ConstraintTestValue *conVal,
87 ExprContext *econtext, bool *isNull);
88 static Datum ExecEvalFieldSelect(GenericExprState *fstate,
89 ExprContext *econtext,
90 bool *isNull, ExprDoneCond *isDone);
96 * This function takes an ArrayRef and returns the extracted Datum
97 * if it's a simple reference, or the modified array value if it's
98 * an array assignment (i.e., array element or slice insertion).
100 * NOTE: if we get a NULL result from a subexpression, we return NULL when
101 * it's an array reference, or the unmodified source array when it's an
102 * array assignment. This may seem peculiar, but if we return NULL (as was
103 * done in versions up through 7.0) then an assignment like
104 * UPDATE table SET arrayfield[4] = NULL
105 * will result in setting the whole array to NULL, which is certainly not
106 * very desirable. By returning the source array we make the assignment
107 * into a no-op, instead. (Eventually we need to redesign arrays so that
108 * individual elements can be NULL, but for now, let's try to protect users
109 * from shooting themselves in the foot.)
111 * NOTE: we deliberately refrain from applying DatumGetArrayTypeP() here,
112 * even though that might seem natural, because this code needs to support
113 * both varlena arrays and fixed-length array types. DatumGetArrayTypeP()
114 * only works for the varlena kind. The routines we call in arrayfuncs.c
115 * have to know the difference (that's what they need refattrlength for).
119 ExecEvalArrayRef(ArrayRefExprState *astate,
120 ExprContext *econtext,
122 ExprDoneCond *isDone)
124 ArrayRef *arrayRef = (ArrayRef *) astate->xprstate.expr;
125 ArrayType *array_source;
126 ArrayType *resultArray;
127 bool isAssignment = (arrayRef->refassgnexpr != NULL);
135 if (arrayRef->refexpr != NULL)
137 array_source = (ArrayType *)
138 DatumGetPointer(ExecEvalExpr(astate->refexpr,
144 * If refexpr yields NULL, result is always NULL, for now anyway.
145 * (This means you cannot assign to an element or slice of an
146 * array that's NULL; it'll just stay NULL.)
154 * Empty refexpr indicates we are doing an INSERT into an array
155 * column. For now, we just take the refassgnexpr (which the
156 * parser will have ensured is an array value) and return it
157 * as-is, ignoring any subscripts that may have been supplied in
158 * the INSERT column list. This is a kluge, but it's not real
159 * clear what the semantics ought to be...
164 foreach(elt, astate->refupperindexpr)
167 elog(ERROR, "ExecEvalArrayRef: can only handle %d dimensions",
170 upper.indx[i++] = DatumGetInt32(ExecEvalExpr((ExprState *) lfirst(elt),
174 /* If any index expr yields NULL, result is NULL or source array */
177 if (!isAssignment || array_source == NULL)
180 return PointerGetDatum(array_source);
184 if (astate->reflowerindexpr != NIL)
186 foreach(elt, astate->reflowerindexpr)
189 elog(ERROR, "ExecEvalArrayRef: can only handle %d dimensions",
192 lower.indx[j++] = DatumGetInt32(ExecEvalExpr((ExprState *) lfirst(elt),
198 * If any index expr yields NULL, result is NULL or source
203 if (!isAssignment || array_source == NULL)
206 return PointerGetDatum(array_source);
211 "ExecEvalArrayRef: upper and lower indices mismatch");
219 Datum sourceData = ExecEvalExpr(astate->refassgnexpr,
225 * For now, can't cope with inserting NULL into an array, so make
226 * it a no-op per discussion above...
230 if (array_source == NULL)
233 return PointerGetDatum(array_source);
236 if (array_source == NULL)
237 return sourceData; /* XXX do something else? */
240 resultArray = array_set(array_source, i,
243 arrayRef->refattrlength,
244 arrayRef->refelemlength,
245 arrayRef->refelembyval,
246 arrayRef->refelemalign,
249 resultArray = array_set_slice(array_source, i,
250 upper.indx, lower.indx,
251 (ArrayType *) DatumGetPointer(sourceData),
252 arrayRef->refattrlength,
253 arrayRef->refelemlength,
254 arrayRef->refelembyval,
255 arrayRef->refelemalign,
257 return PointerGetDatum(resultArray);
261 return array_ref(array_source, i, upper.indx,
262 arrayRef->refattrlength,
263 arrayRef->refelemlength,
264 arrayRef->refelembyval,
265 arrayRef->refelemalign,
269 resultArray = array_get_slice(array_source, i,
270 upper.indx, lower.indx,
271 arrayRef->refattrlength,
272 arrayRef->refelemlength,
273 arrayRef->refelembyval,
274 arrayRef->refelemalign,
276 return PointerGetDatum(resultArray);
281 /* ----------------------------------------------------------------
284 * Returns a Datum whose value is the value of the precomputed
285 * aggregate found in the given expression context.
286 * ----------------------------------------------------------------
289 ExecEvalAggref(AggrefExprState *aggref, ExprContext *econtext, bool *isNull)
291 if (econtext->ecxt_aggvalues == NULL) /* safety check */
292 elog(ERROR, "ExecEvalAggref: no aggregates in this expression context");
294 *isNull = econtext->ecxt_aggnulls[aggref->aggno];
295 return econtext->ecxt_aggvalues[aggref->aggno];
298 /* ----------------------------------------------------------------
301 * Returns a Datum whose value is the value of a range
302 * variable with respect to given expression context.
305 * As an entry condition, we expect that the datatype the
306 * plan expects to get (as told by our "variable" argument) is in
307 * fact the datatype of the attribute the plan says to fetch (as
308 * seen in the current context, identified by our "econtext"
311 * If we fetch a Type A attribute and Caller treats it as if it
312 * were Type B, there will be undefined results (e.g. crash).
313 * One way these might mismatch now is that we're accessing a
314 * catalog class and the type information in the pg_attribute
315 * class does not match the hardcoded pg_attribute information
316 * (in pg_attribute.h) for the class in question.
318 * We have an Assert to make sure this entry condition is met.
320 * ---------------------------------------------------------------- */
322 ExecEvalVar(Var *variable, ExprContext *econtext, bool *isNull)
325 TupleTableSlot *slot;
328 TupleDesc tuple_type;
331 * get the slot we want
333 switch (variable->varno)
335 case INNER: /* get the tuple from the inner node */
336 slot = econtext->ecxt_innertuple;
339 case OUTER: /* get the tuple from the outer node */
340 slot = econtext->ecxt_outertuple;
343 default: /* get the tuple from the relation being
345 slot = econtext->ecxt_scantuple;
350 * extract tuple information from the slot
352 heapTuple = slot->val;
353 tuple_type = slot->ttc_tupleDescriptor;
355 attnum = variable->varattno;
357 /* (See prolog for explanation of this Assert) */
358 Assert(attnum <= 0 ||
359 (attnum - 1 <= tuple_type->natts - 1 &&
360 tuple_type->attrs[attnum - 1] != NULL &&
361 variable->vartype == tuple_type->attrs[attnum - 1]->atttypid));
364 * If the attribute number is invalid, then we are supposed to return
365 * the entire tuple; we give back a whole slot so that callers know
366 * what the tuple looks like.
368 * XXX this is a horrid crock: since the pointer to the slot might live
369 * longer than the current evaluation context, we are forced to copy
370 * the tuple and slot into a long-lived context --- we use
371 * TransactionCommandContext which should be safe enough. This
372 * represents a serious memory leak if many such tuples are processed
373 * in one command, however. We ought to redesign the representation
374 * of whole-tuple datums so that this is not necessary.
376 * We assume it's OK to point to the existing tupleDescriptor, rather
377 * than copy that too.
379 if (attnum == InvalidAttrNumber)
381 MemoryContext oldContext;
382 TupleTableSlot *tempSlot;
385 oldContext = MemoryContextSwitchTo(TransactionCommandContext);
386 tempSlot = MakeTupleTableSlot();
387 tup = heap_copytuple(heapTuple);
388 ExecStoreTuple(tup, tempSlot, InvalidBuffer, true);
389 ExecSetSlotDescriptor(tempSlot, tuple_type, false);
390 MemoryContextSwitchTo(oldContext);
391 return PointerGetDatum(tempSlot);
394 result = heap_getattr(heapTuple, /* tuple containing attribute */
395 attnum, /* attribute number of desired
397 tuple_type, /* tuple descriptor of tuple */
398 isNull); /* return: is attribute null? */
403 /* ----------------------------------------------------------------
406 * Returns the value of a parameter. A param node contains
407 * something like ($.name) and the expression context contains
408 * the current parameter bindings (name = "sam") (age = 34)...
409 * so our job is to find and return the appropriate datum ("sam").
411 * Q: if we have a parameter ($.foo) without a binding, i.e.
412 * there is no (foo = xxx) in the parameter list info,
413 * is this a fatal error or should this be a "not available"
414 * (in which case we could return NULL)? -cim 10/13/89
415 * ----------------------------------------------------------------
418 ExecEvalParam(Param *expression, ExprContext *econtext, bool *isNull)
420 int thisParamKind = expression->paramkind;
421 AttrNumber thisParamId = expression->paramid;
423 if (thisParamKind == PARAM_EXEC)
426 * PARAM_EXEC params (internal executor parameters) are stored in
427 * the ecxt_param_exec_vals array, and can be accessed by array index.
431 prm = &(econtext->ecxt_param_exec_vals[thisParamId]);
432 if (prm->execPlan != NULL)
434 /* Parameter not evaluated yet, so go do it */
435 ExecSetParamPlan(prm->execPlan, econtext);
436 /* ExecSetParamPlan should have processed this param... */
437 Assert(prm->execPlan == NULL);
439 *isNull = prm->isnull;
445 * All other parameter types must be sought in ecxt_param_list_info.
446 * NOTE: The last entry in the param array is always an
447 * entry with kind == PARAM_INVALID.
449 ParamListInfo paramList = econtext->ecxt_param_list_info;
450 char *thisParamName = expression->paramname;
451 bool matchFound = false;
453 if (paramList != NULL)
455 while (paramList->kind != PARAM_INVALID && !matchFound)
457 if (thisParamKind == paramList->kind)
459 switch (thisParamKind)
462 if (strcmp(paramList->name, thisParamName) == 0)
466 if (paramList->id == thisParamId)
470 elog(ERROR, "ExecEvalParam: invalid paramkind %d",
481 if (thisParamKind == PARAM_NAMED)
482 elog(ERROR, "ExecEvalParam: Unknown value for parameter %s",
485 elog(ERROR, "ExecEvalParam: Unknown value for parameter %d",
489 *isNull = paramList->isnull;
490 return paramList->value;
495 /* ----------------------------------------------------------------
496 * ExecEvalOper / ExecEvalFunc support routines
497 * ----------------------------------------------------------------
504 * These are functions which return the value of the
505 * named attribute out of the tuple from the arg slot. User defined
506 * C functions which take a tuple as an argument are expected
507 * to use this. Ex: overpaid(EMP) might call GetAttributeByNum().
510 GetAttributeByNum(TupleTableSlot *slot,
516 if (!AttributeNumberIsValid(attrno))
517 elog(ERROR, "GetAttributeByNum: Invalid attribute number");
519 if (!AttrNumberIsForUserDefinedAttr(attrno))
520 elog(ERROR, "GetAttributeByNum: cannot access system attributes here");
522 if (isNull == (bool *) NULL)
523 elog(ERROR, "GetAttributeByNum: a NULL isNull flag was passed");
531 retval = heap_getattr(slot->val,
533 slot->ttc_tupleDescriptor,
542 GetAttributeByName(TupleTableSlot *slot, char *attname, bool *isNull)
551 elog(ERROR, "GetAttributeByName: Invalid attribute name");
553 if (isNull == (bool *) NULL)
554 elog(ERROR, "GetAttributeByName: a NULL isNull flag was passed");
562 tupdesc = slot->ttc_tupleDescriptor;
563 natts = slot->val->t_data->t_natts;
565 attrno = InvalidAttrNumber;
566 for (i = 0; i < tupdesc->natts; i++)
568 if (namestrcmp(&(tupdesc->attrs[i]->attname), attname) == 0)
570 attrno = tupdesc->attrs[i]->attnum;
575 if (attrno == InvalidAttrNumber)
576 elog(ERROR, "GetAttributeByName: attribute %s not found", attname);
578 retval = heap_getattr(slot->val,
589 * init_fcache - initialize a FuncExprState node during first use
592 init_fcache(Oid foid, FuncExprState *fcache, MemoryContext fcacheCxt)
596 /* Check permission to call function */
597 aclresult = pg_proc_aclcheck(foid, GetUserId(), ACL_EXECUTE);
598 if (aclresult != ACLCHECK_OK)
599 aclcheck_error(aclresult, get_func_name(foid));
601 /* Safety check (should never fail, as parser should check sooner) */
602 if (length(fcache->args) > FUNC_MAX_ARGS)
603 elog(ERROR, "init_fcache: too many arguments");
605 /* Set up the primary fmgr lookup information */
606 fmgr_info_cxt(foid, &(fcache->func), fcacheCxt);
608 /* Initialize additional info */
609 fcache->setArgsValid = false;
613 * Evaluate arguments for a function.
616 ExecEvalFuncArgs(FunctionCallInfo fcinfo,
618 ExprContext *econtext)
620 ExprDoneCond argIsDone;
624 argIsDone = ExprSingleResult; /* default assumption */
627 foreach(arg, argList)
629 ExprDoneCond thisArgIsDone;
631 fcinfo->arg[i] = ExecEvalExpr((ExprState *) lfirst(arg),
636 if (thisArgIsDone != ExprSingleResult)
639 * We allow only one argument to have a set value; we'd need
640 * much more complexity to keep track of multiple set
641 * arguments (cf. ExecTargetList) and it doesn't seem worth
644 if (argIsDone != ExprSingleResult)
645 elog(ERROR, "Functions and operators can take only one set argument");
646 argIsDone = thisArgIsDone;
657 * ExecMakeFunctionResult
659 * Evaluate the arguments to a function and then the function itself.
662 ExecMakeFunctionResult(FuncExprState *fcache,
663 ExprContext *econtext,
665 ExprDoneCond *isDone)
667 List *arguments = fcache->args;
669 FunctionCallInfoData fcinfo;
670 ReturnSetInfo rsinfo; /* for functions returning sets */
671 ExprDoneCond argDone;
676 * arguments is a list of expressions to evaluate before passing to
677 * the function manager. We skip the evaluation if it was already
678 * done in the previous call (ie, we are continuing the evaluation of
679 * a set-valued function). Otherwise, collect the current argument
680 * values into fcinfo.
682 if (!fcache->setArgsValid)
684 /* Need to prep callinfo structure */
685 MemSet(&fcinfo, 0, sizeof(fcinfo));
686 fcinfo.flinfo = &(fcache->func);
687 argDone = ExecEvalFuncArgs(&fcinfo, arguments, econtext);
688 if (argDone == ExprEndResult)
690 /* input is an empty set, so return an empty set. */
693 *isDone = ExprEndResult;
695 elog(ERROR, "Set-valued function called in context that cannot accept a set");
698 hasSetArg = (argDone != ExprSingleResult);
702 /* Copy callinfo from previous evaluation */
703 memcpy(&fcinfo, &fcache->setArgs, sizeof(fcinfo));
704 hasSetArg = fcache->setHasSetArg;
705 /* Reset flag (we may set it again below) */
706 fcache->setArgsValid = false;
710 * If function returns set, prepare a resultinfo node for
713 if (fcache->func.fn_retset)
715 fcinfo.resultinfo = (Node *) &rsinfo;
716 rsinfo.type = T_ReturnSetInfo;
717 rsinfo.econtext = econtext;
718 rsinfo.expectedDesc = NULL;
719 rsinfo.allowedModes = (int) SFRM_ValuePerCall;
720 rsinfo.returnMode = SFRM_ValuePerCall;
721 /* isDone is filled below */
722 rsinfo.setResult = NULL;
723 rsinfo.setDesc = NULL;
727 * now return the value gotten by calling the function manager,
728 * passing the function the evaluated parameter values.
730 if (fcache->func.fn_retset || hasSetArg)
733 * We need to return a set result. Complain if caller not ready
737 elog(ERROR, "Set-valued function called in context that cannot accept a set");
740 * This loop handles the situation where we have both a set
741 * argument and a set-valued function. Once we have exhausted the
742 * function's value(s) for a particular argument value, we have to
743 * get the next argument value and start the function over again.
744 * We might have to do it more than once, if the function produces
745 * an empty result set for a particular input value.
750 * If function is strict, and there are any NULL arguments,
751 * skip calling the function (at least for this set of args).
755 if (fcache->func.fn_strict)
757 for (i = 0; i < fcinfo.nargs; i++)
759 if (fcinfo.argnull[i])
769 fcinfo.isnull = false;
770 rsinfo.isDone = ExprSingleResult;
771 result = FunctionCallInvoke(&fcinfo);
772 *isNull = fcinfo.isnull;
773 *isDone = rsinfo.isDone;
779 *isDone = ExprEndResult;
782 if (*isDone != ExprEndResult)
785 * Got a result from current argument. If function itself
786 * returns set, save the current argument values to re-use
789 if (fcache->func.fn_retset)
791 memcpy(&fcache->setArgs, &fcinfo, sizeof(fcinfo));
792 fcache->setHasSetArg = hasSetArg;
793 fcache->setArgsValid = true;
797 * Make sure we say we are returning a set, even if the
798 * function itself doesn't return sets.
800 *isDone = ExprMultipleResult;
804 /* Else, done with this argument */
806 break; /* input not a set, so done */
808 /* Re-eval args to get the next element of the input set */
809 argDone = ExecEvalFuncArgs(&fcinfo, arguments, econtext);
811 if (argDone != ExprMultipleResult)
813 /* End of argument set, so we're done. */
815 *isDone = ExprEndResult;
821 * If we reach here, loop around to run the function on the
829 * Non-set case: much easier.
831 * If function is strict, and there are any NULL arguments, skip
832 * calling the function and return NULL.
834 if (fcache->func.fn_strict)
836 for (i = 0; i < fcinfo.nargs; i++)
838 if (fcinfo.argnull[i])
845 fcinfo.isnull = false;
846 result = FunctionCallInvoke(&fcinfo);
847 *isNull = fcinfo.isnull;
855 * ExecMakeTableFunctionResult
857 * Evaluate a table function, producing a materialized result in a Tuplestore
858 * object. (If function returns an empty set, we just return NULL instead.)
861 ExecMakeTableFunctionResult(ExprState *funcexpr,
862 ExprContext *econtext,
863 TupleDesc expectedDesc,
864 TupleDesc *returnDesc)
866 Tuplestorestate *tupstore = NULL;
867 TupleDesc tupdesc = NULL;
869 FunctionCallInfoData fcinfo;
870 ReturnSetInfo rsinfo;
871 MemoryContext callerContext;
872 MemoryContext oldcontext;
873 TupleTableSlot *slot;
874 bool direct_function_call;
875 bool first_time = true;
876 bool returnsTuple = false;
879 * Normally the passed expression tree will be a FuncExprState, since the
880 * grammar only allows a function call at the top level of a table
881 * function reference. However, if the function doesn't return set then
882 * the planner might have replaced the function call via constant-folding
883 * or inlining. So if we see any other kind of expression node, execute
884 * it via the general ExecEvalExpr() code; the only difference is that
885 * we don't get a chance to pass a special ReturnSetInfo to any functions
886 * buried in the expression.
888 if (funcexpr && IsA(funcexpr, FuncExprState) &&
889 IsA(funcexpr->expr, FuncExpr))
891 FuncExprState *fcache = (FuncExprState *) funcexpr;
892 ExprDoneCond argDone;
895 * This path is similar to ExecMakeFunctionResult.
897 direct_function_call = true;
900 * Initialize function cache if first time through
902 if (fcache->func.fn_oid == InvalidOid)
904 FuncExpr *func = (FuncExpr *) fcache->xprstate.expr;
906 init_fcache(func->funcid, fcache, econtext->ecxt_per_query_memory);
910 * Evaluate the function's argument list.
912 * Note: ideally, we'd do this in the per-tuple context, but then the
913 * argument values would disappear when we reset the context in the
914 * inner loop. So do it in caller context. Perhaps we should make a
915 * separate context just to hold the evaluated arguments?
917 MemSet(&fcinfo, 0, sizeof(fcinfo));
918 fcinfo.flinfo = &(fcache->func);
919 argDone = ExecEvalFuncArgs(&fcinfo, fcache->args, econtext);
920 /* We don't allow sets in the arguments of the table function */
921 if (argDone != ExprSingleResult)
922 elog(ERROR, "Set-valued function called in context that cannot accept a set");
925 * If function is strict, and there are any NULL arguments, skip
926 * calling the function and return NULL (actually an empty set).
928 if (fcache->func.fn_strict)
932 for (i = 0; i < fcinfo.nargs; i++)
934 if (fcinfo.argnull[i])
944 /* Treat funcexpr as a generic expression */
945 direct_function_call = false;
948 funcrettype = exprType((Node *) funcexpr->expr);
951 * Prepare a resultinfo node for communication. We always do this
952 * even if not expecting a set result, so that we can pass
953 * expectedDesc. In the generic-expression case, the expression
954 * doesn't actually get to see the resultinfo, but set it up anyway
955 * because we use some of the fields as our own state variables.
957 fcinfo.resultinfo = (Node *) &rsinfo;
958 rsinfo.type = T_ReturnSetInfo;
959 rsinfo.econtext = econtext;
960 rsinfo.expectedDesc = expectedDesc;
961 rsinfo.allowedModes = (int) (SFRM_ValuePerCall | SFRM_Materialize);
962 rsinfo.returnMode = SFRM_ValuePerCall;
963 /* isDone is filled below */
964 rsinfo.setResult = NULL;
965 rsinfo.setDesc = NULL;
968 * Switch to short-lived context for calling the function or expression.
970 callerContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
973 * Loop to handle the ValuePerCall protocol (which is also the same
974 * behavior needed in the generic ExecEvalExpr path).
982 * reset per-tuple memory context before each call of the
983 * function or expression. This cleans up any local memory the
984 * function may leak when called.
986 ResetExprContext(econtext);
988 /* Call the function or expression one time */
989 if (direct_function_call)
991 fcinfo.isnull = false;
992 rsinfo.isDone = ExprSingleResult;
993 result = FunctionCallInvoke(&fcinfo);
997 result = ExecEvalExpr(funcexpr, econtext,
998 &fcinfo.isnull, &rsinfo.isDone);
1001 /* Which protocol does function want to use? */
1002 if (rsinfo.returnMode == SFRM_ValuePerCall)
1005 * Check for end of result set.
1007 * Note: if function returns an empty set, we don't build a
1008 * tupdesc or tuplestore (since we can't get a tupdesc in the
1009 * function-returning-tuple case)
1011 if (rsinfo.isDone == ExprEndResult)
1015 * If first time through, build tupdesc and tuplestore for
1020 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1021 if (funcrettype == RECORDOID ||
1022 get_typtype(funcrettype) == 'c')
1025 * Composite type, so function should have returned a
1026 * TupleTableSlot; use its descriptor
1028 slot = (TupleTableSlot *) DatumGetPointer(result);
1029 if (fcinfo.isnull ||
1031 !IsA(slot, TupleTableSlot) ||
1032 !slot->ttc_tupleDescriptor)
1033 elog(ERROR, "ExecMakeTableFunctionResult: Invalid result from function returning tuple");
1034 tupdesc = CreateTupleDescCopy(slot->ttc_tupleDescriptor);
1035 returnsTuple = true;
1040 * Scalar type, so make a single-column descriptor
1042 tupdesc = CreateTemplateTupleDesc(1, false);
1043 TupleDescInitEntry(tupdesc,
1051 tupstore = tuplestore_begin_heap(true, /* randomAccess */
1053 MemoryContextSwitchTo(oldcontext);
1054 rsinfo.setResult = tupstore;
1055 rsinfo.setDesc = tupdesc;
1059 * Store current resultset item.
1063 slot = (TupleTableSlot *) DatumGetPointer(result);
1064 if (fcinfo.isnull ||
1066 !IsA(slot, TupleTableSlot) ||
1068 elog(ERROR, "ExecMakeTableFunctionResult: Invalid result from function returning tuple");
1075 nullflag = fcinfo.isnull ? 'n' : ' ';
1076 tuple = heap_formtuple(tupdesc, &result, &nullflag);
1079 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1080 tuplestore_puttuple(tupstore, tuple);
1081 MemoryContextSwitchTo(oldcontext);
1086 if (rsinfo.isDone != ExprMultipleResult)
1089 else if (rsinfo.returnMode == SFRM_Materialize)
1091 /* check we're on the same page as the function author */
1092 if (!first_time || rsinfo.isDone != ExprSingleResult)
1093 elog(ERROR, "ExecMakeTableFunctionResult: Materialize-mode protocol not followed");
1094 /* Done evaluating the set result */
1098 elog(ERROR, "ExecMakeTableFunctionResult: unknown returnMode %d",
1099 (int) rsinfo.returnMode);
1104 /* If we have a locally-created tupstore, close it up */
1107 MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1108 tuplestore_donestoring(tupstore);
1111 MemoryContextSwitchTo(callerContext);
1113 /* The returned pointers are those in rsinfo */
1114 *returnDesc = rsinfo.setDesc;
1115 return rsinfo.setResult;
1119 /* ----------------------------------------------------------------
1124 * Evaluate the functional result of a list of arguments by calling the
1126 * ----------------------------------------------------------------
1129 /* ----------------------------------------------------------------
1131 * ----------------------------------------------------------------
1134 ExecEvalFunc(FuncExprState *fcache,
1135 ExprContext *econtext,
1137 ExprDoneCond *isDone)
1140 * Initialize function cache if first time through
1142 if (fcache->func.fn_oid == InvalidOid)
1144 FuncExpr *func = (FuncExpr *) fcache->xprstate.expr;
1146 init_fcache(func->funcid, fcache, econtext->ecxt_per_query_memory);
1149 return ExecMakeFunctionResult(fcache, econtext, isNull, isDone);
1152 /* ----------------------------------------------------------------
1154 * ----------------------------------------------------------------
1157 ExecEvalOper(FuncExprState *fcache,
1158 ExprContext *econtext,
1160 ExprDoneCond *isDone)
1163 * Initialize function cache if first time through
1165 if (fcache->func.fn_oid == InvalidOid)
1167 OpExpr *op = (OpExpr *) fcache->xprstate.expr;
1169 init_fcache(op->opfuncid, fcache, econtext->ecxt_per_query_memory);
1172 return ExecMakeFunctionResult(fcache, econtext, isNull, isDone);
1175 /* ----------------------------------------------------------------
1178 * IS DISTINCT FROM must evaluate arguments to determine whether
1179 * they are NULL; if either is NULL then the result is already
1180 * known. If neither is NULL, then proceed to evaluate the
1181 * function. Note that this is *always* derived from the equals
1182 * operator, but since we need special processing of the arguments
1183 * we can not simply reuse ExecEvalOper() or ExecEvalFunc().
1184 * ----------------------------------------------------------------
1187 ExecEvalDistinct(FuncExprState *fcache,
1188 ExprContext *econtext,
1190 ExprDoneCond *isDone)
1193 FunctionCallInfoData fcinfo;
1194 ExprDoneCond argDone;
1198 * Initialize function cache if first time through
1200 if (fcache->func.fn_oid == InvalidOid)
1202 DistinctExpr *op = (DistinctExpr *) fcache->xprstate.expr;
1204 init_fcache(op->opfuncid, fcache, econtext->ecxt_per_query_memory);
1205 Assert(!fcache->func.fn_retset);
1209 * extract info from fcache
1211 argList = fcache->args;
1213 /* Need to prep callinfo structure */
1214 MemSet(&fcinfo, 0, sizeof(fcinfo));
1215 fcinfo.flinfo = &(fcache->func);
1216 argDone = ExecEvalFuncArgs(&fcinfo, argList, econtext);
1217 if (argDone != ExprSingleResult)
1218 elog(ERROR, "IS DISTINCT FROM does not support set arguments");
1219 Assert(fcinfo.nargs == 2);
1221 if (fcinfo.argnull[0] && fcinfo.argnull[1])
1223 /* Both NULL? Then is not distinct... */
1224 result = BoolGetDatum(FALSE);
1226 else if (fcinfo.argnull[0] || fcinfo.argnull[1])
1228 /* Only one is NULL? Then is distinct... */
1229 result = BoolGetDatum(TRUE);
1233 fcinfo.isnull = false;
1234 result = FunctionCallInvoke(&fcinfo);
1235 *isNull = fcinfo.isnull;
1236 /* Must invert result of "=" */
1237 result = BoolGetDatum(!DatumGetBool(result));
1243 /* ----------------------------------------------------------------
1248 * Evaluate boolean expressions, with appropriate short-circuiting.
1250 * The query planner reformulates clause expressions in the
1251 * qualification to conjunctive normal form. If we ever get
1252 * an AND to evaluate, we can be sure that it's not a top-level
1253 * clause in the qualification, but appears lower (as a function
1254 * argument, for example), or in the target list. Not that you
1255 * need to know this, mind you...
1256 * ----------------------------------------------------------------
1259 ExecEvalNot(BoolExprState *notclause, ExprContext *econtext, bool *isNull)
1264 clause = lfirst(notclause->args);
1266 expr_value = ExecEvalExpr(clause, econtext, isNull, NULL);
1269 * if the expression evaluates to null, then we just cascade the null
1270 * back to whoever called us.
1276 * evaluation of 'not' is simple.. expr is false, then return 'true'
1279 return BoolGetDatum(!DatumGetBool(expr_value));
1282 /* ----------------------------------------------------------------
1284 * ----------------------------------------------------------------
1287 ExecEvalOr(BoolExprState *orExpr, ExprContext *econtext, bool *isNull)
1294 clauses = orExpr->args;
1298 * If any of the clauses is TRUE, the OR result is TRUE regardless of
1299 * the states of the rest of the clauses, so we can stop evaluating
1300 * and return TRUE immediately. If none are TRUE and one or more is
1301 * NULL, we return NULL; otherwise we return FALSE. This makes sense
1302 * when you interpret NULL as "don't know": if we have a TRUE then the
1303 * OR is TRUE even if we aren't sure about some of the other inputs.
1304 * If all the known inputs are FALSE, but we have one or more "don't
1305 * knows", then we have to report that we "don't know" what the OR's
1306 * result should be --- perhaps one of the "don't knows" would have
1307 * been TRUE if we'd known its value. Only when all the inputs are
1308 * known to be FALSE can we state confidently that the OR's result is
1311 foreach(clause, clauses)
1313 clause_value = ExecEvalExpr((ExprState *) lfirst(clause),
1314 econtext, isNull, NULL);
1317 * if we have a non-null true result, then return it.
1320 AnyNull = true; /* remember we got a null */
1321 else if (DatumGetBool(clause_value))
1322 return clause_value;
1325 /* AnyNull is true if at least one clause evaluated to NULL */
1327 return BoolGetDatum(false);
1330 /* ----------------------------------------------------------------
1332 * ----------------------------------------------------------------
1335 ExecEvalAnd(BoolExprState *andExpr, ExprContext *econtext, bool *isNull)
1342 clauses = andExpr->args;
1346 * If any of the clauses is FALSE, the AND result is FALSE regardless
1347 * of the states of the rest of the clauses, so we can stop evaluating
1348 * and return FALSE immediately. If none are FALSE and one or more is
1349 * NULL, we return NULL; otherwise we return TRUE. This makes sense
1350 * when you interpret NULL as "don't know", using the same sort of
1351 * reasoning as for OR, above.
1353 foreach(clause, clauses)
1355 clause_value = ExecEvalExpr((ExprState *) lfirst(clause),
1356 econtext, isNull, NULL);
1359 * if we have a non-null false result, then return it.
1362 AnyNull = true; /* remember we got a null */
1363 else if (!DatumGetBool(clause_value))
1364 return clause_value;
1367 /* AnyNull is true if at least one clause evaluated to NULL */
1369 return BoolGetDatum(!AnyNull);
1372 /* ----------------------------------------------------------------
1375 * Evaluate a CASE clause. Will have boolean expressions
1376 * inside the WHEN clauses, and will have expressions
1378 * - thomas 1998-11-09
1379 * ----------------------------------------------------------------
1382 ExecEvalCase(CaseExprState *caseExpr, ExprContext *econtext,
1383 bool *isNull, ExprDoneCond *isDone)
1389 clauses = caseExpr->args;
1392 * we evaluate each of the WHEN clauses in turn, as soon as one is
1393 * true we return the corresponding result. If none are true then we
1394 * return the value of the default clause, or NULL if there is none.
1396 foreach(clause, clauses)
1398 CaseWhenState *wclause = lfirst(clause);
1400 clause_value = ExecEvalExpr(wclause->expr,
1406 * if we have a true test, then we return the result, since the
1407 * case statement is satisfied. A NULL result from the test is
1408 * not considered true.
1410 if (DatumGetBool(clause_value) && !*isNull)
1412 return ExecEvalExpr(wclause->result,
1419 if (caseExpr->defresult)
1421 return ExecEvalExpr(caseExpr->defresult,
1431 /* ----------------------------------------------------------------
1434 * Evaluate a NullTest node.
1435 * ----------------------------------------------------------------
1438 ExecEvalNullTest(GenericExprState *nstate,
1439 ExprContext *econtext,
1441 ExprDoneCond *isDone)
1443 NullTest *ntest = (NullTest *) nstate->xprstate.expr;
1446 result = ExecEvalExpr(nstate->arg, econtext, isNull, isDone);
1448 if (isDone && *isDone == ExprEndResult)
1449 return result; /* nothing to check */
1451 switch (ntest->nulltesttype)
1457 return BoolGetDatum(true);
1460 return BoolGetDatum(false);
1465 return BoolGetDatum(false);
1468 return BoolGetDatum(true);
1470 elog(ERROR, "ExecEvalNullTest: unexpected nulltesttype %d",
1471 (int) ntest->nulltesttype);
1472 return (Datum) 0; /* keep compiler quiet */
1476 /* ----------------------------------------------------------------
1477 * ExecEvalBooleanTest
1479 * Evaluate a BooleanTest node.
1480 * ----------------------------------------------------------------
1483 ExecEvalBooleanTest(GenericExprState *bstate,
1484 ExprContext *econtext,
1486 ExprDoneCond *isDone)
1488 BooleanTest *btest = (BooleanTest *) bstate->xprstate.expr;
1491 result = ExecEvalExpr(bstate->arg, econtext, isNull, isDone);
1493 if (isDone && *isDone == ExprEndResult)
1494 return result; /* nothing to check */
1496 switch (btest->booltesttype)
1502 return BoolGetDatum(false);
1504 else if (DatumGetBool(result))
1505 return BoolGetDatum(true);
1507 return BoolGetDatum(false);
1512 return BoolGetDatum(true);
1514 else if (DatumGetBool(result))
1515 return BoolGetDatum(false);
1517 return BoolGetDatum(true);
1522 return BoolGetDatum(false);
1524 else if (DatumGetBool(result))
1525 return BoolGetDatum(false);
1527 return BoolGetDatum(true);
1532 return BoolGetDatum(true);
1534 else if (DatumGetBool(result))
1535 return BoolGetDatum(true);
1537 return BoolGetDatum(false);
1542 return BoolGetDatum(true);
1545 return BoolGetDatum(false);
1546 case IS_NOT_UNKNOWN:
1550 return BoolGetDatum(false);
1553 return BoolGetDatum(true);
1555 elog(ERROR, "ExecEvalBooleanTest: unexpected booltesttype %d",
1556 (int) btest->booltesttype);
1557 return (Datum) 0; /* keep compiler quiet */
1562 * ExecEvalConstraintTest
1564 * Test the constraint against the data provided. If the data fits
1565 * within the constraint specifications, pass it through (return the
1566 * datum) otherwise throw an error.
1569 ExecEvalConstraintTest(ConstraintTestState *cstate, ExprContext *econtext,
1570 bool *isNull, ExprDoneCond *isDone)
1572 ConstraintTest *constraint = (ConstraintTest *) cstate->xprstate.expr;
1575 result = ExecEvalExpr(cstate->arg, econtext, isNull, isDone);
1577 if (isDone && *isDone == ExprEndResult)
1578 return result; /* nothing to check */
1580 switch (constraint->testtype)
1582 case CONSTR_TEST_NOTNULL:
1584 elog(ERROR, "Domain %s does not allow NULL values",
1585 constraint->domname);
1587 case CONSTR_TEST_CHECK:
1595 * Set up value to be returned by ConstraintTestValue nodes.
1596 * We must save and restore prior setting of econtext's
1597 * domainValue fields, in case this node is itself within
1598 * a check expression for another domain.
1600 save_datum = econtext->domainValue_datum;
1601 save_isNull = econtext->domainValue_isNull;
1603 econtext->domainValue_datum = result;
1604 econtext->domainValue_isNull = *isNull;
1606 conResult = ExecEvalExpr(cstate->check_expr,
1607 econtext, &conIsNull, NULL);
1610 !DatumGetBool(conResult))
1611 elog(ERROR, "ExecEvalConstraintTest: Domain %s constraint %s failed",
1612 constraint->domname, constraint->name);
1614 econtext->domainValue_datum = save_datum;
1615 econtext->domainValue_isNull = save_isNull;
1619 elog(ERROR, "ExecEvalConstraintTest: Constraint type unknown");
1623 /* If all has gone well (constraint did not fail) return the datum */
1628 * ExecEvalConstraintTestValue
1630 * Return the value stored by constraintTest.
1633 ExecEvalConstraintTestValue(ConstraintTestValue *conVal, ExprContext *econtext,
1636 *isNull = econtext->domainValue_isNull;
1637 return econtext->domainValue_datum;
1640 /* ----------------------------------------------------------------
1641 * ExecEvalFieldSelect
1643 * Evaluate a FieldSelect node.
1644 * ----------------------------------------------------------------
1647 ExecEvalFieldSelect(GenericExprState *fstate,
1648 ExprContext *econtext,
1650 ExprDoneCond *isDone)
1652 FieldSelect *fselect = (FieldSelect *) fstate->xprstate.expr;
1654 TupleTableSlot *resSlot;
1656 result = ExecEvalExpr(fstate->arg, econtext, isNull, isDone);
1658 /* this test covers the isDone exception too: */
1662 resSlot = (TupleTableSlot *) DatumGetPointer(result);
1663 Assert(resSlot != NULL && IsA(resSlot, TupleTableSlot));
1664 result = heap_getattr(resSlot->val,
1666 resSlot->ttc_tupleDescriptor,
1671 /* ----------------------------------------------------------------
1674 * Recursively evaluate a targetlist or qualification expression.
1677 * expression: the expression state tree to evaluate
1678 * econtext: evaluation context information
1681 * return value: Datum value of result
1682 * *isNull: set to TRUE if result is NULL (actual return value is
1683 * meaningless if so); set to FALSE if non-null result
1684 * *isDone: set to indicator of set-result status
1686 * A caller that can only accept a singleton (non-set) result should pass
1687 * NULL for isDone; if the expression computes a set result then an elog()
1688 * error will be reported. If the caller does pass an isDone pointer then
1689 * *isDone is set to one of these three states:
1690 * ExprSingleResult singleton result (not a set)
1691 * ExprMultipleResult return value is one element of a set
1692 * ExprEndResult there are no more elements in the set
1693 * When ExprMultipleResult is returned, the caller should invoke
1694 * ExecEvalExpr() repeatedly until ExprEndResult is returned. ExprEndResult
1695 * is returned after the last real set element. For convenience isNull will
1696 * always be set TRUE when ExprEndResult is returned, but this should not be
1697 * taken as indicating a NULL element of the set. Note that these return
1698 * conventions allow us to distinguish among a singleton NULL, a NULL element
1699 * of a set, and an empty set.
1701 * The caller should already have switched into the temporary memory
1702 * context econtext->ecxt_per_tuple_memory. The convenience entry point
1703 * ExecEvalExprSwitchContext() is provided for callers who don't prefer to
1704 * do the switch in an outer loop. We do not do the switch here because
1705 * it'd be a waste of cycles during recursive entries to ExecEvalExpr().
1707 * This routine is an inner loop routine and must be as fast as possible.
1708 * ----------------------------------------------------------------
1711 ExecEvalExpr(ExprState *expression,
1712 ExprContext *econtext,
1714 ExprDoneCond *isDone)
1719 /* Set default values for result flags: non-null, not a set result */
1722 *isDone = ExprSingleResult;
1724 /* Is this still necessary? Doubtful... */
1725 if (expression == NULL)
1732 * here we dispatch the work to the appropriate type of function given
1733 * the type of our expression.
1735 expr = expression->expr;
1736 switch (nodeTag(expr))
1739 retDatum = ExecEvalVar((Var *) expr, econtext, isNull);
1743 Const *con = (Const *) expr;
1745 retDatum = con->constvalue;
1746 *isNull = con->constisnull;
1750 retDatum = ExecEvalParam((Param *) expr, econtext, isNull);
1753 retDatum = ExecEvalAggref((AggrefExprState *) expression,
1758 retDatum = ExecEvalArrayRef((ArrayRefExprState *) expression,
1764 retDatum = ExecEvalFunc((FuncExprState *) expression, econtext,
1768 retDatum = ExecEvalOper((FuncExprState *) expression, econtext,
1771 case T_DistinctExpr:
1772 retDatum = ExecEvalDistinct((FuncExprState *) expression, econtext,
1777 BoolExprState *state = (BoolExprState *) expression;
1779 switch (((BoolExpr *) expr)->boolop)
1782 retDatum = ExecEvalAnd(state, econtext, isNull);
1785 retDatum = ExecEvalOr(state, econtext, isNull);
1788 retDatum = ExecEvalNot(state, econtext, isNull);
1791 elog(ERROR, "ExecEvalExpr: unknown boolop %d",
1792 ((BoolExpr *) expr)->boolop);
1793 retDatum = 0; /* keep compiler quiet */
1799 retDatum = ExecSubPlan((SubPlanState *) expression,
1804 retDatum = ExecEvalFieldSelect((GenericExprState *) expression,
1810 retDatum = ExecEvalExpr(((GenericExprState *) expression)->arg,
1816 retDatum = ExecEvalCase((CaseExprState *) expression,
1822 retDatum = ExecEvalNullTest((GenericExprState *) expression,
1828 retDatum = ExecEvalBooleanTest((GenericExprState *) expression,
1833 case T_ConstraintTest:
1834 retDatum = ExecEvalConstraintTest((ConstraintTestState *) expression,
1839 case T_ConstraintTestValue:
1840 retDatum = ExecEvalConstraintTestValue((ConstraintTestValue *) expr,
1845 elog(ERROR, "ExecEvalExpr: unknown expression type %d",
1846 nodeTag(expression));
1847 retDatum = 0; /* keep compiler quiet */
1852 } /* ExecEvalExpr() */
1856 * Same as above, but get into the right allocation context explicitly.
1859 ExecEvalExprSwitchContext(ExprState *expression,
1860 ExprContext *econtext,
1862 ExprDoneCond *isDone)
1865 MemoryContext oldContext;
1867 oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
1868 retDatum = ExecEvalExpr(expression, econtext, isNull, isDone);
1869 MemoryContextSwitchTo(oldContext);
1875 * ExecInitExpr: prepare an expression tree for execution
1877 * This function builds and returns an ExprState tree paralleling the given
1878 * Expr node tree. The ExprState tree can then be handed to ExecEvalExpr
1879 * for execution. Because the Expr tree itself is read-only as far as
1880 * ExecInitExpr and ExecEvalExpr are concerned, several different executions
1881 * of the same plan tree can occur concurrently.
1883 * This must be called in a memory context that will last as long as repeated
1884 * executions of the expression are needed. Typically the context will be
1885 * the same as the per-query context of the associated ExprContext.
1887 * Any Aggref and SubPlan nodes found in the tree are added to the lists
1888 * of such nodes held by the parent PlanState. Otherwise, we do very little
1889 * initialization here other than building the state-node tree. Any nontrivial
1890 * work associated with initializing runtime info for a node should happen
1891 * during the first actual evaluation of that node. (This policy lets us
1892 * avoid work if the node is never actually evaluated.)
1894 * Note: there is no ExecEndExpr function; we assume that any resource
1895 * cleanup needed will be handled by just releasing the memory context
1896 * in which the state tree is built. Functions that require additional
1897 * cleanup work can register a shutdown callback in the ExprContext.
1899 * 'node' is the root of the expression tree to examine
1900 * 'parent' is the PlanState node that owns the expression.
1902 * 'parent' may be NULL if we are preparing an expression that is not
1903 * associated with a plan tree. (If so, it can't have aggs or subplans.)
1904 * This case should usually come through ExecPrepareExpr, not directly here.
1907 ExecInitExpr(Expr *node, PlanState *parent)
1913 switch (nodeTag(node))
1918 case T_ConstraintTestValue:
1919 /* No special setup needed for these node types */
1920 state = (ExprState *) makeNode(ExprState);
1924 Aggref *aggref = (Aggref *) node;
1925 AggrefExprState *astate = makeNode(AggrefExprState);
1927 if (parent && IsA(parent, AggState))
1929 AggState *aggstate = (AggState *) parent;
1932 aggstate->aggs = lcons(astate, aggstate->aggs);
1933 naggs = ++aggstate->numaggs;
1935 astate->target = ExecInitExpr(aggref->target, parent);
1938 * Complain if the aggregate's argument contains any
1939 * aggregates; nested agg functions are semantically
1940 * nonsensical. (This probably was caught earlier,
1941 * but we defend against it here anyway.)
1943 if (naggs != aggstate->numaggs)
1944 elog(ERROR, "Aggregate function calls may not be nested");
1947 elog(ERROR, "ExecInitExpr: Aggref not expected here");
1948 state = (ExprState *) astate;
1953 ArrayRef *aref = (ArrayRef *) node;
1954 ArrayRefExprState *astate = makeNode(ArrayRefExprState);
1956 astate->refupperindexpr = (List *)
1957 ExecInitExpr((Expr *) aref->refupperindexpr, parent);
1958 astate->reflowerindexpr = (List *)
1959 ExecInitExpr((Expr *) aref->reflowerindexpr, parent);
1960 astate->refexpr = ExecInitExpr(aref->refexpr, parent);
1961 astate->refassgnexpr = ExecInitExpr(aref->refassgnexpr,
1963 state = (ExprState *) astate;
1968 FuncExpr *funcexpr = (FuncExpr *) node;
1969 FuncExprState *fstate = makeNode(FuncExprState);
1971 fstate->args = (List *)
1972 ExecInitExpr((Expr *) funcexpr->args, parent);
1973 fstate->func.fn_oid = InvalidOid; /* not initialized */
1974 state = (ExprState *) fstate;
1979 OpExpr *opexpr = (OpExpr *) node;
1980 FuncExprState *fstate = makeNode(FuncExprState);
1982 fstate->args = (List *)
1983 ExecInitExpr((Expr *) opexpr->args, parent);
1984 fstate->func.fn_oid = InvalidOid; /* not initialized */
1985 state = (ExprState *) fstate;
1988 case T_DistinctExpr:
1990 DistinctExpr *distinctexpr = (DistinctExpr *) node;
1991 FuncExprState *fstate = makeNode(FuncExprState);
1993 fstate->args = (List *)
1994 ExecInitExpr((Expr *) distinctexpr->args, parent);
1995 fstate->func.fn_oid = InvalidOid; /* not initialized */
1996 state = (ExprState *) fstate;
2001 BoolExpr *boolexpr = (BoolExpr *) node;
2002 BoolExprState *bstate = makeNode(BoolExprState);
2004 bstate->args = (List *)
2005 ExecInitExpr((Expr *) boolexpr->args, parent);
2006 state = (ExprState *) bstate;
2011 /* Keep this in sync with ExecInitExprInitPlan, below */
2012 SubPlan *subplan = (SubPlan *) node;
2013 SubPlanState *sstate = makeNode(SubPlanState);
2016 elog(ERROR, "ExecInitExpr: SubPlan not expected here");
2019 * Here we just add the SubPlanState nodes to
2020 * parent->subPlan. The subplans will be initialized later.
2022 parent->subPlan = lcons(sstate, parent->subPlan);
2023 sstate->sub_estate = NULL;
2024 sstate->planstate = NULL;
2026 sstate->oper = (List *)
2027 ExecInitExpr((Expr *) subplan->oper, parent);
2028 sstate->args = (List *)
2029 ExecInitExpr((Expr *) subplan->args, parent);
2031 state = (ExprState *) sstate;
2036 FieldSelect *fselect = (FieldSelect *) node;
2037 GenericExprState *gstate = makeNode(GenericExprState);
2039 gstate->arg = ExecInitExpr(fselect->arg, parent);
2040 state = (ExprState *) gstate;
2045 RelabelType *relabel = (RelabelType *) node;
2046 GenericExprState *gstate = makeNode(GenericExprState);
2048 gstate->arg = ExecInitExpr(relabel->arg, parent);
2049 state = (ExprState *) gstate;
2054 CaseExpr *caseexpr = (CaseExpr *) node;
2055 CaseExprState *cstate = makeNode(CaseExprState);
2056 List *outlist = NIL;
2059 foreach(inlist, caseexpr->args)
2061 CaseWhen *when = (CaseWhen *) lfirst(inlist);
2062 CaseWhenState *wstate = makeNode(CaseWhenState);
2064 Assert(IsA(when, CaseWhen));
2065 wstate->xprstate.expr = (Expr *) when;
2066 wstate->expr = ExecInitExpr(when->expr, parent);
2067 wstate->result = ExecInitExpr(when->result, parent);
2068 outlist = lappend(outlist, wstate);
2070 cstate->args = outlist;
2071 /* caseexpr->arg should be null by now */
2072 Assert(caseexpr->arg == NULL);
2073 cstate->defresult = ExecInitExpr(caseexpr->defresult, parent);
2074 state = (ExprState *) cstate;
2079 NullTest *ntest = (NullTest *) node;
2080 GenericExprState *gstate = makeNode(GenericExprState);
2082 gstate->arg = ExecInitExpr(ntest->arg, parent);
2083 state = (ExprState *) gstate;
2088 BooleanTest *btest = (BooleanTest *) node;
2089 GenericExprState *gstate = makeNode(GenericExprState);
2091 gstate->arg = ExecInitExpr(btest->arg, parent);
2092 state = (ExprState *) gstate;
2095 case T_ConstraintTest:
2097 ConstraintTest *ctest = (ConstraintTest *) node;
2098 ConstraintTestState *cstate = makeNode(ConstraintTestState);
2100 cstate->arg = ExecInitExpr(ctest->arg, parent);
2101 cstate->check_expr = ExecInitExpr(ctest->check_expr, parent);
2102 state = (ExprState *) cstate;
2107 TargetEntry *tle = (TargetEntry *) node;
2108 GenericExprState *gstate = makeNode(GenericExprState);
2110 gstate->arg = ExecInitExpr(tle->expr, parent);
2111 state = (ExprState *) gstate;
2116 List *outlist = NIL;
2119 foreach(inlist, (List *) node)
2121 outlist = lappend(outlist,
2122 ExecInitExpr((Expr *) lfirst(inlist),
2125 /* Don't fall through to the "common" code below */
2126 return (ExprState *) outlist;
2129 elog(ERROR, "ExecInitExpr: unknown expression type %d",
2131 state = NULL; /* keep compiler quiet */
2135 /* Common code for all state-node types */
2142 * ExecInitExprInitPlan --- initialize a subplan expr that's being handled
2143 * as an InitPlan. This is identical to ExecInitExpr's handling of a regular
2144 * subplan expr, except we do NOT want to add the node to the parent's
2148 ExecInitExprInitPlan(SubPlan *node, PlanState *parent)
2150 SubPlanState *sstate = makeNode(SubPlanState);
2153 elog(ERROR, "ExecInitExpr: SubPlan not expected here");
2155 /* The subplan's state will be initialized later */
2156 sstate->sub_estate = NULL;
2157 sstate->planstate = NULL;
2159 sstate->oper = (List *) ExecInitExpr((Expr *) node->oper, parent);
2160 sstate->args = (List *) ExecInitExpr((Expr *) node->args, parent);
2162 sstate->xprstate.expr = (Expr *) node;
2168 * ExecPrepareExpr --- initialize for expression execution outside a normal
2169 * Plan tree context.
2171 * This differs from ExecInitExpr in that we don't assume the caller is
2172 * already running in the EState's per-query context. Also, we apply
2173 * fix_opfuncids() to the passed expression tree to be sure it is ready
2174 * to run. (In ordinary Plan trees the planner will have fixed opfuncids,
2175 * but callers outside the executor will not have done this.)
2178 ExecPrepareExpr(Expr *node, EState *estate)
2181 MemoryContext oldcontext;
2183 fix_opfuncids((Node *) node);
2185 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2187 result = ExecInitExpr(node, NULL);
2189 MemoryContextSwitchTo(oldcontext);
2195 /* ----------------------------------------------------------------
2196 * ExecQual / ExecTargetList / ExecProject
2197 * ----------------------------------------------------------------
2200 /* ----------------------------------------------------------------
2203 * Evaluates a conjunctive boolean expression (qual list) and
2204 * returns true iff none of the subexpressions are false.
2205 * (We also return true if the list is empty.)
2207 * If some of the subexpressions yield NULL but none yield FALSE,
2208 * then the result of the conjunction is NULL (ie, unknown)
2209 * according to three-valued boolean logic. In this case,
2210 * we return the value specified by the "resultForNull" parameter.
2212 * Callers evaluating WHERE clauses should pass resultForNull=FALSE,
2213 * since SQL specifies that tuples with null WHERE results do not
2214 * get selected. On the other hand, callers evaluating constraint
2215 * conditions should pass resultForNull=TRUE, since SQL also specifies
2216 * that NULL constraint conditions are not failures.
2218 * NOTE: it would not be correct to use this routine to evaluate an
2219 * AND subclause of a boolean expression; for that purpose, a NULL
2220 * result must be returned as NULL so that it can be properly treated
2221 * in the next higher operator (cf. ExecEvalAnd and ExecEvalOr).
2222 * This routine is only used in contexts where a complete expression
2223 * is being evaluated and we know that NULL can be treated the same
2224 * as one boolean result or the other.
2226 * ----------------------------------------------------------------
2229 ExecQual(List *qual, ExprContext *econtext, bool resultForNull)
2232 MemoryContext oldContext;
2238 EV_printf("ExecQual: qual is ");
2239 EV_nodeDisplay(qual);
2245 * Run in short-lived per-tuple context while computing expressions.
2247 oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
2250 * Evaluate the qual conditions one at a time. If we find a FALSE
2251 * result, we can stop evaluating and return FALSE --- the AND result
2252 * must be FALSE. Also, if we find a NULL result when resultForNull
2253 * is FALSE, we can stop and return FALSE --- the AND result must be
2254 * FALSE or NULL in that case, and the caller doesn't care which.
2256 * If we get to the end of the list, we can return TRUE. This will
2257 * happen when the AND result is indeed TRUE, or when the AND result
2258 * is NULL (one or more NULL subresult, with all the rest TRUE) and
2259 * the caller has specified resultForNull = TRUE.
2263 foreach(qlist, qual)
2265 ExprState *clause = (ExprState *) lfirst(qlist);
2269 expr_value = ExecEvalExpr(clause, econtext, &isNull, NULL);
2273 if (resultForNull == false)
2275 result = false; /* treat NULL as FALSE */
2281 if (!DatumGetBool(expr_value))
2283 result = false; /* definitely FALSE */
2289 MemoryContextSwitchTo(oldContext);
2295 * Number of items in a tlist (including any resjunk items!)
2298 ExecTargetListLength(List *targetlist)
2300 /* This used to be more complex, but fjoins are dead */
2301 return length(targetlist);
2305 * Number of items in a tlist, not including any resjunk items
2308 ExecCleanTargetListLength(List *targetlist)
2313 foreach(tl, targetlist)
2315 TargetEntry *curTle = (TargetEntry *) lfirst(tl);
2317 Assert(IsA(curTle, TargetEntry));
2318 if (!curTle->resdom->resjunk)
2324 /* ----------------------------------------------------------------
2327 * Evaluates a targetlist with respect to the current
2328 * expression context and return a tuple.
2330 * As with ExecEvalExpr, the caller should pass isDone = NULL if not
2331 * prepared to deal with sets of result tuples. Otherwise, a return
2332 * of *isDone = ExprMultipleResult signifies a set element, and a return
2333 * of *isDone = ExprEndResult signifies end of the set of tuple.
2334 * ----------------------------------------------------------------
2337 ExecTargetList(List *targetlist,
2339 TupleDesc targettype,
2341 ExprContext *econtext,
2342 ExprDoneCond *isDone)
2344 MemoryContext oldContext;
2346 #define NPREALLOCDOMAINS 64
2347 char nullsArray[NPREALLOCDOMAINS];
2348 ExprDoneCond itemIsDoneArray[NPREALLOCDOMAINS];
2350 ExprDoneCond *itemIsDone;
2355 static struct tupleDesc NullTupleDesc; /* we assume this inits to
2361 EV_printf("ExecTargetList: tl is ");
2362 EV_nodeDisplay(targetlist);
2366 * Run in short-lived per-tuple context while computing expressions.
2368 oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
2371 * There used to be some klugy and demonstrably broken code here that
2372 * special-cased the situation where targetlist == NIL. Now we just
2373 * fall through and return an empty-but-valid tuple. We do, however,
2374 * have to cope with the possibility that targettype is NULL ---
2375 * heap_formtuple won't like that, so pass a dummy descriptor with
2376 * natts = 0 to deal with it.
2378 if (targettype == NULL)
2379 targettype = &NullTupleDesc;
2382 * allocate an array of char's to hold the "null" information only if
2383 * we have a really large targetlist. otherwise we use the stack.
2385 * We also allocate another array that holds the isDone status for each
2386 * targetlist item. The isDone status is needed so that we can iterate,
2387 * generating multiple tuples, when one or more tlist items return
2388 * sets. (We expect the caller to call us again if we return
2389 * isDone = ExprMultipleResult.)
2391 if (nodomains > NPREALLOCDOMAINS)
2393 nulls = (char *) palloc(nodomains * sizeof(char));
2394 itemIsDone = (ExprDoneCond *) palloc(nodomains * sizeof(ExprDoneCond));
2399 itemIsDone = itemIsDoneArray;
2403 * evaluate all the expressions in the target list
2407 *isDone = ExprSingleResult; /* until proven otherwise */
2409 haveDoneSets = false; /* any exhausted set exprs in tlist? */
2411 foreach(tl, targetlist)
2413 GenericExprState *gstate = (GenericExprState *) lfirst(tl);
2414 TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr;
2415 AttrNumber resind = tle->resdom->resno - 1;
2417 values[resind] = ExecEvalExpr(gstate->arg,
2420 &itemIsDone[resind]);
2421 nulls[resind] = isNull ? 'n' : ' ';
2423 if (itemIsDone[resind] != ExprSingleResult)
2425 /* We have a set-valued expression in the tlist */
2427 elog(ERROR, "Set-valued function called in context that cannot accept a set");
2428 if (itemIsDone[resind] == ExprMultipleResult)
2430 /* we have undone sets in the tlist, set flag */
2431 *isDone = ExprMultipleResult;
2435 /* we have done sets in the tlist, set flag for that */
2436 haveDoneSets = true;
2444 * note: can't get here unless we verified isDone != NULL
2446 if (*isDone == ExprSingleResult)
2449 * all sets are done, so report that tlist expansion is
2452 *isDone = ExprEndResult;
2453 MemoryContextSwitchTo(oldContext);
2460 * We have some done and some undone sets. Restart the done
2461 * ones so that we can deliver a tuple (if possible).
2463 foreach(tl, targetlist)
2465 GenericExprState *gstate = (GenericExprState *) lfirst(tl);
2466 TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr;
2467 AttrNumber resind = tle->resdom->resno - 1;
2469 if (itemIsDone[resind] == ExprEndResult)
2471 values[resind] = ExecEvalExpr(gstate->arg,
2474 &itemIsDone[resind]);
2475 nulls[resind] = isNull ? 'n' : ' ';
2477 if (itemIsDone[resind] == ExprEndResult)
2480 * Oh dear, this item is returning an empty
2481 * set. Guess we can't make a tuple after all.
2483 *isDone = ExprEndResult;
2490 * If we cannot make a tuple because some sets are empty, we
2491 * still have to cycle the nonempty sets to completion, else
2492 * resources will not be released from subplans etc.
2494 * XXX is that still necessary?
2496 if (*isDone == ExprEndResult)
2498 foreach(tl, targetlist)
2500 GenericExprState *gstate = (GenericExprState *) lfirst(tl);
2501 TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr;
2502 AttrNumber resind = tle->resdom->resno - 1;
2504 while (itemIsDone[resind] == ExprMultipleResult)
2506 (void) ExecEvalExpr(gstate->arg,
2509 &itemIsDone[resind]);
2513 MemoryContextSwitchTo(oldContext);
2521 * form the new result tuple (in the caller's memory context!)
2523 MemoryContextSwitchTo(oldContext);
2525 newTuple = (HeapTuple) heap_formtuple(targettype, values, nulls);
2530 * free the status arrays if we palloc'd them
2532 if (nodomains > NPREALLOCDOMAINS)
2541 /* ----------------------------------------------------------------
2544 * projects a tuple based on projection info and stores
2545 * it in the specified tuple table slot.
2547 * Note: someday soon the executor can be extended to eliminate
2548 * redundant projections by storing pointers to datums
2549 * in the tuple table and then passing these around when
2550 * possible. this should make things much quicker.
2552 * ----------------------------------------------------------------
2555 ExecProject(ProjectionInfo *projInfo, ExprDoneCond *isDone)
2557 TupleTableSlot *slot;
2562 ExprContext *econtext;
2568 if (projInfo == NULL)
2569 return (TupleTableSlot *) NULL;
2572 * get the projection info we want
2574 slot = projInfo->pi_slot;
2575 targetlist = projInfo->pi_targetlist;
2576 len = projInfo->pi_len;
2577 tupType = slot->ttc_tupleDescriptor;
2579 tupValue = projInfo->pi_tupValue;
2580 econtext = projInfo->pi_exprContext;
2583 * form a new result tuple (if possible --- result can be NULL)
2585 newTuple = ExecTargetList(targetlist,
2593 * store the tuple in the projection slot and return the slot.
2595 return ExecStoreTuple(newTuple, /* tuple to store */
2596 slot, /* slot to store in */
2597 InvalidBuffer, /* tuple has no buffer */