1 /*-------------------------------------------------------------------------
4 * Routines to evaluate qualification and targetlist expressions
6 * Portions Copyright (c) 1996-2006, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/executor/execQual.c,v 1.189 2006/03/10 01:51:23 tgl Exp $
13 *-------------------------------------------------------------------------
17 * ExecEvalExpr - (now a macro) evaluate an expression, 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 * The more heavily used ExecEvalExpr routines, such as ExecEvalVar(),
24 * are hotspots. Making these faster will speed up the entire system.
26 * ExecProject() 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
31 * During expression evaluation, we check_stack_depth only in
32 * ExecMakeFunctionResult rather than at every single node. This
33 * is a compromise that trades off precision of the stack limit setting
39 #include "access/heapam.h"
40 #include "access/nbtree.h"
41 #include "catalog/pg_type.h"
42 #include "commands/typecmds.h"
43 #include "executor/execdebug.h"
44 #include "executor/functions.h"
45 #include "executor/nodeSubplan.h"
47 #include "miscadmin.h"
48 #include "nodes/makefuncs.h"
49 #include "optimizer/planmain.h"
50 #include "parser/parse_expr.h"
51 #include "utils/acl.h"
52 #include "utils/array.h"
53 #include "utils/builtins.h"
54 #include "utils/lsyscache.h"
55 #include "utils/memutils.h"
56 #include "utils/typcache.h"
59 /* static function decls */
60 static Datum ExecEvalArrayRef(ArrayRefExprState *astate,
61 ExprContext *econtext,
62 bool *isNull, ExprDoneCond *isDone);
63 static Datum ExecEvalAggref(AggrefExprState *aggref,
64 ExprContext *econtext,
65 bool *isNull, ExprDoneCond *isDone);
66 static Datum ExecEvalVar(ExprState *exprstate, ExprContext *econtext,
67 bool *isNull, ExprDoneCond *isDone);
68 static Datum ExecEvalWholeRowVar(ExprState *exprstate, ExprContext *econtext,
69 bool *isNull, ExprDoneCond *isDone);
70 static Datum ExecEvalConst(ExprState *exprstate, ExprContext *econtext,
71 bool *isNull, ExprDoneCond *isDone);
72 static Datum ExecEvalParam(ExprState *exprstate, ExprContext *econtext,
73 bool *isNull, ExprDoneCond *isDone);
74 static ExprDoneCond ExecEvalFuncArgs(FunctionCallInfo fcinfo,
75 List *argList, ExprContext *econtext);
76 static Datum ExecMakeFunctionResultNoSets(FuncExprState *fcache,
77 ExprContext *econtext,
78 bool *isNull, ExprDoneCond *isDone);
79 static Datum ExecEvalFunc(FuncExprState *fcache, ExprContext *econtext,
80 bool *isNull, ExprDoneCond *isDone);
81 static Datum ExecEvalOper(FuncExprState *fcache, ExprContext *econtext,
82 bool *isNull, ExprDoneCond *isDone);
83 static Datum ExecEvalDistinct(FuncExprState *fcache, ExprContext *econtext,
84 bool *isNull, ExprDoneCond *isDone);
85 static Datum ExecEvalScalarArrayOp(ScalarArrayOpExprState *sstate,
86 ExprContext *econtext,
87 bool *isNull, ExprDoneCond *isDone);
88 static Datum ExecEvalNot(BoolExprState *notclause, ExprContext *econtext,
89 bool *isNull, ExprDoneCond *isDone);
90 static Datum ExecEvalOr(BoolExprState *orExpr, ExprContext *econtext,
91 bool *isNull, ExprDoneCond *isDone);
92 static Datum ExecEvalAnd(BoolExprState *andExpr, ExprContext *econtext,
93 bool *isNull, ExprDoneCond *isDone);
94 static Datum ExecEvalConvertRowtype(ConvertRowtypeExprState *cstate,
95 ExprContext *econtext,
96 bool *isNull, ExprDoneCond *isDone);
97 static Datum ExecEvalCase(CaseExprState *caseExpr, ExprContext *econtext,
98 bool *isNull, ExprDoneCond *isDone);
99 static Datum ExecEvalCaseTestExpr(ExprState *exprstate,
100 ExprContext *econtext,
101 bool *isNull, ExprDoneCond *isDone);
102 static Datum ExecEvalArray(ArrayExprState *astate,
103 ExprContext *econtext,
104 bool *isNull, ExprDoneCond *isDone);
105 static Datum ExecEvalRow(RowExprState *rstate,
106 ExprContext *econtext,
107 bool *isNull, ExprDoneCond *isDone);
108 static Datum ExecEvalRowCompare(RowCompareExprState *rstate,
109 ExprContext *econtext,
110 bool *isNull, ExprDoneCond *isDone);
111 static Datum ExecEvalCoalesce(CoalesceExprState *coalesceExpr,
112 ExprContext *econtext,
113 bool *isNull, ExprDoneCond *isDone);
114 static Datum ExecEvalMinMax(MinMaxExprState *minmaxExpr,
115 ExprContext *econtext,
116 bool *isNull, ExprDoneCond *isDone);
117 static Datum ExecEvalNullIf(FuncExprState *nullIfExpr,
118 ExprContext *econtext,
119 bool *isNull, ExprDoneCond *isDone);
120 static Datum ExecEvalNullTest(GenericExprState *nstate,
121 ExprContext *econtext,
122 bool *isNull, ExprDoneCond *isDone);
123 static Datum ExecEvalBooleanTest(GenericExprState *bstate,
124 ExprContext *econtext,
125 bool *isNull, ExprDoneCond *isDone);
126 static Datum ExecEvalCoerceToDomain(CoerceToDomainState *cstate,
127 ExprContext *econtext,
128 bool *isNull, ExprDoneCond *isDone);
129 static Datum ExecEvalCoerceToDomainValue(ExprState *exprstate,
130 ExprContext *econtext,
131 bool *isNull, ExprDoneCond *isDone);
132 static Datum ExecEvalFieldSelect(FieldSelectState *fstate,
133 ExprContext *econtext,
134 bool *isNull, ExprDoneCond *isDone);
135 static Datum ExecEvalFieldStore(FieldStoreState *fstate,
136 ExprContext *econtext,
137 bool *isNull, ExprDoneCond *isDone);
138 static Datum ExecEvalRelabelType(GenericExprState *exprstate,
139 ExprContext *econtext,
140 bool *isNull, ExprDoneCond *isDone);
143 /* ----------------------------------------------------------------
144 * ExecEvalExpr routines
146 * Recursively evaluate a targetlist or qualification expression.
148 * Each of the following routines having the signature
149 * Datum ExecEvalFoo(ExprState *expression,
150 * ExprContext *econtext,
152 * ExprDoneCond *isDone);
153 * is responsible for evaluating one type or subtype of ExprState node.
154 * They are normally called via the ExecEvalExpr macro, which makes use of
155 * the function pointer set up when the ExprState node was built by
156 * ExecInitExpr. (In some cases, we change this pointer later to avoid
157 * re-executing one-time overhead.)
159 * Note: for notational simplicity we declare these functions as taking the
160 * specific type of ExprState that they work on. This requires casting when
161 * assigning the function pointer in ExecInitExpr. Be careful that the
162 * function signature is declared correctly, because the cast suppresses
163 * automatic checking!
166 * All these functions share this calling convention:
169 * expression: the expression state tree to evaluate
170 * econtext: evaluation context information
173 * return value: Datum value of result
174 * *isNull: set to TRUE if result is NULL (actual return value is
175 * meaningless if so); set to FALSE if non-null result
176 * *isDone: set to indicator of set-result status
178 * A caller that can only accept a singleton (non-set) result should pass
179 * NULL for isDone; if the expression computes a set result then an error
180 * will be reported via ereport. If the caller does pass an isDone pointer
181 * then *isDone is set to one of these three states:
182 * ExprSingleResult singleton result (not a set)
183 * ExprMultipleResult return value is one element of a set
184 * ExprEndResult there are no more elements in the set
185 * When ExprMultipleResult is returned, the caller should invoke
186 * ExecEvalExpr() repeatedly until ExprEndResult is returned. ExprEndResult
187 * is returned after the last real set element. For convenience isNull will
188 * always be set TRUE when ExprEndResult is returned, but this should not be
189 * taken as indicating a NULL element of the set. Note that these return
190 * conventions allow us to distinguish among a singleton NULL, a NULL element
191 * of a set, and an empty set.
193 * The caller should already have switched into the temporary memory
194 * context econtext->ecxt_per_tuple_memory. The convenience entry point
195 * ExecEvalExprSwitchContext() is provided for callers who don't prefer to
196 * do the switch in an outer loop. We do not do the switch in these routines
197 * because it'd be a waste of cycles during nested expression evaluation.
198 * ----------------------------------------------------------------
205 * This function takes an ArrayRef and returns the extracted Datum
206 * if it's a simple reference, or the modified array value if it's
207 * an array assignment (i.e., array element or slice insertion).
209 * NOTE: if we get a NULL result from a subscript expression, we return NULL
210 * when it's an array reference, or raise an error when it's an assignment.
212 * NOTE: we deliberately refrain from applying DatumGetArrayTypeP() here,
213 * even though that might seem natural, because this code needs to support
214 * both varlena arrays and fixed-length array types. DatumGetArrayTypeP()
215 * only works for the varlena kind. The routines we call in arrayfuncs.c
216 * have to know the difference (that's what they need refattrlength for).
220 ExecEvalArrayRef(ArrayRefExprState *astate,
221 ExprContext *econtext,
223 ExprDoneCond *isDone)
225 ArrayRef *arrayRef = (ArrayRef *) astate->xprstate.expr;
226 ArrayType *array_source;
227 ArrayType *resultArray;
228 bool isAssignment = (arrayRef->refassgnexpr != NULL);
237 array_source = (ArrayType *)
238 DatumGetPointer(ExecEvalExpr(astate->refexpr,
244 * If refexpr yields NULL, and it's a fetch, then result is NULL. In the
245 * assignment case, we'll cons up something below.
249 if (isDone && *isDone == ExprEndResult)
250 return (Datum) NULL; /* end of set result */
255 foreach(l, astate->refupperindexpr)
257 ExprState *eltstate = (ExprState *) lfirst(l);
261 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
262 errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
265 upper.indx[i++] = DatumGetInt32(ExecEvalExpr(eltstate,
269 /* If any index expr yields NULL, result is NULL or error */
274 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
275 errmsg("array subscript in assignment must not be NULL")));
281 if (astate->reflowerindexpr != NIL)
283 foreach(l, astate->reflowerindexpr)
285 ExprState *eltstate = (ExprState *) lfirst(l);
289 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
290 errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
293 lower.indx[j++] = DatumGetInt32(ExecEvalExpr(eltstate,
297 /* If any index expr yields NULL, result is NULL or error */
302 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
303 errmsg("array subscript in assignment must not be NULL")));
308 /* this can't happen unless parser messed up */
310 elog(ERROR, "upper and lower index lists are not same length");
321 * Evaluate the value to be assigned into the array.
323 * XXX At some point we'll need to look into making the old value of
324 * the array element available via CaseTestExpr, as is done by
325 * ExecEvalFieldStore. This is not needed now but will be needed to
326 * support arrays of composite types; in an assignment to a field of
327 * an array member, the parser would generate a FieldStore that
328 * expects to fetch its input tuple via CaseTestExpr.
330 sourceData = ExecEvalExpr(astate->refassgnexpr,
336 * For an assignment to a fixed-length array type, both the original
337 * array and the value to be assigned into it must be non-NULL, else
338 * we punt and return the original array.
340 if (astate->refattrlength > 0) /* fixed-length array? */
341 if (eisnull || *isNull)
342 return PointerGetDatum(array_source);
345 * For assignment to varlena arrays, we handle a NULL original array
346 * by substituting an empty (zero-dimensional) array; insertion of the
347 * new element will result in a singleton array value. It does not
348 * matter whether the new element is NULL.
352 array_source = construct_empty_array(arrayRef->refelemtype);
357 resultArray = array_set(array_source, i,
361 astate->refattrlength,
362 astate->refelemlength,
363 astate->refelembyval,
364 astate->refelemalign);
366 resultArray = array_set_slice(array_source, i,
367 upper.indx, lower.indx,
368 (ArrayType *) DatumGetPointer(sourceData),
370 astate->refattrlength,
371 astate->refelemlength,
372 astate->refelembyval,
373 astate->refelemalign);
374 return PointerGetDatum(resultArray);
378 return array_ref(array_source, i, upper.indx,
379 astate->refattrlength,
380 astate->refelemlength,
381 astate->refelembyval,
382 astate->refelemalign,
386 resultArray = array_get_slice(array_source, i,
387 upper.indx, lower.indx,
388 astate->refattrlength,
389 astate->refelemlength,
390 astate->refelembyval,
391 astate->refelemalign);
392 return PointerGetDatum(resultArray);
397 /* ----------------------------------------------------------------
400 * Returns a Datum whose value is the value of the precomputed
401 * aggregate found in the given expression context.
402 * ----------------------------------------------------------------
405 ExecEvalAggref(AggrefExprState *aggref, ExprContext *econtext,
406 bool *isNull, ExprDoneCond *isDone)
409 *isDone = ExprSingleResult;
411 if (econtext->ecxt_aggvalues == NULL) /* safety check */
412 elog(ERROR, "no aggregates in this expression context");
414 *isNull = econtext->ecxt_aggnulls[aggref->aggno];
415 return econtext->ecxt_aggvalues[aggref->aggno];
418 /* ----------------------------------------------------------------
421 * Returns a Datum whose value is the value of a range
422 * variable with respect to given expression context.
423 * ----------------------------------------------------------------
426 ExecEvalVar(ExprState *exprstate, ExprContext *econtext,
427 bool *isNull, ExprDoneCond *isDone)
429 Var *variable = (Var *) exprstate->expr;
430 TupleTableSlot *slot;
434 *isDone = ExprSingleResult;
437 * Get the slot and attribute number we want
439 * The asserts check that references to system attributes only appear at
440 * the level of a relation scan; at higher levels, system attributes must
441 * be treated as ordinary variables (since we no longer have access to the
444 attnum = variable->varattno;
446 switch (variable->varno)
448 case INNER: /* get the tuple from the inner node */
449 slot = econtext->ecxt_innertuple;
453 case OUTER: /* get the tuple from the outer node */
454 slot = econtext->ecxt_outertuple;
458 default: /* get the tuple from the relation being
460 slot = econtext->ecxt_scantuple;
464 #ifdef USE_ASSERT_CHECKING
467 * Some checks that are only applied for user attribute numbers (bogus
468 * system attnums will be caught inside slot_getattr).
472 TupleDesc tuple_type = slot->tts_tupleDescriptor;
475 * This assert checks that the attnum is valid.
477 Assert(attnum <= tuple_type->natts);
480 * This assert checks that the datatype the plan expects to get (as
481 * told by our "variable" argument) is in fact the datatype of the
482 * attribute being fetched (as seen in the current context, identified
483 * by our "econtext" argument). Otherwise crashes are likely.
485 * Note that we can't check dropped columns, since their atttypid has
488 Assert(variable->vartype == tuple_type->attrs[attnum - 1]->atttypid ||
489 tuple_type->attrs[attnum - 1]->attisdropped);
491 #endif /* USE_ASSERT_CHECKING */
493 return slot_getattr(slot, attnum, isNull);
496 /* ----------------------------------------------------------------
497 * ExecEvalWholeRowVar
499 * Returns a Datum for a whole-row variable.
501 * This could be folded into ExecEvalVar, but we make it a separate
502 * routine so as not to slow down ExecEvalVar with tests for this
504 * ----------------------------------------------------------------
507 ExecEvalWholeRowVar(ExprState *exprstate, ExprContext *econtext,
508 bool *isNull, ExprDoneCond *isDone)
510 Var *variable = (Var *) exprstate->expr;
511 TupleTableSlot *slot;
514 HeapTupleHeader dtuple;
517 *isDone = ExprSingleResult;
520 Assert(variable->varattno == InvalidAttrNumber);
523 * Whole-row Vars can only appear at the level of a relation scan, never
526 Assert(variable->varno != INNER);
527 Assert(variable->varno != OUTER);
528 slot = econtext->ecxt_scantuple;
530 tuple = ExecFetchSlotTuple(slot);
531 tupleDesc = slot->tts_tupleDescriptor;
534 * We have to make a copy of the tuple so we can safely insert the Datum
535 * overhead fields, which are not set in on-disk tuples.
537 dtuple = (HeapTupleHeader) palloc(tuple->t_len);
538 memcpy((char *) dtuple, (char *) tuple->t_data, tuple->t_len);
540 HeapTupleHeaderSetDatumLength(dtuple, tuple->t_len);
543 * If the Var identifies a named composite type, label the tuple with that
544 * type; otherwise use what is in the tupleDesc.
546 * It's likely that the slot's tupleDesc is a record type; if so, make
547 * sure it's been "blessed", so that the Datum can be interpreted later.
549 if (variable->vartype != RECORDOID)
551 HeapTupleHeaderSetTypeId(dtuple, variable->vartype);
552 HeapTupleHeaderSetTypMod(dtuple, variable->vartypmod);
556 if (tupleDesc->tdtypeid == RECORDOID &&
557 tupleDesc->tdtypmod < 0)
558 assign_record_type_typmod(tupleDesc);
559 HeapTupleHeaderSetTypeId(dtuple, tupleDesc->tdtypeid);
560 HeapTupleHeaderSetTypMod(dtuple, tupleDesc->tdtypmod);
563 return PointerGetDatum(dtuple);
566 /* ----------------------------------------------------------------
569 * Returns the value of a constant.
571 * Note that for pass-by-ref datatypes, we return a pointer to the
572 * actual constant node. This is one of the reasons why functions
573 * must treat their input arguments as read-only.
574 * ----------------------------------------------------------------
577 ExecEvalConst(ExprState *exprstate, ExprContext *econtext,
578 bool *isNull, ExprDoneCond *isDone)
580 Const *con = (Const *) exprstate->expr;
583 *isDone = ExprSingleResult;
585 *isNull = con->constisnull;
586 return con->constvalue;
589 /* ----------------------------------------------------------------
592 * Returns the value of a parameter. A param node contains
593 * something like ($.name) and the expression context contains
594 * the current parameter bindings (name = "sam") (age = 34)...
595 * so our job is to find and return the appropriate datum ("sam").
597 * Q: if we have a parameter ($.foo) without a binding, i.e.
598 * there is no (foo = xxx) in the parameter list info,
599 * is this a fatal error or should this be a "not available"
600 * (in which case we could return NULL)? -cim 10/13/89
601 * ----------------------------------------------------------------
604 ExecEvalParam(ExprState *exprstate, ExprContext *econtext,
605 bool *isNull, ExprDoneCond *isDone)
607 Param *expression = (Param *) exprstate->expr;
608 int thisParamKind = expression->paramkind;
609 AttrNumber thisParamId = expression->paramid;
612 *isDone = ExprSingleResult;
614 if (thisParamKind == PARAM_EXEC)
617 * PARAM_EXEC params (internal executor parameters) are stored in the
618 * ecxt_param_exec_vals array, and can be accessed by array index.
622 prm = &(econtext->ecxt_param_exec_vals[thisParamId]);
623 if (prm->execPlan != NULL)
625 /* Parameter not evaluated yet, so go do it */
626 ExecSetParamPlan(prm->execPlan, econtext);
627 /* ExecSetParamPlan should have processed this param... */
628 Assert(prm->execPlan == NULL);
630 *isNull = prm->isnull;
636 * All other parameter types must be sought in ecxt_param_list_info.
638 ParamListInfo paramInfo;
640 paramInfo = lookupParam(econtext->ecxt_param_list_info,
642 expression->paramname,
645 Assert(paramInfo->ptype == expression->paramtype);
646 *isNull = paramInfo->isnull;
647 return paramInfo->value;
652 /* ----------------------------------------------------------------
653 * ExecEvalOper / ExecEvalFunc support routines
654 * ----------------------------------------------------------------
661 * These functions return the value of the requested attribute
662 * out of the given tuple Datum.
663 * C functions which take a tuple as an argument are expected
664 * to use these. Ex: overpaid(EMP) might call GetAttributeByNum().
665 * Note: these are actually rather slow because they do a typcache
666 * lookup on each call.
669 GetAttributeByNum(HeapTupleHeader tuple,
677 HeapTupleData tmptup;
679 if (!AttributeNumberIsValid(attrno))
680 elog(ERROR, "invalid attribute number %d", attrno);
683 elog(ERROR, "a NULL isNull pointer was passed");
687 /* Kinda bogus but compatible with old behavior... */
692 tupType = HeapTupleHeaderGetTypeId(tuple);
693 tupTypmod = HeapTupleHeaderGetTypMod(tuple);
694 tupDesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
697 * heap_getattr needs a HeapTuple not a bare HeapTupleHeader. We set all
698 * the fields in the struct just in case user tries to inspect system
701 tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
702 ItemPointerSetInvalid(&(tmptup.t_self));
703 tmptup.t_tableOid = InvalidOid;
704 tmptup.t_data = tuple;
706 result = heap_getattr(&tmptup,
714 GetAttributeByName(HeapTupleHeader tuple, const char *attname, bool *isNull)
721 HeapTupleData tmptup;
725 elog(ERROR, "invalid attribute name");
728 elog(ERROR, "a NULL isNull pointer was passed");
732 /* Kinda bogus but compatible with old behavior... */
737 tupType = HeapTupleHeaderGetTypeId(tuple);
738 tupTypmod = HeapTupleHeaderGetTypMod(tuple);
739 tupDesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
741 attrno = InvalidAttrNumber;
742 for (i = 0; i < tupDesc->natts; i++)
744 if (namestrcmp(&(tupDesc->attrs[i]->attname), attname) == 0)
746 attrno = tupDesc->attrs[i]->attnum;
751 if (attrno == InvalidAttrNumber)
752 elog(ERROR, "attribute \"%s\" does not exist", attname);
755 * heap_getattr needs a HeapTuple not a bare HeapTupleHeader. We set all
756 * the fields in the struct just in case user tries to inspect system
759 tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
760 ItemPointerSetInvalid(&(tmptup.t_self));
761 tmptup.t_tableOid = InvalidOid;
762 tmptup.t_data = tuple;
764 result = heap_getattr(&tmptup,
772 * init_fcache - initialize a FuncExprState node during first use
775 init_fcache(Oid foid, FuncExprState *fcache, MemoryContext fcacheCxt)
779 /* Check permission to call function */
780 aclresult = pg_proc_aclcheck(foid, GetUserId(), ACL_EXECUTE);
781 if (aclresult != ACLCHECK_OK)
782 aclcheck_error(aclresult, ACL_KIND_PROC, get_func_name(foid));
785 * Safety check on nargs. Under normal circumstances this should never
786 * fail, as parser should check sooner. But possibly it might fail if
787 * server has been compiled with FUNC_MAX_ARGS smaller than some functions
788 * declared in pg_proc?
790 if (list_length(fcache->args) > FUNC_MAX_ARGS)
792 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
793 errmsg("cannot pass more than %d arguments to a function",
796 /* Set up the primary fmgr lookup information */
797 fmgr_info_cxt(foid, &(fcache->func), fcacheCxt);
799 /* Initialize additional info */
800 fcache->setArgsValid = false;
801 fcache->shutdown_reg = false;
802 fcache->func.fn_expr = (Node *) fcache->xprstate.expr;
806 * callback function in case a FuncExpr returning a set needs to be shut down
807 * before it has been run to completion
810 ShutdownFuncExpr(Datum arg)
812 FuncExprState *fcache = (FuncExprState *) DatumGetPointer(arg);
814 /* Clear any active set-argument state */
815 fcache->setArgsValid = false;
817 /* execUtils will deregister the callback... */
818 fcache->shutdown_reg = false;
822 * Evaluate arguments for a function.
825 ExecEvalFuncArgs(FunctionCallInfo fcinfo,
827 ExprContext *econtext)
829 ExprDoneCond argIsDone;
833 argIsDone = ExprSingleResult; /* default assumption */
836 foreach(arg, argList)
838 ExprState *argstate = (ExprState *) lfirst(arg);
839 ExprDoneCond thisArgIsDone;
841 fcinfo->arg[i] = ExecEvalExpr(argstate,
846 if (thisArgIsDone != ExprSingleResult)
849 * We allow only one argument to have a set value; we'd need much
850 * more complexity to keep track of multiple set arguments (cf.
851 * ExecTargetList) and it doesn't seem worth it.
853 if (argIsDone != ExprSingleResult)
855 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
856 errmsg("functions and operators can take at most one set argument")));
857 argIsDone = thisArgIsDone;
868 * ExecMakeFunctionResult
870 * Evaluate the arguments to a function and then the function itself.
873 ExecMakeFunctionResult(FuncExprState *fcache,
874 ExprContext *econtext,
876 ExprDoneCond *isDone)
878 List *arguments = fcache->args;
880 FunctionCallInfoData fcinfo;
881 ReturnSetInfo rsinfo; /* for functions returning sets */
882 ExprDoneCond argDone;
886 /* Guard against stack overflow due to overly complex expressions */
890 * arguments is a list of expressions to evaluate before passing to the
891 * function manager. We skip the evaluation if it was already done in the
892 * previous call (ie, we are continuing the evaluation of a set-valued
893 * function). Otherwise, collect the current argument values into fcinfo.
895 if (!fcache->setArgsValid)
897 /* Need to prep callinfo structure */
898 InitFunctionCallInfoData(fcinfo, &(fcache->func), 0, NULL, NULL);
899 argDone = ExecEvalFuncArgs(&fcinfo, arguments, econtext);
900 if (argDone == ExprEndResult)
902 /* input is an empty set, so return an empty set. */
905 *isDone = ExprEndResult;
908 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
909 errmsg("set-valued function called in context that cannot accept a set")));
912 hasSetArg = (argDone != ExprSingleResult);
916 /* Copy callinfo from previous evaluation */
917 memcpy(&fcinfo, &fcache->setArgs, sizeof(fcinfo));
918 hasSetArg = fcache->setHasSetArg;
919 /* Reset flag (we may set it again below) */
920 fcache->setArgsValid = false;
924 * If function returns set, prepare a resultinfo node for communication
926 if (fcache->func.fn_retset)
928 fcinfo.resultinfo = (Node *) &rsinfo;
929 rsinfo.type = T_ReturnSetInfo;
930 rsinfo.econtext = econtext;
931 rsinfo.expectedDesc = NULL;
932 rsinfo.allowedModes = (int) SFRM_ValuePerCall;
933 rsinfo.returnMode = SFRM_ValuePerCall;
934 /* isDone is filled below */
935 rsinfo.setResult = NULL;
936 rsinfo.setDesc = NULL;
940 * now return the value gotten by calling the function manager, passing
941 * the function the evaluated parameter values.
943 if (fcache->func.fn_retset || hasSetArg)
946 * We need to return a set result. Complain if caller not ready to
951 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
952 errmsg("set-valued function called in context that cannot accept a set")));
955 * This loop handles the situation where we have both a set argument
956 * and a set-valued function. Once we have exhausted the function's
957 * value(s) for a particular argument value, we have to get the next
958 * argument value and start the function over again. We might have to
959 * do it more than once, if the function produces an empty result set
960 * for a particular input value.
965 * If function is strict, and there are any NULL arguments, skip
966 * calling the function (at least for this set of args).
970 if (fcache->func.fn_strict)
972 for (i = 0; i < fcinfo.nargs; i++)
974 if (fcinfo.argnull[i])
984 fcinfo.isnull = false;
985 rsinfo.isDone = ExprSingleResult;
986 result = FunctionCallInvoke(&fcinfo);
987 *isNull = fcinfo.isnull;
988 *isDone = rsinfo.isDone;
994 *isDone = ExprEndResult;
997 if (*isDone != ExprEndResult)
1000 * Got a result from current argument. If function itself
1001 * returns set, save the current argument values to re-use on
1004 if (fcache->func.fn_retset && *isDone == ExprMultipleResult)
1006 memcpy(&fcache->setArgs, &fcinfo, sizeof(fcinfo));
1007 fcache->setHasSetArg = hasSetArg;
1008 fcache->setArgsValid = true;
1009 /* Register cleanup callback if we didn't already */
1010 if (!fcache->shutdown_reg)
1012 RegisterExprContextCallback(econtext,
1014 PointerGetDatum(fcache));
1015 fcache->shutdown_reg = true;
1020 * Make sure we say we are returning a set, even if the
1021 * function itself doesn't return sets.
1024 *isDone = ExprMultipleResult;
1028 /* Else, done with this argument */
1030 break; /* input not a set, so done */
1032 /* Re-eval args to get the next element of the input set */
1033 argDone = ExecEvalFuncArgs(&fcinfo, arguments, econtext);
1035 if (argDone != ExprMultipleResult)
1037 /* End of argument set, so we're done. */
1039 *isDone = ExprEndResult;
1045 * If we reach here, loop around to run the function on the new
1053 * Non-set case: much easier.
1055 * We change the ExprState function pointer to use the simpler
1056 * ExecMakeFunctionResultNoSets on subsequent calls. This amounts to
1057 * assuming that no argument can return a set if it didn't do so the
1060 fcache->xprstate.evalfunc = (ExprStateEvalFunc) ExecMakeFunctionResultNoSets;
1063 *isDone = ExprSingleResult;
1066 * If function is strict, and there are any NULL arguments, skip
1067 * calling the function and return NULL.
1069 if (fcache->func.fn_strict)
1071 for (i = 0; i < fcinfo.nargs; i++)
1073 if (fcinfo.argnull[i])
1080 fcinfo.isnull = false;
1081 result = FunctionCallInvoke(&fcinfo);
1082 *isNull = fcinfo.isnull;
1089 * ExecMakeFunctionResultNoSets
1091 * Simplified version of ExecMakeFunctionResult that can only handle
1092 * non-set cases. Hand-tuned for speed.
1095 ExecMakeFunctionResultNoSets(FuncExprState *fcache,
1096 ExprContext *econtext,
1098 ExprDoneCond *isDone)
1102 FunctionCallInfoData fcinfo;
1105 /* Guard against stack overflow due to overly complex expressions */
1106 check_stack_depth();
1109 *isDone = ExprSingleResult;
1111 /* inlined, simplified version of ExecEvalFuncArgs */
1113 foreach(arg, fcache->args)
1115 ExprState *argstate = (ExprState *) lfirst(arg);
1117 fcinfo.arg[i] = ExecEvalExpr(argstate,
1124 InitFunctionCallInfoData(fcinfo, &(fcache->func), i, NULL, NULL);
1127 * If function is strict, and there are any NULL arguments, skip calling
1128 * the function and return NULL.
1130 if (fcache->func.fn_strict)
1134 if (fcinfo.argnull[i])
1141 /* fcinfo.isnull = false; */ /* handled by InitFunctionCallInfoData */
1142 result = FunctionCallInvoke(&fcinfo);
1143 *isNull = fcinfo.isnull;
1150 * ExecMakeTableFunctionResult
1152 * Evaluate a table function, producing a materialized result in a Tuplestore
1153 * object. *returnDesc is set to the tupledesc actually returned by the
1154 * function, or NULL if it didn't provide one.
1157 ExecMakeTableFunctionResult(ExprState *funcexpr,
1158 ExprContext *econtext,
1159 TupleDesc expectedDesc,
1160 TupleDesc *returnDesc)
1162 Tuplestorestate *tupstore = NULL;
1163 TupleDesc tupdesc = NULL;
1166 bool returnsSet = false;
1167 FunctionCallInfoData fcinfo;
1168 ReturnSetInfo rsinfo;
1169 HeapTupleData tmptup;
1170 MemoryContext callerContext;
1171 MemoryContext oldcontext;
1172 bool direct_function_call;
1173 bool first_time = true;
1175 callerContext = CurrentMemoryContext;
1177 funcrettype = exprType((Node *) funcexpr->expr);
1179 returnsTuple = (funcrettype == RECORDOID ||
1180 get_typtype(funcrettype) == 'c');
1183 * Prepare a resultinfo node for communication. We always do this even if
1184 * not expecting a set result, so that we can pass expectedDesc. In the
1185 * generic-expression case, the expression doesn't actually get to see the
1186 * resultinfo, but set it up anyway because we use some of the fields as
1187 * our own state variables.
1189 InitFunctionCallInfoData(fcinfo, NULL, 0, NULL, (Node *) &rsinfo);
1190 rsinfo.type = T_ReturnSetInfo;
1191 rsinfo.econtext = econtext;
1192 rsinfo.expectedDesc = expectedDesc;
1193 rsinfo.allowedModes = (int) (SFRM_ValuePerCall | SFRM_Materialize);
1194 rsinfo.returnMode = SFRM_ValuePerCall;
1195 /* isDone is filled below */
1196 rsinfo.setResult = NULL;
1197 rsinfo.setDesc = NULL;
1200 * Normally the passed expression tree will be a FuncExprState, since the
1201 * grammar only allows a function call at the top level of a table
1202 * function reference. However, if the function doesn't return set then
1203 * the planner might have replaced the function call via constant-folding
1204 * or inlining. So if we see any other kind of expression node, execute
1205 * it via the general ExecEvalExpr() code; the only difference is that we
1206 * don't get a chance to pass a special ReturnSetInfo to any functions
1207 * buried in the expression.
1209 if (funcexpr && IsA(funcexpr, FuncExprState) &&
1210 IsA(funcexpr->expr, FuncExpr))
1212 FuncExprState *fcache = (FuncExprState *) funcexpr;
1213 ExprDoneCond argDone;
1216 * This path is similar to ExecMakeFunctionResult.
1218 direct_function_call = true;
1221 * Initialize function cache if first time through
1223 if (fcache->func.fn_oid == InvalidOid)
1225 FuncExpr *func = (FuncExpr *) fcache->xprstate.expr;
1227 init_fcache(func->funcid, fcache, econtext->ecxt_per_query_memory);
1229 returnsSet = fcache->func.fn_retset;
1232 * Evaluate the function's argument list.
1234 * Note: ideally, we'd do this in the per-tuple context, but then the
1235 * argument values would disappear when we reset the context in the
1236 * inner loop. So do it in caller context. Perhaps we should make a
1237 * separate context just to hold the evaluated arguments?
1239 fcinfo.flinfo = &(fcache->func);
1240 argDone = ExecEvalFuncArgs(&fcinfo, fcache->args, econtext);
1241 /* We don't allow sets in the arguments of the table function */
1242 if (argDone != ExprSingleResult)
1244 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1245 errmsg("set-valued function called in context that cannot accept a set")));
1248 * If function is strict, and there are any NULL arguments, skip
1249 * calling the function and act like it returned NULL (or an empty
1250 * set, in the returns-set case).
1252 if (fcache->func.fn_strict)
1256 for (i = 0; i < fcinfo.nargs; i++)
1258 if (fcinfo.argnull[i])
1259 goto no_function_result;
1265 /* Treat funcexpr as a generic expression */
1266 direct_function_call = false;
1270 * Switch to short-lived context for calling the function or expression.
1272 MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
1275 * Loop to handle the ValuePerCall protocol (which is also the same
1276 * behavior needed in the generic ExecEvalExpr path).
1283 CHECK_FOR_INTERRUPTS();
1286 * reset per-tuple memory context before each call of the function or
1287 * expression. This cleans up any local memory the function may leak
1290 ResetExprContext(econtext);
1292 /* Call the function or expression one time */
1293 if (direct_function_call)
1295 fcinfo.isnull = false;
1296 rsinfo.isDone = ExprSingleResult;
1297 result = FunctionCallInvoke(&fcinfo);
1301 result = ExecEvalExpr(funcexpr, econtext,
1302 &fcinfo.isnull, &rsinfo.isDone);
1305 /* Which protocol does function want to use? */
1306 if (rsinfo.returnMode == SFRM_ValuePerCall)
1309 * Check for end of result set.
1311 if (rsinfo.isDone == ExprEndResult)
1315 * Can't do anything very useful with NULL rowtype values. For a
1316 * function returning set, we consider this a protocol violation
1317 * (but another alternative would be to just ignore the result and
1318 * "continue" to get another row). For a function not returning
1319 * set, we fall out of the loop; we'll cons up an all-nulls result
1322 if (returnsTuple && fcinfo.isnull)
1327 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1328 errmsg("function returning set of rows cannot return null value")));
1332 * If first time through, build tupdesc and tuplestore for result
1336 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1340 * Use the type info embedded in the rowtype Datum to look
1341 * up the needed tupdesc. Make a copy for the query.
1345 td = DatumGetHeapTupleHeader(result);
1346 tupdesc = lookup_rowtype_tupdesc(HeapTupleHeaderGetTypeId(td),
1347 HeapTupleHeaderGetTypMod(td));
1348 tupdesc = CreateTupleDescCopy(tupdesc);
1353 * Scalar type, so make a single-column descriptor
1355 tupdesc = CreateTemplateTupleDesc(1, false);
1356 TupleDescInitEntry(tupdesc,
1363 tupstore = tuplestore_begin_heap(true, false, work_mem);
1364 MemoryContextSwitchTo(oldcontext);
1365 rsinfo.setResult = tupstore;
1366 rsinfo.setDesc = tupdesc;
1370 * Store current resultset item.
1376 td = DatumGetHeapTupleHeader(result);
1379 * tuplestore_puttuple needs a HeapTuple not a bare
1380 * HeapTupleHeader, but it doesn't need all the fields.
1382 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
1388 tuple = heap_form_tuple(tupdesc, &result, &fcinfo.isnull);
1391 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1392 tuplestore_puttuple(tupstore, tuple);
1393 MemoryContextSwitchTo(oldcontext);
1398 if (rsinfo.isDone != ExprMultipleResult)
1401 else if (rsinfo.returnMode == SFRM_Materialize)
1403 /* check we're on the same page as the function author */
1404 if (!first_time || rsinfo.isDone != ExprSingleResult)
1406 (errcode(ERRCODE_E_R_I_E_SRF_PROTOCOL_VIOLATED),
1407 errmsg("table-function protocol for materialize mode was not followed")));
1408 /* Done evaluating the set result */
1413 (errcode(ERRCODE_E_R_I_E_SRF_PROTOCOL_VIOLATED),
1414 errmsg("unrecognized table-function returnMode: %d",
1415 (int) rsinfo.returnMode)));
1423 * If we got nothing from the function (ie, an empty-set or NULL result),
1424 * we have to create the tuplestore to return, and if it's a
1425 * non-set-returning function then insert a single all-nulls row.
1427 if (rsinfo.setResult == NULL)
1429 MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1430 tupstore = tuplestore_begin_heap(true, false, work_mem);
1431 rsinfo.setResult = tupstore;
1434 int natts = expectedDesc->natts;
1439 MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
1440 nulldatums = (Datum *) palloc0(natts * sizeof(Datum));
1441 nullflags = (bool *) palloc(natts * sizeof(bool));
1442 memset(nullflags, true, natts * sizeof(bool));
1443 tuple = heap_form_tuple(expectedDesc, nulldatums, nullflags);
1444 MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1445 tuplestore_puttuple(tupstore, tuple);
1449 MemoryContextSwitchTo(callerContext);
1451 /* The returned pointers are those in rsinfo */
1452 *returnDesc = rsinfo.setDesc;
1453 return rsinfo.setResult;
1457 /* ----------------------------------------------------------------
1461 * Evaluate the functional result of a list of arguments by calling the
1463 * ----------------------------------------------------------------
1466 /* ----------------------------------------------------------------
1468 * ----------------------------------------------------------------
1471 ExecEvalFunc(FuncExprState *fcache,
1472 ExprContext *econtext,
1474 ExprDoneCond *isDone)
1476 /* This is called only the first time through */
1477 FuncExpr *func = (FuncExpr *) fcache->xprstate.expr;
1479 /* Initialize function lookup info */
1480 init_fcache(func->funcid, fcache, econtext->ecxt_per_query_memory);
1482 /* Go directly to ExecMakeFunctionResult on subsequent uses */
1483 fcache->xprstate.evalfunc = (ExprStateEvalFunc) ExecMakeFunctionResult;
1485 return ExecMakeFunctionResult(fcache, econtext, isNull, isDone);
1488 /* ----------------------------------------------------------------
1490 * ----------------------------------------------------------------
1493 ExecEvalOper(FuncExprState *fcache,
1494 ExprContext *econtext,
1496 ExprDoneCond *isDone)
1498 /* This is called only the first time through */
1499 OpExpr *op = (OpExpr *) fcache->xprstate.expr;
1501 /* Initialize function lookup info */
1502 init_fcache(op->opfuncid, fcache, econtext->ecxt_per_query_memory);
1504 /* Go directly to ExecMakeFunctionResult on subsequent uses */
1505 fcache->xprstate.evalfunc = (ExprStateEvalFunc) ExecMakeFunctionResult;
1507 return ExecMakeFunctionResult(fcache, econtext, isNull, isDone);
1510 /* ----------------------------------------------------------------
1513 * IS DISTINCT FROM must evaluate arguments to determine whether
1514 * they are NULL; if either is NULL then the result is already
1515 * known. If neither is NULL, then proceed to evaluate the
1516 * function. Note that this is *always* derived from the equals
1517 * operator, but since we need special processing of the arguments
1518 * we can not simply reuse ExecEvalOper() or ExecEvalFunc().
1519 * ----------------------------------------------------------------
1522 ExecEvalDistinct(FuncExprState *fcache,
1523 ExprContext *econtext,
1525 ExprDoneCond *isDone)
1528 FunctionCallInfoData fcinfo;
1529 ExprDoneCond argDone;
1532 /* Set default values for result flags: non-null, not a set result */
1535 *isDone = ExprSingleResult;
1538 * Initialize function cache if first time through
1540 if (fcache->func.fn_oid == InvalidOid)
1542 DistinctExpr *op = (DistinctExpr *) fcache->xprstate.expr;
1544 init_fcache(op->opfuncid, fcache, econtext->ecxt_per_query_memory);
1545 Assert(!fcache->func.fn_retset);
1549 * extract info from fcache
1551 argList = fcache->args;
1553 /* Need to prep callinfo structure */
1554 InitFunctionCallInfoData(fcinfo, &(fcache->func), 0, NULL, NULL);
1555 argDone = ExecEvalFuncArgs(&fcinfo, argList, econtext);
1556 if (argDone != ExprSingleResult)
1558 (errcode(ERRCODE_DATATYPE_MISMATCH),
1559 errmsg("IS DISTINCT FROM does not support set arguments")));
1560 Assert(fcinfo.nargs == 2);
1562 if (fcinfo.argnull[0] && fcinfo.argnull[1])
1564 /* Both NULL? Then is not distinct... */
1565 result = BoolGetDatum(FALSE);
1567 else if (fcinfo.argnull[0] || fcinfo.argnull[1])
1569 /* Only one is NULL? Then is distinct... */
1570 result = BoolGetDatum(TRUE);
1574 fcinfo.isnull = false;
1575 result = FunctionCallInvoke(&fcinfo);
1576 *isNull = fcinfo.isnull;
1577 /* Must invert result of "=" */
1578 result = BoolGetDatum(!DatumGetBool(result));
1585 * ExecEvalScalarArrayOp
1587 * Evaluate "scalar op ANY/ALL (array)". The operator always yields boolean,
1588 * and we combine the results across all array elements using OR and AND
1589 * (for ANY and ALL respectively). Of course we short-circuit as soon as
1590 * the result is known.
1593 ExecEvalScalarArrayOp(ScalarArrayOpExprState *sstate,
1594 ExprContext *econtext,
1595 bool *isNull, ExprDoneCond *isDone)
1597 ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) sstate->fxprstate.xprstate.expr;
1598 bool useOr = opexpr->useOr;
1603 FunctionCallInfoData fcinfo;
1604 ExprDoneCond argDone;
1613 /* Set default values for result flags: non-null, not a set result */
1616 *isDone = ExprSingleResult;
1619 * Initialize function cache if first time through
1621 if (sstate->fxprstate.func.fn_oid == InvalidOid)
1623 init_fcache(opexpr->opfuncid, &sstate->fxprstate,
1624 econtext->ecxt_per_query_memory);
1625 Assert(!sstate->fxprstate.func.fn_retset);
1628 /* Need to prep callinfo structure */
1629 InitFunctionCallInfoData(fcinfo, &(sstate->fxprstate.func), 0, NULL, NULL);
1630 argDone = ExecEvalFuncArgs(&fcinfo, sstate->fxprstate.args, econtext);
1631 if (argDone != ExprSingleResult)
1633 (errcode(ERRCODE_DATATYPE_MISMATCH),
1634 errmsg("op ANY/ALL (array) does not support set arguments")));
1635 Assert(fcinfo.nargs == 2);
1638 * If the array is NULL then we return NULL --- it's not very meaningful
1639 * to do anything else, even if the operator isn't strict.
1641 if (fcinfo.argnull[1])
1646 /* Else okay to fetch and detoast the array */
1647 arr = DatumGetArrayTypeP(fcinfo.arg[1]);
1650 * If the array is empty, we return either FALSE or TRUE per the useOr
1651 * flag. This is correct even if the scalar is NULL; since we would
1652 * evaluate the operator zero times, it matters not whether it would want
1655 nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr));
1657 return BoolGetDatum(!useOr);
1660 * If the scalar is NULL, and the function is strict, return NULL; no
1661 * point in iterating the loop.
1663 if (fcinfo.argnull[0] && sstate->fxprstate.func.fn_strict)
1670 * We arrange to look up info about the element type only once per series
1671 * of calls, assuming the element type doesn't change underneath us.
1673 if (sstate->element_type != ARR_ELEMTYPE(arr))
1675 get_typlenbyvalalign(ARR_ELEMTYPE(arr),
1679 sstate->element_type = ARR_ELEMTYPE(arr);
1681 typlen = sstate->typlen;
1682 typbyval = sstate->typbyval;
1683 typalign = sstate->typalign;
1685 result = BoolGetDatum(!useOr);
1688 /* Loop over the array elements */
1689 s = (char *) ARR_DATA_PTR(arr);
1690 bitmap = ARR_NULLBITMAP(arr);
1693 for (i = 0; i < nitems; i++)
1698 /* Get array element, checking for NULL */
1699 if (bitmap && (*bitmap & bitmask) == 0)
1701 fcinfo.arg[1] = (Datum) 0;
1702 fcinfo.argnull[1] = true;
1706 elt = fetch_att(s, typbyval, typlen);
1707 s = att_addlength(s, typlen, PointerGetDatum(s));
1708 s = (char *) att_align(s, typalign);
1709 fcinfo.arg[1] = elt;
1710 fcinfo.argnull[1] = false;
1713 /* Call comparison function */
1714 if (fcinfo.argnull[1] && sstate->fxprstate.func.fn_strict)
1716 fcinfo.isnull = true;
1717 thisresult = (Datum) 0;
1721 fcinfo.isnull = false;
1722 thisresult = FunctionCallInvoke(&fcinfo);
1725 /* Combine results per OR or AND semantics */
1730 if (DatumGetBool(thisresult))
1732 result = BoolGetDatum(true);
1734 break; /* needn't look at any more elements */
1739 if (!DatumGetBool(thisresult))
1741 result = BoolGetDatum(false);
1743 break; /* needn't look at any more elements */
1747 /* advance bitmap pointer if any */
1751 if (bitmask == 0x100)
1759 *isNull = resultnull;
1763 /* ----------------------------------------------------------------
1768 * Evaluate boolean expressions, with appropriate short-circuiting.
1770 * The query planner reformulates clause expressions in the
1771 * qualification to conjunctive normal form. If we ever get
1772 * an AND to evaluate, we can be sure that it's not a top-level
1773 * clause in the qualification, but appears lower (as a function
1774 * argument, for example), or in the target list. Not that you
1775 * need to know this, mind you...
1776 * ----------------------------------------------------------------
1779 ExecEvalNot(BoolExprState *notclause, ExprContext *econtext,
1780 bool *isNull, ExprDoneCond *isDone)
1782 ExprState *clause = linitial(notclause->args);
1786 *isDone = ExprSingleResult;
1788 expr_value = ExecEvalExpr(clause, econtext, isNull, NULL);
1791 * if the expression evaluates to null, then we just cascade the null back
1792 * to whoever called us.
1798 * evaluation of 'not' is simple.. expr is false, then return 'true' and
1801 return BoolGetDatum(!DatumGetBool(expr_value));
1804 /* ----------------------------------------------------------------
1806 * ----------------------------------------------------------------
1809 ExecEvalOr(BoolExprState *orExpr, ExprContext *econtext,
1810 bool *isNull, ExprDoneCond *isDone)
1812 List *clauses = orExpr->args;
1817 *isDone = ExprSingleResult;
1822 * If any of the clauses is TRUE, the OR result is TRUE regardless of the
1823 * states of the rest of the clauses, so we can stop evaluating and return
1824 * TRUE immediately. If none are TRUE and one or more is NULL, we return
1825 * NULL; otherwise we return FALSE. This makes sense when you interpret
1826 * NULL as "don't know": if we have a TRUE then the OR is TRUE even if we
1827 * aren't sure about some of the other inputs. If all the known inputs are
1828 * FALSE, but we have one or more "don't knows", then we have to report
1829 * that we "don't know" what the OR's result should be --- perhaps one of
1830 * the "don't knows" would have been TRUE if we'd known its value. Only
1831 * when all the inputs are known to be FALSE can we state confidently that
1832 * the OR's result is FALSE.
1834 foreach(clause, clauses)
1836 ExprState *clausestate = (ExprState *) lfirst(clause);
1839 clause_value = ExecEvalExpr(clausestate, econtext, isNull, NULL);
1842 * if we have a non-null true result, then return it.
1845 AnyNull = true; /* remember we got a null */
1846 else if (DatumGetBool(clause_value))
1847 return clause_value;
1850 /* AnyNull is true if at least one clause evaluated to NULL */
1852 return BoolGetDatum(false);
1855 /* ----------------------------------------------------------------
1857 * ----------------------------------------------------------------
1860 ExecEvalAnd(BoolExprState *andExpr, ExprContext *econtext,
1861 bool *isNull, ExprDoneCond *isDone)
1863 List *clauses = andExpr->args;
1868 *isDone = ExprSingleResult;
1873 * If any of the clauses is FALSE, the AND result is FALSE regardless of
1874 * the states of the rest of the clauses, so we can stop evaluating and
1875 * return FALSE immediately. If none are FALSE and one or more is NULL,
1876 * we return NULL; otherwise we return TRUE. This makes sense when you
1877 * interpret NULL as "don't know", using the same sort of reasoning as for
1881 foreach(clause, clauses)
1883 ExprState *clausestate = (ExprState *) lfirst(clause);
1886 clause_value = ExecEvalExpr(clausestate, econtext, isNull, NULL);
1889 * if we have a non-null false result, then return it.
1892 AnyNull = true; /* remember we got a null */
1893 else if (!DatumGetBool(clause_value))
1894 return clause_value;
1897 /* AnyNull is true if at least one clause evaluated to NULL */
1899 return BoolGetDatum(!AnyNull);
1902 /* ----------------------------------------------------------------
1903 * ExecEvalConvertRowtype
1905 * Evaluate a rowtype coercion operation. This may require
1906 * rearranging field positions.
1907 * ----------------------------------------------------------------
1910 ExecEvalConvertRowtype(ConvertRowtypeExprState *cstate,
1911 ExprContext *econtext,
1912 bool *isNull, ExprDoneCond *isDone)
1916 HeapTupleHeader tuple;
1917 HeapTupleData tmptup;
1918 AttrNumber *attrMap = cstate->attrMap;
1919 Datum *invalues = cstate->invalues;
1920 bool *inisnull = cstate->inisnull;
1921 Datum *outvalues = cstate->outvalues;
1922 bool *outisnull = cstate->outisnull;
1924 int outnatts = cstate->outdesc->natts;
1926 tupDatum = ExecEvalExpr(cstate->arg, econtext, isNull, isDone);
1928 /* this test covers the isDone exception too: */
1932 tuple = DatumGetHeapTupleHeader(tupDatum);
1934 Assert(HeapTupleHeaderGetTypeId(tuple) == cstate->indesc->tdtypeid);
1935 Assert(HeapTupleHeaderGetTypMod(tuple) == cstate->indesc->tdtypmod);
1938 * heap_deform_tuple needs a HeapTuple not a bare HeapTupleHeader.
1940 tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
1941 tmptup.t_data = tuple;
1944 * Extract all the values of the old tuple, offsetting the arrays so that
1945 * invalues[0] is NULL and invalues[1] is the first source attribute; this
1946 * exactly matches the numbering convention in attrMap.
1948 heap_deform_tuple(&tmptup, cstate->indesc, invalues + 1, inisnull + 1);
1949 invalues[0] = (Datum) 0;
1953 * Transpose into proper fields of the new tuple.
1955 for (i = 0; i < outnatts; i++)
1959 outvalues[i] = invalues[j];
1960 outisnull[i] = inisnull[j];
1964 * Now form the new tuple.
1966 result = heap_form_tuple(cstate->outdesc, outvalues, outisnull);
1968 return HeapTupleGetDatum(result);
1971 /* ----------------------------------------------------------------
1974 * Evaluate a CASE clause. Will have boolean expressions
1975 * inside the WHEN clauses, and will have expressions
1977 * - thomas 1998-11-09
1978 * ----------------------------------------------------------------
1981 ExecEvalCase(CaseExprState *caseExpr, ExprContext *econtext,
1982 bool *isNull, ExprDoneCond *isDone)
1984 List *clauses = caseExpr->args;
1990 *isDone = ExprSingleResult;
1993 * If there's a test expression, we have to evaluate it and save the value
1994 * where the CaseTestExpr placeholders can find it. We must save and
1995 * restore prior setting of econtext's caseValue fields, in case this node
1996 * is itself within a larger CASE.
1998 save_datum = econtext->caseValue_datum;
1999 save_isNull = econtext->caseValue_isNull;
2003 econtext->caseValue_datum = ExecEvalExpr(caseExpr->arg,
2005 &econtext->caseValue_isNull,
2010 * we evaluate each of the WHEN clauses in turn, as soon as one is true we
2011 * return the corresponding result. If none are true then we return the
2012 * value of the default clause, or NULL if there is none.
2014 foreach(clause, clauses)
2016 CaseWhenState *wclause = lfirst(clause);
2019 clause_value = ExecEvalExpr(wclause->expr,
2025 * if we have a true test, then we return the result, since the case
2026 * statement is satisfied. A NULL result from the test is not
2029 if (DatumGetBool(clause_value) && !*isNull)
2031 econtext->caseValue_datum = save_datum;
2032 econtext->caseValue_isNull = save_isNull;
2033 return ExecEvalExpr(wclause->result,
2040 econtext->caseValue_datum = save_datum;
2041 econtext->caseValue_isNull = save_isNull;
2043 if (caseExpr->defresult)
2045 return ExecEvalExpr(caseExpr->defresult,
2056 * ExecEvalCaseTestExpr
2058 * Return the value stored by CASE.
2061 ExecEvalCaseTestExpr(ExprState *exprstate,
2062 ExprContext *econtext,
2063 bool *isNull, ExprDoneCond *isDone)
2066 *isDone = ExprSingleResult;
2067 *isNull = econtext->caseValue_isNull;
2068 return econtext->caseValue_datum;
2071 /* ----------------------------------------------------------------
2072 * ExecEvalArray - ARRAY[] expressions
2073 * ----------------------------------------------------------------
2076 ExecEvalArray(ArrayExprState *astate, ExprContext *econtext,
2077 bool *isNull, ExprDoneCond *isDone)
2079 ArrayExpr *arrayExpr = (ArrayExpr *) astate->xprstate.expr;
2082 Oid element_type = arrayExpr->element_typeid;
2087 /* Set default values for result flags: non-null, not a set result */
2090 *isDone = ExprSingleResult;
2092 if (!arrayExpr->multidims)
2094 /* Elements are presumably of scalar type */
2101 nelems = list_length(astate->elements);
2103 /* Shouldn't happen here, but if length is 0, return empty array */
2105 return PointerGetDatum(construct_empty_array(element_type));
2107 dvalues = (Datum *) palloc(nelems * sizeof(Datum));
2108 dnulls = (bool *) palloc(nelems * sizeof(bool));
2110 /* loop through and build array of datums */
2111 foreach(element, astate->elements)
2113 ExprState *e = (ExprState *) lfirst(element);
2115 dvalues[i] = ExecEvalExpr(e, econtext, &dnulls[i], NULL);
2119 /* setup for 1-D array of the given length */
2123 result = construct_md_array(dvalues, dnulls, ndims, dims, lbs,
2131 /* Must be nested array expressions */
2134 int outer_nelems = 0;
2136 int *elem_dims = NULL;
2137 int *elem_lbs = NULL;
2138 bool firstone = true;
2139 bool havenulls = false;
2149 i = list_length(astate->elements);
2150 subdata = (char **) palloc(i * sizeof(char *));
2151 subbitmaps = (bits8 **) palloc(i * sizeof(bits8 *));
2152 subbytes = (int *) palloc(i * sizeof(int));
2153 subnitems = (int *) palloc(i * sizeof(int));
2155 /* loop through and get data area from each element */
2156 foreach(element, astate->elements)
2158 ExprState *e = (ExprState *) lfirst(element);
2163 arraydatum = ExecEvalExpr(e, econtext, &eisnull, NULL);
2164 /* ignore null subarrays */
2168 array = DatumGetArrayTypeP(arraydatum);
2170 /* run-time double-check on element type */
2171 if (element_type != ARR_ELEMTYPE(array))
2173 (errcode(ERRCODE_DATATYPE_MISMATCH),
2174 errmsg("cannot merge incompatible arrays"),
2175 errdetail("Array with element type %s cannot be "
2176 "included in ARRAY construct with element type %s.",
2177 format_type_be(ARR_ELEMTYPE(array)),
2178 format_type_be(element_type))));
2182 /* Get sub-array details from first member */
2183 elem_ndims = ARR_NDIM(array);
2184 ndims = elem_ndims + 1;
2185 if (ndims <= 0 || ndims > MAXDIM)
2187 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
2188 errmsg("number of array dimensions (%d) exceeds " \
2189 "the maximum allowed (%d)", ndims, MAXDIM)));
2191 elem_dims = (int *) palloc(elem_ndims * sizeof(int));
2192 memcpy(elem_dims, ARR_DIMS(array), elem_ndims * sizeof(int));
2193 elem_lbs = (int *) palloc(elem_ndims * sizeof(int));
2194 memcpy(elem_lbs, ARR_LBOUND(array), elem_ndims * sizeof(int));
2200 /* Check other sub-arrays are compatible */
2201 if (elem_ndims != ARR_NDIM(array) ||
2202 memcmp(elem_dims, ARR_DIMS(array),
2203 elem_ndims * sizeof(int)) != 0 ||
2204 memcmp(elem_lbs, ARR_LBOUND(array),
2205 elem_ndims * sizeof(int)) != 0)
2207 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2208 errmsg("multidimensional arrays must have array "
2209 "expressions with matching dimensions")));
2212 subdata[outer_nelems] = ARR_DATA_PTR(array);
2213 subbitmaps[outer_nelems] = ARR_NULLBITMAP(array);
2214 subbytes[outer_nelems] = ARR_SIZE(array) - ARR_DATA_OFFSET(array);
2215 nbytes += subbytes[outer_nelems];
2216 subnitems[outer_nelems] = ArrayGetNItems(ARR_NDIM(array),
2218 nitems += subnitems[outer_nelems];
2219 havenulls |= ARR_HASNULL(array);
2223 /* setup for multi-D array */
2224 dims[0] = outer_nelems;
2226 for (i = 1; i < ndims; i++)
2228 dims[i] = elem_dims[i - 1];
2229 lbs[i] = elem_lbs[i - 1];
2234 dataoffset = ARR_OVERHEAD_WITHNULLS(ndims, nitems);
2235 nbytes += dataoffset;
2239 dataoffset = 0; /* marker for no null bitmap */
2240 nbytes += ARR_OVERHEAD_NONULLS(ndims);
2243 result = (ArrayType *) palloc(nbytes);
2244 result->size = nbytes;
2245 result->ndim = ndims;
2246 result->dataoffset = dataoffset;
2247 result->elemtype = element_type;
2248 memcpy(ARR_DIMS(result), dims, ndims * sizeof(int));
2249 memcpy(ARR_LBOUND(result), lbs, ndims * sizeof(int));
2251 dat = ARR_DATA_PTR(result);
2253 for (i = 0; i < outer_nelems; i++)
2255 memcpy(dat, subdata[i], subbytes[i]);
2258 array_bitmap_copy(ARR_NULLBITMAP(result), iitem,
2261 iitem += subnitems[i];
2265 return PointerGetDatum(result);
2268 /* ----------------------------------------------------------------
2269 * ExecEvalRow - ROW() expressions
2270 * ----------------------------------------------------------------
2273 ExecEvalRow(RowExprState *rstate,
2274 ExprContext *econtext,
2275 bool *isNull, ExprDoneCond *isDone)
2284 /* Set default values for result flags: non-null, not a set result */
2287 *isDone = ExprSingleResult;
2289 /* Allocate workspace */
2290 natts = rstate->tupdesc->natts;
2291 values = (Datum *) palloc0(natts * sizeof(Datum));
2292 isnull = (bool *) palloc(natts * sizeof(bool));
2294 /* preset to nulls in case rowtype has some later-added columns */
2295 memset(isnull, true, natts * sizeof(bool));
2297 /* Evaluate field values */
2299 foreach(arg, rstate->args)
2301 ExprState *e = (ExprState *) lfirst(arg);
2303 values[i] = ExecEvalExpr(e, econtext, &isnull[i], NULL);
2307 tuple = heap_form_tuple(rstate->tupdesc, values, isnull);
2312 return HeapTupleGetDatum(tuple);
2315 /* ----------------------------------------------------------------
2316 * ExecEvalRowCompare - ROW() comparison-op ROW()
2317 * ----------------------------------------------------------------
2320 ExecEvalRowCompare(RowCompareExprState *rstate,
2321 ExprContext *econtext,
2322 bool *isNull, ExprDoneCond *isDone)
2325 RowCompareType rctype = ((RowCompareExpr *) rstate->xprstate.expr)->rctype;
2326 int32 cmpresult = 0;
2332 *isDone = ExprSingleResult;
2333 *isNull = true; /* until we get a result */
2336 forboth(l, rstate->largs, r, rstate->rargs)
2338 ExprState *le = (ExprState *) lfirst(l);
2339 ExprState *re = (ExprState *) lfirst(r);
2340 FunctionCallInfoData locfcinfo;
2342 InitFunctionCallInfoData(locfcinfo, &(rstate->funcs[i]), 2,
2344 locfcinfo.arg[0] = ExecEvalExpr(le, econtext,
2345 &locfcinfo.argnull[0], NULL);
2346 locfcinfo.arg[1] = ExecEvalExpr(re, econtext,
2347 &locfcinfo.argnull[1], NULL);
2348 if (rstate->funcs[i].fn_strict &&
2349 (locfcinfo.argnull[0] || locfcinfo.argnull[1]))
2350 return (Datum) 0; /* force NULL result */
2351 locfcinfo.isnull = false;
2352 cmpresult = DatumGetInt32(FunctionCallInvoke(&locfcinfo));
2353 if (locfcinfo.isnull)
2354 return (Datum) 0; /* force NULL result */
2356 break; /* no need to compare remaining columns */
2362 /* EQ and NE cases aren't allowed here */
2364 result = (cmpresult < 0);
2367 result = (cmpresult <= 0);
2370 result = (cmpresult >= 0);
2373 result = (cmpresult > 0);
2376 elog(ERROR, "unrecognized RowCompareType: %d", (int) rctype);
2377 result = 0; /* keep compiler quiet */
2382 return BoolGetDatum(result);
2385 /* ----------------------------------------------------------------
2387 * ----------------------------------------------------------------
2390 ExecEvalCoalesce(CoalesceExprState *coalesceExpr, ExprContext *econtext,
2391 bool *isNull, ExprDoneCond *isDone)
2396 *isDone = ExprSingleResult;
2398 /* Simply loop through until something NOT NULL is found */
2399 foreach(arg, coalesceExpr->args)
2401 ExprState *e = (ExprState *) lfirst(arg);
2404 value = ExecEvalExpr(e, econtext, isNull, NULL);
2409 /* Else return NULL */
2414 /* ----------------------------------------------------------------
2416 * ----------------------------------------------------------------
2419 ExecEvalMinMax(MinMaxExprState *minmaxExpr, ExprContext *econtext,
2420 bool *isNull, ExprDoneCond *isDone)
2422 Datum result = (Datum) 0;
2423 MinMaxOp op = ((MinMaxExpr *) minmaxExpr->xprstate.expr)->op;
2424 FunctionCallInfoData locfcinfo;
2428 *isDone = ExprSingleResult;
2429 *isNull = true; /* until we get a result */
2431 InitFunctionCallInfoData(locfcinfo, &minmaxExpr->cfunc, 2, NULL, NULL);
2432 locfcinfo.argnull[0] = false;
2433 locfcinfo.argnull[1] = false;
2435 foreach(arg, minmaxExpr->args)
2437 ExprState *e = (ExprState *) lfirst(arg);
2442 value = ExecEvalExpr(e, econtext, &valueIsNull, NULL);
2444 continue; /* ignore NULL inputs */
2448 /* first nonnull input, adopt value */
2454 /* apply comparison function */
2455 locfcinfo.arg[0] = result;
2456 locfcinfo.arg[1] = value;
2457 locfcinfo.isnull = false;
2458 cmpresult = DatumGetInt32(FunctionCallInvoke(&locfcinfo));
2459 if (locfcinfo.isnull) /* probably should not happen */
2461 if (cmpresult > 0 && op == IS_LEAST)
2463 else if (cmpresult < 0 && op == IS_GREATEST)
2471 /* ----------------------------------------------------------------
2474 * Note that this is *always* derived from the equals operator,
2475 * but since we need special processing of the arguments
2476 * we can not simply reuse ExecEvalOper() or ExecEvalFunc().
2477 * ----------------------------------------------------------------
2480 ExecEvalNullIf(FuncExprState *nullIfExpr,
2481 ExprContext *econtext,
2482 bool *isNull, ExprDoneCond *isDone)
2485 FunctionCallInfoData fcinfo;
2486 ExprDoneCond argDone;
2490 *isDone = ExprSingleResult;
2493 * Initialize function cache if first time through
2495 if (nullIfExpr->func.fn_oid == InvalidOid)
2497 NullIfExpr *op = (NullIfExpr *) nullIfExpr->xprstate.expr;
2499 init_fcache(op->opfuncid, nullIfExpr, econtext->ecxt_per_query_memory);
2500 Assert(!nullIfExpr->func.fn_retset);
2504 * extract info from nullIfExpr
2506 argList = nullIfExpr->args;
2508 /* Need to prep callinfo structure */
2509 InitFunctionCallInfoData(fcinfo, &(nullIfExpr->func), 0, NULL, NULL);
2510 argDone = ExecEvalFuncArgs(&fcinfo, argList, econtext);
2511 if (argDone != ExprSingleResult)
2513 (errcode(ERRCODE_DATATYPE_MISMATCH),
2514 errmsg("NULLIF does not support set arguments")));
2515 Assert(fcinfo.nargs == 2);
2517 /* if either argument is NULL they can't be equal */
2518 if (!fcinfo.argnull[0] && !fcinfo.argnull[1])
2520 fcinfo.isnull = false;
2521 result = FunctionCallInvoke(&fcinfo);
2522 /* if the arguments are equal return null */
2523 if (!fcinfo.isnull && DatumGetBool(result))
2530 /* else return first argument */
2531 *isNull = fcinfo.argnull[0];
2532 return fcinfo.arg[0];
2535 /* ----------------------------------------------------------------
2538 * Evaluate a NullTest node.
2539 * ----------------------------------------------------------------
2542 ExecEvalNullTest(GenericExprState *nstate,
2543 ExprContext *econtext,
2545 ExprDoneCond *isDone)
2547 NullTest *ntest = (NullTest *) nstate->xprstate.expr;
2550 result = ExecEvalExpr(nstate->arg, econtext, isNull, isDone);
2552 if (isDone && *isDone == ExprEndResult)
2553 return result; /* nothing to check */
2555 switch (ntest->nulltesttype)
2561 return BoolGetDatum(true);
2564 return BoolGetDatum(false);
2569 return BoolGetDatum(false);
2572 return BoolGetDatum(true);
2574 elog(ERROR, "unrecognized nulltesttype: %d",
2575 (int) ntest->nulltesttype);
2576 return (Datum) 0; /* keep compiler quiet */
2580 /* ----------------------------------------------------------------
2581 * ExecEvalBooleanTest
2583 * Evaluate a BooleanTest node.
2584 * ----------------------------------------------------------------
2587 ExecEvalBooleanTest(GenericExprState *bstate,
2588 ExprContext *econtext,
2590 ExprDoneCond *isDone)
2592 BooleanTest *btest = (BooleanTest *) bstate->xprstate.expr;
2595 result = ExecEvalExpr(bstate->arg, econtext, isNull, isDone);
2597 if (isDone && *isDone == ExprEndResult)
2598 return result; /* nothing to check */
2600 switch (btest->booltesttype)
2606 return BoolGetDatum(false);
2608 else if (DatumGetBool(result))
2609 return BoolGetDatum(true);
2611 return BoolGetDatum(false);
2616 return BoolGetDatum(true);
2618 else if (DatumGetBool(result))
2619 return BoolGetDatum(false);
2621 return BoolGetDatum(true);
2626 return BoolGetDatum(false);
2628 else if (DatumGetBool(result))
2629 return BoolGetDatum(false);
2631 return BoolGetDatum(true);
2636 return BoolGetDatum(true);
2638 else if (DatumGetBool(result))
2639 return BoolGetDatum(true);
2641 return BoolGetDatum(false);
2646 return BoolGetDatum(true);
2649 return BoolGetDatum(false);
2650 case IS_NOT_UNKNOWN:
2654 return BoolGetDatum(false);
2657 return BoolGetDatum(true);
2659 elog(ERROR, "unrecognized booltesttype: %d",
2660 (int) btest->booltesttype);
2661 return (Datum) 0; /* keep compiler quiet */
2666 * ExecEvalCoerceToDomain
2668 * Test the provided data against the domain constraint(s). If the data
2669 * passes the constraint specifications, pass it through (return the
2670 * datum) otherwise throw an error.
2673 ExecEvalCoerceToDomain(CoerceToDomainState *cstate, ExprContext *econtext,
2674 bool *isNull, ExprDoneCond *isDone)
2676 CoerceToDomain *ctest = (CoerceToDomain *) cstate->xprstate.expr;
2680 result = ExecEvalExpr(cstate->arg, econtext, isNull, isDone);
2682 if (isDone && *isDone == ExprEndResult)
2683 return result; /* nothing to check */
2685 foreach(l, cstate->constraints)
2687 DomainConstraintState *con = (DomainConstraintState *) lfirst(l);
2689 switch (con->constrainttype)
2691 case DOM_CONSTRAINT_NOTNULL:
2694 (errcode(ERRCODE_NOT_NULL_VIOLATION),
2695 errmsg("domain %s does not allow null values",
2696 format_type_be(ctest->resulttype))));
2698 case DOM_CONSTRAINT_CHECK:
2706 * Set up value to be returned by CoerceToDomainValue
2707 * nodes. We must save and restore prior setting of
2708 * econtext's domainValue fields, in case this node is
2709 * itself within a check expression for another domain.
2711 save_datum = econtext->domainValue_datum;
2712 save_isNull = econtext->domainValue_isNull;
2714 econtext->domainValue_datum = result;
2715 econtext->domainValue_isNull = *isNull;
2717 conResult = ExecEvalExpr(con->check_expr,
2718 econtext, &conIsNull, NULL);
2721 !DatumGetBool(conResult))
2723 (errcode(ERRCODE_CHECK_VIOLATION),
2724 errmsg("value for domain %s violates check constraint \"%s\"",
2725 format_type_be(ctest->resulttype),
2727 econtext->domainValue_datum = save_datum;
2728 econtext->domainValue_isNull = save_isNull;
2733 elog(ERROR, "unrecognized constraint type: %d",
2734 (int) con->constrainttype);
2739 /* If all has gone well (constraints did not fail) return the datum */
2744 * ExecEvalCoerceToDomainValue
2746 * Return the value stored by CoerceToDomain.
2749 ExecEvalCoerceToDomainValue(ExprState *exprstate,
2750 ExprContext *econtext,
2751 bool *isNull, ExprDoneCond *isDone)
2754 *isDone = ExprSingleResult;
2755 *isNull = econtext->domainValue_isNull;
2756 return econtext->domainValue_datum;
2759 /* ----------------------------------------------------------------
2760 * ExecEvalFieldSelect
2762 * Evaluate a FieldSelect node.
2763 * ----------------------------------------------------------------
2766 ExecEvalFieldSelect(FieldSelectState *fstate,
2767 ExprContext *econtext,
2769 ExprDoneCond *isDone)
2771 FieldSelect *fselect = (FieldSelect *) fstate->xprstate.expr;
2774 HeapTupleHeader tuple;
2778 HeapTupleData tmptup;
2780 tupDatum = ExecEvalExpr(fstate->arg, econtext, isNull, isDone);
2782 /* this test covers the isDone exception too: */
2786 tuple = DatumGetHeapTupleHeader(tupDatum);
2788 tupType = HeapTupleHeaderGetTypeId(tuple);
2789 tupTypmod = HeapTupleHeaderGetTypMod(tuple);
2791 /* Lookup tupdesc if first time through or if type changes */
2792 tupDesc = fstate->argdesc;
2793 if (tupDesc == NULL ||
2794 tupType != tupDesc->tdtypeid ||
2795 tupTypmod != tupDesc->tdtypmod)
2797 MemoryContext oldcontext;
2799 tupDesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
2800 /* Copy the tupdesc into query storage for safety */
2801 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
2802 tupDesc = CreateTupleDescCopy(tupDesc);
2803 if (fstate->argdesc)
2804 FreeTupleDesc(fstate->argdesc);
2805 fstate->argdesc = tupDesc;
2806 MemoryContextSwitchTo(oldcontext);
2810 * heap_getattr needs a HeapTuple not a bare HeapTupleHeader. We set all
2811 * the fields in the struct just in case user tries to inspect system
2814 tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
2815 ItemPointerSetInvalid(&(tmptup.t_self));
2816 tmptup.t_tableOid = InvalidOid;
2817 tmptup.t_data = tuple;
2819 result = heap_getattr(&tmptup,
2826 /* ----------------------------------------------------------------
2827 * ExecEvalFieldStore
2829 * Evaluate a FieldStore node.
2830 * ----------------------------------------------------------------
2833 ExecEvalFieldStore(FieldStoreState *fstate,
2834 ExprContext *econtext,
2836 ExprDoneCond *isDone)
2838 FieldStore *fstore = (FieldStore *) fstate->xprstate.expr;
2849 tupDatum = ExecEvalExpr(fstate->arg, econtext, isNull, isDone);
2851 if (isDone && *isDone == ExprEndResult)
2854 /* Lookup tupdesc if first time through or if type changes */
2855 tupDesc = fstate->argdesc;
2856 if (tupDesc == NULL ||
2857 fstore->resulttype != tupDesc->tdtypeid)
2859 MemoryContext oldcontext;
2861 tupDesc = lookup_rowtype_tupdesc(fstore->resulttype, -1);
2862 /* Copy the tupdesc into query storage for safety */
2863 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
2864 tupDesc = CreateTupleDescCopy(tupDesc);
2865 if (fstate->argdesc)
2866 FreeTupleDesc(fstate->argdesc);
2867 fstate->argdesc = tupDesc;
2868 MemoryContextSwitchTo(oldcontext);
2871 /* Allocate workspace */
2872 values = (Datum *) palloc(tupDesc->natts * sizeof(Datum));
2873 isnull = (bool *) palloc(tupDesc->natts * sizeof(bool));
2878 * heap_deform_tuple needs a HeapTuple not a bare HeapTupleHeader. We
2879 * set all the fields in the struct just in case.
2881 HeapTupleHeader tuphdr;
2882 HeapTupleData tmptup;
2884 tuphdr = DatumGetHeapTupleHeader(tupDatum);
2885 tmptup.t_len = HeapTupleHeaderGetDatumLength(tuphdr);
2886 ItemPointerSetInvalid(&(tmptup.t_self));
2887 tmptup.t_tableOid = InvalidOid;
2888 tmptup.t_data = tuphdr;
2890 heap_deform_tuple(&tmptup, tupDesc, values, isnull);
2894 /* Convert null input tuple into an all-nulls row */
2895 memset(isnull, true, tupDesc->natts * sizeof(bool));
2898 /* Result is never null */
2901 save_datum = econtext->caseValue_datum;
2902 save_isNull = econtext->caseValue_isNull;
2904 forboth(l1, fstate->newvals, l2, fstore->fieldnums)
2906 ExprState *newval = (ExprState *) lfirst(l1);
2907 AttrNumber fieldnum = lfirst_int(l2);
2909 Assert(fieldnum > 0 && fieldnum <= tupDesc->natts);
2912 * Use the CaseTestExpr mechanism to pass down the old value of the
2913 * field being replaced; this is useful in case we have a nested field
2914 * update situation. It's safe to reuse the CASE mechanism because
2915 * there cannot be a CASE between here and where the value would be
2918 econtext->caseValue_datum = values[fieldnum - 1];
2919 econtext->caseValue_isNull = isnull[fieldnum - 1];
2921 values[fieldnum - 1] = ExecEvalExpr(newval,
2923 &isnull[fieldnum - 1],
2927 econtext->caseValue_datum = save_datum;
2928 econtext->caseValue_isNull = save_isNull;
2930 tuple = heap_form_tuple(tupDesc, values, isnull);
2935 return HeapTupleGetDatum(tuple);
2938 /* ----------------------------------------------------------------
2939 * ExecEvalRelabelType
2941 * Evaluate a RelabelType node.
2942 * ----------------------------------------------------------------
2945 ExecEvalRelabelType(GenericExprState *exprstate,
2946 ExprContext *econtext,
2947 bool *isNull, ExprDoneCond *isDone)
2949 return ExecEvalExpr(exprstate->arg, econtext, isNull, isDone);
2954 * ExecEvalExprSwitchContext
2956 * Same as ExecEvalExpr, but get into the right allocation context explicitly.
2959 ExecEvalExprSwitchContext(ExprState *expression,
2960 ExprContext *econtext,
2962 ExprDoneCond *isDone)
2965 MemoryContext oldContext;
2967 oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
2968 retDatum = ExecEvalExpr(expression, econtext, isNull, isDone);
2969 MemoryContextSwitchTo(oldContext);
2975 * ExecInitExpr: prepare an expression tree for execution
2977 * This function builds and returns an ExprState tree paralleling the given
2978 * Expr node tree. The ExprState tree can then be handed to ExecEvalExpr
2979 * for execution. Because the Expr tree itself is read-only as far as
2980 * ExecInitExpr and ExecEvalExpr are concerned, several different executions
2981 * of the same plan tree can occur concurrently.
2983 * This must be called in a memory context that will last as long as repeated
2984 * executions of the expression are needed. Typically the context will be
2985 * the same as the per-query context of the associated ExprContext.
2987 * Any Aggref and SubPlan nodes found in the tree are added to the lists
2988 * of such nodes held by the parent PlanState. Otherwise, we do very little
2989 * initialization here other than building the state-node tree. Any nontrivial
2990 * work associated with initializing runtime info for a node should happen
2991 * during the first actual evaluation of that node. (This policy lets us
2992 * avoid work if the node is never actually evaluated.)
2994 * Note: there is no ExecEndExpr function; we assume that any resource
2995 * cleanup needed will be handled by just releasing the memory context
2996 * in which the state tree is built. Functions that require additional
2997 * cleanup work can register a shutdown callback in the ExprContext.
2999 * 'node' is the root of the expression tree to examine
3000 * 'parent' is the PlanState node that owns the expression.
3002 * 'parent' may be NULL if we are preparing an expression that is not
3003 * associated with a plan tree. (If so, it can't have aggs or subplans.)
3004 * This case should usually come through ExecPrepareExpr, not directly here.
3007 ExecInitExpr(Expr *node, PlanState *parent)
3014 /* Guard against stack overflow due to overly complex expressions */
3015 check_stack_depth();
3017 switch (nodeTag(node))
3021 Var *var = (Var *) node;
3023 state = (ExprState *) makeNode(ExprState);
3024 if (var->varattno != InvalidAttrNumber)
3025 state->evalfunc = ExecEvalVar;
3027 state->evalfunc = ExecEvalWholeRowVar;
3031 state = (ExprState *) makeNode(ExprState);
3032 state->evalfunc = ExecEvalConst;
3035 state = (ExprState *) makeNode(ExprState);
3036 state->evalfunc = ExecEvalParam;
3038 case T_CoerceToDomainValue:
3039 state = (ExprState *) makeNode(ExprState);
3040 state->evalfunc = ExecEvalCoerceToDomainValue;
3042 case T_CaseTestExpr:
3043 state = (ExprState *) makeNode(ExprState);
3044 state->evalfunc = ExecEvalCaseTestExpr;
3048 Aggref *aggref = (Aggref *) node;
3049 AggrefExprState *astate = makeNode(AggrefExprState);
3051 astate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalAggref;
3052 if (parent && IsA(parent, AggState))
3054 AggState *aggstate = (AggState *) parent;
3057 aggstate->aggs = lcons(astate, aggstate->aggs);
3058 naggs = ++aggstate->numaggs;
3060 astate->target = ExecInitExpr(aggref->target, parent);
3063 * Complain if the aggregate's argument contains any
3064 * aggregates; nested agg functions are semantically
3065 * nonsensical. (This should have been caught earlier,
3066 * but we defend against it here anyway.)
3068 if (naggs != aggstate->numaggs)
3070 (errcode(ERRCODE_GROUPING_ERROR),
3071 errmsg("aggregate function calls may not be nested")));
3075 /* planner messed up */
3076 elog(ERROR, "aggref found in non-Agg plan node");
3078 state = (ExprState *) astate;
3083 ArrayRef *aref = (ArrayRef *) node;
3084 ArrayRefExprState *astate = makeNode(ArrayRefExprState);
3086 astate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalArrayRef;
3087 astate->refupperindexpr = (List *)
3088 ExecInitExpr((Expr *) aref->refupperindexpr, parent);
3089 astate->reflowerindexpr = (List *)
3090 ExecInitExpr((Expr *) aref->reflowerindexpr, parent);
3091 astate->refexpr = ExecInitExpr(aref->refexpr, parent);
3092 astate->refassgnexpr = ExecInitExpr(aref->refassgnexpr,
3094 /* do one-time catalog lookups for type info */
3095 astate->refattrlength = get_typlen(aref->refarraytype);
3096 get_typlenbyvalalign(aref->refelemtype,
3097 &astate->refelemlength,
3098 &astate->refelembyval,
3099 &astate->refelemalign);
3100 state = (ExprState *) astate;
3105 FuncExpr *funcexpr = (FuncExpr *) node;
3106 FuncExprState *fstate = makeNode(FuncExprState);
3108 fstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalFunc;
3109 fstate->args = (List *)
3110 ExecInitExpr((Expr *) funcexpr->args, parent);
3111 fstate->func.fn_oid = InvalidOid; /* not initialized */
3112 state = (ExprState *) fstate;
3117 OpExpr *opexpr = (OpExpr *) node;
3118 FuncExprState *fstate = makeNode(FuncExprState);
3120 fstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalOper;
3121 fstate->args = (List *)
3122 ExecInitExpr((Expr *) opexpr->args, parent);
3123 fstate->func.fn_oid = InvalidOid; /* not initialized */
3124 state = (ExprState *) fstate;
3127 case T_DistinctExpr:
3129 DistinctExpr *distinctexpr = (DistinctExpr *) node;
3130 FuncExprState *fstate = makeNode(FuncExprState);
3132 fstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalDistinct;
3133 fstate->args = (List *)
3134 ExecInitExpr((Expr *) distinctexpr->args, parent);
3135 fstate->func.fn_oid = InvalidOid; /* not initialized */
3136 state = (ExprState *) fstate;
3139 case T_ScalarArrayOpExpr:
3141 ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) node;
3142 ScalarArrayOpExprState *sstate = makeNode(ScalarArrayOpExprState);
3144 sstate->fxprstate.xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalScalarArrayOp;
3145 sstate->fxprstate.args = (List *)
3146 ExecInitExpr((Expr *) opexpr->args, parent);
3147 sstate->fxprstate.func.fn_oid = InvalidOid; /* not initialized */
3148 sstate->element_type = InvalidOid; /* ditto */
3149 state = (ExprState *) sstate;
3154 BoolExpr *boolexpr = (BoolExpr *) node;
3155 BoolExprState *bstate = makeNode(BoolExprState);
3157 switch (boolexpr->boolop)
3160 bstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalAnd;
3163 bstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalOr;
3166 bstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalNot;
3169 elog(ERROR, "unrecognized boolop: %d",
3170 (int) boolexpr->boolop);
3173 bstate->args = (List *)
3174 ExecInitExpr((Expr *) boolexpr->args, parent);
3175 state = (ExprState *) bstate;
3180 /* Keep this in sync with ExecInitExprInitPlan, below */
3181 SubPlan *subplan = (SubPlan *) node;
3182 SubPlanState *sstate = makeNode(SubPlanState);
3184 sstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecSubPlan;
3187 elog(ERROR, "SubPlan found with no parent plan");
3190 * Here we just add the SubPlanState nodes to parent->subPlan.
3191 * The subplans will be initialized later.
3193 parent->subPlan = lcons(sstate, parent->subPlan);
3194 sstate->sub_estate = NULL;
3195 sstate->planstate = NULL;
3198 ExecInitExpr((Expr *) subplan->testexpr, parent);
3199 sstate->args = (List *)
3200 ExecInitExpr((Expr *) subplan->args, parent);
3202 state = (ExprState *) sstate;
3207 FieldSelect *fselect = (FieldSelect *) node;
3208 FieldSelectState *fstate = makeNode(FieldSelectState);
3210 fstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalFieldSelect;
3211 fstate->arg = ExecInitExpr(fselect->arg, parent);
3212 fstate->argdesc = NULL;
3213 state = (ExprState *) fstate;
3218 FieldStore *fstore = (FieldStore *) node;
3219 FieldStoreState *fstate = makeNode(FieldStoreState);
3221 fstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalFieldStore;
3222 fstate->arg = ExecInitExpr(fstore->arg, parent);
3223 fstate->newvals = (List *) ExecInitExpr((Expr *) fstore->newvals, parent);
3224 fstate->argdesc = NULL;
3225 state = (ExprState *) fstate;
3230 RelabelType *relabel = (RelabelType *) node;
3231 GenericExprState *gstate = makeNode(GenericExprState);
3233 gstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalRelabelType;
3234 gstate->arg = ExecInitExpr(relabel->arg, parent);
3235 state = (ExprState *) gstate;
3238 case T_ConvertRowtypeExpr:
3240 ConvertRowtypeExpr *convert = (ConvertRowtypeExpr *) node;
3241 ConvertRowtypeExprState *cstate = makeNode(ConvertRowtypeExprState);
3245 cstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalConvertRowtype;
3246 cstate->arg = ExecInitExpr(convert->arg, parent);
3247 /* save copies of needed tuple descriptors */
3248 cstate->indesc = lookup_rowtype_tupdesc(exprType((Node *) convert->arg), -1);
3249 cstate->indesc = CreateTupleDescCopy(cstate->indesc);
3250 cstate->outdesc = lookup_rowtype_tupdesc(convert->resulttype, -1);
3251 cstate->outdesc = CreateTupleDescCopy(cstate->outdesc);
3252 /* prepare map from old to new attribute numbers */
3253 n = cstate->outdesc->natts;
3254 cstate->attrMap = (AttrNumber *) palloc0(n * sizeof(AttrNumber));
3255 for (i = 0; i < n; i++)
3257 Form_pg_attribute att = cstate->outdesc->attrs[i];
3263 if (att->attisdropped)
3264 continue; /* attrMap[i] is already 0 */
3265 attname = NameStr(att->attname);
3266 atttypid = att->atttypid;
3267 atttypmod = att->atttypmod;
3268 for (j = 0; j < cstate->indesc->natts; j++)
3270 att = cstate->indesc->attrs[j];
3271 if (att->attisdropped)
3273 if (strcmp(attname, NameStr(att->attname)) == 0)
3275 /* Found it, check type */
3276 if (atttypid != att->atttypid || atttypmod != att->atttypmod)
3277 elog(ERROR, "attribute \"%s\" of type %s does not match corresponding attribute of type %s",
3279 format_type_be(cstate->indesc->tdtypeid),
3280 format_type_be(cstate->outdesc->tdtypeid));
3281 cstate->attrMap[i] = (AttrNumber) (j + 1);
3285 if (cstate->attrMap[i] == 0)
3286 elog(ERROR, "attribute \"%s\" of type %s does not exist",
3288 format_type_be(cstate->indesc->tdtypeid));
3290 /* preallocate workspace for Datum arrays */
3291 n = cstate->indesc->natts + 1; /* +1 for NULL */
3292 cstate->invalues = (Datum *) palloc(n * sizeof(Datum));
3293 cstate->inisnull = (bool *) palloc(n * sizeof(bool));
3294 n = cstate->outdesc->natts;
3295 cstate->outvalues = (Datum *) palloc(n * sizeof(Datum));
3296 cstate->outisnull = (bool *) palloc(n * sizeof(bool));
3297 state = (ExprState *) cstate;
3302 CaseExpr *caseexpr = (CaseExpr *) node;
3303 CaseExprState *cstate = makeNode(CaseExprState);
3304 List *outlist = NIL;
3307 cstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalCase;
3308 cstate->arg = ExecInitExpr(caseexpr->arg, parent);
3309 foreach(l, caseexpr->args)
3311 CaseWhen *when = (CaseWhen *) lfirst(l);
3312 CaseWhenState *wstate = makeNode(CaseWhenState);
3314 Assert(IsA(when, CaseWhen));
3315 wstate->xprstate.evalfunc = NULL; /* not used */
3316 wstate->xprstate.expr = (Expr *) when;
3317 wstate->expr = ExecInitExpr(when->expr, parent);
3318 wstate->result = ExecInitExpr(when->result, parent);
3319 outlist = lappend(outlist, wstate);
3321 cstate->args = outlist;
3322 cstate->defresult = ExecInitExpr(caseexpr->defresult, parent);
3323 state = (ExprState *) cstate;
3328 ArrayExpr *arrayexpr = (ArrayExpr *) node;
3329 ArrayExprState *astate = makeNode(ArrayExprState);
3330 List *outlist = NIL;
3333 astate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalArray;
3334 foreach(l, arrayexpr->elements)
3336 Expr *e = (Expr *) lfirst(l);
3339 estate = ExecInitExpr(e, parent);
3340 outlist = lappend(outlist, estate);
3342 astate->elements = outlist;
3343 /* do one-time catalog lookup for type info */
3344 get_typlenbyvalalign(arrayexpr->element_typeid,
3345 &astate->elemlength,
3347 &astate->elemalign);
3348 state = (ExprState *) astate;
3353 RowExpr *rowexpr = (RowExpr *) node;
3354 RowExprState *rstate = makeNode(RowExprState);
3355 Form_pg_attribute *attrs;
3356 List *outlist = NIL;
3360 rstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalRow;
3361 /* Build tupdesc to describe result tuples */
3362 if (rowexpr->row_typeid == RECORDOID)
3364 /* generic record, use runtime type assignment */
3365 rstate->tupdesc = ExecTypeFromExprList(rowexpr->args);
3366 BlessTupleDesc(rstate->tupdesc);
3370 /* it's been cast to a named type, use that */
3371 rstate->tupdesc = lookup_rowtype_tupdesc(rowexpr->row_typeid, -1);
3372 rstate->tupdesc = CreateTupleDescCopy(rstate->tupdesc);
3374 /* Set up evaluation, skipping any deleted columns */
3375 Assert(list_length(rowexpr->args) <= rstate->tupdesc->natts);
3376 attrs = rstate->tupdesc->attrs;
3378 foreach(l, rowexpr->args)
3380 Expr *e = (Expr *) lfirst(l);
3383 if (!attrs[i]->attisdropped)
3386 * Guard against ALTER COLUMN TYPE on rowtype since
3387 * the RowExpr was created. XXX should we check
3388 * typmod too? Not sure we can be sure it'll be the
3391 if (exprType((Node *) e) != attrs[i]->atttypid)
3393 (errcode(ERRCODE_DATATYPE_MISMATCH),
3394 errmsg("ROW() column has type %s instead of type %s",
3395 format_type_be(exprType((Node *) e)),
3396 format_type_be(attrs[i]->atttypid))));
3401 * Ignore original expression and insert a NULL. We
3402 * don't really care what type of NULL it is, so
3403 * always make an int4 NULL.
3405 e = (Expr *) makeNullConst(INT4OID);
3407 estate = ExecInitExpr(e, parent);
3408 outlist = lappend(outlist, estate);
3411 rstate->args = outlist;
3412 state = (ExprState *) rstate;
3415 case T_RowCompareExpr:
3417 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
3418 RowCompareExprState *rstate = makeNode(RowCompareExprState);
3419 int nopers = list_length(rcexpr->opnos);
3425 rstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalRowCompare;
3426 Assert(list_length(rcexpr->largs) == nopers);
3428 foreach(l, rcexpr->largs)
3430 Expr *e = (Expr *) lfirst(l);
3433 estate = ExecInitExpr(e, parent);
3434 outlist = lappend(outlist, estate);
3436 rstate->largs = outlist;
3437 Assert(list_length(rcexpr->rargs) == nopers);
3439 foreach(l, rcexpr->rargs)
3441 Expr *e = (Expr *) lfirst(l);
3444 estate = ExecInitExpr(e, parent);
3445 outlist = lappend(outlist, estate);
3447 rstate->rargs = outlist;
3448 Assert(list_length(rcexpr->opclasses) == nopers);
3449 rstate->funcs = (FmgrInfo *) palloc(nopers * sizeof(FmgrInfo));
3451 forboth(l, rcexpr->opnos, l2, rcexpr->opclasses)
3453 Oid opno = lfirst_oid(l);
3454 Oid opclass = lfirst_oid(l2);
3460 get_op_opclass_properties(opno, opclass,
3461 &strategy, &subtype, &recheck);
3462 proc = get_opclass_proc(opclass, subtype, BTORDER_PROC);
3464 * If we enforced permissions checks on index support
3465 * functions, we'd need to make a check here. But the
3466 * index support machinery doesn't do that, and neither
3469 fmgr_info(proc, &(rstate->funcs[i]));
3472 state = (ExprState *) rstate;
3475 case T_CoalesceExpr:
3477 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
3478 CoalesceExprState *cstate = makeNode(CoalesceExprState);
3479 List *outlist = NIL;
3482 cstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalCoalesce;
3483 foreach(l, coalesceexpr->args)
3485 Expr *e = (Expr *) lfirst(l);
3488 estate = ExecInitExpr(e, parent);
3489 outlist = lappend(outlist, estate);
3491 cstate->args = outlist;
3492 state = (ExprState *) cstate;
3497 MinMaxExpr *minmaxexpr = (MinMaxExpr *) node;
3498 MinMaxExprState *mstate = makeNode(MinMaxExprState);
3499 List *outlist = NIL;
3501 TypeCacheEntry *typentry;
3503 mstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalMinMax;
3504 foreach(l, minmaxexpr->args)
3506 Expr *e = (Expr *) lfirst(l);
3509 estate = ExecInitExpr(e, parent);
3510 outlist = lappend(outlist, estate);
3512 mstate->args = outlist;
3513 /* Look up the btree comparison function for the datatype */
3514 typentry = lookup_type_cache(minmaxexpr->minmaxtype,
3515 TYPECACHE_CMP_PROC);
3516 if (!OidIsValid(typentry->cmp_proc))
3518 (errcode(ERRCODE_UNDEFINED_FUNCTION),
3519 errmsg("could not identify a comparison function for type %s",
3520 format_type_be(minmaxexpr->minmaxtype))));
3522 * If we enforced permissions checks on index support
3523 * functions, we'd need to make a check here. But the
3524 * index support machinery doesn't do that, and neither
3527 fmgr_info(typentry->cmp_proc, &(mstate->cfunc));
3528 state = (ExprState *) mstate;
3533 NullIfExpr *nullifexpr = (NullIfExpr *) node;
3534 FuncExprState *fstate = makeNode(FuncExprState);
3536 fstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalNullIf;
3537 fstate->args = (List *)
3538 ExecInitExpr((Expr *) nullifexpr->args, parent);
3539 fstate->func.fn_oid = InvalidOid; /* not initialized */
3540 state = (ExprState *) fstate;
3545 NullTest *ntest = (NullTest *) node;
3546 GenericExprState *gstate = makeNode(GenericExprState);
3548 gstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalNullTest;
3549 gstate->arg = ExecInitExpr(ntest->arg, parent);
3550 state = (ExprState *) gstate;
3555 BooleanTest *btest = (BooleanTest *) node;
3556 GenericExprState *gstate = makeNode(GenericExprState);
3558 gstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalBooleanTest;
3559 gstate->arg = ExecInitExpr(btest->arg, parent);
3560 state = (ExprState *) gstate;
3563 case T_CoerceToDomain:
3565 CoerceToDomain *ctest = (CoerceToDomain *) node;
3566 CoerceToDomainState *cstate = makeNode(CoerceToDomainState);
3568 cstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalCoerceToDomain;
3569 cstate->arg = ExecInitExpr(ctest->arg, parent);
3570 cstate->constraints = GetDomainConstraints(ctest->resulttype);
3571 state = (ExprState *) cstate;
3576 TargetEntry *tle = (TargetEntry *) node;
3577 GenericExprState *gstate = makeNode(GenericExprState);
3579 gstate->xprstate.evalfunc = NULL; /* not used */
3580 gstate->arg = ExecInitExpr(tle->expr, parent);
3581 state = (ExprState *) gstate;
3586 List *outlist = NIL;
3589 foreach(l, (List *) node)
3591 outlist = lappend(outlist,
3592 ExecInitExpr((Expr *) lfirst(l),
3595 /* Don't fall through to the "common" code below */
3596 return (ExprState *) outlist;
3599 elog(ERROR, "unrecognized node type: %d",
3600 (int) nodeTag(node));
3601 state = NULL; /* keep compiler quiet */
3605 /* Common code for all state-node types */
3612 * ExecInitExprInitPlan --- initialize a subplan expr that's being handled
3613 * as an InitPlan. This is identical to ExecInitExpr's handling of a regular
3614 * subplan expr, except we do NOT want to add the node to the parent's
3618 ExecInitExprInitPlan(SubPlan *node, PlanState *parent)
3620 SubPlanState *sstate = makeNode(SubPlanState);
3623 elog(ERROR, "SubPlan found with no parent plan");
3625 /* The subplan's state will be initialized later */
3626 sstate->sub_estate = NULL;
3627 sstate->planstate = NULL;
3629 sstate->testexpr = ExecInitExpr((Expr *) node->testexpr, parent);
3630 sstate->args = (List *) ExecInitExpr((Expr *) node->args, parent);
3632 sstate->xprstate.expr = (Expr *) node;
3638 * ExecPrepareExpr --- initialize for expression execution outside a normal
3639 * Plan tree context.
3641 * This differs from ExecInitExpr in that we don't assume the caller is
3642 * already running in the EState's per-query context. Also, we apply
3643 * fix_opfuncids() to the passed expression tree to be sure it is ready
3644 * to run. (In ordinary Plan trees the planner will have fixed opfuncids,
3645 * but callers outside the executor will not have done this.)
3648 ExecPrepareExpr(Expr *node, EState *estate)
3651 MemoryContext oldcontext;
3653 fix_opfuncids((Node *) node);
3655 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
3657 result = ExecInitExpr(node, NULL);
3659 MemoryContextSwitchTo(oldcontext);
3665 /* ----------------------------------------------------------------
3666 * ExecQual / ExecTargetList / ExecProject
3667 * ----------------------------------------------------------------
3670 /* ----------------------------------------------------------------
3673 * Evaluates a conjunctive boolean expression (qual list) and
3674 * returns true iff none of the subexpressions are false.
3675 * (We also return true if the list is empty.)
3677 * If some of the subexpressions yield NULL but none yield FALSE,
3678 * then the result of the conjunction is NULL (ie, unknown)
3679 * according to three-valued boolean logic. In this case,
3680 * we return the value specified by the "resultForNull" parameter.
3682 * Callers evaluating WHERE clauses should pass resultForNull=FALSE,
3683 * since SQL specifies that tuples with null WHERE results do not
3684 * get selected. On the other hand, callers evaluating constraint
3685 * conditions should pass resultForNull=TRUE, since SQL also specifies
3686 * that NULL constraint conditions are not failures.
3688 * NOTE: it would not be correct to use this routine to evaluate an
3689 * AND subclause of a boolean expression; for that purpose, a NULL
3690 * result must be returned as NULL so that it can be properly treated
3691 * in the next higher operator (cf. ExecEvalAnd and ExecEvalOr).
3692 * This routine is only used in contexts where a complete expression
3693 * is being evaluated and we know that NULL can be treated the same
3694 * as one boolean result or the other.
3696 * ----------------------------------------------------------------
3699 ExecQual(List *qual, ExprContext *econtext, bool resultForNull)
3702 MemoryContext oldContext;
3708 EV_printf("ExecQual: qual is ");
3709 EV_nodeDisplay(qual);
3715 * Run in short-lived per-tuple context while computing expressions.
3717 oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
3720 * Evaluate the qual conditions one at a time. If we find a FALSE result,
3721 * we can stop evaluating and return FALSE --- the AND result must be
3722 * FALSE. Also, if we find a NULL result when resultForNull is FALSE, we
3723 * can stop and return FALSE --- the AND result must be FALSE or NULL in
3724 * that case, and the caller doesn't care which.
3726 * If we get to the end of the list, we can return TRUE. This will happen
3727 * when the AND result is indeed TRUE, or when the AND result is NULL (one
3728 * or more NULL subresult, with all the rest TRUE) and the caller has
3729 * specified resultForNull = TRUE.
3735 ExprState *clause = (ExprState *) lfirst(l);
3739 expr_value = ExecEvalExpr(clause, econtext, &isNull, NULL);
3743 if (resultForNull == false)
3745 result = false; /* treat NULL as FALSE */
3751 if (!DatumGetBool(expr_value))
3753 result = false; /* definitely FALSE */
3759 MemoryContextSwitchTo(oldContext);
3765 * Number of items in a tlist (including any resjunk items!)
3768 ExecTargetListLength(List *targetlist)
3770 /* This used to be more complex, but fjoins are dead */
3771 return list_length(targetlist);
3775 * Number of items in a tlist, not including any resjunk items
3778 ExecCleanTargetListLength(List *targetlist)
3783 foreach(tl, targetlist)
3785 TargetEntry *curTle = (TargetEntry *) lfirst(tl);
3787 Assert(IsA(curTle, TargetEntry));
3788 if (!curTle->resjunk)
3796 * Evaluates a targetlist with respect to the given
3797 * expression context. Returns TRUE if we were able to create
3798 * a result, FALSE if we have exhausted a set-valued expression.
3800 * Results are stored into the passed values and isnull arrays.
3801 * The caller must provide an itemIsDone array that persists across calls.
3803 * As with ExecEvalExpr, the caller should pass isDone = NULL if not
3804 * prepared to deal with sets of result tuples. Otherwise, a return
3805 * of *isDone = ExprMultipleResult signifies a set element, and a return
3806 * of *isDone = ExprEndResult signifies end of the set of tuple.
3809 ExecTargetList(List *targetlist,
3810 ExprContext *econtext,
3813 ExprDoneCond *itemIsDone,
3814 ExprDoneCond *isDone)
3816 MemoryContext oldContext;
3821 * Run in short-lived per-tuple context while computing expressions.
3823 oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
3826 * evaluate all the expressions in the target list
3829 *isDone = ExprSingleResult; /* until proven otherwise */
3831 haveDoneSets = false; /* any exhausted set exprs in tlist? */
3833 foreach(tl, targetlist)
3835 GenericExprState *gstate = (GenericExprState *) lfirst(tl);
3836 TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr;
3837 AttrNumber resind = tle->resno - 1;
3839 values[resind] = ExecEvalExpr(gstate->arg,
3842 &itemIsDone[resind]);
3844 if (itemIsDone[resind] != ExprSingleResult)
3846 /* We have a set-valued expression in the tlist */
3849 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3850 errmsg("set-valued function called in context that cannot accept a set")));
3851 if (itemIsDone[resind] == ExprMultipleResult)
3853 /* we have undone sets in the tlist, set flag */
3854 *isDone = ExprMultipleResult;
3858 /* we have done sets in the tlist, set flag for that */
3859 haveDoneSets = true;
3867 * note: can't get here unless we verified isDone != NULL
3869 if (*isDone == ExprSingleResult)
3872 * all sets are done, so report that tlist expansion is complete.
3874 *isDone = ExprEndResult;
3875 MemoryContextSwitchTo(oldContext);
3881 * We have some done and some undone sets. Restart the done ones
3882 * so that we can deliver a tuple (if possible).
3884 foreach(tl, targetlist)
3886 GenericExprState *gstate = (GenericExprState *) lfirst(tl);
3887 TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr;
3888 AttrNumber resind = tle->resno - 1;
3890 if (itemIsDone[resind] == ExprEndResult)
3892 values[resind] = ExecEvalExpr(gstate->arg,
3895 &itemIsDone[resind]);
3897 if (itemIsDone[resind] == ExprEndResult)
3900 * Oh dear, this item is returning an empty set. Guess
3901 * we can't make a tuple after all.
3903 *isDone = ExprEndResult;
3910 * If we cannot make a tuple because some sets are empty, we still
3911 * have to cycle the nonempty sets to completion, else resources
3912 * will not be released from subplans etc.
3914 * XXX is that still necessary?
3916 if (*isDone == ExprEndResult)
3918 foreach(tl, targetlist)
3920 GenericExprState *gstate = (GenericExprState *) lfirst(tl);
3921 TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr;
3922 AttrNumber resind = tle->resno - 1;
3924 while (itemIsDone[resind] == ExprMultipleResult)
3926 values[resind] = ExecEvalExpr(gstate->arg,
3929 &itemIsDone[resind]);
3933 MemoryContextSwitchTo(oldContext);
3939 /* Report success */
3940 MemoryContextSwitchTo(oldContext);
3947 * Evaluates a simple-Variable-list projection.
3949 * Results are stored into the passed values and isnull arrays.
3952 ExecVariableList(ProjectionInfo *projInfo,
3956 ExprContext *econtext = projInfo->pi_exprContext;
3957 int *varSlotOffsets = projInfo->pi_varSlotOffsets;
3958 int *varNumbers = projInfo->pi_varNumbers;
3962 * Force extraction of all input values that we need.
3964 if (projInfo->pi_lastInnerVar > 0)
3965 slot_getsomeattrs(econtext->ecxt_innertuple,
3966 projInfo->pi_lastInnerVar);
3967 if (projInfo->pi_lastOuterVar > 0)
3968 slot_getsomeattrs(econtext->ecxt_outertuple,
3969 projInfo->pi_lastOuterVar);
3970 if (projInfo->pi_lastScanVar > 0)
3971 slot_getsomeattrs(econtext->ecxt_scantuple,
3972 projInfo->pi_lastScanVar);
3975 * Assign to result by direct extraction of fields from source slots ... a
3976 * mite ugly, but fast ...
3978 for (i = list_length(projInfo->pi_targetlist) - 1; i >= 0; i--)
3980 char *slotptr = ((char *) econtext) + varSlotOffsets[i];
3981 TupleTableSlot *varSlot = *((TupleTableSlot **) slotptr);
3982 int varNumber = varNumbers[i] - 1;
3984 values[i] = varSlot->tts_values[varNumber];
3985 isnull[i] = varSlot->tts_isnull[varNumber];
3992 * projects a tuple based on projection info and stores
3993 * it in the previously specified tuple table slot.
3995 * Note: the result is always a virtual tuple; therefore it
3996 * may reference the contents of the exprContext's scan tuples
3997 * and/or temporary results constructed in the exprContext.
3998 * If the caller wishes the result to be valid longer than that
3999 * data will be valid, he must call ExecMaterializeSlot on the
4003 ExecProject(ProjectionInfo *projInfo, ExprDoneCond *isDone)
4005 TupleTableSlot *slot;
4010 Assert(projInfo != NULL);
4013 * get the projection info we want
4015 slot = projInfo->pi_slot;
4018 * Clear any former contents of the result slot. This makes it safe for
4019 * us to use the slot's Datum/isnull arrays as workspace. (Also, we can
4020 * return the slot as-is if we decide no rows can be projected.)
4022 ExecClearTuple(slot);
4025 * form a new result tuple (if possible); if successful, mark the result
4026 * slot as containing a valid virtual tuple
4028 if (projInfo->pi_isVarList)
4030 /* simple Var list: this always succeeds with one result row */
4032 *isDone = ExprSingleResult;
4033 ExecVariableList(projInfo,
4036 ExecStoreVirtualTuple(slot);
4040 if (ExecTargetList(projInfo->pi_targetlist,
4041 projInfo->pi_exprContext,
4044 projInfo->pi_itemIsDone,
4046 ExecStoreVirtualTuple(slot);