1 /*-------------------------------------------------------------------------
4 * Routines to evaluate qualification and targetlist expressions
6 * Copyright (c) 1994, Regents of the University of California
10 * $Header: /cvsroot/pgsql/src/backend/executor/execQual.c,v 1.63 1999/10/08 03:49:55 tgl Exp $
12 *-------------------------------------------------------------------------
16 * ExecEvalExpr - evaluate an expression and return a datum
17 * ExecQual - return true/false if qualification is satisified
18 * ExecTargetList - form a new tuple by projecting the given tuple
21 * ExecEvalExpr() and ExecEvalVar() are hotspots. making these faster
22 * will speed up the entire system. Unfortunately they are currently
23 * implemented recursively. Eliminating the recursion is bound to
24 * improve the speed of the executor.
26 * ExecTargetList() is used to make tuple projections. Rather then
27 * trying to speed it up, the execution plan should be pre-processed
28 * to facilitate attribute sharing between nodes wherever possible,
29 * instead of doing needless copying. -cim 5/31/91
35 #include "access/heapam.h"
36 #include "catalog/pg_language.h"
37 #include "executor/execFlatten.h"
38 #include "executor/execdebug.h"
39 #include "executor/executor.h"
40 #include "executor/functions.h"
41 #include "executor/nodeSubplan.h"
42 #include "utils/builtins.h"
43 #include "utils/fcache2.h"
47 * externs and constants
51 * XXX Used so we can get rid of use of Const nodes in the executor.
52 * Currently only used by ExecHashGetBucket and set only by ExecMakeVarConst
53 * and by ExecEvalArrayRef.
58 /* static functions decls */
59 static Datum ExecEvalAggref(Aggref *aggref, ExprContext *econtext, bool *isNull);
60 static Datum ExecEvalArrayRef(ArrayRef *arrayRef, ExprContext *econtext,
61 bool *isNull, bool *isDone);
62 static Datum ExecEvalAnd(Expr *andExpr, ExprContext *econtext, bool *isNull);
63 static Datum ExecEvalFunc(Expr *funcClause, ExprContext *econtext,
64 bool *isNull, bool *isDone);
65 static void ExecEvalFuncArgs(FunctionCachePtr fcache, ExprContext *econtext,
66 List *argList, Datum argV[], bool *argIsDone);
67 static Datum ExecEvalNot(Expr *notclause, ExprContext *econtext, bool *isNull);
68 static Datum ExecEvalOper(Expr *opClause, ExprContext *econtext,
70 static Datum ExecEvalOr(Expr *orExpr, ExprContext *econtext, bool *isNull);
71 static Datum ExecEvalVar(Var *variable, ExprContext *econtext, bool *isNull);
72 static Datum ExecMakeFunctionResult(Node *node, List *arguments,
73 ExprContext *econtext, bool *isNull, bool *isDone);
74 static bool ExecQualClause(Node *clause, ExprContext *econtext);
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,
111 /* Null refexpr indicates we are doing an INSERT into an array column.
112 * For now, we just take the refassgnexpr (which the parser will have
113 * ensured is an array value) and return it as-is, ignoring any
114 * subscripts that may have been supplied in the INSERT column list.
115 * This is a kluge, but it's not real clear what the semantics ought
118 array_scanner = NULL;
121 foreach(elt, arrayRef->refupperindexpr)
124 elog(ERROR, "ExecEvalArrayRef: can only handle %d dimensions",
127 upper.indx[i++] = (int32) ExecEvalExpr((Node *) lfirst(elt),
135 if (arrayRef->reflowerindexpr != NIL)
137 foreach(elt, arrayRef->reflowerindexpr)
140 elog(ERROR, "ExecEvalArrayRef: can only handle %d dimensions",
143 lower.indx[j++] = (int32) ExecEvalExpr((Node *) lfirst(elt),
152 "ExecEvalArrayRef: upper and lower indices mismatch");
160 if (arrayRef->refassgnexpr != NULL)
162 Datum sourceData = ExecEvalExpr(arrayRef->refassgnexpr,
169 execConstByVal = arrayRef->refelembyval;
170 execConstLen = arrayRef->refelemlength;
172 if (array_scanner == NULL)
173 return sourceData; /* XXX do something else? */
176 return (Datum) array_set(array_scanner, i, upper.indx,
178 arrayRef->refelembyval,
179 arrayRef->refelemlength,
180 arrayRef->refattrlength, isNull);
181 return (Datum) array_assgn(array_scanner, i, upper.indx,
183 (ArrayType *) sourceData,
184 arrayRef->refelembyval,
185 arrayRef->refelemlength, isNull);
188 execConstByVal = arrayRef->refelembyval;
189 execConstLen = arrayRef->refelemlength;
192 return (Datum) array_ref(array_scanner, i, upper.indx,
193 arrayRef->refelembyval,
194 arrayRef->refelemlength,
195 arrayRef->refattrlength, isNull);
196 return (Datum) array_clip(array_scanner, i, upper.indx, lower.indx,
197 arrayRef->refelembyval,
198 arrayRef->refelemlength, isNull);
202 /* ----------------------------------------------------------------
205 * Returns a Datum whose value is the value of the precomputed
206 * aggregate found in the given expression context.
207 * ----------------------------------------------------------------
210 ExecEvalAggref(Aggref *aggref, ExprContext *econtext, bool *isNull)
212 if (econtext->ecxt_aggvalues == NULL) /* safety check */
213 elog(ERROR, "ExecEvalAggref: no aggregates in this expression context");
215 *isNull = econtext->ecxt_aggnulls[aggref->aggno];
216 return econtext->ecxt_aggvalues[aggref->aggno];
219 /* ----------------------------------------------------------------
222 * Returns a Datum whose value is the value of a range
223 * variable with respect to given expression context.
226 * As an entry condition, we expect that the datatype the
227 * plan expects to get (as told by our "variable" argument) is in
228 * fact the datatype of the attribute the plan says to fetch (as
229 * seen in the current context, identified by our "econtext"
232 * If we fetch a Type A attribute and Caller treats it as if it
233 * were Type B, there will be undefined results (e.g. crash).
234 * One way these might mismatch now is that we're accessing a
235 * catalog class and the type information in the pg_attribute
236 * class does not match the hardcoded pg_attribute information
237 * (in pg_attribute.h) for the class in question.
239 * We have an Assert to make sure this entry condition is met.
241 * ---------------------------------------------------------------- */
243 ExecEvalVar(Var *variable, ExprContext *econtext, bool *isNull)
246 TupleTableSlot *slot;
249 TupleDesc tuple_type;
254 * get the slot we want
256 switch (variable->varno)
258 case INNER: /* get the tuple from the inner node */
259 slot = econtext->ecxt_innertuple;
262 case OUTER: /* get the tuple from the outer node */
263 slot = econtext->ecxt_outertuple;
266 default: /* get the tuple from the relation being
268 slot = econtext->ecxt_scantuple;
273 * extract tuple information from the slot
275 heapTuple = slot->val;
276 tuple_type = slot->ttc_tupleDescriptor;
278 attnum = variable->varattno;
280 /* (See prolog for explanation of this Assert) */
281 Assert(attnum <= 0 ||
282 (attnum - 1 <= tuple_type->natts - 1 &&
283 tuple_type->attrs[attnum - 1] != NULL &&
284 variable->vartype == tuple_type->attrs[attnum - 1]->atttypid));
287 * If the attribute number is invalid, then we are supposed to return
288 * the entire tuple, we give back a whole slot so that callers know
289 * what the tuple looks like.
291 if (attnum == InvalidAttrNumber)
293 TupleTableSlot *tempSlot;
297 tempSlot = makeNode(TupleTableSlot);
298 tempSlot->ttc_shouldFree = false;
299 tempSlot->ttc_descIsNew = true;
300 tempSlot->ttc_tupleDescriptor = (TupleDesc) NULL;
301 tempSlot->ttc_buffer = InvalidBuffer;
302 tempSlot->ttc_whichplan = -1;
304 tup = heap_copytuple(heapTuple);
305 td = CreateTupleDescCopy(tuple_type);
307 ExecSetSlotDescriptor(tempSlot, td);
309 ExecStoreTuple(tup, tempSlot, InvalidBuffer, true);
310 return (Datum) tempSlot;
313 result = heap_getattr(heapTuple, /* tuple containing attribute */
314 attnum, /* attribute number of desired
316 tuple_type, /* tuple descriptor of tuple */
317 isNull); /* return: is attribute null? */
320 * return null if att is null
326 * get length and type information.. ??? what should we do about
327 * variable length attributes - variable length attributes have their
328 * length stored in the first 4 bytes of the memory pointed to by the
329 * returned value.. If we can determine that the type is a variable
330 * length type, we can do the right thing. -cim 9/15/89
336 * If this is a pseudo-att, we get the type and fake the length.
337 * There ought to be a routine to return the real lengths, so
338 * we'll mark this one ... XXX -mao
340 len = heap_sysattrlen(attnum); /* XXX see -mao above */
341 byval = heap_sysattrbyval(attnum); /* XXX see -mao above */
345 len = tuple_type->attrs[attnum - 1]->attlen;
346 byval = tuple_type->attrs[attnum - 1]->attbyval ? true : false;
349 execConstByVal = byval;
355 /* ----------------------------------------------------------------
358 * Returns the value of a parameter. A param node contains
359 * something like ($.name) and the expression context contains
360 * the current parameter bindings (name = "sam") (age = 34)...
361 * so our job is to replace the param node with the datum
362 * containing the appropriate information ("sam").
364 * Q: if we have a parameter ($.foo) without a binding, i.e.
365 * there is no (foo = xxx) in the parameter list info,
366 * is this a fatal error or should this be a "not available"
367 * (in which case we shoud return a Const node with the
368 * isnull flag) ? -cim 10/13/89
370 * Minor modification: Param nodes now have an extra field,
371 * `paramkind' which specifies the type of parameter
372 * (see params.h). So while searching the paramList for
373 * a paramname/value pair, we have also to check for `kind'.
375 * NOTE: The last entry in `paramList' is always an
376 * entry with kind == PARAM_INVALID.
377 * ----------------------------------------------------------------
380 ExecEvalParam(Param *expression, ExprContext *econtext, bool *isNull)
383 char *thisParameterName;
384 int thisParameterKind = expression->paramkind;
385 AttrNumber thisParameterId = expression->paramid;
387 ParamListInfo paramList;
389 if (thisParameterKind == PARAM_EXEC)
391 ParamExecData *prm = &(econtext->ecxt_param_exec_vals[thisParameterId]);
393 if (prm->execPlan != NULL)
394 ExecSetParamPlan(prm->execPlan);
395 Assert(prm->execPlan == NULL);
396 *isNull = prm->isnull;
400 thisParameterName = expression->paramname;
401 paramList = econtext->ecxt_param_list_info;
406 * search the list with the parameter info to find a matching name. An
407 * entry with an InvalidName denotes the last element in the array.
410 if (paramList != NULL)
414 * search for an entry in 'paramList' that matches the
417 while (paramList->kind != PARAM_INVALID && !matchFound)
419 switch (thisParameterKind)
422 if (thisParameterKind == paramList->kind &&
423 strcmp(paramList->name, thisParameterName) == 0)
427 if (thisParameterKind == paramList->kind &&
428 paramList->id == thisParameterId)
433 if (thisParameterKind == paramList->kind &&
434 paramList->id == thisParameterId)
441 if (strcmp(paramList->name, thisParameterName) != 0)
444 "ExecEvalParam: new/old params with same id & diff names");
451 * oops! this is not supposed to happen!
453 elog(ERROR, "ExecEvalParam: invalid paramkind %d",
465 * ooops! we couldn't find this parameter in the parameter list.
468 elog(ERROR, "ExecEvalParam: Unknown value for parameter %s",
475 if (paramList->isnull)
481 if (expression->param_tlist != NIL)
485 List *tlist = expression->param_tlist;
486 TargetEntry *tle = (TargetEntry *) lfirst(tlist);
487 TupleTableSlot *slot = (TupleTableSlot *) paramList->value;
490 value = ProjectAttribute(slot->ttc_tupleDescriptor,
494 return paramList->value;
498 /* ----------------------------------------------------------------
499 * ExecEvalOper / ExecEvalFunc support routines
500 * ----------------------------------------------------------------
507 * These are functions which return the value of the
508 * named attribute out of the tuple from the arg slot. User defined
509 * C functions which take a tuple as an argument are expected
510 * to use this. Ex: overpaid(EMP) might call GetAttributeByNum().
512 /* static but gets called from external functions */
514 GetAttributeByNum(TupleTableSlot *slot,
520 if (!AttributeNumberIsValid(attrno))
521 elog(ERROR, "GetAttributeByNum: Invalid attribute number");
523 if (!AttrNumberIsForUserDefinedAttr(attrno))
524 elog(ERROR, "GetAttributeByNum: cannot access system attributes here");
526 if (isNull == (bool *) NULL)
527 elog(ERROR, "GetAttributeByNum: a NULL isNull flag was passed");
532 return (char *) NULL;
535 retval = heap_getattr(slot->val,
537 slot->ttc_tupleDescriptor,
540 return (char *) NULL;
541 return (char *) retval;
544 /* XXX name for catalogs */
547 att_by_num(TupleTableSlot *slot,
551 return GetAttributeByNum(slot, attrno, isNull);
557 GetAttributeByName(TupleTableSlot *slot, char *attname, bool *isNull)
566 elog(ERROR, "GetAttributeByName: Invalid attribute name");
568 if (isNull == (bool *) NULL)
569 elog(ERROR, "GetAttributeByName: a NULL isNull flag was passed");
574 return (char *) NULL;
577 tupdesc = slot->ttc_tupleDescriptor;
578 natts = slot->val->t_data->t_natts;
580 attrno = InvalidAttrNumber;
581 for (i = 0; i < tupdesc->natts; i++)
583 if (namestrcmp(&(tupdesc->attrs[i]->attname), attname) == 0)
585 attrno = tupdesc->attrs[i]->attnum;
590 if (attrno == InvalidAttrNumber)
591 elog(ERROR, "GetAttributeByName: attribute %s not found", attname);
593 retval = heap_getattr(slot->val,
598 return (char *) NULL;
599 return (char *) retval;
602 /* XXX name for catalogs */
605 att_by_name(TupleTableSlot *slot, char *attname, bool *isNull)
607 return GetAttributeByName(slot, attname, isNull);
613 ExecEvalFuncArgs(FunctionCachePtr fcache,
614 ExprContext *econtext,
623 nullVect = fcache->nullVect;
626 foreach(arg, argList)
630 * evaluate the expression, in general functions cannot take sets
631 * as arguments but we make an exception in the case of nested dot
632 * expressions. We have to watch out for this case here.
634 argV[i] = ExecEvalExpr((Node *) lfirst(arg),
642 elog(ERROR, "functions can only take sets in their first argument");
643 fcache->setArg = (char *) argV[0];
644 fcache->hasSetArg = true;
651 * ExecMakeFunctionResult
654 ExecMakeFunctionResult(Node *node,
656 ExprContext *econtext,
660 Datum argV[MAXFMGRARGS];
661 FunctionCachePtr fcache;
662 Func *funcNode = NULL;
663 Oper *operNode = NULL;
664 bool funcisset = false;
667 * This is kind of ugly, Func nodes now have targetlists so that we
668 * know when and what to project out from postquel function results.
669 * This means we have to pass the func node all the way down instead
670 * of using only the fcache struct as before. ExecMakeFunctionResult
671 * becomes a little bit more of a dual personality as a result.
675 funcNode = (Func *) node;
676 fcache = funcNode->func_fcache;
680 operNode = (Oper *) node;
681 fcache = operNode->op_fcache;
685 * arguments is a list of expressions to evaluate before passing to
686 * the function manager. We collect the results of evaluating the
687 * expressions into a datum array (argV) and pass this array to
690 if (fcache->nargs != 0)
694 if (fcache->nargs > MAXFMGRARGS)
695 elog(ERROR, "ExecMakeFunctionResult: too many arguments");
698 * If the setArg in the fcache is set we have an argument
699 * returning a set of tuples (i.e. a nested dot expression). We
700 * don't want to evaluate the arguments again until the function
701 * is done. hasSetArg will always be false until we eval the args
702 * for the first time. We should set this in the parser.
704 if ((fcache->hasSetArg) && fcache->setArg != NULL)
706 argV[0] = (Datum) fcache->setArg;
710 ExecEvalFuncArgs(fcache, econtext, arguments, argV, &argDone);
712 if ((fcache->hasSetArg) && (argDone))
721 * If this function is really a set, we have to diddle with things. If
722 * the function has already been called at least once, then the setArg
723 * field of the fcache holds the OID of this set in pg_proc. (This is
724 * not quite legit, since the setArg field is really for functions
725 * which take sets of tuples as input - set functions take no inputs
726 * at all. But it's a nice place to stash this value, for now.)
728 * If this is the first call of the set's function, then the call to
729 * ExecEvalFuncArgs above just returned the OID of the pg_proc tuple
730 * which defines this set. So replace the existing funcid in the
731 * funcnode with the set's OID. Also, we want a new fcache which
732 * points to the right function, so get that, now that we have the
733 * right OID. Also zero out the argV, since the real set doesn't take
736 if (((Func *) node)->funcid == F_SETEVAL)
743 ((Func *) node)->funcid = (Oid) PointerGetDatum(fcache->setArg);
748 ((Func *) node)->funcid = (Oid) argV[0];
749 setFcache(node, argV[0], NIL, econtext);
750 fcache = ((Func *) node)->func_fcache;
751 fcache->setArg = (char *) argV[0];
757 * now return the value gotten by calling the function manager,
758 * passing the function the evaluated parameter values.
760 if (fcache->language == SQLlanguageId)
767 /*--------------------
768 * This loop handles the situation where we are iterating through
769 * all results in a nested dot function (whose argument function
770 * returns a set of tuples) and the current function finally
771 * finishes. We need to get the next argument in the set and start
772 * the function all over again. We might have to do it more than
773 * once, if the function produces no results for a particular argument.
774 * This is getting unclean.
775 *--------------------
779 result = postquel_function(funcNode, (char **) argV,
783 break; /* got a result from current argument */
784 if (! fcache->hasSetArg)
785 break; /* input not a set, so done */
787 /* OK, get the next argument... */
788 ExecEvalFuncArgs(fcache, econtext, arguments, argV, &argDone);
792 /* End of arguments, so reset the setArg flag and say "Done" */
793 fcache->setArg = (char *) NULL;
794 fcache->hasSetArg = false;
796 result = (Datum) NULL;
800 /* If we reach here, loop around to run the function on the
809 * reset the funcid so that next call to this routine will
810 * still recognize this func as a set. Note that for now we
811 * assume that the set function in pg_proc must be a Postquel
812 * function - the funcid is not reset below for C functions.
814 ((Func *) node)->funcid = F_SETEVAL;
817 * If we're done with the results of this function, get rid of
821 ((Func *) node)->func_fcache = NULL;
832 for (i = 0; i < fcache->nargs; i++)
833 if (fcache->nullVect[i] == true)
836 return (Datum) fmgr_c(&fcache->func, (FmgrValues *) argV, isNull);
841 /* ----------------------------------------------------------------
845 * Evaluate the functional result of a list of arguments by calling the
846 * function manager. Note that in the case of operator expressions, the
847 * optimizer had better have already replaced the operator OID with the
848 * appropriate function OID or we're hosed.
851 * Presumably the function manager will not take null arguments, so we
852 * check for null arguments before sending the arguments to (fmgr).
854 * Returns the value of the functional expression.
855 * ----------------------------------------------------------------
858 /* ----------------------------------------------------------------
860 * ----------------------------------------------------------------
863 ExecEvalOper(Expr *opClause, ExprContext *econtext, bool *isNull)
867 FunctionCachePtr fcache;
871 * an opclause is a list (op args). (I think)
873 * we extract the oid of the function associated with the op and then
874 * pass the work onto ExecMakeFunctionResult which evaluates the
875 * arguments and returns the result of calling the function on the
876 * evaluated arguments.
878 op = (Oper *) opClause->oper;
879 argList = opClause->args;
882 * get the fcache from the Oper node. If it is NULL, then initialize
885 fcache = op->op_fcache;
888 setFcache((Node *) op, op->opid, argList, econtext);
889 fcache = op->op_fcache;
893 * call ExecMakeFunctionResult() with a dummy isDone that we ignore.
894 * We don't have operator whose arguments are sets.
896 return ExecMakeFunctionResult((Node *) op, argList, econtext, isNull, &isDone);
899 /* ----------------------------------------------------------------
901 * ----------------------------------------------------------------
905 ExecEvalFunc(Expr *funcClause,
906 ExprContext *econtext,
912 FunctionCachePtr fcache;
915 * an funcclause is a list (func args). (I think)
917 * we extract the oid of the function associated with the func node and
918 * then pass the work onto ExecMakeFunctionResult which evaluates the
919 * arguments and returns the result of calling the function on the
920 * evaluated arguments.
922 * this is nearly identical to the ExecEvalOper code.
924 func = (Func *) funcClause->oper;
925 argList = funcClause->args;
928 * get the fcache from the Func node. If it is NULL, then initialize
931 fcache = func->func_fcache;
934 setFcache((Node *) func, func->funcid, argList, econtext);
935 fcache = func->func_fcache;
938 return ExecMakeFunctionResult((Node *) func, argList, econtext, isNull, isDone);
941 /* ----------------------------------------------------------------
946 * Evaluate boolean expressions. Evaluation of 'or' is
947 * short-circuited when the first true (or null) value is found.
949 * The query planner reformulates clause expressions in the
950 * qualification to conjunctive normal form. If we ever get
951 * an AND to evaluate, we can be sure that it's not a top-level
952 * clause in the qualification, but appears lower (as a function
953 * argument, for example), or in the target list. Not that you
954 * need to know this, mind you...
955 * ----------------------------------------------------------------
958 ExecEvalNot(Expr *notclause, ExprContext *econtext, bool *isNull)
964 clause = lfirst(notclause->args);
967 * We don't iterate over sets in the quals, so pass in an isDone flag,
970 expr_value = ExecEvalExpr(clause, econtext, isNull, &isDone);
973 * if the expression evaluates to null, then we just cascade the null
974 * back to whoever called us.
980 * evaluation of 'not' is simple.. expr is false, then return 'true'
983 if (DatumGetInt32(expr_value) == 0)
986 return (Datum) false;
989 /* ----------------------------------------------------------------
991 * ----------------------------------------------------------------
994 ExecEvalOr(Expr *orExpr, ExprContext *econtext, bool *isNull)
1002 clauses = orExpr->args;
1006 * If any of the clauses is TRUE, the OR result is TRUE regardless
1007 * of the states of the rest of the clauses, so we can stop evaluating
1008 * and return TRUE immediately. If none are TRUE and one or more is
1009 * NULL, we return NULL; otherwise we return FALSE. This makes sense
1010 * when you interpret NULL as "don't know": if we have a TRUE then the
1011 * OR is TRUE even if we aren't sure about some of the other inputs.
1012 * If all the known inputs are FALSE, but we have one or more "don't
1013 * knows", then we have to report that we "don't know" what the OR's
1014 * result should be --- perhaps one of the "don't knows" would have been
1015 * TRUE if we'd known its value. Only when all the inputs are known
1016 * to be FALSE can we state confidently that the OR's result is FALSE.
1018 foreach(clause, clauses)
1021 * We don't iterate over sets in the quals, so pass in an isDone
1022 * flag, but ignore it.
1024 clause_value = ExecEvalExpr((Node *) lfirst(clause),
1029 * if we have a non-null true result, then return it.
1032 AnyNull = true; /* remember we got a null */
1033 else if (DatumGetInt32(clause_value) != 0)
1034 return clause_value;
1037 /* AnyNull is true if at least one clause evaluated to NULL */
1039 return (Datum) false;
1042 /* ----------------------------------------------------------------
1044 * ----------------------------------------------------------------
1047 ExecEvalAnd(Expr *andExpr, ExprContext *econtext, bool *isNull)
1055 clauses = andExpr->args;
1059 * If any of the clauses is FALSE, the AND result is FALSE regardless
1060 * of the states of the rest of the clauses, so we can stop evaluating
1061 * and return FALSE immediately. If none are FALSE and one or more is
1062 * NULL, we return NULL; otherwise we return TRUE. This makes sense
1063 * when you interpret NULL as "don't know", using the same sort of
1064 * reasoning as for OR, above.
1066 foreach(clause, clauses)
1069 * We don't iterate over sets in the quals, so pass in an isDone
1070 * flag, but ignore it.
1072 clause_value = ExecEvalExpr((Node *) lfirst(clause),
1077 * if we have a non-null false result, then return it.
1080 AnyNull = true; /* remember we got a null */
1081 else if (DatumGetInt32(clause_value) == 0)
1082 return clause_value;
1085 /* AnyNull is true if at least one clause evaluated to NULL */
1087 return (Datum) (! AnyNull);
1090 /* ----------------------------------------------------------------
1093 * Evaluate a CASE clause. Will have boolean expressions
1094 * inside the WHEN clauses, and will have expressions
1096 * - thomas 1998-11-09
1097 * ----------------------------------------------------------------
1100 ExecEvalCase(CaseExpr *caseExpr, ExprContext *econtext, bool *isNull)
1107 clauses = caseExpr->args;
1110 * we evaluate each of the WHEN clauses in turn, as soon as one is
1111 * true we return the corresponding result. If none are true then we
1112 * return the value of the default clause, or NULL if there is none.
1114 foreach(clause, clauses)
1116 CaseWhen *wclause = lfirst(clause);
1119 * We don't iterate over sets in the quals, so pass in an isDone
1120 * flag, but ignore it.
1122 clause_value = ExecEvalExpr(wclause->expr,
1128 * if we have a true test, then we return the result, since the
1129 * case statement is satisfied. A NULL result from the test is
1130 * not considered true.
1132 if (DatumGetInt32(clause_value) != 0 && ! *isNull)
1134 return ExecEvalExpr(wclause->result,
1141 if (caseExpr->defresult)
1143 return ExecEvalExpr(caseExpr->defresult,
1153 /* ----------------------------------------------------------------
1156 * Recursively evaluate a targetlist or qualification expression.
1158 * This routine is an inner loop routine and should be as fast
1161 * Node comparison functions were replaced by macros for speed and to plug
1162 * memory leaks incurred by using the planner's Lispy stuff for
1163 * comparisons. Order of evaluation of node comparisons IS IMPORTANT;
1164 * the macros do no checks. Order of evaluation:
1166 * o an isnull check, largely to avoid coredumps since greg doubts this
1167 * routine is called with a null ptr anyway in proper operation, but is
1168 * not completely sure...
1169 * o ExactNodeType checks.
1170 * o clause checks or other checks where we look at the lfirst of something.
1171 * ----------------------------------------------------------------
1174 ExecEvalExpr(Node *expression,
1175 ExprContext *econtext,
1184 * Some callers don't care about is done and only want 1 result. They
1185 * indicate this by passing NULL
1191 * here we dispatch the work to the appropriate type of function given
1192 * the type of our expression.
1194 if (expression == NULL)
1197 return (Datum) true;
1200 switch (nodeTag(expression))
1203 retDatum = (Datum) ExecEvalVar((Var *) expression, econtext, isNull);
1207 Const *con = (Const *) expression;
1209 if (con->constisnull)
1211 retDatum = con->constvalue;
1215 retDatum = (Datum) ExecEvalParam((Param *) expression, econtext, isNull);
1218 retDatum = (Datum) ExecEvalIter((Iter *) expression,
1224 retDatum = (Datum) ExecEvalAggref((Aggref *) expression,
1229 retDatum = (Datum) ExecEvalArrayRef((ArrayRef *) expression,
1236 Expr *expr = (Expr *) expression;
1238 switch (expr->opType)
1241 retDatum = (Datum) ExecEvalOper(expr, econtext, isNull);
1244 retDatum = (Datum) ExecEvalFunc(expr, econtext, isNull, isDone);
1247 retDatum = (Datum) ExecEvalOr(expr, econtext, isNull);
1250 retDatum = (Datum) ExecEvalAnd(expr, econtext, isNull);
1253 retDatum = (Datum) ExecEvalNot(expr, econtext, isNull);
1256 retDatum = (Datum) ExecSubPlan((SubPlan *) expr->oper, expr->args, econtext);
1259 elog(ERROR, "ExecEvalExpr: unknown expression type %d", expr->opType);
1265 retDatum = (Datum) ExecEvalCase((CaseExpr *) expression, econtext, isNull);
1269 elog(ERROR, "ExecEvalExpr: unknown expression type %d", nodeTag(expression));
1274 } /* ExecEvalExpr() */
1277 /* ----------------------------------------------------------------
1278 * ExecQual / ExecTargetList
1279 * ----------------------------------------------------------------
1282 /* ----------------------------------------------------------------
1285 * this is a workhorse for ExecQual. ExecQual has to deal
1286 * with a list of qualifications, so it passes each qualification
1287 * in the list to this function one at a time. ExecQualClause
1288 * returns true when the qualification *fails* and false if
1289 * the qualification succeeded (meaning we have to test the
1290 * rest of the qualification)
1291 * ----------------------------------------------------------------
1294 ExecQualClause(Node *clause, ExprContext *econtext)
1300 /* when there is a null clause, consider the qualification to fail */
1305 * pass isDone, but ignore it. We don't iterate over multiple returns
1306 * in the qualifications.
1308 expr_value = ExecEvalExpr(clause, econtext, &isNull, &isDone);
1311 * remember, we return true when the qualification fails;
1312 * NULL is considered failure.
1316 if (DatumGetInt32(expr_value) == 0)
1322 /* ----------------------------------------------------------------
1325 * Evaluates a conjunctive boolean expression and returns t
1326 * iff none of the subexpressions are false (or null).
1327 * ----------------------------------------------------------------
1330 ExecQual(List *qual, ExprContext *econtext)
1337 EV_printf("ExecQual: qual is ");
1338 EV_nodeDisplay(qual);
1344 * return true immediately if no qual
1350 * a "qual" is a list of clauses. To evaluate the qual, we evaluate
1351 * each of the clauses in the list.
1353 * ExecQualClause returns true when we know the qualification *failed*
1354 * so we just pass each clause in qual to it until we know the qual
1355 * failed or there are no more clauses.
1358 foreach(clause, qual)
1360 if (ExecQualClause((Node *) lfirst(clause), econtext))
1361 return false; /* qual failed, so return false */
1368 ExecTargetListLength(List *targetlist)
1372 TargetEntry *curTle;
1375 foreach(tl, targetlist)
1377 curTle = lfirst(tl);
1379 if (curTle->resdom != NULL)
1382 len += curTle->fjoin->fj_nNodes;
1387 /* ----------------------------------------------------------------
1390 * Evaluates a targetlist with respect to the current
1391 * expression context and return a tuple.
1392 * ----------------------------------------------------------------
1395 ExecTargetList(List *targetlist,
1397 TupleDesc targettype,
1399 ExprContext *econtext,
1402 char nulls_array[64];
1403 bool fjNullArray[64];
1404 bool itemIsDoneArray[64];
1417 static struct tupleDesc NullTupleDesc; /* we assume this inits to zeroes */
1422 EV_printf("ExecTargetList: tl is ");
1423 EV_nodeDisplay(targetlist);
1427 * There used to be some klugy and demonstrably broken code here that
1428 * special-cased the situation where targetlist == NIL. Now we just
1429 * fall through and return an empty-but-valid tuple. We do, however,
1430 * have to cope with the possibility that targettype is NULL ---
1431 * heap_formtuple won't like that, so pass a dummy descriptor with
1432 * natts = 0 to deal with it.
1434 if (targettype == NULL)
1435 targettype = &NullTupleDesc;
1438 * allocate an array of char's to hold the "null" information only if
1439 * we have a really large targetlist. otherwise we use the stack.
1441 * We also allocate a bool array that is used to hold fjoin result state,
1442 * and another that holds the isDone status for each targetlist item.
1446 null_head = (char *) palloc(nodomains + 1);
1447 fjIsNull = (bool *) palloc(nodomains + 1);
1448 itemIsDone = (bool *) palloc(nodomains + 1);
1452 null_head = &nulls_array[0];
1453 fjIsNull = &fjNullArray[0];
1454 itemIsDone = &itemIsDoneArray[0];
1458 * evaluate all the expressions in the target list
1461 *isDone = true; /* until proven otherwise */
1462 haveDoneIters = false; /* any isDone Iter exprs in tlist? */
1464 foreach(tl, targetlist)
1468 * remember, a target list is a list of lists:
1470 * ((<resdom | fjoin> expr) (<resdom | fjoin> expr) ...)
1472 * tl is a pointer to successive cdr's of the targetlist tle is a
1473 * pointer to the target list entry in tl
1477 if (tle->resdom != NULL)
1480 resdom = tle->resdom;
1481 resind = resdom->resno - 1;
1483 constvalue = (Datum) ExecEvalExpr(expr,
1486 &itemIsDone[resind]);
1488 values[resind] = constvalue;
1491 null_head[resind] = ' ';
1493 null_head[resind] = 'n';
1495 if (IsA(expr, Iter))
1497 if (itemIsDone[resind])
1498 haveDoneIters = true;
1500 *isDone = false; /* we have undone Iters in the list */
1507 List *fjTlist = (List *) tle->expr;
1508 Fjoin *fjNode = tle->fjoin;
1509 int nNodes = fjNode->fj_nNodes;
1510 DatumPtr results = fjNode->fj_results;
1512 ExecEvalFjoin(tle, econtext, fjIsNull, isDone);
1514 /* this is probably wrong: */
1516 return (HeapTuple) NULL;
1519 * get the result from the inner node
1521 fjRes = (Resdom *) fjNode->fj_innerNode;
1522 resind = fjRes->resno - 1;
1524 null_head[resind] = 'n';
1527 null_head[resind] = ' ';
1528 values[resind] = results[0];
1532 * Get results from all of the outer nodes
1536 curNode++, fjTlist = lnext(fjTlist))
1538 #ifdef NOT_USED /* what is this?? */
1539 Node *outernode = lfirst(fjTlist);
1541 fjRes = (Resdom *) outernode->iterexpr;
1543 resind = fjRes->resno - 1;
1544 if (fjIsNull[curNode])
1545 null_head[resind] = 'n';
1548 null_head[resind] = ' ';
1549 values[resind] = results[curNode];
1559 /* all Iters are done, so return a null indicating tlist set
1560 * expansion is complete.
1567 /* We have some done and some undone Iters. Restart the done ones
1568 * so that we can deliver a tuple (if possible).
1570 * XXX this code is a crock, because it only works for Iters at
1571 * the top level of tlist expressions, and doesn't even work right
1572 * for them: you should get all possible combinations of Iter
1573 * results, but you won't unless the numbers of values returned by
1574 * each are relatively prime. Should have a mechanism more like
1575 * aggregate functions, where we make a list of all Iters
1576 * contained in the tlist and cycle through their values in a
1577 * methodical fashion. To do someday; can't get excited about
1578 * fixing a Berkeley feature that's not in SQL92. (The only
1579 * reason we're doing this much is that we have to be sure all
1580 * the Iters are run to completion, or their subplan executors
1581 * will have unreleased resources, e.g. pinned buffers...)
1583 foreach(tl, targetlist)
1587 if (tle->resdom != NULL)
1590 resdom = tle->resdom;
1591 resind = resdom->resno - 1;
1593 if (IsA(expr, Iter) && itemIsDone[resind])
1595 constvalue = (Datum) ExecEvalExpr(expr,
1598 &itemIsDone[resind]);
1599 if (itemIsDone[resind])
1601 /* Oh dear, this Iter is returning an empty set.
1602 * Guess we can't make a tuple after all.
1609 values[resind] = constvalue;
1612 null_head[resind] = ' ';
1614 null_head[resind] = 'n';
1622 * form the new result tuple (in the "normal" context)
1624 newTuple = (HeapTuple) heap_formtuple(targettype, values, null_head);
1628 * free the status arrays if we palloc'd them
1640 /* ----------------------------------------------------------------
1643 * projects a tuple based in projection info and stores
1644 * it in the specified tuple table slot.
1646 * Note: someday soon the executor can be extended to eliminate
1647 * redundant projections by storing pointers to datums
1648 * in the tuple table and then passing these around when
1649 * possible. this should make things much quicker.
1651 * ----------------------------------------------------------------
1654 ExecProject(ProjectionInfo *projInfo, bool *isDone)
1656 TupleTableSlot *slot;
1661 ExprContext *econtext;
1667 if (projInfo == NULL)
1668 return (TupleTableSlot *) NULL;
1671 * get the projection info we want
1673 slot = projInfo->pi_slot;
1674 targetlist = projInfo->pi_targetlist;
1675 len = projInfo->pi_len;
1676 tupType = slot->ttc_tupleDescriptor;
1678 tupValue = projInfo->pi_tupValue;
1679 econtext = projInfo->pi_exprContext;
1682 * form a new (result) tuple
1684 newTuple = ExecTargetList(targetlist,
1692 * store the tuple in the projection slot and return the slot.
1694 return (TupleTableSlot *)
1695 ExecStoreTuple(newTuple,/* tuple to store */
1696 slot, /* slot to store in */
1697 InvalidBuffer, /* tuple has no buffer */