1 /*-------------------------------------------------------------------------
4 * Routines to evaluate qualification and targetlist expressions
6 * Portions Copyright (c) 1996-2001, 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.89 2001/10/25 05:49:27 momjian Exp $
13 *-------------------------------------------------------------------------
17 * ExecEvalExpr - evaluate an expression and return a datum
18 * ExecEvalExprSwitchContext - same, but switch into eval memory context
19 * ExecQual - return true/false if qualification is satisfied
20 * ExecProject - form a new tuple by projecting the given tuple
23 * ExecEvalExpr() and ExecEvalVar() are hotspots. making these faster
24 * will speed up the entire system. Unfortunately they are currently
25 * implemented recursively. Eliminating the recursion is bound to
26 * improve the speed of the executor.
28 * ExecProject() is used to make tuple projections. Rather then
29 * trying to speed it up, the execution plan should be pre-processed
30 * to facilitate attribute sharing between nodes wherever possible,
31 * instead of doing needless copying. -cim 5/31/91
37 #include "access/heapam.h"
38 #include "executor/execFlatten.h"
39 #include "executor/execdebug.h"
40 #include "executor/functions.h"
41 #include "executor/nodeSubplan.h"
42 #include "utils/array.h"
43 #include "utils/builtins.h"
44 #include "utils/fcache.h"
47 /* static function decls */
48 static Datum ExecEvalAggref(Aggref *aggref, ExprContext *econtext,
50 static Datum ExecEvalArrayRef(ArrayRef *arrayRef, ExprContext *econtext,
51 bool *isNull, ExprDoneCond *isDone);
52 static Datum ExecEvalVar(Var *variable, ExprContext *econtext, bool *isNull);
53 static Datum ExecEvalOper(Expr *opClause, ExprContext *econtext,
54 bool *isNull, ExprDoneCond *isDone);
55 static Datum ExecEvalFunc(Expr *funcClause, ExprContext *econtext,
56 bool *isNull, ExprDoneCond *isDone);
57 static ExprDoneCond ExecEvalFuncArgs(FunctionCallInfo fcinfo,
58 List *argList, ExprContext *econtext);
59 static Datum ExecEvalNot(Expr *notclause, ExprContext *econtext, bool *isNull);
60 static Datum ExecEvalAnd(Expr *andExpr, ExprContext *econtext, bool *isNull);
61 static Datum ExecEvalOr(Expr *orExpr, ExprContext *econtext, bool *isNull);
62 static Datum ExecEvalCase(CaseExpr *caseExpr, ExprContext *econtext,
63 bool *isNull, ExprDoneCond *isDone);
64 static Datum ExecEvalNullTest(NullTest *ntest, ExprContext *econtext,
65 bool *isNull, ExprDoneCond *isDone);
66 static Datum ExecEvalBooleanTest(BooleanTest *btest, ExprContext *econtext,
67 bool *isNull, ExprDoneCond *isDone);
73 * This function takes an ArrayRef and returns the extracted Datum
74 * if it's a simple reference, or the modified array value if it's
75 * an array assignment (i.e., array element or slice insertion).
77 * NOTE: if we get a NULL result from a subexpression, we return NULL when
78 * it's an array reference, or the unmodified source array when it's an
79 * array assignment. This may seem peculiar, but if we return NULL (as was
80 * done in versions up through 7.0) then an assignment like
81 * UPDATE table SET arrayfield[4] = NULL
82 * will result in setting the whole array to NULL, which is certainly not
83 * very desirable. By returning the source array we make the assignment
84 * into a no-op, instead. (Eventually we need to redesign arrays so that
85 * individual elements can be NULL, but for now, let's try to protect users
86 * from shooting themselves in the foot.)
88 * NOTE: we deliberately refrain from applying DatumGetArrayTypeP() here,
89 * even though that might seem natural, because this code needs to support
90 * both varlena arrays and fixed-length array types. DatumGetArrayTypeP()
91 * only works for the varlena kind. The routines we call in arrayfuncs.c
92 * have to know the difference (that's what they need refattrlength for).
96 ExecEvalArrayRef(ArrayRef *arrayRef,
97 ExprContext *econtext,
101 ArrayType *array_source;
102 ArrayType *resultArray;
103 bool isAssignment = (arrayRef->refassgnexpr != NULL);
111 if (arrayRef->refexpr != NULL)
113 array_source = (ArrayType *)
114 DatumGetPointer(ExecEvalExpr(arrayRef->refexpr,
120 * If refexpr yields NULL, result is always NULL, for now anyway.
121 * (This means you cannot assign to an element or slice of an
122 * array that's NULL; it'll just stay NULL.)
130 * Empty refexpr indicates we are doing an INSERT into an array
131 * column. For now, we just take the refassgnexpr (which the
132 * parser will have ensured is an array value) and return it
133 * as-is, ignoring any subscripts that may have been supplied in
134 * the INSERT column list. This is a kluge, but it's not real
135 * clear what the semantics ought to be...
140 foreach(elt, arrayRef->refupperindexpr)
143 elog(ERROR, "ExecEvalArrayRef: can only handle %d dimensions",
146 upper.indx[i++] = DatumGetInt32(ExecEvalExpr((Node *) lfirst(elt),
150 /* If any index expr yields NULL, result is NULL or source array */
153 if (!isAssignment || array_source == NULL)
156 return PointerGetDatum(array_source);
160 if (arrayRef->reflowerindexpr != NIL)
162 foreach(elt, arrayRef->reflowerindexpr)
165 elog(ERROR, "ExecEvalArrayRef: can only handle %d dimensions",
168 lower.indx[j++] = DatumGetInt32(ExecEvalExpr((Node *) lfirst(elt),
174 * If any index expr yields NULL, result is NULL or source
179 if (!isAssignment || array_source == NULL)
182 return PointerGetDatum(array_source);
187 "ExecEvalArrayRef: upper and lower indices mismatch");
195 Datum sourceData = ExecEvalExpr(arrayRef->refassgnexpr,
201 * For now, can't cope with inserting NULL into an array, so make
202 * it a no-op per discussion above...
206 if (array_source == NULL)
209 return PointerGetDatum(array_source);
212 if (array_source == NULL)
213 return sourceData; /* XXX do something else? */
216 resultArray = array_set(array_source, i,
219 arrayRef->refelembyval,
220 arrayRef->refelemlength,
221 arrayRef->refattrlength,
224 resultArray = array_set_slice(array_source, i,
225 upper.indx, lower.indx,
226 (ArrayType *) DatumGetPointer(sourceData),
227 arrayRef->refelembyval,
228 arrayRef->refelemlength,
229 arrayRef->refattrlength,
231 return PointerGetDatum(resultArray);
235 return array_ref(array_source, i,
237 arrayRef->refelembyval,
238 arrayRef->refelemlength,
239 arrayRef->refattrlength,
243 resultArray = array_get_slice(array_source, i,
244 upper.indx, lower.indx,
245 arrayRef->refelembyval,
246 arrayRef->refelemlength,
247 arrayRef->refattrlength,
249 return PointerGetDatum(resultArray);
254 /* ----------------------------------------------------------------
257 * Returns a Datum whose value is the value of the precomputed
258 * aggregate found in the given expression context.
259 * ----------------------------------------------------------------
262 ExecEvalAggref(Aggref *aggref, ExprContext *econtext, bool *isNull)
264 if (econtext->ecxt_aggvalues == NULL) /* safety check */
265 elog(ERROR, "ExecEvalAggref: no aggregates in this expression context");
267 *isNull = econtext->ecxt_aggnulls[aggref->aggno];
268 return econtext->ecxt_aggvalues[aggref->aggno];
271 /* ----------------------------------------------------------------
274 * Returns a Datum whose value is the value of a range
275 * variable with respect to given expression context.
278 * As an entry condition, we expect that the datatype the
279 * plan expects to get (as told by our "variable" argument) is in
280 * fact the datatype of the attribute the plan says to fetch (as
281 * seen in the current context, identified by our "econtext"
284 * If we fetch a Type A attribute and Caller treats it as if it
285 * were Type B, there will be undefined results (e.g. crash).
286 * One way these might mismatch now is that we're accessing a
287 * catalog class and the type information in the pg_attribute
288 * class does not match the hardcoded pg_attribute information
289 * (in pg_attribute.h) for the class in question.
291 * We have an Assert to make sure this entry condition is met.
293 * ---------------------------------------------------------------- */
295 ExecEvalVar(Var *variable, ExprContext *econtext, bool *isNull)
298 TupleTableSlot *slot;
301 TupleDesc tuple_type;
304 * get the slot we want
306 switch (variable->varno)
308 case INNER: /* get the tuple from the inner node */
309 slot = econtext->ecxt_innertuple;
312 case OUTER: /* get the tuple from the outer node */
313 slot = econtext->ecxt_outertuple;
316 default: /* get the tuple from the relation being
318 slot = econtext->ecxt_scantuple;
323 * extract tuple information from the slot
325 heapTuple = slot->val;
326 tuple_type = slot->ttc_tupleDescriptor;
328 attnum = variable->varattno;
330 /* (See prolog for explanation of this Assert) */
331 Assert(attnum <= 0 ||
332 (attnum - 1 <= tuple_type->natts - 1 &&
333 tuple_type->attrs[attnum - 1] != NULL &&
334 variable->vartype == tuple_type->attrs[attnum - 1]->atttypid));
337 * If the attribute number is invalid, then we are supposed to return
338 * the entire tuple; we give back a whole slot so that callers know
339 * what the tuple looks like.
341 * XXX this is a horrid crock: since the pointer to the slot might live
342 * longer than the current evaluation context, we are forced to copy
343 * the tuple and slot into a long-lived context --- we use
344 * TransactionCommandContext which should be safe enough. This
345 * represents a serious memory leak if many such tuples are processed
346 * in one command, however. We ought to redesign the representation
347 * of whole-tuple datums so that this is not necessary.
349 * We assume it's OK to point to the existing tupleDescriptor, rather
350 * than copy that too.
352 if (attnum == InvalidAttrNumber)
354 MemoryContext oldContext;
355 TupleTableSlot *tempSlot;
358 oldContext = MemoryContextSwitchTo(TransactionCommandContext);
359 tempSlot = MakeTupleTableSlot();
360 tup = heap_copytuple(heapTuple);
361 ExecStoreTuple(tup, tempSlot, InvalidBuffer, true);
362 ExecSetSlotDescriptor(tempSlot, tuple_type, false);
363 MemoryContextSwitchTo(oldContext);
364 return PointerGetDatum(tempSlot);
367 result = heap_getattr(heapTuple, /* tuple containing attribute */
368 attnum, /* attribute number of desired
370 tuple_type, /* tuple descriptor of tuple */
371 isNull); /* return: is attribute null? */
376 /* ----------------------------------------------------------------
379 * Returns the value of a parameter. A param node contains
380 * something like ($.name) and the expression context contains
381 * the current parameter bindings (name = "sam") (age = 34)...
382 * so our job is to replace the param node with the datum
383 * containing the appropriate information ("sam").
385 * Q: if we have a parameter ($.foo) without a binding, i.e.
386 * there is no (foo = xxx) in the parameter list info,
387 * is this a fatal error or should this be a "not available"
388 * (in which case we shoud return a Const node with the
389 * isnull flag) ? -cim 10/13/89
391 * Minor modification: Param nodes now have an extra field,
392 * `paramkind' which specifies the type of parameter
393 * (see params.h). So while searching the paramList for
394 * a paramname/value pair, we have also to check for `kind'.
396 * NOTE: The last entry in `paramList' is always an
397 * entry with kind == PARAM_INVALID.
398 * ----------------------------------------------------------------
401 ExecEvalParam(Param *expression, ExprContext *econtext, bool *isNull)
403 char *thisParameterName;
404 int thisParameterKind = expression->paramkind;
405 AttrNumber thisParameterId = expression->paramid;
407 ParamListInfo paramList;
409 if (thisParameterKind == PARAM_EXEC)
413 prm = &(econtext->ecxt_param_exec_vals[thisParameterId]);
414 if (prm->execPlan != NULL)
416 ExecSetParamPlan(prm->execPlan, econtext);
417 /* ExecSetParamPlan should have processed this param... */
418 Assert(prm->execPlan == NULL);
420 *isNull = prm->isnull;
424 thisParameterName = expression->paramname;
425 paramList = econtext->ecxt_param_list_info;
430 * search the list with the parameter info to find a matching name. An
431 * entry with an InvalidName denotes the last element in the array.
434 if (paramList != NULL)
437 * search for an entry in 'paramList' that matches the
440 while (paramList->kind != PARAM_INVALID && !matchFound)
442 switch (thisParameterKind)
445 if (thisParameterKind == paramList->kind &&
446 strcmp(paramList->name, thisParameterName) == 0)
450 if (thisParameterKind == paramList->kind &&
451 paramList->id == thisParameterId)
456 if (thisParameterKind == paramList->kind &&
457 paramList->id == thisParameterId)
464 if (strcmp(paramList->name, thisParameterName) != 0)
467 "ExecEvalParam: new/old params with same id & diff names");
474 * oops! this is not supposed to happen!
476 elog(ERROR, "ExecEvalParam: invalid paramkind %d",
487 * ooops! we couldn't find this parameter in the parameter list.
490 elog(ERROR, "ExecEvalParam: Unknown value for parameter %s",
497 *isNull = paramList->isnull;
498 return paramList->value;
502 /* ----------------------------------------------------------------
503 * ExecEvalOper / ExecEvalFunc support routines
504 * ----------------------------------------------------------------
511 * These are functions which return the value of the
512 * named attribute out of the tuple from the arg slot. User defined
513 * C functions which take a tuple as an argument are expected
514 * to use this. Ex: overpaid(EMP) might call GetAttributeByNum().
517 GetAttributeByNum(TupleTableSlot *slot,
523 if (!AttributeNumberIsValid(attrno))
524 elog(ERROR, "GetAttributeByNum: Invalid attribute number");
526 if (!AttrNumberIsForUserDefinedAttr(attrno))
527 elog(ERROR, "GetAttributeByNum: cannot access system attributes here");
529 if (isNull == (bool *) NULL)
530 elog(ERROR, "GetAttributeByNum: a NULL isNull flag was passed");
538 retval = heap_getattr(slot->val,
540 slot->ttc_tupleDescriptor,
549 GetAttributeByName(TupleTableSlot *slot, char *attname, bool *isNull)
558 elog(ERROR, "GetAttributeByName: Invalid attribute name");
560 if (isNull == (bool *) NULL)
561 elog(ERROR, "GetAttributeByName: a NULL isNull flag was passed");
569 tupdesc = slot->ttc_tupleDescriptor;
570 natts = slot->val->t_data->t_natts;
572 attrno = InvalidAttrNumber;
573 for (i = 0; i < tupdesc->natts; i++)
575 if (namestrcmp(&(tupdesc->attrs[i]->attname), attname) == 0)
577 attrno = tupdesc->attrs[i]->attnum;
582 if (attrno == InvalidAttrNumber)
583 elog(ERROR, "GetAttributeByName: attribute %s not found", attname);
585 retval = heap_getattr(slot->val,
596 * Evaluate arguments for a function.
599 ExecEvalFuncArgs(FunctionCallInfo fcinfo,
601 ExprContext *econtext)
603 ExprDoneCond argIsDone;
607 argIsDone = ExprSingleResult; /* default assumption */
610 foreach(arg, argList)
612 ExprDoneCond thisArgIsDone;
614 fcinfo->arg[i] = ExecEvalExpr((Node *) lfirst(arg),
619 if (thisArgIsDone != ExprSingleResult)
622 * We allow only one argument to have a set value; we'd need
623 * much more complexity to keep track of multiple set
624 * arguments (cf. ExecTargetList) and it doesn't seem worth
627 if (argIsDone != ExprSingleResult)
628 elog(ERROR, "Functions and operators can take only one set argument");
629 argIsDone = thisArgIsDone;
640 * ExecMakeFunctionResult
642 * Evaluate the arguments to a function and then the function itself.
644 * NOTE: econtext is used only for evaluating the argument expressions;
645 * it is not passed to the function itself.
648 ExecMakeFunctionResult(FunctionCachePtr fcache,
650 ExprContext *econtext,
652 ExprDoneCond *isDone)
655 FunctionCallInfoData fcinfo;
656 ReturnSetInfo rsinfo; /* for functions returning sets */
657 ExprDoneCond argDone;
662 * arguments is a list of expressions to evaluate before passing to
663 * the function manager. We skip the evaluation if it was already
664 * done in the previous call (ie, we are continuing the evaluation of
665 * a set-valued function). Otherwise, collect the current argument
666 * values into fcinfo.
668 if (!fcache->setArgsValid)
670 /* Need to prep callinfo structure */
671 MemSet(&fcinfo, 0, sizeof(fcinfo));
672 fcinfo.flinfo = &(fcache->func);
673 argDone = ExecEvalFuncArgs(&fcinfo, arguments, econtext);
674 if (argDone == ExprEndResult)
676 /* input is an empty set, so return an empty set. */
679 *isDone = ExprEndResult;
681 elog(ERROR, "Set-valued function called in context that cannot accept a set");
684 hasSetArg = (argDone != ExprSingleResult);
688 /* Copy callinfo from previous evaluation */
689 memcpy(&fcinfo, &fcache->setArgs, sizeof(fcinfo));
690 hasSetArg = fcache->setHasSetArg;
691 /* Reset flag (we may set it again below) */
692 fcache->setArgsValid = false;
696 * If function returns set, prepare a resultinfo node for
699 if (fcache->func.fn_retset)
701 fcinfo.resultinfo = (Node *) &rsinfo;
702 rsinfo.type = T_ReturnSetInfo;
706 * now return the value gotten by calling the function manager,
707 * passing the function the evaluated parameter values.
709 if (fcache->func.fn_retset || hasSetArg)
712 * We need to return a set result. Complain if caller not ready
716 elog(ERROR, "Set-valued function called in context that cannot accept a set");
719 * This loop handles the situation where we have both a set
720 * argument and a set-valued function. Once we have exhausted the
721 * function's value(s) for a particular argument value, we have to
722 * get the next argument value and start the function over again.
723 * We might have to do it more than once, if the function produces
724 * an empty result set for a particular input value.
729 * If function is strict, and there are any NULL arguments,
730 * skip calling the function (at least for this set of args).
734 if (fcache->func.fn_strict)
736 for (i = 0; i < fcinfo.nargs; i++)
738 if (fcinfo.argnull[i])
748 fcinfo.isnull = false;
749 rsinfo.isDone = ExprSingleResult;
750 result = FunctionCallInvoke(&fcinfo);
751 *isNull = fcinfo.isnull;
752 *isDone = rsinfo.isDone;
758 *isDone = ExprEndResult;
761 if (*isDone != ExprEndResult)
764 * Got a result from current argument. If function itself
765 * returns set, save the current argument values to re-use
768 if (fcache->func.fn_retset)
770 memcpy(&fcache->setArgs, &fcinfo, sizeof(fcinfo));
771 fcache->setHasSetArg = hasSetArg;
772 fcache->setArgsValid = true;
776 * Make sure we say we are returning a set, even if the
777 * function itself doesn't return sets.
779 *isDone = ExprMultipleResult;
783 /* Else, done with this argument */
785 break; /* input not a set, so done */
787 /* Re-eval args to get the next element of the input set */
788 argDone = ExecEvalFuncArgs(&fcinfo, arguments, econtext);
790 if (argDone != ExprMultipleResult)
792 /* End of argument set, so we're done. */
794 *isDone = ExprEndResult;
800 * If we reach here, loop around to run the function on the
808 * Non-set case: much easier.
810 * If function is strict, and there are any NULL arguments, skip
811 * calling the function and return NULL.
813 if (fcache->func.fn_strict)
815 for (i = 0; i < fcinfo.nargs; i++)
817 if (fcinfo.argnull[i])
824 fcinfo.isnull = false;
825 result = FunctionCallInvoke(&fcinfo);
826 *isNull = fcinfo.isnull;
833 /* ----------------------------------------------------------------
837 * Evaluate the functional result of a list of arguments by calling the
839 * ----------------------------------------------------------------
842 /* ----------------------------------------------------------------
844 * ----------------------------------------------------------------
847 ExecEvalOper(Expr *opClause,
848 ExprContext *econtext,
850 ExprDoneCond *isDone)
854 FunctionCachePtr fcache;
857 * we extract the oid of the function associated with the op and then
858 * pass the work onto ExecMakeFunctionResult which evaluates the
859 * arguments and returns the result of calling the function on the
860 * evaluated arguments.
862 op = (Oper *) opClause->oper;
863 argList = opClause->args;
866 * get the fcache from the Oper node. If it is NULL, then initialize
869 fcache = op->op_fcache;
872 fcache = init_fcache(op->opid, length(argList),
873 econtext->ecxt_per_query_memory);
874 op->op_fcache = fcache;
877 return ExecMakeFunctionResult(fcache, argList, econtext,
881 /* ----------------------------------------------------------------
883 * ----------------------------------------------------------------
887 ExecEvalFunc(Expr *funcClause,
888 ExprContext *econtext,
890 ExprDoneCond *isDone)
894 FunctionCachePtr fcache;
897 * we extract the oid of the function associated with the func node
898 * and then pass the work onto ExecMakeFunctionResult which evaluates
899 * the arguments and returns the result of calling the function on the
900 * evaluated arguments.
902 * this is nearly identical to the ExecEvalOper code.
904 func = (Func *) funcClause->oper;
905 argList = funcClause->args;
908 * get the fcache from the Func node. If it is NULL, then initialize
911 fcache = func->func_fcache;
914 fcache = init_fcache(func->funcid, length(argList),
915 econtext->ecxt_per_query_memory);
916 func->func_fcache = fcache;
919 return ExecMakeFunctionResult(fcache, argList, econtext,
923 /* ----------------------------------------------------------------
928 * Evaluate boolean expressions. Evaluation of 'or' is
929 * short-circuited when the first true (or null) value is found.
931 * The query planner reformulates clause expressions in the
932 * qualification to conjunctive normal form. If we ever get
933 * an AND to evaluate, we can be sure that it's not a top-level
934 * clause in the qualification, but appears lower (as a function
935 * argument, for example), or in the target list. Not that you
936 * need to know this, mind you...
937 * ----------------------------------------------------------------
940 ExecEvalNot(Expr *notclause, ExprContext *econtext, bool *isNull)
945 clause = lfirst(notclause->args);
947 expr_value = ExecEvalExpr(clause, econtext, isNull, NULL);
950 * if the expression evaluates to null, then we just cascade the null
951 * back to whoever called us.
957 * evaluation of 'not' is simple.. expr is false, then return 'true'
960 return BoolGetDatum(!DatumGetBool(expr_value));
963 /* ----------------------------------------------------------------
965 * ----------------------------------------------------------------
968 ExecEvalOr(Expr *orExpr, ExprContext *econtext, bool *isNull)
975 clauses = orExpr->args;
979 * If any of the clauses is TRUE, the OR result is TRUE regardless of
980 * the states of the rest of the clauses, so we can stop evaluating
981 * and return TRUE immediately. If none are TRUE and one or more is
982 * NULL, we return NULL; otherwise we return FALSE. This makes sense
983 * when you interpret NULL as "don't know": if we have a TRUE then the
984 * OR is TRUE even if we aren't sure about some of the other inputs.
985 * If all the known inputs are FALSE, but we have one or more "don't
986 * knows", then we have to report that we "don't know" what the OR's
987 * result should be --- perhaps one of the "don't knows" would have
988 * been TRUE if we'd known its value. Only when all the inputs are
989 * known to be FALSE can we state confidently that the OR's result is
992 foreach(clause, clauses)
994 clause_value = ExecEvalExpr((Node *) lfirst(clause),
995 econtext, isNull, NULL);
998 * if we have a non-null true result, then return it.
1001 AnyNull = true; /* remember we got a null */
1002 else if (DatumGetBool(clause_value))
1003 return clause_value;
1006 /* AnyNull is true if at least one clause evaluated to NULL */
1008 return BoolGetDatum(false);
1011 /* ----------------------------------------------------------------
1013 * ----------------------------------------------------------------
1016 ExecEvalAnd(Expr *andExpr, ExprContext *econtext, bool *isNull)
1023 clauses = andExpr->args;
1027 * If any of the clauses is FALSE, the AND result is FALSE regardless
1028 * of the states of the rest of the clauses, so we can stop evaluating
1029 * and return FALSE immediately. If none are FALSE and one or more is
1030 * NULL, we return NULL; otherwise we return TRUE. This makes sense
1031 * when you interpret NULL as "don't know", using the same sort of
1032 * reasoning as for OR, above.
1034 foreach(clause, clauses)
1036 clause_value = ExecEvalExpr((Node *) lfirst(clause),
1037 econtext, isNull, NULL);
1040 * if we have a non-null false result, then return it.
1043 AnyNull = true; /* remember we got a null */
1044 else if (!DatumGetBool(clause_value))
1045 return clause_value;
1048 /* AnyNull is true if at least one clause evaluated to NULL */
1050 return BoolGetDatum(!AnyNull);
1053 /* ----------------------------------------------------------------
1056 * Evaluate a CASE clause. Will have boolean expressions
1057 * inside the WHEN clauses, and will have expressions
1059 * - thomas 1998-11-09
1060 * ----------------------------------------------------------------
1063 ExecEvalCase(CaseExpr *caseExpr, ExprContext *econtext,
1064 bool *isNull, ExprDoneCond *isDone)
1070 clauses = caseExpr->args;
1073 * we evaluate each of the WHEN clauses in turn, as soon as one is
1074 * true we return the corresponding result. If none are true then we
1075 * return the value of the default clause, or NULL if there is none.
1077 foreach(clause, clauses)
1079 CaseWhen *wclause = lfirst(clause);
1081 clause_value = ExecEvalExpr(wclause->expr,
1087 * if we have a true test, then we return the result, since the
1088 * case statement is satisfied. A NULL result from the test is
1089 * not considered true.
1091 if (DatumGetBool(clause_value) && !*isNull)
1093 return ExecEvalExpr(wclause->result,
1100 if (caseExpr->defresult)
1102 return ExecEvalExpr(caseExpr->defresult,
1112 /* ----------------------------------------------------------------
1115 * Evaluate a NullTest node.
1116 * ----------------------------------------------------------------
1119 ExecEvalNullTest(NullTest *ntest,
1120 ExprContext *econtext,
1122 ExprDoneCond *isDone)
1126 result = ExecEvalExpr(ntest->arg, econtext, isNull, isDone);
1127 switch (ntest->nulltesttype)
1133 return BoolGetDatum(true);
1136 return BoolGetDatum(false);
1141 return BoolGetDatum(false);
1144 return BoolGetDatum(true);
1146 elog(ERROR, "ExecEvalNullTest: unexpected nulltesttype %d",
1147 (int) ntest->nulltesttype);
1148 return (Datum) 0; /* keep compiler quiet */
1152 /* ----------------------------------------------------------------
1153 * ExecEvalBooleanTest
1155 * Evaluate a BooleanTest node.
1156 * ----------------------------------------------------------------
1159 ExecEvalBooleanTest(BooleanTest *btest,
1160 ExprContext *econtext,
1162 ExprDoneCond *isDone)
1166 result = ExecEvalExpr(btest->arg, econtext, isNull, isDone);
1167 switch (btest->booltesttype)
1173 return BoolGetDatum(false);
1175 else if (DatumGetBool(result))
1176 return BoolGetDatum(true);
1178 return BoolGetDatum(false);
1183 return BoolGetDatum(true);
1185 else if (DatumGetBool(result))
1186 return BoolGetDatum(false);
1188 return BoolGetDatum(true);
1193 return BoolGetDatum(false);
1195 else if (DatumGetBool(result))
1196 return BoolGetDatum(false);
1198 return BoolGetDatum(true);
1203 return BoolGetDatum(true);
1205 else if (DatumGetBool(result))
1206 return BoolGetDatum(true);
1208 return BoolGetDatum(false);
1213 return BoolGetDatum(true);
1216 return BoolGetDatum(false);
1217 case IS_NOT_UNKNOWN:
1221 return BoolGetDatum(false);
1224 return BoolGetDatum(true);
1226 elog(ERROR, "ExecEvalBooleanTest: unexpected booltesttype %d",
1227 (int) btest->booltesttype);
1228 return (Datum) 0; /* keep compiler quiet */
1232 /* ----------------------------------------------------------------
1233 * ExecEvalFieldSelect
1235 * Evaluate a FieldSelect node.
1236 * ----------------------------------------------------------------
1239 ExecEvalFieldSelect(FieldSelect *fselect,
1240 ExprContext *econtext,
1242 ExprDoneCond *isDone)
1245 TupleTableSlot *resSlot;
1247 result = ExecEvalExpr(fselect->arg, econtext, isNull, isDone);
1250 resSlot = (TupleTableSlot *) DatumGetPointer(result);
1251 Assert(resSlot != NULL && IsA(resSlot, TupleTableSlot));
1252 result = heap_getattr(resSlot->val,
1254 resSlot->ttc_tupleDescriptor,
1259 /* ----------------------------------------------------------------
1262 * Recursively evaluate a targetlist or qualification expression.
1265 * expression: the expression tree to evaluate
1266 * econtext: evaluation context information
1269 * return value: Datum value of result
1270 * *isNull: set to TRUE if result is NULL (actual return value is
1271 * meaningless if so); set to FALSE if non-null result
1272 * *isDone: set to indicator of set-result status
1274 * A caller that can only accept a singleton (non-set) result should pass
1275 * NULL for isDone; if the expression computes a set result then an elog()
1276 * error will be reported. If the caller does pass an isDone pointer then
1277 * *isDone is set to one of these three states:
1278 * ExprSingleResult singleton result (not a set)
1279 * ExprMultipleResult return value is one element of a set
1280 * ExprEndResult there are no more elements in the set
1281 * When ExprMultipleResult is returned, the caller should invoke
1282 * ExecEvalExpr() repeatedly until ExprEndResult is returned. ExprEndResult
1283 * is returned after the last real set element. For convenience isNull will
1284 * always be set TRUE when ExprEndResult is returned, but this should not be
1285 * taken as indicating a NULL element of the set. Note that these return
1286 * conventions allow us to distinguish among a singleton NULL, a NULL element
1287 * of a set, and an empty set.
1289 * The caller should already have switched into the temporary memory
1290 * context econtext->ecxt_per_tuple_memory. The convenience entry point
1291 * ExecEvalExprSwitchContext() is provided for callers who don't prefer to
1292 * do the switch in an outer loop. We do not do the switch here because
1293 * it'd be a waste of cycles during recursive entries to ExecEvalExpr().
1295 * This routine is an inner loop routine and must be as fast as possible.
1296 * ----------------------------------------------------------------
1299 ExecEvalExpr(Node *expression,
1300 ExprContext *econtext,
1302 ExprDoneCond *isDone)
1306 /* Set default values for result flags: non-null, not a set result */
1309 *isDone = ExprSingleResult;
1311 /* Is this still necessary? Doubtful... */
1312 if (expression == NULL)
1319 * here we dispatch the work to the appropriate type of function given
1320 * the type of our expression.
1322 switch (nodeTag(expression))
1325 retDatum = ExecEvalVar((Var *) expression, econtext, isNull);
1329 Const *con = (Const *) expression;
1331 retDatum = con->constvalue;
1332 *isNull = con->constisnull;
1336 retDatum = ExecEvalParam((Param *) expression, econtext, isNull);
1339 retDatum = ExecEvalIter((Iter *) expression,
1345 retDatum = ExecEvalAggref((Aggref *) expression, econtext, isNull);
1348 retDatum = ExecEvalArrayRef((ArrayRef *) expression,
1355 Expr *expr = (Expr *) expression;
1357 switch (expr->opType)
1360 retDatum = ExecEvalOper(expr, econtext,
1364 retDatum = ExecEvalFunc(expr, econtext,
1368 retDatum = ExecEvalOr(expr, econtext, isNull);
1371 retDatum = ExecEvalAnd(expr, econtext, isNull);
1374 retDatum = ExecEvalNot(expr, econtext, isNull);
1377 retDatum = ExecSubPlan((SubPlan *) expr->oper,
1378 expr->args, econtext,
1382 elog(ERROR, "ExecEvalExpr: unknown expression type %d",
1384 retDatum = 0; /* keep compiler quiet */
1390 retDatum = ExecEvalFieldSelect((FieldSelect *) expression,
1396 retDatum = ExecEvalExpr(((RelabelType *) expression)->arg,
1402 retDatum = ExecEvalCase((CaseExpr *) expression,
1408 retDatum = ExecEvalNullTest((NullTest *) expression,
1414 retDatum = ExecEvalBooleanTest((BooleanTest *) expression,
1421 elog(ERROR, "ExecEvalExpr: unknown expression type %d",
1422 nodeTag(expression));
1423 retDatum = 0; /* keep compiler quiet */
1428 } /* ExecEvalExpr() */
1432 * Same as above, but get into the right allocation context explicitly.
1435 ExecEvalExprSwitchContext(Node *expression,
1436 ExprContext *econtext,
1438 ExprDoneCond *isDone)
1441 MemoryContext oldContext;
1443 oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
1444 retDatum = ExecEvalExpr(expression, econtext, isNull, isDone);
1445 MemoryContextSwitchTo(oldContext);
1450 /* ----------------------------------------------------------------
1451 * ExecQual / ExecTargetList / ExecProject
1452 * ----------------------------------------------------------------
1455 /* ----------------------------------------------------------------
1458 * Evaluates a conjunctive boolean expression (qual list) and
1459 * returns true iff none of the subexpressions are false.
1460 * (We also return true if the list is empty.)
1462 * If some of the subexpressions yield NULL but none yield FALSE,
1463 * then the result of the conjunction is NULL (ie, unknown)
1464 * according to three-valued boolean logic. In this case,
1465 * we return the value specified by the "resultForNull" parameter.
1467 * Callers evaluating WHERE clauses should pass resultForNull=FALSE,
1468 * since SQL specifies that tuples with null WHERE results do not
1469 * get selected. On the other hand, callers evaluating constraint
1470 * conditions should pass resultForNull=TRUE, since SQL also specifies
1471 * that NULL constraint conditions are not failures.
1473 * NOTE: it would not be correct to use this routine to evaluate an
1474 * AND subclause of a boolean expression; for that purpose, a NULL
1475 * result must be returned as NULL so that it can be properly treated
1476 * in the next higher operator (cf. ExecEvalAnd and ExecEvalOr).
1477 * This routine is only used in contexts where a complete expression
1478 * is being evaluated and we know that NULL can be treated the same
1479 * as one boolean result or the other.
1481 * ----------------------------------------------------------------
1484 ExecQual(List *qual, ExprContext *econtext, bool resultForNull)
1487 MemoryContext oldContext;
1493 EV_printf("ExecQual: qual is ");
1494 EV_nodeDisplay(qual);
1500 * Run in short-lived per-tuple context while computing expressions.
1502 oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
1505 * Evaluate the qual conditions one at a time. If we find a FALSE
1506 * result, we can stop evaluating and return FALSE --- the AND result
1507 * must be FALSE. Also, if we find a NULL result when resultForNull
1508 * is FALSE, we can stop and return FALSE --- the AND result must be
1509 * FALSE or NULL in that case, and the caller doesn't care which.
1511 * If we get to the end of the list, we can return TRUE. This will
1512 * happen when the AND result is indeed TRUE, or when the AND result
1513 * is NULL (one or more NULL subresult, with all the rest TRUE) and
1514 * the caller has specified resultForNull = TRUE.
1518 foreach(qlist, qual)
1520 Node *clause = (Node *) lfirst(qlist);
1524 expr_value = ExecEvalExpr(clause, econtext, &isNull, NULL);
1528 if (resultForNull == false)
1530 result = false; /* treat NULL as FALSE */
1536 if (!DatumGetBool(expr_value))
1538 result = false; /* definitely FALSE */
1544 MemoryContextSwitchTo(oldContext);
1550 * Number of items in a tlist (including any resjunk items!)
1553 ExecTargetListLength(List *targetlist)
1558 foreach(tl, targetlist)
1560 TargetEntry *curTle = (TargetEntry *) lfirst(tl);
1562 if (curTle->resdom != NULL)
1565 len += curTle->fjoin->fj_nNodes;
1571 * Number of items in a tlist, not including any resjunk items
1574 ExecCleanTargetListLength(List *targetlist)
1579 foreach(tl, targetlist)
1581 TargetEntry *curTle = (TargetEntry *) lfirst(tl);
1583 if (curTle->resdom != NULL)
1585 if (!curTle->resdom->resjunk)
1589 len += curTle->fjoin->fj_nNodes;
1594 /* ----------------------------------------------------------------
1597 * Evaluates a targetlist with respect to the current
1598 * expression context and return a tuple.
1600 * As with ExecEvalExpr, the caller should pass isDone = NULL if not
1601 * prepared to deal with sets of result tuples. Otherwise, a return
1602 * of *isDone = ExprMultipleResult signifies a set element, and a return
1603 * of *isDone = ExprEndResult signifies end of the set of tuple.
1604 * ----------------------------------------------------------------
1607 ExecTargetList(List *targetlist,
1609 TupleDesc targettype,
1611 ExprContext *econtext,
1612 ExprDoneCond *isDone)
1614 MemoryContext oldContext;
1616 #define NPREALLOCDOMAINS 64
1617 char nullsArray[NPREALLOCDOMAINS];
1618 bool fjIsNullArray[NPREALLOCDOMAINS];
1619 ExprDoneCond itemIsDoneArray[NPREALLOCDOMAINS];
1622 ExprDoneCond *itemIsDone;
1629 static struct tupleDesc NullTupleDesc; /* we assume this inits to
1635 EV_printf("ExecTargetList: tl is ");
1636 EV_nodeDisplay(targetlist);
1640 * Run in short-lived per-tuple context while computing expressions.
1642 oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
1645 * There used to be some klugy and demonstrably broken code here that
1646 * special-cased the situation where targetlist == NIL. Now we just
1647 * fall through and return an empty-but-valid tuple. We do, however,
1648 * have to cope with the possibility that targettype is NULL ---
1649 * heap_formtuple won't like that, so pass a dummy descriptor with
1650 * natts = 0 to deal with it.
1652 if (targettype == NULL)
1653 targettype = &NullTupleDesc;
1656 * allocate an array of char's to hold the "null" information only if
1657 * we have a really large targetlist. otherwise we use the stack.
1659 * We also allocate a bool array that is used to hold fjoin result state,
1660 * and another array that holds the isDone status for each targetlist
1661 * item. The isDone status is needed so that we can iterate,
1662 * generating multiple tuples, when one or more tlist items return
1663 * sets. (We expect the caller to call us again if we return:
1665 * isDone = ExprMultipleResult.)
1667 if (nodomains > NPREALLOCDOMAINS)
1669 nulls = (char *) palloc(nodomains * sizeof(char));
1670 fjIsNull = (bool *) palloc(nodomains * sizeof(bool));
1671 itemIsDone = (ExprDoneCond *) palloc(nodomains * sizeof(ExprDoneCond));
1676 fjIsNull = fjIsNullArray;
1677 itemIsDone = itemIsDoneArray;
1681 * evaluate all the expressions in the target list
1685 *isDone = ExprSingleResult; /* until proven otherwise */
1687 haveDoneSets = false; /* any exhausted set exprs in tlist? */
1689 foreach(tl, targetlist)
1693 if (tle->resdom != NULL)
1695 resind = tle->resdom->resno - 1;
1697 values[resind] = ExecEvalExpr(tle->expr,
1700 &itemIsDone[resind]);
1701 nulls[resind] = isNull ? 'n' : ' ';
1703 if (itemIsDone[resind] != ExprSingleResult)
1705 /* We have a set-valued expression in the tlist */
1707 elog(ERROR, "Set-valued function called in context that cannot accept a set");
1708 if (itemIsDone[resind] == ExprMultipleResult)
1710 /* we have undone sets in the tlist, set flag */
1711 *isDone = ExprMultipleResult;
1715 /* we have done sets in the tlist, set flag for that */
1716 haveDoneSets = true;
1725 List *fjTlist = (List *) tle->expr;
1726 Fjoin *fjNode = tle->fjoin;
1727 int nNodes = fjNode->fj_nNodes;
1728 DatumPtr results = fjNode->fj_results;
1730 ExecEvalFjoin(tle, econtext, fjIsNull, isDone);
1733 * XXX this is wrong, but since fjoin code is completely
1734 * broken anyway, I'm not going to worry about it now --- tgl
1737 if (isDone && *isDone == ExprEndResult)
1739 MemoryContextSwitchTo(oldContext);
1745 * get the result from the inner node
1747 fjRes = (Resdom *) fjNode->fj_innerNode;
1748 resind = fjRes->resno - 1;
1749 values[resind] = results[0];
1750 nulls[resind] = fjIsNull[0] ? 'n' : ' ';
1753 * Get results from all of the outer nodes
1757 curNode++, fjTlist = lnext(fjTlist))
1759 Node *outernode = lfirst(fjTlist);
1761 fjRes = (Resdom *) outernode->iterexpr;
1762 resind = fjRes->resno - 1;
1763 values[resind] = results[curNode];
1764 nulls[resind] = fjIsNull[curNode] ? 'n' : ' ';
1767 elog(ERROR, "ExecTargetList: fjoin nodes not currently supported");
1775 * note: can't get here unless we verified isDone != NULL
1777 if (*isDone == ExprSingleResult)
1780 * all sets are done, so report that tlist expansion is
1783 *isDone = ExprEndResult;
1784 MemoryContextSwitchTo(oldContext);
1791 * We have some done and some undone sets. Restart the done
1792 * ones so that we can deliver a tuple (if possible).
1794 foreach(tl, targetlist)
1798 if (tle->resdom != NULL)
1800 resind = tle->resdom->resno - 1;
1802 if (itemIsDone[resind] == ExprEndResult)
1804 values[resind] = ExecEvalExpr(tle->expr,
1807 &itemIsDone[resind]);
1808 nulls[resind] = isNull ? 'n' : ' ';
1810 if (itemIsDone[resind] == ExprEndResult)
1813 * Oh dear, this item is returning an empty
1814 * set. Guess we can't make a tuple after all.
1816 *isDone = ExprEndResult;
1824 * If we cannot make a tuple because some sets are empty, we
1825 * still have to cycle the nonempty sets to completion, else
1826 * resources will not be released from subplans etc.
1828 if (*isDone == ExprEndResult)
1830 foreach(tl, targetlist)
1834 if (tle->resdom != NULL)
1836 resind = tle->resdom->resno - 1;
1838 while (itemIsDone[resind] == ExprMultipleResult)
1840 (void) ExecEvalExpr(tle->expr,
1843 &itemIsDone[resind]);
1848 MemoryContextSwitchTo(oldContext);
1856 * form the new result tuple (in the caller's memory context!)
1858 MemoryContextSwitchTo(oldContext);
1860 newTuple = (HeapTuple) heap_formtuple(targettype, values, nulls);
1865 * free the status arrays if we palloc'd them
1867 if (nodomains > NPREALLOCDOMAINS)
1877 /* ----------------------------------------------------------------
1880 * projects a tuple based on projection info and stores
1881 * it in the specified tuple table slot.
1883 * Note: someday soon the executor can be extended to eliminate
1884 * redundant projections by storing pointers to datums
1885 * in the tuple table and then passing these around when
1886 * possible. this should make things much quicker.
1888 * ----------------------------------------------------------------
1891 ExecProject(ProjectionInfo *projInfo, ExprDoneCond *isDone)
1893 TupleTableSlot *slot;
1898 ExprContext *econtext;
1904 if (projInfo == NULL)
1905 return (TupleTableSlot *) NULL;
1908 * get the projection info we want
1910 slot = projInfo->pi_slot;
1911 targetlist = projInfo->pi_targetlist;
1912 len = projInfo->pi_len;
1913 tupType = slot->ttc_tupleDescriptor;
1915 tupValue = projInfo->pi_tupValue;
1916 econtext = projInfo->pi_exprContext;
1919 * form a new result tuple (if possible --- result can be NULL)
1921 newTuple = ExecTargetList(targetlist,
1929 * store the tuple in the projection slot and return the slot.
1931 return ExecStoreTuple(newTuple, /* tuple to store */
1932 slot, /* slot to store in */
1933 InvalidBuffer, /* tuple has no buffer */