1 /*-------------------------------------------------------------------------
4 * Routines to evaluate qualification and targetlist expressions
6 * Portions Copyright (c) 1996-2000, PostgreSQL, Inc
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $Header: /cvsroot/pgsql/src/backend/executor/execQual.c,v 1.69 2000/04/12 17:15:08 momjian Exp $
13 *-------------------------------------------------------------------------
17 * ExecEvalExpr - evaluate an expression and return a datum
18 * ExecQual - return true/false if qualification is satisfied
19 * ExecTargetList - form a new tuple by projecting the given tuple
22 * ExecEvalExpr() and ExecEvalVar() are hotspots. making these faster
23 * will speed up the entire system. Unfortunately they are currently
24 * implemented recursively. Eliminating the recursion is bound to
25 * improve the speed of the executor.
27 * ExecTargetList() is used to make tuple projections. Rather then
28 * trying to speed it up, the execution plan should be pre-processed
29 * to facilitate attribute sharing between nodes wherever possible,
30 * instead of doing needless copying. -cim 5/31/91
36 #include "access/heapam.h"
37 #include "catalog/pg_language.h"
38 #include "executor/execFlatten.h"
39 #include "executor/execdebug.h"
40 #include "executor/executor.h"
41 #include "executor/functions.h"
42 #include "executor/nodeSubplan.h"
43 #include "utils/builtins.h"
44 #include "utils/fcache2.h"
48 * externs and constants
52 * XXX Used so we can get rid of use of Const nodes in the executor.
53 * Currently only used by ExecHashGetBucket and set only by ExecMakeVarConst
54 * and by ExecEvalArrayRef.
59 /* static functions decls */
60 static Datum ExecEvalAggref(Aggref *aggref, ExprContext *econtext, bool *isNull);
61 static Datum ExecEvalArrayRef(ArrayRef *arrayRef, ExprContext *econtext,
62 bool *isNull, bool *isDone);
63 static Datum ExecEvalAnd(Expr *andExpr, ExprContext *econtext, bool *isNull);
64 static Datum ExecEvalFunc(Expr *funcClause, ExprContext *econtext,
65 bool *isNull, bool *isDone);
66 static void ExecEvalFuncArgs(FunctionCachePtr fcache, ExprContext *econtext,
67 List *argList, Datum argV[], bool *argIsDone);
68 static Datum ExecEvalNot(Expr *notclause, ExprContext *econtext, bool *isNull);
69 static Datum ExecEvalOper(Expr *opClause, ExprContext *econtext,
71 static Datum ExecEvalOr(Expr *orExpr, ExprContext *econtext, bool *isNull);
72 static Datum ExecEvalVar(Var *variable, ExprContext *econtext, bool *isNull);
73 static Datum ExecMakeFunctionResult(Node *node, List *arguments,
74 ExprContext *econtext, bool *isNull, bool *isDone);
79 * This function takes an ArrayRef and returns a Const Node if it
80 * is an array reference or returns the changed Array Node if it is
81 * an array assignment.
84 ExecEvalArrayRef(ArrayRef *arrayRef,
85 ExprContext *econtext,
89 ArrayType *array_scanner;
100 if (arrayRef->refexpr != NULL)
102 array_scanner = (ArrayType *) ExecEvalExpr(arrayRef->refexpr,
113 * Null refexpr indicates we are doing an INSERT into an array
114 * column. For now, we just take the refassgnexpr (which the
115 * parser will have ensured is an array value) and return it
116 * as-is, ignoring any subscripts that may have been supplied in
117 * the INSERT column list. This is a kluge, but it's not real
118 * clear what the semantics ought to be...
120 array_scanner = NULL;
123 foreach(elt, arrayRef->refupperindexpr)
126 elog(ERROR, "ExecEvalArrayRef: can only handle %d dimensions",
129 upper.indx[i++] = (int32) ExecEvalExpr((Node *) lfirst(elt),
137 if (arrayRef->reflowerindexpr != NIL)
139 foreach(elt, arrayRef->reflowerindexpr)
142 elog(ERROR, "ExecEvalArrayRef: can only handle %d dimensions",
145 lower.indx[j++] = (int32) ExecEvalExpr((Node *) lfirst(elt),
154 "ExecEvalArrayRef: upper and lower indices mismatch");
160 if (arrayRef->refassgnexpr != NULL)
162 Datum sourceData = ExecEvalExpr(arrayRef->refassgnexpr,
170 execConstByVal = arrayRef->refelembyval;
171 execConstLen = arrayRef->refelemlength;
173 if (array_scanner == NULL)
174 return sourceData; /* XXX do something else? */
177 return (Datum) array_set(array_scanner, i, upper.indx,
179 arrayRef->refelembyval,
180 arrayRef->refelemlength,
181 arrayRef->refattrlength, isNull);
182 return (Datum) array_assgn(array_scanner, i, upper.indx,
184 (ArrayType *) sourceData,
185 arrayRef->refelembyval,
186 arrayRef->refelemlength, isNull);
189 execConstByVal = arrayRef->refelembyval;
190 execConstLen = arrayRef->refelemlength;
193 return (Datum) array_ref(array_scanner, i, upper.indx,
194 arrayRef->refelembyval,
195 arrayRef->refelemlength,
196 arrayRef->refattrlength, isNull);
197 return (Datum) array_clip(array_scanner, i, upper.indx, lower.indx,
198 arrayRef->refelembyval,
199 arrayRef->refelemlength, isNull);
203 /* ----------------------------------------------------------------
206 * Returns a Datum whose value is the value of the precomputed
207 * aggregate found in the given expression context.
208 * ----------------------------------------------------------------
211 ExecEvalAggref(Aggref *aggref, ExprContext *econtext, bool *isNull)
213 if (econtext->ecxt_aggvalues == NULL) /* safety check */
214 elog(ERROR, "ExecEvalAggref: no aggregates in this expression context");
216 *isNull = econtext->ecxt_aggnulls[aggref->aggno];
217 return econtext->ecxt_aggvalues[aggref->aggno];
220 /* ----------------------------------------------------------------
223 * Returns a Datum whose value is the value of a range
224 * variable with respect to given expression context.
227 * As an entry condition, we expect that the datatype the
228 * plan expects to get (as told by our "variable" argument) is in
229 * fact the datatype of the attribute the plan says to fetch (as
230 * seen in the current context, identified by our "econtext"
233 * If we fetch a Type A attribute and Caller treats it as if it
234 * were Type B, there will be undefined results (e.g. crash).
235 * One way these might mismatch now is that we're accessing a
236 * catalog class and the type information in the pg_attribute
237 * class does not match the hardcoded pg_attribute information
238 * (in pg_attribute.h) for the class in question.
240 * We have an Assert to make sure this entry condition is met.
242 * ---------------------------------------------------------------- */
244 ExecEvalVar(Var *variable, ExprContext *econtext, bool *isNull)
247 TupleTableSlot *slot;
250 TupleDesc tuple_type;
255 * get the slot we want
257 switch (variable->varno)
259 case INNER: /* get the tuple from the inner node */
260 slot = econtext->ecxt_innertuple;
263 case OUTER: /* get the tuple from the outer node */
264 slot = econtext->ecxt_outertuple;
267 default: /* get the tuple from the relation being
269 slot = econtext->ecxt_scantuple;
274 * extract tuple information from the slot
276 heapTuple = slot->val;
277 tuple_type = slot->ttc_tupleDescriptor;
279 attnum = variable->varattno;
281 /* (See prolog for explanation of this Assert) */
282 Assert(attnum <= 0 ||
283 (attnum - 1 <= tuple_type->natts - 1 &&
284 tuple_type->attrs[attnum - 1] != NULL &&
285 variable->vartype == tuple_type->attrs[attnum - 1]->atttypid));
288 * If the attribute number is invalid, then we are supposed to return
289 * the entire tuple, we give back a whole slot so that callers know
290 * what the tuple looks like.
292 if (attnum == InvalidAttrNumber)
294 TupleTableSlot *tempSlot;
298 tempSlot = makeNode(TupleTableSlot);
299 tempSlot->ttc_shouldFree = false;
300 tempSlot->ttc_descIsNew = true;
301 tempSlot->ttc_tupleDescriptor = (TupleDesc) NULL;
302 tempSlot->ttc_buffer = InvalidBuffer;
303 tempSlot->ttc_whichplan = -1;
305 tup = heap_copytuple(heapTuple);
306 td = CreateTupleDescCopy(tuple_type);
308 ExecSetSlotDescriptor(tempSlot, td);
310 ExecStoreTuple(tup, tempSlot, InvalidBuffer, true);
311 return (Datum) tempSlot;
314 result = heap_getattr(heapTuple, /* tuple containing attribute */
315 attnum, /* attribute number of desired
317 tuple_type, /* tuple descriptor of tuple */
318 isNull); /* return: is attribute null? */
321 * return null if att is null
327 * get length and type information.. ??? what should we do about
328 * variable length attributes - variable length attributes have their
329 * length stored in the first 4 bytes of the memory pointed to by the
330 * returned value.. If we can determine that the type is a variable
331 * length type, we can do the right thing. -cim 9/15/89
337 * If this is a pseudo-att, we get the type and fake the length.
338 * There ought to be a routine to return the real lengths, so
339 * we'll mark this one ... XXX -mao
341 len = heap_sysattrlen(attnum); /* XXX see -mao above */
342 byval = heap_sysattrbyval(attnum); /* XXX see -mao above */
346 len = tuple_type->attrs[attnum - 1]->attlen;
347 byval = tuple_type->attrs[attnum - 1]->attbyval ? true : false;
350 execConstByVal = byval;
356 /* ----------------------------------------------------------------
359 * Returns the value of a parameter. A param node contains
360 * something like ($.name) and the expression context contains
361 * the current parameter bindings (name = "sam") (age = 34)...
362 * so our job is to replace the param node with the datum
363 * containing the appropriate information ("sam").
365 * Q: if we have a parameter ($.foo) without a binding, i.e.
366 * there is no (foo = xxx) in the parameter list info,
367 * is this a fatal error or should this be a "not available"
368 * (in which case we shoud return a Const node with the
369 * isnull flag) ? -cim 10/13/89
371 * Minor modification: Param nodes now have an extra field,
372 * `paramkind' which specifies the type of parameter
373 * (see params.h). So while searching the paramList for
374 * a paramname/value pair, we have also to check for `kind'.
376 * NOTE: The last entry in `paramList' is always an
377 * entry with kind == PARAM_INVALID.
378 * ----------------------------------------------------------------
381 ExecEvalParam(Param *expression, ExprContext *econtext, bool *isNull)
384 char *thisParameterName;
385 int thisParameterKind = expression->paramkind;
386 AttrNumber thisParameterId = expression->paramid;
388 ParamListInfo paramList;
390 if (thisParameterKind == PARAM_EXEC)
392 ParamExecData *prm = &(econtext->ecxt_param_exec_vals[thisParameterId]);
394 if (prm->execPlan != NULL)
395 ExecSetParamPlan(prm->execPlan);
396 Assert(prm->execPlan == NULL);
397 *isNull = prm->isnull;
401 thisParameterName = expression->paramname;
402 paramList = econtext->ecxt_param_list_info;
407 * search the list with the parameter info to find a matching name. An
408 * entry with an InvalidName denotes the last element in the array.
411 if (paramList != NULL)
415 * search for an entry in 'paramList' that matches the
418 while (paramList->kind != PARAM_INVALID && !matchFound)
420 switch (thisParameterKind)
423 if (thisParameterKind == paramList->kind &&
424 strcmp(paramList->name, thisParameterName) == 0)
428 if (thisParameterKind == paramList->kind &&
429 paramList->id == thisParameterId)
434 if (thisParameterKind == paramList->kind &&
435 paramList->id == thisParameterId)
442 if (strcmp(paramList->name, thisParameterName) != 0)
445 "ExecEvalParam: new/old params with same id & diff names");
452 * oops! this is not supposed to happen!
454 elog(ERROR, "ExecEvalParam: invalid paramkind %d",
466 * ooops! we couldn't find this parameter in the parameter list.
469 elog(ERROR, "ExecEvalParam: Unknown value for parameter %s",
476 if (paramList->isnull)
482 if (expression->param_tlist != NIL)
486 List *tlist = expression->param_tlist;
487 TargetEntry *tle = (TargetEntry *) lfirst(tlist);
488 TupleTableSlot *slot = (TupleTableSlot *) paramList->value;
491 value = ProjectAttribute(slot->ttc_tupleDescriptor,
495 return paramList->value;
499 /* ----------------------------------------------------------------
500 * ExecEvalOper / ExecEvalFunc support routines
501 * ----------------------------------------------------------------
508 * These are functions which return the value of the
509 * named attribute out of the tuple from the arg slot. User defined
510 * C functions which take a tuple as an argument are expected
511 * to use this. Ex: overpaid(EMP) might call GetAttributeByNum().
513 /* static but gets called from external functions */
515 GetAttributeByNum(TupleTableSlot *slot,
521 if (!AttributeNumberIsValid(attrno))
522 elog(ERROR, "GetAttributeByNum: Invalid attribute number");
524 if (!AttrNumberIsForUserDefinedAttr(attrno))
525 elog(ERROR, "GetAttributeByNum: cannot access system attributes here");
527 if (isNull == (bool *) NULL)
528 elog(ERROR, "GetAttributeByNum: a NULL isNull flag was passed");
533 return (char *) NULL;
536 retval = heap_getattr(slot->val,
538 slot->ttc_tupleDescriptor,
541 return (char *) NULL;
542 return (char *) retval;
545 /* XXX name for catalogs */
548 att_by_num(TupleTableSlot *slot,
552 return GetAttributeByNum(slot, attrno, isNull);
558 GetAttributeByName(TupleTableSlot *slot, char *attname, bool *isNull)
567 elog(ERROR, "GetAttributeByName: Invalid attribute name");
569 if (isNull == (bool *) NULL)
570 elog(ERROR, "GetAttributeByName: a NULL isNull flag was passed");
575 return (char *) NULL;
578 tupdesc = slot->ttc_tupleDescriptor;
579 natts = slot->val->t_data->t_natts;
581 attrno = InvalidAttrNumber;
582 for (i = 0; i < tupdesc->natts; i++)
584 if (namestrcmp(&(tupdesc->attrs[i]->attname), attname) == 0)
586 attrno = tupdesc->attrs[i]->attnum;
591 if (attrno == InvalidAttrNumber)
592 elog(ERROR, "GetAttributeByName: attribute %s not found", attname);
594 retval = heap_getattr(slot->val,
599 return (char *) NULL;
600 return (char *) retval;
603 /* XXX name for catalogs */
606 att_by_name(TupleTableSlot *slot, char *attname, bool *isNull)
608 return GetAttributeByName(slot, attname, isNull);
614 ExecEvalFuncArgs(FunctionCachePtr fcache,
615 ExprContext *econtext,
624 nullVect = fcache->nullVect;
627 foreach(arg, argList)
631 * evaluate the expression, in general functions cannot take sets
632 * as arguments but we make an exception in the case of nested dot
633 * expressions. We have to watch out for this case here.
635 argV[i] = ExecEvalExpr((Node *) lfirst(arg),
643 elog(ERROR, "functions can only take sets in their first argument");
644 fcache->setArg = (char *) argV[0];
645 fcache->hasSetArg = true;
652 * ExecMakeFunctionResult
655 ExecMakeFunctionResult(Node *node,
657 ExprContext *econtext,
661 Datum argV[FUNC_MAX_ARGS];
662 FunctionCachePtr fcache;
663 Func *funcNode = NULL;
664 Oper *operNode = NULL;
665 bool funcisset = false;
668 * This is kind of ugly, Func nodes now have targetlists so that we
669 * know when and what to project out from postquel function results.
670 * This means we have to pass the func node all the way down instead
671 * of using only the fcache struct as before. ExecMakeFunctionResult
672 * becomes a little bit more of a dual personality as a result.
676 funcNode = (Func *) node;
677 fcache = funcNode->func_fcache;
681 operNode = (Oper *) node;
682 fcache = operNode->op_fcache;
686 * arguments is a list of expressions to evaluate before passing to
687 * the function manager. We collect the results of evaluating the
688 * expressions into a datum array (argV) and pass this array to
691 if (fcache->nargs != 0)
695 if (fcache->nargs > FUNC_MAX_ARGS)
696 elog(ERROR, "ExecMakeFunctionResult: too many arguments");
699 * If the setArg in the fcache is set we have an argument
700 * returning a set of tuples (i.e. a nested dot expression). We
701 * don't want to evaluate the arguments again until the function
702 * is done. hasSetArg will always be false until we eval the args
703 * for the first time. We should set this in the parser.
705 if ((fcache->hasSetArg) && fcache->setArg != NULL)
707 argV[0] = (Datum) fcache->setArg;
711 ExecEvalFuncArgs(fcache, econtext, arguments, argV, &argDone);
713 if ((fcache->hasSetArg) && (argDone))
722 * If this function is really a set, we have to diddle with things. If
723 * the function has already been called at least once, then the setArg
724 * field of the fcache holds the OID of this set in pg_proc. (This is
725 * not quite legit, since the setArg field is really for functions
726 * which take sets of tuples as input - set functions take no inputs
727 * at all. But it's a nice place to stash this value, for now.)
729 * If this is the first call of the set's function, then the call to
730 * ExecEvalFuncArgs above just returned the OID of the pg_proc tuple
731 * which defines this set. So replace the existing funcid in the
732 * funcnode with the set's OID. Also, we want a new fcache which
733 * points to the right function, so get that, now that we have the
734 * right OID. Also zero out the argV, since the real set doesn't take
737 if (((Func *) node)->funcid == F_SETEVAL)
744 ((Func *) node)->funcid = (Oid) PointerGetDatum(fcache->setArg);
749 ((Func *) node)->funcid = (Oid) argV[0];
750 setFcache(node, argV[0], NIL, econtext);
751 fcache = ((Func *) node)->func_fcache;
752 fcache->setArg = (char *) argV[0];
758 * now return the value gotten by calling the function manager,
759 * passing the function the evaluated parameter values.
761 if (fcache->language == SQLlanguageId)
768 /*--------------------
769 * This loop handles the situation where we are iterating through
770 * all results in a nested dot function (whose argument function
771 * returns a set of tuples) and the current function finally
772 * finishes. We need to get the next argument in the set and start
773 * the function all over again. We might have to do it more than
774 * once, if the function produces no results for a particular argument.
775 * This is getting unclean.
776 *--------------------
780 result = postquel_function(funcNode, (char **) argV,
784 break; /* got a result from current argument */
785 if (!fcache->hasSetArg)
786 break; /* input not a set, so done */
788 /* OK, get the next argument... */
789 ExecEvalFuncArgs(fcache, econtext, arguments, argV, &argDone);
795 * End of arguments, so reset the setArg flag and say
798 fcache->setArg = (char *) NULL;
799 fcache->hasSetArg = false;
801 result = (Datum) NULL;
806 * If we reach here, loop around to run the function on the
815 * reset the funcid so that next call to this routine will
816 * still recognize this func as a set. Note that for now we
817 * assume that the set function in pg_proc must be a Postquel
818 * function - the funcid is not reset below for C functions.
820 ((Func *) node)->funcid = F_SETEVAL;
823 * If we're done with the results of this function, get rid of
827 ((Func *) node)->func_fcache = NULL;
838 for (i = 0; i < fcache->nargs; i++)
839 if (fcache->nullVect[i] == true)
842 return (Datum) fmgr_c(&fcache->func, (FmgrValues *) argV, isNull);
847 /* ----------------------------------------------------------------
851 * Evaluate the functional result of a list of arguments by calling the
852 * function manager. Note that in the case of operator expressions, the
853 * optimizer had better have already replaced the operator OID with the
854 * appropriate function OID or we're hosed.
857 * Presumably the function manager will not take null arguments, so we
858 * check for null arguments before sending the arguments to (fmgr).
860 * Returns the value of the functional expression.
861 * ----------------------------------------------------------------
864 /* ----------------------------------------------------------------
866 * ----------------------------------------------------------------
869 ExecEvalOper(Expr *opClause, ExprContext *econtext, bool *isNull)
873 FunctionCachePtr fcache;
877 * an opclause is a list (op args). (I think)
879 * we extract the oid of the function associated with the op and then
880 * pass the work onto ExecMakeFunctionResult which evaluates the
881 * arguments and returns the result of calling the function on the
882 * evaluated arguments.
884 op = (Oper *) opClause->oper;
885 argList = opClause->args;
888 * get the fcache from the Oper node. If it is NULL, then initialize
891 fcache = op->op_fcache;
894 setFcache((Node *) op, op->opid, argList, econtext);
895 fcache = op->op_fcache;
899 * call ExecMakeFunctionResult() with a dummy isDone that we ignore.
900 * We don't have operator whose arguments are sets.
902 return ExecMakeFunctionResult((Node *) op, argList, econtext, isNull, &isDone);
905 /* ----------------------------------------------------------------
907 * ----------------------------------------------------------------
911 ExecEvalFunc(Expr *funcClause,
912 ExprContext *econtext,
918 FunctionCachePtr fcache;
921 * an funcclause is a list (func args). (I think)
923 * we extract the oid of the function associated with the func node and
924 * then pass the work onto ExecMakeFunctionResult which evaluates the
925 * arguments and returns the result of calling the function on the
926 * evaluated arguments.
928 * this is nearly identical to the ExecEvalOper code.
930 func = (Func *) funcClause->oper;
931 argList = funcClause->args;
934 * get the fcache from the Func node. If it is NULL, then initialize
937 fcache = func->func_fcache;
940 setFcache((Node *) func, func->funcid, argList, econtext);
941 fcache = func->func_fcache;
944 return ExecMakeFunctionResult((Node *) func, argList, econtext, isNull, isDone);
947 /* ----------------------------------------------------------------
952 * Evaluate boolean expressions. Evaluation of 'or' is
953 * short-circuited when the first true (or null) value is found.
955 * The query planner reformulates clause expressions in the
956 * qualification to conjunctive normal form. If we ever get
957 * an AND to evaluate, we can be sure that it's not a top-level
958 * clause in the qualification, but appears lower (as a function
959 * argument, for example), or in the target list. Not that you
960 * need to know this, mind you...
961 * ----------------------------------------------------------------
964 ExecEvalNot(Expr *notclause, ExprContext *econtext, bool *isNull)
970 clause = lfirst(notclause->args);
973 * We don't iterate over sets in the quals, so pass in an isDone flag,
976 expr_value = ExecEvalExpr(clause, econtext, isNull, &isDone);
979 * if the expression evaluates to null, then we just cascade the null
980 * back to whoever called us.
986 * evaluation of 'not' is simple.. expr is false, then return 'true'
989 if (DatumGetInt32(expr_value) == 0)
992 return (Datum) false;
995 /* ----------------------------------------------------------------
997 * ----------------------------------------------------------------
1000 ExecEvalOr(Expr *orExpr, ExprContext *econtext, bool *isNull)
1008 clauses = orExpr->args;
1012 * If any of the clauses is TRUE, the OR result is TRUE regardless of
1013 * the states of the rest of the clauses, so we can stop evaluating
1014 * and return TRUE immediately. If none are TRUE and one or more is
1015 * NULL, we return NULL; otherwise we return FALSE. This makes sense
1016 * when you interpret NULL as "don't know": if we have a TRUE then the
1017 * OR is TRUE even if we aren't sure about some of the other inputs.
1018 * If all the known inputs are FALSE, but we have one or more "don't
1019 * knows", then we have to report that we "don't know" what the OR's
1020 * result should be --- perhaps one of the "don't knows" would have
1021 * been TRUE if we'd known its value. Only when all the inputs are
1022 * known to be FALSE can we state confidently that the OR's result is
1025 foreach(clause, clauses)
1029 * We don't iterate over sets in the quals, so pass in an isDone
1030 * flag, but ignore it.
1032 clause_value = ExecEvalExpr((Node *) lfirst(clause),
1038 * if we have a non-null true result, then return it.
1041 AnyNull = true; /* remember we got a null */
1042 else if (DatumGetInt32(clause_value) != 0)
1043 return clause_value;
1046 /* AnyNull is true if at least one clause evaluated to NULL */
1048 return (Datum) false;
1051 /* ----------------------------------------------------------------
1053 * ----------------------------------------------------------------
1056 ExecEvalAnd(Expr *andExpr, ExprContext *econtext, bool *isNull)
1064 clauses = andExpr->args;
1068 * If any of the clauses is FALSE, the AND result is FALSE regardless
1069 * of the states of the rest of the clauses, so we can stop evaluating
1070 * and return FALSE immediately. If none are FALSE and one or more is
1071 * NULL, we return NULL; otherwise we return TRUE. This makes sense
1072 * when you interpret NULL as "don't know", using the same sort of
1073 * reasoning as for OR, above.
1075 foreach(clause, clauses)
1079 * We don't iterate over sets in the quals, so pass in an isDone
1080 * flag, but ignore it.
1082 clause_value = ExecEvalExpr((Node *) lfirst(clause),
1088 * if we have a non-null false result, then return it.
1091 AnyNull = true; /* remember we got a null */
1092 else if (DatumGetInt32(clause_value) == 0)
1093 return clause_value;
1096 /* AnyNull is true if at least one clause evaluated to NULL */
1098 return (Datum) (!AnyNull);
1101 /* ----------------------------------------------------------------
1104 * Evaluate a CASE clause. Will have boolean expressions
1105 * inside the WHEN clauses, and will have expressions
1107 * - thomas 1998-11-09
1108 * ----------------------------------------------------------------
1111 ExecEvalCase(CaseExpr *caseExpr, ExprContext *econtext, bool *isNull)
1118 clauses = caseExpr->args;
1121 * we evaluate each of the WHEN clauses in turn, as soon as one is
1122 * true we return the corresponding result. If none are true then we
1123 * return the value of the default clause, or NULL if there is none.
1125 foreach(clause, clauses)
1127 CaseWhen *wclause = lfirst(clause);
1130 * We don't iterate over sets in the quals, so pass in an isDone
1131 * flag, but ignore it.
1133 clause_value = ExecEvalExpr(wclause->expr,
1139 * if we have a true test, then we return the result, since the
1140 * case statement is satisfied. A NULL result from the test is
1141 * not considered true.
1143 if (DatumGetInt32(clause_value) != 0 && !*isNull)
1145 return ExecEvalExpr(wclause->result,
1152 if (caseExpr->defresult)
1154 return ExecEvalExpr(caseExpr->defresult,
1164 /* ----------------------------------------------------------------
1167 * Recursively evaluate a targetlist or qualification expression.
1169 * This routine is an inner loop routine and should be as fast
1172 * Node comparison functions were replaced by macros for speed and to plug
1173 * memory leaks incurred by using the planner's Lispy stuff for
1174 * comparisons. Order of evaluation of node comparisons IS IMPORTANT;
1175 * the macros do no checks. Order of evaluation:
1177 * o an isnull check, largely to avoid coredumps since greg doubts this
1178 * routine is called with a null ptr anyway in proper operation, but is
1179 * not completely sure...
1180 * o ExactNodeType checks.
1181 * o clause checks or other checks where we look at the lfirst of something.
1182 * ----------------------------------------------------------------
1185 ExecEvalExpr(Node *expression,
1186 ExprContext *econtext,
1195 * Some callers don't care about is done and only want 1 result. They
1196 * indicate this by passing NULL
1202 * here we dispatch the work to the appropriate type of function given
1203 * the type of our expression.
1205 if (expression == NULL)
1208 return (Datum) true;
1211 switch (nodeTag(expression))
1214 retDatum = ExecEvalVar((Var *) expression, econtext, isNull);
1218 Const *con = (Const *) expression;
1220 retDatum = con->constvalue;
1221 *isNull = con->constisnull;
1225 retDatum = ExecEvalParam((Param *) expression, econtext, isNull);
1228 retDatum = ExecEvalIter((Iter *) expression,
1234 retDatum = ExecEvalAggref((Aggref *) expression, econtext, isNull);
1237 retDatum = ExecEvalArrayRef((ArrayRef *) expression,
1244 Expr *expr = (Expr *) expression;
1246 switch (expr->opType)
1249 retDatum = ExecEvalOper(expr, econtext, isNull);
1252 retDatum = ExecEvalFunc(expr, econtext,
1256 retDatum = ExecEvalOr(expr, econtext, isNull);
1259 retDatum = ExecEvalAnd(expr, econtext, isNull);
1262 retDatum = ExecEvalNot(expr, econtext, isNull);
1265 retDatum = ExecSubPlan((SubPlan *) expr->oper,
1266 expr->args, econtext,
1270 elog(ERROR, "ExecEvalExpr: unknown expression type %d",
1272 retDatum = 0; /* keep compiler quiet */
1278 retDatum = ExecEvalExpr(((RelabelType *) expression)->arg,
1284 retDatum = ExecEvalCase((CaseExpr *) expression, econtext, isNull);
1288 elog(ERROR, "ExecEvalExpr: unknown expression type %d",
1289 nodeTag(expression));
1290 retDatum = 0; /* keep compiler quiet */
1295 } /* ExecEvalExpr() */
1298 /* ----------------------------------------------------------------
1299 * ExecQual / ExecTargetList
1300 * ----------------------------------------------------------------
1303 /* ----------------------------------------------------------------
1306 * Evaluates a conjunctive boolean expression (qual list) and
1307 * returns true iff none of the subexpressions are false.
1308 * (We also return true if the list is empty.)
1310 * If some of the subexpressions yield NULL but none yield FALSE,
1311 * then the result of the conjunction is NULL (ie, unknown)
1312 * according to three-valued boolean logic. In this case,
1313 * we return the value specified by the "resultForNull" parameter.
1315 * Callers evaluating WHERE clauses should pass resultForNull=FALSE,
1316 * since SQL specifies that tuples with null WHERE results do not
1317 * get selected. On the other hand, callers evaluating constraint
1318 * conditions should pass resultForNull=TRUE, since SQL also specifies
1319 * that NULL constraint conditions are not failures.
1321 * NOTE: it would not be correct to use this routine to evaluate an
1322 * AND subclause of a boolean expression; for that purpose, a NULL
1323 * result must be returned as NULL so that it can be properly treated
1324 * in the next higher operator (cf. ExecEvalAnd and ExecEvalOr).
1325 * This routine is only used in contexts where a complete expression
1326 * is being evaluated and we know that NULL can be treated the same
1327 * as one boolean result or the other.
1329 * ----------------------------------------------------------------
1332 ExecQual(List *qual, ExprContext *econtext, bool resultForNull)
1339 EV_printf("ExecQual: qual is ");
1340 EV_nodeDisplay(qual);
1346 * Evaluate the qual conditions one at a time. If we find a FALSE
1347 * result, we can stop evaluating and return FALSE --- the AND result
1348 * must be FALSE. Also, if we find a NULL result when resultForNull
1349 * is FALSE, we can stop and return FALSE --- the AND result must be
1350 * FALSE or NULL in that case, and the caller doesn't care which.
1352 * If we get to the end of the list, we can return TRUE. This will
1353 * happen when the AND result is indeed TRUE, or when the AND result
1354 * is NULL (one or more NULL subresult, with all the rest TRUE) and
1355 * the caller has specified resultForNull = TRUE.
1358 foreach(qlist, qual)
1360 Node *clause = (Node *) lfirst(qlist);
1366 * If there is a null clause, consider the qualification to fail.
1367 * XXX is this still correct for constraints? It probably
1368 * shouldn't happen at all ...
1374 * pass isDone, but ignore it. We don't iterate over multiple
1375 * returns in the qualifications.
1377 expr_value = ExecEvalExpr(clause, econtext, &isNull, &isDone);
1381 if (resultForNull == false)
1382 return false; /* treat NULL as FALSE */
1386 if (DatumGetInt32(expr_value) == 0)
1387 return false; /* definitely FALSE */
1395 ExecTargetListLength(List *targetlist)
1399 TargetEntry *curTle;
1402 foreach(tl, targetlist)
1404 curTle = lfirst(tl);
1406 if (curTle->resdom != NULL)
1409 len += curTle->fjoin->fj_nNodes;
1414 /* ----------------------------------------------------------------
1417 * Evaluates a targetlist with respect to the current
1418 * expression context and return a tuple.
1419 * ----------------------------------------------------------------
1422 ExecTargetList(List *targetlist,
1424 TupleDesc targettype,
1426 ExprContext *econtext,
1429 char nulls_array[64];
1430 bool fjNullArray[64];
1431 bool itemIsDoneArray[64];
1444 static struct tupleDesc NullTupleDesc; /* we assume this inits to
1450 EV_printf("ExecTargetList: tl is ");
1451 EV_nodeDisplay(targetlist);
1455 * There used to be some klugy and demonstrably broken code here that
1456 * special-cased the situation where targetlist == NIL. Now we just
1457 * fall through and return an empty-but-valid tuple. We do, however,
1458 * have to cope with the possibility that targettype is NULL ---
1459 * heap_formtuple won't like that, so pass a dummy descriptor with
1460 * natts = 0 to deal with it.
1462 if (targettype == NULL)
1463 targettype = &NullTupleDesc;
1466 * allocate an array of char's to hold the "null" information only if
1467 * we have a really large targetlist. otherwise we use the stack.
1469 * We also allocate a bool array that is used to hold fjoin result state,
1470 * and another that holds the isDone status for each targetlist item.
1474 null_head = (char *) palloc(nodomains + 1);
1475 fjIsNull = (bool *) palloc(nodomains + 1);
1476 itemIsDone = (bool *) palloc(nodomains + 1);
1480 null_head = &nulls_array[0];
1481 fjIsNull = &fjNullArray[0];
1482 itemIsDone = &itemIsDoneArray[0];
1486 * evaluate all the expressions in the target list
1489 *isDone = true; /* until proven otherwise */
1490 haveDoneIters = false; /* any isDone Iter exprs in tlist? */
1492 foreach(tl, targetlist)
1496 * remember, a target list is a list of lists:
1498 * ((<resdom | fjoin> expr) (<resdom | fjoin> expr) ...)
1500 * tl is a pointer to successive cdr's of the targetlist tle is a
1501 * pointer to the target list entry in tl
1505 if (tle->resdom != NULL)
1508 resdom = tle->resdom;
1509 resind = resdom->resno - 1;
1511 constvalue = (Datum) ExecEvalExpr(expr,
1514 &itemIsDone[resind]);
1516 values[resind] = constvalue;
1519 null_head[resind] = ' ';
1521 null_head[resind] = 'n';
1523 if (IsA(expr, Iter))
1525 if (itemIsDone[resind])
1526 haveDoneIters = true;
1528 *isDone = false; /* we have undone Iters in the
1536 List *fjTlist = (List *) tle->expr;
1537 Fjoin *fjNode = tle->fjoin;
1538 int nNodes = fjNode->fj_nNodes;
1539 DatumPtr results = fjNode->fj_results;
1541 ExecEvalFjoin(tle, econtext, fjIsNull, isDone);
1543 /* this is probably wrong: */
1545 return (HeapTuple) NULL;
1548 * get the result from the inner node
1550 fjRes = (Resdom *) fjNode->fj_innerNode;
1551 resind = fjRes->resno - 1;
1553 null_head[resind] = 'n';
1556 null_head[resind] = ' ';
1557 values[resind] = results[0];
1561 * Get results from all of the outer nodes
1565 curNode++, fjTlist = lnext(fjTlist))
1567 #ifdef NOT_USED /* what is this?? */
1568 Node *outernode = lfirst(fjTlist);
1570 fjRes = (Resdom *) outernode->iterexpr;
1572 resind = fjRes->resno - 1;
1573 if (fjIsNull[curNode])
1574 null_head[resind] = 'n';
1577 null_head[resind] = ' ';
1578 values[resind] = results[curNode];
1590 * all Iters are done, so return a null indicating tlist set
1591 * expansion is complete.
1600 * We have some done and some undone Iters. Restart the done
1601 * ones so that we can deliver a tuple (if possible).
1603 * XXX this code is a crock, because it only works for Iters at
1604 * the top level of tlist expressions, and doesn't even work
1605 * right for them: you should get all possible combinations of
1606 * Iter results, but you won't unless the numbers of values
1607 * returned by each are relatively prime. Should have a
1608 * mechanism more like aggregate functions, where we make a
1609 * list of all Iters contained in the tlist and cycle through
1610 * their values in a methodical fashion. To do someday; can't
1611 * get excited about fixing a Berkeley feature that's not in
1612 * SQL92. (The only reason we're doing this much is that we
1613 * have to be sure all the Iters are run to completion, or
1614 * their subplan executors will have unreleased resources,
1615 * e.g. pinned buffers...)
1617 foreach(tl, targetlist)
1621 if (tle->resdom != NULL)
1624 resdom = tle->resdom;
1625 resind = resdom->resno - 1;
1627 if (IsA(expr, Iter) &&itemIsDone[resind])
1629 constvalue = (Datum) ExecEvalExpr(expr,
1632 &itemIsDone[resind]);
1633 if (itemIsDone[resind])
1637 * Oh dear, this Iter is returning an empty
1638 * set. Guess we can't make a tuple after all.
1645 values[resind] = constvalue;
1648 null_head[resind] = ' ';
1650 null_head[resind] = 'n';
1658 * form the new result tuple (in the "normal" context)
1660 newTuple = (HeapTuple) heap_formtuple(targettype, values, null_head);
1665 * free the status arrays if we palloc'd them
1677 /* ----------------------------------------------------------------
1680 * projects a tuple based in projection info and stores
1681 * it in the specified tuple table slot.
1683 * Note: someday soon the executor can be extended to eliminate
1684 * redundant projections by storing pointers to datums
1685 * in the tuple table and then passing these around when
1686 * possible. this should make things much quicker.
1688 * ----------------------------------------------------------------
1691 ExecProject(ProjectionInfo *projInfo, bool *isDone)
1693 TupleTableSlot *slot;
1698 ExprContext *econtext;
1704 if (projInfo == NULL)
1705 return (TupleTableSlot *) NULL;
1708 * get the projection info we want
1710 slot = projInfo->pi_slot;
1711 targetlist = projInfo->pi_targetlist;
1712 len = projInfo->pi_len;
1713 tupType = slot->ttc_tupleDescriptor;
1715 tupValue = projInfo->pi_tupValue;
1716 econtext = projInfo->pi_exprContext;
1719 * form a new (result) tuple
1721 newTuple = ExecTargetList(targetlist,
1729 * store the tuple in the projection slot and return the slot.
1731 return (TupleTableSlot *)
1732 ExecStoreTuple(newTuple,/* tuple to store */
1733 slot, /* slot to store in */
1734 InvalidBuffer, /* tuple has no buffer */