1 /*-------------------------------------------------------------------------
4 * Routines to evaluate qualification and targetlist expressions
6 * Portions Copyright (c) 1996-2007, 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.205 2007/01/10 20:33:54 petere 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/nodeSubplan.h"
46 #include "miscadmin.h"
47 #include "nodes/makefuncs.h"
48 #include "optimizer/planmain.h"
49 #include "parser/parse_expr.h"
50 #include "utils/acl.h"
51 #include "utils/builtins.h"
52 #include "utils/lsyscache.h"
53 #include "utils/memutils.h"
54 #include "utils/typcache.h"
55 #include "utils/xml.h"
58 /* static function decls */
59 static Datum ExecEvalArrayRef(ArrayRefExprState *astate,
60 ExprContext *econtext,
61 bool *isNull, ExprDoneCond *isDone);
62 static Datum ExecEvalAggref(AggrefExprState *aggref,
63 ExprContext *econtext,
64 bool *isNull, ExprDoneCond *isDone);
65 static Datum ExecEvalVar(ExprState *exprstate, ExprContext *econtext,
66 bool *isNull, ExprDoneCond *isDone);
67 static Datum ExecEvalWholeRowVar(ExprState *exprstate, ExprContext *econtext,
68 bool *isNull, ExprDoneCond *isDone);
69 static Datum ExecEvalConst(ExprState *exprstate, ExprContext *econtext,
70 bool *isNull, ExprDoneCond *isDone);
71 static Datum ExecEvalParam(ExprState *exprstate, ExprContext *econtext,
72 bool *isNull, ExprDoneCond *isDone);
73 static void ShutdownFuncExpr(Datum arg);
74 static TupleDesc get_cached_rowtype(Oid type_id, int32 typmod,
75 TupleDesc *cache_field, ExprContext *econtext);
76 static void ShutdownTupleDescRef(Datum arg);
77 static ExprDoneCond ExecEvalFuncArgs(FunctionCallInfo fcinfo,
78 List *argList, ExprContext *econtext);
79 static Datum ExecMakeFunctionResultNoSets(FuncExprState *fcache,
80 ExprContext *econtext,
81 bool *isNull, ExprDoneCond *isDone);
82 static Datum ExecEvalFunc(FuncExprState *fcache, ExprContext *econtext,
83 bool *isNull, ExprDoneCond *isDone);
84 static Datum ExecEvalOper(FuncExprState *fcache, ExprContext *econtext,
85 bool *isNull, ExprDoneCond *isDone);
86 static Datum ExecEvalDistinct(FuncExprState *fcache, ExprContext *econtext,
87 bool *isNull, ExprDoneCond *isDone);
88 static Datum ExecEvalScalarArrayOp(ScalarArrayOpExprState *sstate,
89 ExprContext *econtext,
90 bool *isNull, ExprDoneCond *isDone);
91 static Datum ExecEvalNot(BoolExprState *notclause, ExprContext *econtext,
92 bool *isNull, ExprDoneCond *isDone);
93 static Datum ExecEvalOr(BoolExprState *orExpr, ExprContext *econtext,
94 bool *isNull, ExprDoneCond *isDone);
95 static Datum ExecEvalAnd(BoolExprState *andExpr, ExprContext *econtext,
96 bool *isNull, ExprDoneCond *isDone);
97 static Datum ExecEvalConvertRowtype(ConvertRowtypeExprState *cstate,
98 ExprContext *econtext,
99 bool *isNull, ExprDoneCond *isDone);
100 static Datum ExecEvalCase(CaseExprState *caseExpr, ExprContext *econtext,
101 bool *isNull, ExprDoneCond *isDone);
102 static Datum ExecEvalCaseTestExpr(ExprState *exprstate,
103 ExprContext *econtext,
104 bool *isNull, ExprDoneCond *isDone);
105 static Datum ExecEvalArray(ArrayExprState *astate,
106 ExprContext *econtext,
107 bool *isNull, ExprDoneCond *isDone);
108 static Datum ExecEvalRow(RowExprState *rstate,
109 ExprContext *econtext,
110 bool *isNull, ExprDoneCond *isDone);
111 static Datum ExecEvalRowCompare(RowCompareExprState *rstate,
112 ExprContext *econtext,
113 bool *isNull, ExprDoneCond *isDone);
114 static Datum ExecEvalCoalesce(CoalesceExprState *coalesceExpr,
115 ExprContext *econtext,
116 bool *isNull, ExprDoneCond *isDone);
117 static Datum ExecEvalMinMax(MinMaxExprState *minmaxExpr,
118 ExprContext *econtext,
119 bool *isNull, ExprDoneCond *isDone);
120 static Datum ExecEvalXml(XmlExprState *xmlExpr, ExprContext *econtext,
121 bool *isNull, ExprDoneCond *isDone);
122 static Datum ExecEvalNullIf(FuncExprState *nullIfExpr,
123 ExprContext *econtext,
124 bool *isNull, ExprDoneCond *isDone);
125 static Datum ExecEvalNullTest(NullTestState *nstate,
126 ExprContext *econtext,
127 bool *isNull, ExprDoneCond *isDone);
128 static Datum ExecEvalBooleanTest(GenericExprState *bstate,
129 ExprContext *econtext,
130 bool *isNull, ExprDoneCond *isDone);
131 static Datum ExecEvalCoerceToDomain(CoerceToDomainState *cstate,
132 ExprContext *econtext,
133 bool *isNull, ExprDoneCond *isDone);
134 static Datum ExecEvalCoerceToDomainValue(ExprState *exprstate,
135 ExprContext *econtext,
136 bool *isNull, ExprDoneCond *isDone);
137 static Datum ExecEvalFieldSelect(FieldSelectState *fstate,
138 ExprContext *econtext,
139 bool *isNull, ExprDoneCond *isDone);
140 static Datum ExecEvalFieldStore(FieldStoreState *fstate,
141 ExprContext *econtext,
142 bool *isNull, ExprDoneCond *isDone);
143 static Datum ExecEvalRelabelType(GenericExprState *exprstate,
144 ExprContext *econtext,
145 bool *isNull, ExprDoneCond *isDone);
148 /* ----------------------------------------------------------------
149 * ExecEvalExpr routines
151 * Recursively evaluate a targetlist or qualification expression.
153 * Each of the following routines having the signature
154 * Datum ExecEvalFoo(ExprState *expression,
155 * ExprContext *econtext,
157 * ExprDoneCond *isDone);
158 * is responsible for evaluating one type or subtype of ExprState node.
159 * They are normally called via the ExecEvalExpr macro, which makes use of
160 * the function pointer set up when the ExprState node was built by
161 * ExecInitExpr. (In some cases, we change this pointer later to avoid
162 * re-executing one-time overhead.)
164 * Note: for notational simplicity we declare these functions as taking the
165 * specific type of ExprState that they work on. This requires casting when
166 * assigning the function pointer in ExecInitExpr. Be careful that the
167 * function signature is declared correctly, because the cast suppresses
168 * automatic checking!
171 * All these functions share this calling convention:
174 * expression: the expression state tree to evaluate
175 * econtext: evaluation context information
178 * return value: Datum value of result
179 * *isNull: set to TRUE if result is NULL (actual return value is
180 * meaningless if so); set to FALSE if non-null result
181 * *isDone: set to indicator of set-result status
183 * A caller that can only accept a singleton (non-set) result should pass
184 * NULL for isDone; if the expression computes a set result then an error
185 * will be reported via ereport. If the caller does pass an isDone pointer
186 * then *isDone is set to one of these three states:
187 * ExprSingleResult singleton result (not a set)
188 * ExprMultipleResult return value is one element of a set
189 * ExprEndResult there are no more elements in the set
190 * When ExprMultipleResult is returned, the caller should invoke
191 * ExecEvalExpr() repeatedly until ExprEndResult is returned. ExprEndResult
192 * is returned after the last real set element. For convenience isNull will
193 * always be set TRUE when ExprEndResult is returned, but this should not be
194 * taken as indicating a NULL element of the set. Note that these return
195 * conventions allow us to distinguish among a singleton NULL, a NULL element
196 * of a set, and an empty set.
198 * The caller should already have switched into the temporary memory
199 * context econtext->ecxt_per_tuple_memory. The convenience entry point
200 * ExecEvalExprSwitchContext() is provided for callers who don't prefer to
201 * do the switch in an outer loop. We do not do the switch in these routines
202 * because it'd be a waste of cycles during nested expression evaluation.
203 * ----------------------------------------------------------------
210 * This function takes an ArrayRef and returns the extracted Datum
211 * if it's a simple reference, or the modified array value if it's
212 * an array assignment (i.e., array element or slice insertion).
214 * NOTE: if we get a NULL result from a subscript expression, we return NULL
215 * when it's an array reference, or raise an error when it's an assignment.
217 * NOTE: we deliberately refrain from applying DatumGetArrayTypeP() here,
218 * even though that might seem natural, because this code needs to support
219 * both varlena arrays and fixed-length array types. DatumGetArrayTypeP()
220 * only works for the varlena kind. The routines we call in arrayfuncs.c
221 * have to know the difference (that's what they need refattrlength for).
225 ExecEvalArrayRef(ArrayRefExprState *astate,
226 ExprContext *econtext,
228 ExprDoneCond *isDone)
230 ArrayRef *arrayRef = (ArrayRef *) astate->xprstate.expr;
231 ArrayType *array_source;
232 ArrayType *resultArray;
233 bool isAssignment = (arrayRef->refassgnexpr != NULL);
242 array_source = (ArrayType *)
243 DatumGetPointer(ExecEvalExpr(astate->refexpr,
249 * If refexpr yields NULL, and it's a fetch, then result is NULL. In the
250 * assignment case, we'll cons up something below.
254 if (isDone && *isDone == ExprEndResult)
255 return (Datum) NULL; /* end of set result */
260 foreach(l, astate->refupperindexpr)
262 ExprState *eltstate = (ExprState *) lfirst(l);
266 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
267 errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
270 upper.indx[i++] = DatumGetInt32(ExecEvalExpr(eltstate,
274 /* If any index expr yields NULL, result is NULL or error */
279 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
280 errmsg("array subscript in assignment must not be null")));
286 if (astate->reflowerindexpr != NIL)
288 foreach(l, astate->reflowerindexpr)
290 ExprState *eltstate = (ExprState *) lfirst(l);
294 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
295 errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
298 lower.indx[j++] = DatumGetInt32(ExecEvalExpr(eltstate,
302 /* If any index expr yields NULL, result is NULL or error */
307 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
308 errmsg("array subscript in assignment must not be null")));
313 /* this can't happen unless parser messed up */
315 elog(ERROR, "upper and lower index lists are not same length");
326 * Evaluate the value to be assigned into the array.
328 * XXX At some point we'll need to look into making the old value of
329 * the array element available via CaseTestExpr, as is done by
330 * ExecEvalFieldStore. This is not needed now but will be needed to
331 * support arrays of composite types; in an assignment to a field of
332 * an array member, the parser would generate a FieldStore that
333 * expects to fetch its input tuple via CaseTestExpr.
335 sourceData = ExecEvalExpr(astate->refassgnexpr,
341 * For an assignment to a fixed-length array type, both the original
342 * array and the value to be assigned into it must be non-NULL, else
343 * we punt and return the original array.
345 if (astate->refattrlength > 0) /* fixed-length array? */
346 if (eisnull || *isNull)
347 return PointerGetDatum(array_source);
350 * For assignment to varlena arrays, we handle a NULL original array
351 * by substituting an empty (zero-dimensional) array; insertion of the
352 * new element will result in a singleton array value. It does not
353 * matter whether the new element is NULL.
357 array_source = construct_empty_array(arrayRef->refelemtype);
362 resultArray = array_set(array_source, i,
366 astate->refattrlength,
367 astate->refelemlength,
368 astate->refelembyval,
369 astate->refelemalign);
371 resultArray = array_set_slice(array_source, i,
372 upper.indx, lower.indx,
373 (ArrayType *) DatumGetPointer(sourceData),
375 astate->refattrlength,
376 astate->refelemlength,
377 astate->refelembyval,
378 astate->refelemalign);
379 return PointerGetDatum(resultArray);
383 return array_ref(array_source, i, upper.indx,
384 astate->refattrlength,
385 astate->refelemlength,
386 astate->refelembyval,
387 astate->refelemalign,
391 resultArray = array_get_slice(array_source, i,
392 upper.indx, lower.indx,
393 astate->refattrlength,
394 astate->refelemlength,
395 astate->refelembyval,
396 astate->refelemalign);
397 return PointerGetDatum(resultArray);
402 /* ----------------------------------------------------------------
405 * Returns a Datum whose value is the value of the precomputed
406 * aggregate found in the given expression context.
407 * ----------------------------------------------------------------
410 ExecEvalAggref(AggrefExprState *aggref, ExprContext *econtext,
411 bool *isNull, ExprDoneCond *isDone)
414 *isDone = ExprSingleResult;
416 if (econtext->ecxt_aggvalues == NULL) /* safety check */
417 elog(ERROR, "no aggregates in this expression context");
419 *isNull = econtext->ecxt_aggnulls[aggref->aggno];
420 return econtext->ecxt_aggvalues[aggref->aggno];
423 /* ----------------------------------------------------------------
426 * Returns a Datum whose value is the value of a range
427 * variable with respect to given expression context.
428 * ----------------------------------------------------------------
431 ExecEvalVar(ExprState *exprstate, ExprContext *econtext,
432 bool *isNull, ExprDoneCond *isDone)
434 Var *variable = (Var *) exprstate->expr;
435 TupleTableSlot *slot;
439 *isDone = ExprSingleResult;
442 * Get the slot and attribute number we want
444 * The asserts check that references to system attributes only appear at
445 * the level of a relation scan; at higher levels, system attributes must
446 * be treated as ordinary variables (since we no longer have access to the
449 attnum = variable->varattno;
451 switch (variable->varno)
453 case INNER: /* get the tuple from the inner node */
454 slot = econtext->ecxt_innertuple;
458 case OUTER: /* get the tuple from the outer node */
459 slot = econtext->ecxt_outertuple;
463 default: /* get the tuple from the relation being
465 slot = econtext->ecxt_scantuple;
469 #ifdef USE_ASSERT_CHECKING
472 * Some checks that are only applied for user attribute numbers (bogus
473 * system attnums will be caught inside slot_getattr).
477 TupleDesc tuple_type = slot->tts_tupleDescriptor;
480 * This assert checks that the attnum is valid.
482 Assert(attnum <= tuple_type->natts);
485 * This assert checks that the datatype the plan expects to get (as
486 * told by our "variable" argument) is in fact the datatype of the
487 * attribute being fetched (as seen in the current context, identified
488 * by our "econtext" argument). Otherwise crashes are likely.
490 * Note that we can't check dropped columns, since their atttypid has
493 Assert(variable->vartype == tuple_type->attrs[attnum - 1]->atttypid ||
494 tuple_type->attrs[attnum - 1]->attisdropped);
496 #endif /* USE_ASSERT_CHECKING */
498 return slot_getattr(slot, attnum, isNull);
501 /* ----------------------------------------------------------------
502 * ExecEvalWholeRowVar
504 * Returns a Datum for a whole-row variable.
506 * This could be folded into ExecEvalVar, but we make it a separate
507 * routine so as not to slow down ExecEvalVar with tests for this
509 * ----------------------------------------------------------------
512 ExecEvalWholeRowVar(ExprState *exprstate, ExprContext *econtext,
513 bool *isNull, ExprDoneCond *isDone)
515 Var *variable = (Var *) exprstate->expr;
516 TupleTableSlot *slot;
519 HeapTupleHeader dtuple;
522 *isDone = ExprSingleResult;
525 Assert(variable->varattno == InvalidAttrNumber);
528 * Whole-row Vars can only appear at the level of a relation scan, never
531 Assert(variable->varno != INNER);
532 Assert(variable->varno != OUTER);
533 slot = econtext->ecxt_scantuple;
535 tuple = ExecFetchSlotTuple(slot);
536 tupleDesc = slot->tts_tupleDescriptor;
539 * We have to make a copy of the tuple so we can safely insert the Datum
540 * overhead fields, which are not set in on-disk tuples.
542 dtuple = (HeapTupleHeader) palloc(tuple->t_len);
543 memcpy((char *) dtuple, (char *) tuple->t_data, tuple->t_len);
545 HeapTupleHeaderSetDatumLength(dtuple, tuple->t_len);
548 * If the Var identifies a named composite type, label the tuple with that
549 * type; otherwise use what is in the tupleDesc.
551 * It's likely that the slot's tupleDesc is a record type; if so, make
552 * sure it's been "blessed", so that the Datum can be interpreted later.
554 if (variable->vartype != RECORDOID)
556 HeapTupleHeaderSetTypeId(dtuple, variable->vartype);
557 HeapTupleHeaderSetTypMod(dtuple, variable->vartypmod);
561 if (tupleDesc->tdtypeid == RECORDOID &&
562 tupleDesc->tdtypmod < 0)
563 assign_record_type_typmod(tupleDesc);
564 HeapTupleHeaderSetTypeId(dtuple, tupleDesc->tdtypeid);
565 HeapTupleHeaderSetTypMod(dtuple, tupleDesc->tdtypmod);
568 return PointerGetDatum(dtuple);
571 /* ----------------------------------------------------------------
574 * Returns the value of a constant.
576 * Note that for pass-by-ref datatypes, we return a pointer to the
577 * actual constant node. This is one of the reasons why functions
578 * must treat their input arguments as read-only.
579 * ----------------------------------------------------------------
582 ExecEvalConst(ExprState *exprstate, ExprContext *econtext,
583 bool *isNull, ExprDoneCond *isDone)
585 Const *con = (Const *) exprstate->expr;
588 *isDone = ExprSingleResult;
590 *isNull = con->constisnull;
591 return con->constvalue;
594 /* ----------------------------------------------------------------
597 * Returns the value of a parameter. A param node contains
598 * something like ($.name) and the expression context contains
599 * the current parameter bindings (name = "sam") (age = 34)...
600 * so our job is to find and return the appropriate datum ("sam").
601 * ----------------------------------------------------------------
604 ExecEvalParam(ExprState *exprstate, ExprContext *econtext,
605 bool *isNull, ExprDoneCond *isDone)
607 Param *expression = (Param *) exprstate->expr;
608 int thisParamId = expression->paramid;
611 *isDone = ExprSingleResult;
613 if (expression->paramkind == PARAM_EXEC)
616 * PARAM_EXEC params (internal executor parameters) are stored in the
617 * ecxt_param_exec_vals array, and can be accessed by array index.
621 prm = &(econtext->ecxt_param_exec_vals[thisParamId]);
622 if (prm->execPlan != NULL)
624 /* Parameter not evaluated yet, so go do it */
625 ExecSetParamPlan(prm->execPlan, econtext);
626 /* ExecSetParamPlan should have processed this param... */
627 Assert(prm->execPlan == NULL);
629 *isNull = prm->isnull;
635 * PARAM_EXTERN parameters must be sought in ecxt_param_list_info.
637 ParamListInfo paramInfo = econtext->ecxt_param_list_info;
639 Assert(expression->paramkind == PARAM_EXTERN);
641 thisParamId > 0 && thisParamId <= paramInfo->numParams)
643 ParamExternData *prm = ¶mInfo->params[thisParamId - 1];
645 if (OidIsValid(prm->ptype))
647 Assert(prm->ptype == expression->paramtype);
648 *isNull = prm->isnull;
653 (errcode(ERRCODE_UNDEFINED_OBJECT),
654 errmsg("no value found for parameter %d", thisParamId)));
655 return (Datum) 0; /* keep compiler quiet */
660 /* ----------------------------------------------------------------
661 * ExecEvalOper / ExecEvalFunc support routines
662 * ----------------------------------------------------------------
669 * These functions return the value of the requested attribute
670 * out of the given tuple Datum.
671 * C functions which take a tuple as an argument are expected
672 * to use these. Ex: overpaid(EMP) might call GetAttributeByNum().
673 * Note: these are actually rather slow because they do a typcache
674 * lookup on each call.
677 GetAttributeByNum(HeapTupleHeader tuple,
685 HeapTupleData tmptup;
687 if (!AttributeNumberIsValid(attrno))
688 elog(ERROR, "invalid attribute number %d", attrno);
691 elog(ERROR, "a NULL isNull pointer was passed");
695 /* Kinda bogus but compatible with old behavior... */
700 tupType = HeapTupleHeaderGetTypeId(tuple);
701 tupTypmod = HeapTupleHeaderGetTypMod(tuple);
702 tupDesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
705 * heap_getattr needs a HeapTuple not a bare HeapTupleHeader. We set all
706 * the fields in the struct just in case user tries to inspect system
709 tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
710 ItemPointerSetInvalid(&(tmptup.t_self));
711 tmptup.t_tableOid = InvalidOid;
712 tmptup.t_data = tuple;
714 result = heap_getattr(&tmptup,
719 ReleaseTupleDesc(tupDesc);
725 GetAttributeByName(HeapTupleHeader tuple, const char *attname, bool *isNull)
732 HeapTupleData tmptup;
736 elog(ERROR, "invalid attribute name");
739 elog(ERROR, "a NULL isNull pointer was passed");
743 /* Kinda bogus but compatible with old behavior... */
748 tupType = HeapTupleHeaderGetTypeId(tuple);
749 tupTypmod = HeapTupleHeaderGetTypMod(tuple);
750 tupDesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
752 attrno = InvalidAttrNumber;
753 for (i = 0; i < tupDesc->natts; i++)
755 if (namestrcmp(&(tupDesc->attrs[i]->attname), attname) == 0)
757 attrno = tupDesc->attrs[i]->attnum;
762 if (attrno == InvalidAttrNumber)
763 elog(ERROR, "attribute \"%s\" does not exist", attname);
766 * heap_getattr needs a HeapTuple not a bare HeapTupleHeader. We set all
767 * the fields in the struct just in case user tries to inspect system
770 tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
771 ItemPointerSetInvalid(&(tmptup.t_self));
772 tmptup.t_tableOid = InvalidOid;
773 tmptup.t_data = tuple;
775 result = heap_getattr(&tmptup,
780 ReleaseTupleDesc(tupDesc);
786 * init_fcache - initialize a FuncExprState node during first use
789 init_fcache(Oid foid, FuncExprState *fcache, MemoryContext fcacheCxt)
793 /* Check permission to call function */
794 aclresult = pg_proc_aclcheck(foid, GetUserId(), ACL_EXECUTE);
795 if (aclresult != ACLCHECK_OK)
796 aclcheck_error(aclresult, ACL_KIND_PROC, get_func_name(foid));
799 * Safety check on nargs. Under normal circumstances this should never
800 * fail, as parser should check sooner. But possibly it might fail if
801 * server has been compiled with FUNC_MAX_ARGS smaller than some functions
802 * declared in pg_proc?
804 if (list_length(fcache->args) > FUNC_MAX_ARGS)
806 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
807 errmsg("cannot pass more than %d arguments to a function",
810 /* Set up the primary fmgr lookup information */
811 fmgr_info_cxt(foid, &(fcache->func), fcacheCxt);
813 /* Initialize additional info */
814 fcache->setArgsValid = false;
815 fcache->shutdown_reg = false;
816 fcache->func.fn_expr = (Node *) fcache->xprstate.expr;
820 * callback function in case a FuncExpr returning a set needs to be shut down
821 * before it has been run to completion
824 ShutdownFuncExpr(Datum arg)
826 FuncExprState *fcache = (FuncExprState *) DatumGetPointer(arg);
828 /* Clear any active set-argument state */
829 fcache->setArgsValid = false;
831 /* execUtils will deregister the callback... */
832 fcache->shutdown_reg = false;
836 * get_cached_rowtype: utility function to lookup a rowtype tupdesc
838 * type_id, typmod: identity of the rowtype
839 * cache_field: where to cache the TupleDesc pointer in expression state node
840 * (field must be initialized to NULL)
841 * econtext: expression context we are executing in
843 * NOTE: because the shutdown callback will be called during plan rescan,
844 * must be prepared to re-do this during any node execution; cannot call
845 * just once during expression initialization
848 get_cached_rowtype(Oid type_id, int32 typmod,
849 TupleDesc *cache_field, ExprContext *econtext)
851 TupleDesc tupDesc = *cache_field;
853 /* Do lookup if no cached value or if requested type changed */
854 if (tupDesc == NULL ||
855 type_id != tupDesc->tdtypeid ||
856 typmod != tupDesc->tdtypmod)
858 tupDesc = lookup_rowtype_tupdesc(type_id, typmod);
862 /* Release old tupdesc; but callback is already registered */
863 ReleaseTupleDesc(*cache_field);
867 /* Need to register shutdown callback to release tupdesc */
868 RegisterExprContextCallback(econtext,
869 ShutdownTupleDescRef,
870 PointerGetDatum(cache_field));
872 *cache_field = tupDesc;
878 * Callback function to release a tupdesc refcount at expression tree shutdown
881 ShutdownTupleDescRef(Datum arg)
883 TupleDesc *cache_field = (TupleDesc *) DatumGetPointer(arg);
886 ReleaseTupleDesc(*cache_field);
891 * Evaluate arguments for a function.
894 ExecEvalFuncArgs(FunctionCallInfo fcinfo,
896 ExprContext *econtext)
898 ExprDoneCond argIsDone;
902 argIsDone = ExprSingleResult; /* default assumption */
905 foreach(arg, argList)
907 ExprState *argstate = (ExprState *) lfirst(arg);
908 ExprDoneCond thisArgIsDone;
910 fcinfo->arg[i] = ExecEvalExpr(argstate,
915 if (thisArgIsDone != ExprSingleResult)
918 * We allow only one argument to have a set value; we'd need much
919 * more complexity to keep track of multiple set arguments (cf.
920 * ExecTargetList) and it doesn't seem worth it.
922 if (argIsDone != ExprSingleResult)
924 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
925 errmsg("functions and operators can take at most one set argument")));
926 argIsDone = thisArgIsDone;
937 * ExecMakeFunctionResult
939 * Evaluate the arguments to a function and then the function itself.
942 ExecMakeFunctionResult(FuncExprState *fcache,
943 ExprContext *econtext,
945 ExprDoneCond *isDone)
947 List *arguments = fcache->args;
949 FunctionCallInfoData fcinfo;
950 ReturnSetInfo rsinfo; /* for functions returning sets */
951 ExprDoneCond argDone;
955 /* Guard against stack overflow due to overly complex expressions */
959 * arguments is a list of expressions to evaluate before passing to the
960 * function manager. We skip the evaluation if it was already done in the
961 * previous call (ie, we are continuing the evaluation of a set-valued
962 * function). Otherwise, collect the current argument values into fcinfo.
964 if (!fcache->setArgsValid)
966 /* Need to prep callinfo structure */
967 InitFunctionCallInfoData(fcinfo, &(fcache->func), 0, NULL, NULL);
968 argDone = ExecEvalFuncArgs(&fcinfo, arguments, econtext);
969 if (argDone == ExprEndResult)
971 /* input is an empty set, so return an empty set. */
974 *isDone = ExprEndResult;
977 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
978 errmsg("set-valued function called in context that cannot accept a set")));
981 hasSetArg = (argDone != ExprSingleResult);
985 /* Copy callinfo from previous evaluation */
986 memcpy(&fcinfo, &fcache->setArgs, sizeof(fcinfo));
987 hasSetArg = fcache->setHasSetArg;
988 /* Reset flag (we may set it again below) */
989 fcache->setArgsValid = false;
993 * If function returns set, prepare a resultinfo node for communication
995 if (fcache->func.fn_retset)
997 fcinfo.resultinfo = (Node *) &rsinfo;
998 rsinfo.type = T_ReturnSetInfo;
999 rsinfo.econtext = econtext;
1000 rsinfo.expectedDesc = NULL;
1001 rsinfo.allowedModes = (int) SFRM_ValuePerCall;
1002 rsinfo.returnMode = SFRM_ValuePerCall;
1003 /* isDone is filled below */
1004 rsinfo.setResult = NULL;
1005 rsinfo.setDesc = NULL;
1009 * now return the value gotten by calling the function manager, passing
1010 * the function the evaluated parameter values.
1012 if (fcache->func.fn_retset || hasSetArg)
1015 * We need to return a set result. Complain if caller not ready to
1020 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1021 errmsg("set-valued function called in context that cannot accept a set")));
1024 * This loop handles the situation where we have both a set argument
1025 * and a set-valued function. Once we have exhausted the function's
1026 * value(s) for a particular argument value, we have to get the next
1027 * argument value and start the function over again. We might have to
1028 * do it more than once, if the function produces an empty result set
1029 * for a particular input value.
1034 * If function is strict, and there are any NULL arguments, skip
1035 * calling the function (at least for this set of args).
1039 if (fcache->func.fn_strict)
1041 for (i = 0; i < fcinfo.nargs; i++)
1043 if (fcinfo.argnull[i])
1053 fcinfo.isnull = false;
1054 rsinfo.isDone = ExprSingleResult;
1055 result = FunctionCallInvoke(&fcinfo);
1056 *isNull = fcinfo.isnull;
1057 *isDone = rsinfo.isDone;
1063 *isDone = ExprEndResult;
1066 if (*isDone != ExprEndResult)
1069 * Got a result from current argument. If function itself
1070 * returns set, save the current argument values to re-use on
1073 if (fcache->func.fn_retset && *isDone == ExprMultipleResult)
1075 memcpy(&fcache->setArgs, &fcinfo, sizeof(fcinfo));
1076 fcache->setHasSetArg = hasSetArg;
1077 fcache->setArgsValid = true;
1078 /* Register cleanup callback if we didn't already */
1079 if (!fcache->shutdown_reg)
1081 RegisterExprContextCallback(econtext,
1083 PointerGetDatum(fcache));
1084 fcache->shutdown_reg = true;
1089 * Make sure we say we are returning a set, even if the
1090 * function itself doesn't return sets.
1093 *isDone = ExprMultipleResult;
1097 /* Else, done with this argument */
1099 break; /* input not a set, so done */
1101 /* Re-eval args to get the next element of the input set */
1102 argDone = ExecEvalFuncArgs(&fcinfo, arguments, econtext);
1104 if (argDone != ExprMultipleResult)
1106 /* End of argument set, so we're done. */
1108 *isDone = ExprEndResult;
1114 * If we reach here, loop around to run the function on the new
1122 * Non-set case: much easier.
1124 * We change the ExprState function pointer to use the simpler
1125 * ExecMakeFunctionResultNoSets on subsequent calls. This amounts to
1126 * assuming that no argument can return a set if it didn't do so the
1129 fcache->xprstate.evalfunc = (ExprStateEvalFunc) ExecMakeFunctionResultNoSets;
1132 *isDone = ExprSingleResult;
1135 * If function is strict, and there are any NULL arguments, skip
1136 * calling the function and return NULL.
1138 if (fcache->func.fn_strict)
1140 for (i = 0; i < fcinfo.nargs; i++)
1142 if (fcinfo.argnull[i])
1149 fcinfo.isnull = false;
1150 result = FunctionCallInvoke(&fcinfo);
1151 *isNull = fcinfo.isnull;
1158 * ExecMakeFunctionResultNoSets
1160 * Simplified version of ExecMakeFunctionResult that can only handle
1161 * non-set cases. Hand-tuned for speed.
1164 ExecMakeFunctionResultNoSets(FuncExprState *fcache,
1165 ExprContext *econtext,
1167 ExprDoneCond *isDone)
1171 FunctionCallInfoData fcinfo;
1174 /* Guard against stack overflow due to overly complex expressions */
1175 check_stack_depth();
1178 *isDone = ExprSingleResult;
1180 /* inlined, simplified version of ExecEvalFuncArgs */
1182 foreach(arg, fcache->args)
1184 ExprState *argstate = (ExprState *) lfirst(arg);
1186 fcinfo.arg[i] = ExecEvalExpr(argstate,
1193 InitFunctionCallInfoData(fcinfo, &(fcache->func), i, NULL, NULL);
1196 * If function is strict, and there are any NULL arguments, skip calling
1197 * the function and return NULL.
1199 if (fcache->func.fn_strict)
1203 if (fcinfo.argnull[i])
1210 /* fcinfo.isnull = false; */ /* handled by InitFunctionCallInfoData */
1211 result = FunctionCallInvoke(&fcinfo);
1212 *isNull = fcinfo.isnull;
1219 * ExecMakeTableFunctionResult
1221 * Evaluate a table function, producing a materialized result in a Tuplestore
1222 * object. *returnDesc is set to the tupledesc actually returned by the
1223 * function, or NULL if it didn't provide one.
1226 ExecMakeTableFunctionResult(ExprState *funcexpr,
1227 ExprContext *econtext,
1228 TupleDesc expectedDesc,
1229 TupleDesc *returnDesc)
1231 Tuplestorestate *tupstore = NULL;
1232 TupleDesc tupdesc = NULL;
1235 bool returnsSet = false;
1236 FunctionCallInfoData fcinfo;
1237 ReturnSetInfo rsinfo;
1238 HeapTupleData tmptup;
1239 MemoryContext callerContext;
1240 MemoryContext oldcontext;
1241 bool direct_function_call;
1242 bool first_time = true;
1244 callerContext = CurrentMemoryContext;
1246 funcrettype = exprType((Node *) funcexpr->expr);
1248 returnsTuple = type_is_rowtype(funcrettype);
1251 * Prepare a resultinfo node for communication. We always do this even if
1252 * not expecting a set result, so that we can pass expectedDesc. In the
1253 * generic-expression case, the expression doesn't actually get to see the
1254 * resultinfo, but set it up anyway because we use some of the fields as
1255 * our own state variables.
1257 InitFunctionCallInfoData(fcinfo, NULL, 0, NULL, (Node *) &rsinfo);
1258 rsinfo.type = T_ReturnSetInfo;
1259 rsinfo.econtext = econtext;
1260 rsinfo.expectedDesc = expectedDesc;
1261 rsinfo.allowedModes = (int) (SFRM_ValuePerCall | SFRM_Materialize);
1262 rsinfo.returnMode = SFRM_ValuePerCall;
1263 /* isDone is filled below */
1264 rsinfo.setResult = NULL;
1265 rsinfo.setDesc = NULL;
1268 * Normally the passed expression tree will be a FuncExprState, since the
1269 * grammar only allows a function call at the top level of a table
1270 * function reference. However, if the function doesn't return set then
1271 * the planner might have replaced the function call via constant-folding
1272 * or inlining. So if we see any other kind of expression node, execute
1273 * it via the general ExecEvalExpr() code; the only difference is that we
1274 * don't get a chance to pass a special ReturnSetInfo to any functions
1275 * buried in the expression.
1277 if (funcexpr && IsA(funcexpr, FuncExprState) &&
1278 IsA(funcexpr->expr, FuncExpr))
1280 FuncExprState *fcache = (FuncExprState *) funcexpr;
1281 ExprDoneCond argDone;
1284 * This path is similar to ExecMakeFunctionResult.
1286 direct_function_call = true;
1289 * Initialize function cache if first time through
1291 if (fcache->func.fn_oid == InvalidOid)
1293 FuncExpr *func = (FuncExpr *) fcache->xprstate.expr;
1295 init_fcache(func->funcid, fcache, econtext->ecxt_per_query_memory);
1297 returnsSet = fcache->func.fn_retset;
1300 * Evaluate the function's argument list.
1302 * Note: ideally, we'd do this in the per-tuple context, but then the
1303 * argument values would disappear when we reset the context in the
1304 * inner loop. So do it in caller context. Perhaps we should make a
1305 * separate context just to hold the evaluated arguments?
1307 fcinfo.flinfo = &(fcache->func);
1308 argDone = ExecEvalFuncArgs(&fcinfo, fcache->args, econtext);
1309 /* We don't allow sets in the arguments of the table function */
1310 if (argDone != ExprSingleResult)
1312 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1313 errmsg("set-valued function called in context that cannot accept a set")));
1316 * If function is strict, and there are any NULL arguments, skip
1317 * calling the function and act like it returned NULL (or an empty
1318 * set, in the returns-set case).
1320 if (fcache->func.fn_strict)
1324 for (i = 0; i < fcinfo.nargs; i++)
1326 if (fcinfo.argnull[i])
1327 goto no_function_result;
1333 /* Treat funcexpr as a generic expression */
1334 direct_function_call = false;
1338 * Switch to short-lived context for calling the function or expression.
1340 MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
1343 * Loop to handle the ValuePerCall protocol (which is also the same
1344 * behavior needed in the generic ExecEvalExpr path).
1351 CHECK_FOR_INTERRUPTS();
1354 * reset per-tuple memory context before each call of the function or
1355 * expression. This cleans up any local memory the function may leak
1358 ResetExprContext(econtext);
1360 /* Call the function or expression one time */
1361 if (direct_function_call)
1363 fcinfo.isnull = false;
1364 rsinfo.isDone = ExprSingleResult;
1365 result = FunctionCallInvoke(&fcinfo);
1369 result = ExecEvalExpr(funcexpr, econtext,
1370 &fcinfo.isnull, &rsinfo.isDone);
1373 /* Which protocol does function want to use? */
1374 if (rsinfo.returnMode == SFRM_ValuePerCall)
1377 * Check for end of result set.
1379 if (rsinfo.isDone == ExprEndResult)
1383 * Can't do anything very useful with NULL rowtype values. For a
1384 * function returning set, we consider this a protocol violation
1385 * (but another alternative would be to just ignore the result and
1386 * "continue" to get another row). For a function not returning
1387 * set, we fall out of the loop; we'll cons up an all-nulls result
1390 if (returnsTuple && fcinfo.isnull)
1395 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1396 errmsg("function returning set of rows cannot return null value")));
1400 * If first time through, build tupdesc and tuplestore for result
1404 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1408 * Use the type info embedded in the rowtype Datum to look
1409 * up the needed tupdesc. Make a copy for the query.
1413 td = DatumGetHeapTupleHeader(result);
1414 tupdesc = lookup_rowtype_tupdesc_copy(HeapTupleHeaderGetTypeId(td),
1415 HeapTupleHeaderGetTypMod(td));
1420 * Scalar type, so make a single-column descriptor
1422 tupdesc = CreateTemplateTupleDesc(1, false);
1423 TupleDescInitEntry(tupdesc,
1430 tupstore = tuplestore_begin_heap(true, false, work_mem);
1431 MemoryContextSwitchTo(oldcontext);
1432 rsinfo.setResult = tupstore;
1433 rsinfo.setDesc = tupdesc;
1437 * Store current resultset item.
1443 td = DatumGetHeapTupleHeader(result);
1446 * tuplestore_puttuple needs a HeapTuple not a bare
1447 * HeapTupleHeader, but it doesn't need all the fields.
1449 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
1455 tuple = heap_form_tuple(tupdesc, &result, &fcinfo.isnull);
1458 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1459 tuplestore_puttuple(tupstore, tuple);
1460 MemoryContextSwitchTo(oldcontext);
1465 if (rsinfo.isDone != ExprMultipleResult)
1468 else if (rsinfo.returnMode == SFRM_Materialize)
1470 /* check we're on the same page as the function author */
1471 if (!first_time || rsinfo.isDone != ExprSingleResult)
1473 (errcode(ERRCODE_E_R_I_E_SRF_PROTOCOL_VIOLATED),
1474 errmsg("table-function protocol for materialize mode was not followed")));
1475 /* Done evaluating the set result */
1480 (errcode(ERRCODE_E_R_I_E_SRF_PROTOCOL_VIOLATED),
1481 errmsg("unrecognized table-function returnMode: %d",
1482 (int) rsinfo.returnMode)));
1490 * If we got nothing from the function (ie, an empty-set or NULL result),
1491 * we have to create the tuplestore to return, and if it's a
1492 * non-set-returning function then insert a single all-nulls row.
1494 if (rsinfo.setResult == NULL)
1496 MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1497 tupstore = tuplestore_begin_heap(true, false, work_mem);
1498 rsinfo.setResult = tupstore;
1501 int natts = expectedDesc->natts;
1506 MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
1507 nulldatums = (Datum *) palloc0(natts * sizeof(Datum));
1508 nullflags = (bool *) palloc(natts * sizeof(bool));
1509 memset(nullflags, true, natts * sizeof(bool));
1510 tuple = heap_form_tuple(expectedDesc, nulldatums, nullflags);
1511 MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1512 tuplestore_puttuple(tupstore, tuple);
1516 MemoryContextSwitchTo(callerContext);
1518 /* The returned pointers are those in rsinfo */
1519 *returnDesc = rsinfo.setDesc;
1520 return rsinfo.setResult;
1524 /* ----------------------------------------------------------------
1528 * Evaluate the functional result of a list of arguments by calling the
1530 * ----------------------------------------------------------------
1533 /* ----------------------------------------------------------------
1535 * ----------------------------------------------------------------
1538 ExecEvalFunc(FuncExprState *fcache,
1539 ExprContext *econtext,
1541 ExprDoneCond *isDone)
1543 /* This is called only the first time through */
1544 FuncExpr *func = (FuncExpr *) fcache->xprstate.expr;
1546 /* Initialize function lookup info */
1547 init_fcache(func->funcid, fcache, econtext->ecxt_per_query_memory);
1549 /* Go directly to ExecMakeFunctionResult on subsequent uses */
1550 fcache->xprstate.evalfunc = (ExprStateEvalFunc) ExecMakeFunctionResult;
1552 return ExecMakeFunctionResult(fcache, econtext, isNull, isDone);
1555 /* ----------------------------------------------------------------
1557 * ----------------------------------------------------------------
1560 ExecEvalOper(FuncExprState *fcache,
1561 ExprContext *econtext,
1563 ExprDoneCond *isDone)
1565 /* This is called only the first time through */
1566 OpExpr *op = (OpExpr *) fcache->xprstate.expr;
1568 /* Initialize function lookup info */
1569 init_fcache(op->opfuncid, fcache, econtext->ecxt_per_query_memory);
1571 /* Go directly to ExecMakeFunctionResult on subsequent uses */
1572 fcache->xprstate.evalfunc = (ExprStateEvalFunc) ExecMakeFunctionResult;
1574 return ExecMakeFunctionResult(fcache, econtext, isNull, isDone);
1577 /* ----------------------------------------------------------------
1580 * IS DISTINCT FROM must evaluate arguments to determine whether
1581 * they are NULL; if either is NULL then the result is already
1582 * known. If neither is NULL, then proceed to evaluate the
1583 * function. Note that this is *always* derived from the equals
1584 * operator, but since we need special processing of the arguments
1585 * we can not simply reuse ExecEvalOper() or ExecEvalFunc().
1586 * ----------------------------------------------------------------
1589 ExecEvalDistinct(FuncExprState *fcache,
1590 ExprContext *econtext,
1592 ExprDoneCond *isDone)
1595 FunctionCallInfoData fcinfo;
1596 ExprDoneCond argDone;
1599 /* Set default values for result flags: non-null, not a set result */
1602 *isDone = ExprSingleResult;
1605 * Initialize function cache if first time through
1607 if (fcache->func.fn_oid == InvalidOid)
1609 DistinctExpr *op = (DistinctExpr *) fcache->xprstate.expr;
1611 init_fcache(op->opfuncid, fcache, econtext->ecxt_per_query_memory);
1612 Assert(!fcache->func.fn_retset);
1616 * extract info from fcache
1618 argList = fcache->args;
1620 /* Need to prep callinfo structure */
1621 InitFunctionCallInfoData(fcinfo, &(fcache->func), 0, NULL, NULL);
1622 argDone = ExecEvalFuncArgs(&fcinfo, argList, econtext);
1623 if (argDone != ExprSingleResult)
1625 (errcode(ERRCODE_DATATYPE_MISMATCH),
1626 errmsg("IS DISTINCT FROM does not support set arguments")));
1627 Assert(fcinfo.nargs == 2);
1629 if (fcinfo.argnull[0] && fcinfo.argnull[1])
1631 /* Both NULL? Then is not distinct... */
1632 result = BoolGetDatum(FALSE);
1634 else if (fcinfo.argnull[0] || fcinfo.argnull[1])
1636 /* Only one is NULL? Then is distinct... */
1637 result = BoolGetDatum(TRUE);
1641 fcinfo.isnull = false;
1642 result = FunctionCallInvoke(&fcinfo);
1643 *isNull = fcinfo.isnull;
1644 /* Must invert result of "=" */
1645 result = BoolGetDatum(!DatumGetBool(result));
1652 * ExecEvalScalarArrayOp
1654 * Evaluate "scalar op ANY/ALL (array)". The operator always yields boolean,
1655 * and we combine the results across all array elements using OR and AND
1656 * (for ANY and ALL respectively). Of course we short-circuit as soon as
1657 * the result is known.
1660 ExecEvalScalarArrayOp(ScalarArrayOpExprState *sstate,
1661 ExprContext *econtext,
1662 bool *isNull, ExprDoneCond *isDone)
1664 ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) sstate->fxprstate.xprstate.expr;
1665 bool useOr = opexpr->useOr;
1670 FunctionCallInfoData fcinfo;
1671 ExprDoneCond argDone;
1680 /* Set default values for result flags: non-null, not a set result */
1683 *isDone = ExprSingleResult;
1686 * Initialize function cache if first time through
1688 if (sstate->fxprstate.func.fn_oid == InvalidOid)
1690 init_fcache(opexpr->opfuncid, &sstate->fxprstate,
1691 econtext->ecxt_per_query_memory);
1692 Assert(!sstate->fxprstate.func.fn_retset);
1695 /* Need to prep callinfo structure */
1696 InitFunctionCallInfoData(fcinfo, &(sstate->fxprstate.func), 0, NULL, NULL);
1697 argDone = ExecEvalFuncArgs(&fcinfo, sstate->fxprstate.args, econtext);
1698 if (argDone != ExprSingleResult)
1700 (errcode(ERRCODE_DATATYPE_MISMATCH),
1701 errmsg("op ANY/ALL (array) does not support set arguments")));
1702 Assert(fcinfo.nargs == 2);
1705 * If the array is NULL then we return NULL --- it's not very meaningful
1706 * to do anything else, even if the operator isn't strict.
1708 if (fcinfo.argnull[1])
1713 /* Else okay to fetch and detoast the array */
1714 arr = DatumGetArrayTypeP(fcinfo.arg[1]);
1717 * If the array is empty, we return either FALSE or TRUE per the useOr
1718 * flag. This is correct even if the scalar is NULL; since we would
1719 * evaluate the operator zero times, it matters not whether it would want
1722 nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr));
1724 return BoolGetDatum(!useOr);
1727 * If the scalar is NULL, and the function is strict, return NULL; no
1728 * point in iterating the loop.
1730 if (fcinfo.argnull[0] && sstate->fxprstate.func.fn_strict)
1737 * We arrange to look up info about the element type only once per series
1738 * of calls, assuming the element type doesn't change underneath us.
1740 if (sstate->element_type != ARR_ELEMTYPE(arr))
1742 get_typlenbyvalalign(ARR_ELEMTYPE(arr),
1746 sstate->element_type = ARR_ELEMTYPE(arr);
1748 typlen = sstate->typlen;
1749 typbyval = sstate->typbyval;
1750 typalign = sstate->typalign;
1752 result = BoolGetDatum(!useOr);
1755 /* Loop over the array elements */
1756 s = (char *) ARR_DATA_PTR(arr);
1757 bitmap = ARR_NULLBITMAP(arr);
1760 for (i = 0; i < nitems; i++)
1765 /* Get array element, checking for NULL */
1766 if (bitmap && (*bitmap & bitmask) == 0)
1768 fcinfo.arg[1] = (Datum) 0;
1769 fcinfo.argnull[1] = true;
1773 elt = fetch_att(s, typbyval, typlen);
1774 s = att_addlength(s, typlen, PointerGetDatum(s));
1775 s = (char *) att_align(s, typalign);
1776 fcinfo.arg[1] = elt;
1777 fcinfo.argnull[1] = false;
1780 /* Call comparison function */
1781 if (fcinfo.argnull[1] && sstate->fxprstate.func.fn_strict)
1783 fcinfo.isnull = true;
1784 thisresult = (Datum) 0;
1788 fcinfo.isnull = false;
1789 thisresult = FunctionCallInvoke(&fcinfo);
1792 /* Combine results per OR or AND semantics */
1797 if (DatumGetBool(thisresult))
1799 result = BoolGetDatum(true);
1801 break; /* needn't look at any more elements */
1806 if (!DatumGetBool(thisresult))
1808 result = BoolGetDatum(false);
1810 break; /* needn't look at any more elements */
1814 /* advance bitmap pointer if any */
1818 if (bitmask == 0x100)
1826 *isNull = resultnull;
1830 /* ----------------------------------------------------------------
1835 * Evaluate boolean expressions, with appropriate short-circuiting.
1837 * The query planner reformulates clause expressions in the
1838 * qualification to conjunctive normal form. If we ever get
1839 * an AND to evaluate, we can be sure that it's not a top-level
1840 * clause in the qualification, but appears lower (as a function
1841 * argument, for example), or in the target list. Not that you
1842 * need to know this, mind you...
1843 * ----------------------------------------------------------------
1846 ExecEvalNot(BoolExprState *notclause, ExprContext *econtext,
1847 bool *isNull, ExprDoneCond *isDone)
1849 ExprState *clause = linitial(notclause->args);
1853 *isDone = ExprSingleResult;
1855 expr_value = ExecEvalExpr(clause, econtext, isNull, NULL);
1858 * if the expression evaluates to null, then we just cascade the null back
1859 * to whoever called us.
1865 * evaluation of 'not' is simple.. expr is false, then return 'true' and
1868 return BoolGetDatum(!DatumGetBool(expr_value));
1871 /* ----------------------------------------------------------------
1873 * ----------------------------------------------------------------
1876 ExecEvalOr(BoolExprState *orExpr, ExprContext *econtext,
1877 bool *isNull, ExprDoneCond *isDone)
1879 List *clauses = orExpr->args;
1884 *isDone = ExprSingleResult;
1889 * If any of the clauses is TRUE, the OR result is TRUE regardless of the
1890 * states of the rest of the clauses, so we can stop evaluating and return
1891 * TRUE immediately. If none are TRUE and one or more is NULL, we return
1892 * NULL; otherwise we return FALSE. This makes sense when you interpret
1893 * NULL as "don't know": if we have a TRUE then the OR is TRUE even if we
1894 * aren't sure about some of the other inputs. If all the known inputs are
1895 * FALSE, but we have one or more "don't knows", then we have to report
1896 * that we "don't know" what the OR's result should be --- perhaps one of
1897 * the "don't knows" would have been TRUE if we'd known its value. Only
1898 * when all the inputs are known to be FALSE can we state confidently that
1899 * the OR's result is FALSE.
1901 foreach(clause, clauses)
1903 ExprState *clausestate = (ExprState *) lfirst(clause);
1906 clause_value = ExecEvalExpr(clausestate, econtext, isNull, NULL);
1909 * if we have a non-null true result, then return it.
1912 AnyNull = true; /* remember we got a null */
1913 else if (DatumGetBool(clause_value))
1914 return clause_value;
1917 /* AnyNull is true if at least one clause evaluated to NULL */
1919 return BoolGetDatum(false);
1922 /* ----------------------------------------------------------------
1924 * ----------------------------------------------------------------
1927 ExecEvalAnd(BoolExprState *andExpr, ExprContext *econtext,
1928 bool *isNull, ExprDoneCond *isDone)
1930 List *clauses = andExpr->args;
1935 *isDone = ExprSingleResult;
1940 * If any of the clauses is FALSE, the AND result is FALSE regardless of
1941 * the states of the rest of the clauses, so we can stop evaluating and
1942 * return FALSE immediately. If none are FALSE and one or more is NULL,
1943 * we return NULL; otherwise we return TRUE. This makes sense when you
1944 * interpret NULL as "don't know", using the same sort of reasoning as for
1948 foreach(clause, clauses)
1950 ExprState *clausestate = (ExprState *) lfirst(clause);
1953 clause_value = ExecEvalExpr(clausestate, econtext, isNull, NULL);
1956 * if we have a non-null false result, then return it.
1959 AnyNull = true; /* remember we got a null */
1960 else if (!DatumGetBool(clause_value))
1961 return clause_value;
1964 /* AnyNull is true if at least one clause evaluated to NULL */
1966 return BoolGetDatum(!AnyNull);
1969 /* ----------------------------------------------------------------
1970 * ExecEvalConvertRowtype
1972 * Evaluate a rowtype coercion operation. This may require
1973 * rearranging field positions.
1974 * ----------------------------------------------------------------
1977 ExecEvalConvertRowtype(ConvertRowtypeExprState *cstate,
1978 ExprContext *econtext,
1979 bool *isNull, ExprDoneCond *isDone)
1981 ConvertRowtypeExpr *convert = (ConvertRowtypeExpr *) cstate->xprstate.expr;
1984 HeapTupleHeader tuple;
1985 HeapTupleData tmptup;
1986 AttrNumber *attrMap;
1994 tupDatum = ExecEvalExpr(cstate->arg, econtext, isNull, isDone);
1996 /* this test covers the isDone exception too: */
2000 tuple = DatumGetHeapTupleHeader(tupDatum);
2002 /* Lookup tupdescs if first time through or after rescan */
2003 if (cstate->indesc == NULL)
2004 get_cached_rowtype(exprType((Node *) convert->arg), -1,
2005 &cstate->indesc, econtext);
2006 if (cstate->outdesc == NULL)
2007 get_cached_rowtype(convert->resulttype, -1,
2008 &cstate->outdesc, econtext);
2010 Assert(HeapTupleHeaderGetTypeId(tuple) == cstate->indesc->tdtypeid);
2011 Assert(HeapTupleHeaderGetTypMod(tuple) == cstate->indesc->tdtypmod);
2013 /* if first time through, initialize */
2014 if (cstate->attrMap == NULL)
2016 MemoryContext old_cxt;
2019 /* allocate state in long-lived memory context */
2020 old_cxt = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
2022 /* prepare map from old to new attribute numbers */
2023 n = cstate->outdesc->natts;
2024 cstate->attrMap = (AttrNumber *) palloc0(n * sizeof(AttrNumber));
2025 for (i = 0; i < n; i++)
2027 Form_pg_attribute att = cstate->outdesc->attrs[i];
2033 if (att->attisdropped)
2034 continue; /* attrMap[i] is already 0 */
2035 attname = NameStr(att->attname);
2036 atttypid = att->atttypid;
2037 atttypmod = att->atttypmod;
2038 for (j = 0; j < cstate->indesc->natts; j++)
2040 att = cstate->indesc->attrs[j];
2041 if (att->attisdropped)
2043 if (strcmp(attname, NameStr(att->attname)) == 0)
2045 /* Found it, check type */
2046 if (atttypid != att->atttypid || atttypmod != att->atttypmod)
2047 elog(ERROR, "attribute \"%s\" of type %s does not match corresponding attribute of type %s",
2049 format_type_be(cstate->indesc->tdtypeid),
2050 format_type_be(cstate->outdesc->tdtypeid));
2051 cstate->attrMap[i] = (AttrNumber) (j + 1);
2055 if (cstate->attrMap[i] == 0)
2056 elog(ERROR, "attribute \"%s\" of type %s does not exist",
2058 format_type_be(cstate->indesc->tdtypeid));
2060 /* preallocate workspace for Datum arrays */
2061 n = cstate->indesc->natts + 1; /* +1 for NULL */
2062 cstate->invalues = (Datum *) palloc(n * sizeof(Datum));
2063 cstate->inisnull = (bool *) palloc(n * sizeof(bool));
2064 n = cstate->outdesc->natts;
2065 cstate->outvalues = (Datum *) palloc(n * sizeof(Datum));
2066 cstate->outisnull = (bool *) palloc(n * sizeof(bool));
2068 MemoryContextSwitchTo(old_cxt);
2071 attrMap = cstate->attrMap;
2072 invalues = cstate->invalues;
2073 inisnull = cstate->inisnull;
2074 outvalues = cstate->outvalues;
2075 outisnull = cstate->outisnull;
2076 outnatts = cstate->outdesc->natts;
2079 * heap_deform_tuple needs a HeapTuple not a bare HeapTupleHeader.
2081 tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
2082 tmptup.t_data = tuple;
2085 * Extract all the values of the old tuple, offsetting the arrays so that
2086 * invalues[0] is NULL and invalues[1] is the first source attribute; this
2087 * exactly matches the numbering convention in attrMap.
2089 heap_deform_tuple(&tmptup, cstate->indesc, invalues + 1, inisnull + 1);
2090 invalues[0] = (Datum) 0;
2094 * Transpose into proper fields of the new tuple.
2096 for (i = 0; i < outnatts; i++)
2100 outvalues[i] = invalues[j];
2101 outisnull[i] = inisnull[j];
2105 * Now form the new tuple.
2107 result = heap_form_tuple(cstate->outdesc, outvalues, outisnull);
2109 return HeapTupleGetDatum(result);
2112 /* ----------------------------------------------------------------
2115 * Evaluate a CASE clause. Will have boolean expressions
2116 * inside the WHEN clauses, and will have expressions
2118 * - thomas 1998-11-09
2119 * ----------------------------------------------------------------
2122 ExecEvalCase(CaseExprState *caseExpr, ExprContext *econtext,
2123 bool *isNull, ExprDoneCond *isDone)
2125 List *clauses = caseExpr->args;
2131 *isDone = ExprSingleResult;
2134 * If there's a test expression, we have to evaluate it and save the value
2135 * where the CaseTestExpr placeholders can find it. We must save and
2136 * restore prior setting of econtext's caseValue fields, in case this node
2137 * is itself within a larger CASE.
2139 save_datum = econtext->caseValue_datum;
2140 save_isNull = econtext->caseValue_isNull;
2144 econtext->caseValue_datum = ExecEvalExpr(caseExpr->arg,
2146 &econtext->caseValue_isNull,
2151 * we evaluate each of the WHEN clauses in turn, as soon as one is true we
2152 * return the corresponding result. If none are true then we return the
2153 * value of the default clause, or NULL if there is none.
2155 foreach(clause, clauses)
2157 CaseWhenState *wclause = lfirst(clause);
2160 clause_value = ExecEvalExpr(wclause->expr,
2166 * if we have a true test, then we return the result, since the case
2167 * statement is satisfied. A NULL result from the test is not
2170 if (DatumGetBool(clause_value) && !*isNull)
2172 econtext->caseValue_datum = save_datum;
2173 econtext->caseValue_isNull = save_isNull;
2174 return ExecEvalExpr(wclause->result,
2181 econtext->caseValue_datum = save_datum;
2182 econtext->caseValue_isNull = save_isNull;
2184 if (caseExpr->defresult)
2186 return ExecEvalExpr(caseExpr->defresult,
2197 * ExecEvalCaseTestExpr
2199 * Return the value stored by CASE.
2202 ExecEvalCaseTestExpr(ExprState *exprstate,
2203 ExprContext *econtext,
2204 bool *isNull, ExprDoneCond *isDone)
2207 *isDone = ExprSingleResult;
2208 *isNull = econtext->caseValue_isNull;
2209 return econtext->caseValue_datum;
2212 /* ----------------------------------------------------------------
2213 * ExecEvalArray - ARRAY[] expressions
2214 * ----------------------------------------------------------------
2217 ExecEvalArray(ArrayExprState *astate, ExprContext *econtext,
2218 bool *isNull, ExprDoneCond *isDone)
2220 ArrayExpr *arrayExpr = (ArrayExpr *) astate->xprstate.expr;
2223 Oid element_type = arrayExpr->element_typeid;
2228 /* Set default values for result flags: non-null, not a set result */
2231 *isDone = ExprSingleResult;
2233 if (!arrayExpr->multidims)
2235 /* Elements are presumably of scalar type */
2242 nelems = list_length(astate->elements);
2244 /* Shouldn't happen here, but if length is 0, return empty array */
2246 return PointerGetDatum(construct_empty_array(element_type));
2248 dvalues = (Datum *) palloc(nelems * sizeof(Datum));
2249 dnulls = (bool *) palloc(nelems * sizeof(bool));
2251 /* loop through and build array of datums */
2252 foreach(element, astate->elements)
2254 ExprState *e = (ExprState *) lfirst(element);
2256 dvalues[i] = ExecEvalExpr(e, econtext, &dnulls[i], NULL);
2260 /* setup for 1-D array of the given length */
2264 result = construct_md_array(dvalues, dnulls, ndims, dims, lbs,
2272 /* Must be nested array expressions */
2275 int outer_nelems = 0;
2277 int *elem_dims = NULL;
2278 int *elem_lbs = NULL;
2279 bool firstone = true;
2280 bool havenulls = false;
2281 bool haveempty = false;
2291 i = list_length(astate->elements);
2292 subdata = (char **) palloc(i * sizeof(char *));
2293 subbitmaps = (bits8 **) palloc(i * sizeof(bits8 *));
2294 subbytes = (int *) palloc(i * sizeof(int));
2295 subnitems = (int *) palloc(i * sizeof(int));
2297 /* loop through and get data area from each element */
2298 foreach(element, astate->elements)
2300 ExprState *e = (ExprState *) lfirst(element);
2306 arraydatum = ExecEvalExpr(e, econtext, &eisnull, NULL);
2307 /* temporarily ignore null subarrays */
2314 array = DatumGetArrayTypeP(arraydatum);
2316 /* run-time double-check on element type */
2317 if (element_type != ARR_ELEMTYPE(array))
2319 (errcode(ERRCODE_DATATYPE_MISMATCH),
2320 errmsg("cannot merge incompatible arrays"),
2321 errdetail("Array with element type %s cannot be "
2322 "included in ARRAY construct with element type %s.",
2323 format_type_be(ARR_ELEMTYPE(array)),
2324 format_type_be(element_type))));
2326 this_ndims = ARR_NDIM(array);
2327 /* temporarily ignore zero-dimensional subarrays */
2328 if (this_ndims <= 0)
2336 /* Get sub-array details from first member */
2337 elem_ndims = this_ndims;
2338 ndims = elem_ndims + 1;
2339 if (ndims <= 0 || ndims > MAXDIM)
2341 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
2342 errmsg("number of array dimensions (%d) exceeds " \
2343 "the maximum allowed (%d)", ndims, MAXDIM)));
2345 elem_dims = (int *) palloc(elem_ndims * sizeof(int));
2346 memcpy(elem_dims, ARR_DIMS(array), elem_ndims * sizeof(int));
2347 elem_lbs = (int *) palloc(elem_ndims * sizeof(int));
2348 memcpy(elem_lbs, ARR_LBOUND(array), elem_ndims * sizeof(int));
2354 /* Check other sub-arrays are compatible */
2355 if (elem_ndims != this_ndims ||
2356 memcmp(elem_dims, ARR_DIMS(array),
2357 elem_ndims * sizeof(int)) != 0 ||
2358 memcmp(elem_lbs, ARR_LBOUND(array),
2359 elem_ndims * sizeof(int)) != 0)
2361 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2362 errmsg("multidimensional arrays must have array "
2363 "expressions with matching dimensions")));
2366 subdata[outer_nelems] = ARR_DATA_PTR(array);
2367 subbitmaps[outer_nelems] = ARR_NULLBITMAP(array);
2368 subbytes[outer_nelems] = ARR_SIZE(array) - ARR_DATA_OFFSET(array);
2369 nbytes += subbytes[outer_nelems];
2370 subnitems[outer_nelems] = ArrayGetNItems(this_ndims,
2372 nitems += subnitems[outer_nelems];
2373 havenulls |= ARR_HASNULL(array);
2378 * If all items were null or empty arrays, return an empty array;
2379 * otherwise, if some were and some weren't, raise error. (Note:
2380 * we must special-case this somehow to avoid trying to generate
2381 * a 1-D array formed from empty arrays. It's not ideal...)
2385 if (ndims == 0) /* didn't find any nonempty array */
2386 return PointerGetDatum(construct_empty_array(element_type));
2388 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2389 errmsg("multidimensional arrays must have array "
2390 "expressions with matching dimensions")));
2393 /* setup for multi-D array */
2394 dims[0] = outer_nelems;
2396 for (i = 1; i < ndims; i++)
2398 dims[i] = elem_dims[i - 1];
2399 lbs[i] = elem_lbs[i - 1];
2404 dataoffset = ARR_OVERHEAD_WITHNULLS(ndims, nitems);
2405 nbytes += dataoffset;
2409 dataoffset = 0; /* marker for no null bitmap */
2410 nbytes += ARR_OVERHEAD_NONULLS(ndims);
2413 result = (ArrayType *) palloc(nbytes);
2414 result->size = nbytes;
2415 result->ndim = ndims;
2416 result->dataoffset = dataoffset;
2417 result->elemtype = element_type;
2418 memcpy(ARR_DIMS(result), dims, ndims * sizeof(int));
2419 memcpy(ARR_LBOUND(result), lbs, ndims * sizeof(int));
2421 dat = ARR_DATA_PTR(result);
2423 for (i = 0; i < outer_nelems; i++)
2425 memcpy(dat, subdata[i], subbytes[i]);
2428 array_bitmap_copy(ARR_NULLBITMAP(result), iitem,
2431 iitem += subnitems[i];
2435 return PointerGetDatum(result);
2438 /* ----------------------------------------------------------------
2439 * ExecEvalRow - ROW() expressions
2440 * ----------------------------------------------------------------
2443 ExecEvalRow(RowExprState *rstate,
2444 ExprContext *econtext,
2445 bool *isNull, ExprDoneCond *isDone)
2454 /* Set default values for result flags: non-null, not a set result */
2457 *isDone = ExprSingleResult;
2459 /* Allocate workspace */
2460 natts = rstate->tupdesc->natts;
2461 values = (Datum *) palloc0(natts * sizeof(Datum));
2462 isnull = (bool *) palloc(natts * sizeof(bool));
2464 /* preset to nulls in case rowtype has some later-added columns */
2465 memset(isnull, true, natts * sizeof(bool));
2467 /* Evaluate field values */
2469 foreach(arg, rstate->args)
2471 ExprState *e = (ExprState *) lfirst(arg);
2473 values[i] = ExecEvalExpr(e, econtext, &isnull[i], NULL);
2477 tuple = heap_form_tuple(rstate->tupdesc, values, isnull);
2482 return HeapTupleGetDatum(tuple);
2485 /* ----------------------------------------------------------------
2486 * ExecEvalRowCompare - ROW() comparison-op ROW()
2487 * ----------------------------------------------------------------
2490 ExecEvalRowCompare(RowCompareExprState *rstate,
2491 ExprContext *econtext,
2492 bool *isNull, ExprDoneCond *isDone)
2495 RowCompareType rctype = ((RowCompareExpr *) rstate->xprstate.expr)->rctype;
2496 int32 cmpresult = 0;
2502 *isDone = ExprSingleResult;
2503 *isNull = true; /* until we get a result */
2506 forboth(l, rstate->largs, r, rstate->rargs)
2508 ExprState *le = (ExprState *) lfirst(l);
2509 ExprState *re = (ExprState *) lfirst(r);
2510 FunctionCallInfoData locfcinfo;
2512 InitFunctionCallInfoData(locfcinfo, &(rstate->funcs[i]), 2,
2514 locfcinfo.arg[0] = ExecEvalExpr(le, econtext,
2515 &locfcinfo.argnull[0], NULL);
2516 locfcinfo.arg[1] = ExecEvalExpr(re, econtext,
2517 &locfcinfo.argnull[1], NULL);
2518 if (rstate->funcs[i].fn_strict &&
2519 (locfcinfo.argnull[0] || locfcinfo.argnull[1]))
2520 return (Datum) 0; /* force NULL result */
2521 locfcinfo.isnull = false;
2522 cmpresult = DatumGetInt32(FunctionCallInvoke(&locfcinfo));
2523 if (locfcinfo.isnull)
2524 return (Datum) 0; /* force NULL result */
2526 break; /* no need to compare remaining columns */
2532 /* EQ and NE cases aren't allowed here */
2534 result = (cmpresult < 0);
2537 result = (cmpresult <= 0);
2540 result = (cmpresult >= 0);
2543 result = (cmpresult > 0);
2546 elog(ERROR, "unrecognized RowCompareType: %d", (int) rctype);
2547 result = 0; /* keep compiler quiet */
2552 return BoolGetDatum(result);
2555 /* ----------------------------------------------------------------
2557 * ----------------------------------------------------------------
2560 ExecEvalCoalesce(CoalesceExprState *coalesceExpr, ExprContext *econtext,
2561 bool *isNull, ExprDoneCond *isDone)
2566 *isDone = ExprSingleResult;
2568 /* Simply loop through until something NOT NULL is found */
2569 foreach(arg, coalesceExpr->args)
2571 ExprState *e = (ExprState *) lfirst(arg);
2574 value = ExecEvalExpr(e, econtext, isNull, NULL);
2579 /* Else return NULL */
2584 /* ----------------------------------------------------------------
2586 * ----------------------------------------------------------------
2589 ExecEvalMinMax(MinMaxExprState *minmaxExpr, ExprContext *econtext,
2590 bool *isNull, ExprDoneCond *isDone)
2592 Datum result = (Datum) 0;
2593 MinMaxOp op = ((MinMaxExpr *) minmaxExpr->xprstate.expr)->op;
2594 FunctionCallInfoData locfcinfo;
2598 *isDone = ExprSingleResult;
2599 *isNull = true; /* until we get a result */
2601 InitFunctionCallInfoData(locfcinfo, &minmaxExpr->cfunc, 2, NULL, NULL);
2602 locfcinfo.argnull[0] = false;
2603 locfcinfo.argnull[1] = false;
2605 foreach(arg, minmaxExpr->args)
2607 ExprState *e = (ExprState *) lfirst(arg);
2612 value = ExecEvalExpr(e, econtext, &valueIsNull, NULL);
2614 continue; /* ignore NULL inputs */
2618 /* first nonnull input, adopt value */
2624 /* apply comparison function */
2625 locfcinfo.arg[0] = result;
2626 locfcinfo.arg[1] = value;
2627 locfcinfo.isnull = false;
2628 cmpresult = DatumGetInt32(FunctionCallInvoke(&locfcinfo));
2629 if (locfcinfo.isnull) /* probably should not happen */
2631 if (cmpresult > 0 && op == IS_LEAST)
2633 else if (cmpresult < 0 && op == IS_GREATEST)
2641 /* ----------------------------------------------------------------
2643 * ----------------------------------------------------------------
2646 ExecEvalXml(XmlExprState *xmlExpr, ExprContext *econtext,
2647 bool *isNull, ExprDoneCond *isDone)
2649 XmlExpr *xexpr = (XmlExpr *) xmlExpr->xprstate.expr;
2660 *isDone = ExprSingleResult;
2661 *isNull = true; /* until we get a result */
2666 initStringInfo(&buf);
2667 foreach(arg, xmlExpr->args)
2669 ExprState *e = (ExprState *) lfirst(arg);
2671 value = ExecEvalExpr(e, econtext, &isnull, NULL);
2674 /* we know the value is XML type */
2675 str = DatumGetCString(DirectFunctionCall1(xml_out,
2677 appendStringInfoString(&buf, str);
2685 initStringInfo(&buf);
2687 forboth(arg, xmlExpr->named_args, narg, xexpr->arg_names)
2689 ExprState *e = (ExprState *) lfirst(arg);
2690 char *argname = strVal(lfirst(narg));
2692 value = ExecEvalExpr(e, econtext, &isnull, NULL);
2695 str = OutputFunctionCall(&xmlExpr->named_outfuncs[i],
2697 appendStringInfo(&buf, "<%s>%s</%s>",
2698 argname, str, argname);
2706 /* The remaining cases don't need to set up buf */
2709 return PointerGetDatum(xmlelement(xmlExpr, econtext));
2717 bool preserve_whitespace;
2719 /* arguments are known to be text, bool, bool */
2720 Assert(list_length(xmlExpr->args) == 3);
2722 e = (ExprState *) linitial(xmlExpr->args);
2723 value = ExecEvalExpr(e, econtext, &isnull, NULL);
2726 data = DatumGetTextP(value);
2728 e = (ExprState *) lsecond(xmlExpr->args);
2729 value = ExecEvalExpr(e, econtext, &isnull, NULL);
2730 if (isnull) /* probably can't happen */
2732 is_document = DatumGetBool(value);
2734 e = (ExprState *) lthird(xmlExpr->args);
2735 value = ExecEvalExpr(e, econtext, &isnull, NULL);
2736 if (isnull) /* probably can't happen */
2738 preserve_whitespace = DatumGetBool(value);
2742 return PointerGetDatum(xmlparse(data,
2744 preserve_whitespace));
2753 /* optional argument is known to be text */
2754 Assert(list_length(xmlExpr->args) <= 1);
2758 e = (ExprState *) linitial(xmlExpr->args);
2759 value = ExecEvalExpr(e, econtext, &isnull, NULL);
2763 arg = DatumGetTextP(value);
2771 return PointerGetDatum(xmlpi(xexpr->name, arg, isnull, isNull));
2782 /* arguments are known to be xml, text, bool */
2783 Assert(list_length(xmlExpr->args) == 3);
2785 e = (ExprState *) linitial(xmlExpr->args);
2786 value = ExecEvalExpr(e, econtext, &isnull, NULL);
2789 data = DatumGetXmlP(value);
2791 e = (ExprState *) lsecond(xmlExpr->args);
2792 value = ExecEvalExpr(e, econtext, &isnull, NULL);
2796 version = DatumGetTextP(value);
2798 e = (ExprState *) lthird(xmlExpr->args);
2799 value = ExecEvalExpr(e, econtext, &isnull, NULL);
2803 standalone = (DatumGetBool(value) ? 1 : -1);
2807 return PointerGetDatum(xmlroot(data,
2818 int len = buf.len + VARHDRSZ;
2820 result = palloc(len);
2821 VARATT_SIZEP(result) = len;
2822 memcpy(VARDATA(result), buf.data, buf.len);
2826 return PointerGetDatum(result);
2829 /* ----------------------------------------------------------------
2832 * Note that this is *always* derived from the equals operator,
2833 * but since we need special processing of the arguments
2834 * we can not simply reuse ExecEvalOper() or ExecEvalFunc().
2835 * ----------------------------------------------------------------
2838 ExecEvalNullIf(FuncExprState *nullIfExpr,
2839 ExprContext *econtext,
2840 bool *isNull, ExprDoneCond *isDone)
2843 FunctionCallInfoData fcinfo;
2844 ExprDoneCond argDone;
2848 *isDone = ExprSingleResult;
2851 * Initialize function cache if first time through
2853 if (nullIfExpr->func.fn_oid == InvalidOid)
2855 NullIfExpr *op = (NullIfExpr *) nullIfExpr->xprstate.expr;
2857 init_fcache(op->opfuncid, nullIfExpr, econtext->ecxt_per_query_memory);
2858 Assert(!nullIfExpr->func.fn_retset);
2862 * extract info from nullIfExpr
2864 argList = nullIfExpr->args;
2866 /* Need to prep callinfo structure */
2867 InitFunctionCallInfoData(fcinfo, &(nullIfExpr->func), 0, NULL, NULL);
2868 argDone = ExecEvalFuncArgs(&fcinfo, argList, econtext);
2869 if (argDone != ExprSingleResult)
2871 (errcode(ERRCODE_DATATYPE_MISMATCH),
2872 errmsg("NULLIF does not support set arguments")));
2873 Assert(fcinfo.nargs == 2);
2875 /* if either argument is NULL they can't be equal */
2876 if (!fcinfo.argnull[0] && !fcinfo.argnull[1])
2878 fcinfo.isnull = false;
2879 result = FunctionCallInvoke(&fcinfo);
2880 /* if the arguments are equal return null */
2881 if (!fcinfo.isnull && DatumGetBool(result))
2888 /* else return first argument */
2889 *isNull = fcinfo.argnull[0];
2890 return fcinfo.arg[0];
2893 /* ----------------------------------------------------------------
2896 * Evaluate a NullTest node.
2897 * ----------------------------------------------------------------
2900 ExecEvalNullTest(NullTestState *nstate,
2901 ExprContext *econtext,
2903 ExprDoneCond *isDone)
2905 NullTest *ntest = (NullTest *) nstate->xprstate.expr;
2908 result = ExecEvalExpr(nstate->arg, econtext, isNull, isDone);
2910 if (isDone && *isDone == ExprEndResult)
2911 return result; /* nothing to check */
2913 if (nstate->argisrow && !(*isNull))
2915 HeapTupleHeader tuple;
2919 HeapTupleData tmptup;
2922 tuple = DatumGetHeapTupleHeader(result);
2924 tupType = HeapTupleHeaderGetTypeId(tuple);
2925 tupTypmod = HeapTupleHeaderGetTypMod(tuple);
2927 /* Lookup tupdesc if first time through or if type changes */
2928 tupDesc = get_cached_rowtype(tupType, tupTypmod,
2929 &nstate->argdesc, econtext);
2932 * heap_attisnull needs a HeapTuple not a bare HeapTupleHeader.
2934 tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
2935 tmptup.t_data = tuple;
2937 for (att = 1; att <= tupDesc->natts; att++)
2939 /* ignore dropped columns */
2940 if (tupDesc->attrs[att - 1]->attisdropped)
2942 if (heap_attisnull(&tmptup, att))
2944 /* null field disproves IS NOT NULL */
2945 if (ntest->nulltesttype == IS_NOT_NULL)
2946 return BoolGetDatum(false);
2950 /* non-null field disproves IS NULL */
2951 if (ntest->nulltesttype == IS_NULL)
2952 return BoolGetDatum(false);
2956 return BoolGetDatum(true);
2960 /* Simple scalar-argument case, or a null rowtype datum */
2961 switch (ntest->nulltesttype)
2967 return BoolGetDatum(true);
2970 return BoolGetDatum(false);
2975 return BoolGetDatum(false);
2978 return BoolGetDatum(true);
2980 elog(ERROR, "unrecognized nulltesttype: %d",
2981 (int) ntest->nulltesttype);
2982 return (Datum) 0; /* keep compiler quiet */
2987 /* ----------------------------------------------------------------
2988 * ExecEvalBooleanTest
2990 * Evaluate a BooleanTest node.
2991 * ----------------------------------------------------------------
2994 ExecEvalBooleanTest(GenericExprState *bstate,
2995 ExprContext *econtext,
2997 ExprDoneCond *isDone)
2999 BooleanTest *btest = (BooleanTest *) bstate->xprstate.expr;
3002 result = ExecEvalExpr(bstate->arg, econtext, isNull, isDone);
3004 if (isDone && *isDone == ExprEndResult)
3005 return result; /* nothing to check */
3007 switch (btest->booltesttype)
3013 return BoolGetDatum(false);
3015 else if (DatumGetBool(result))
3016 return BoolGetDatum(true);
3018 return BoolGetDatum(false);
3023 return BoolGetDatum(true);
3025 else if (DatumGetBool(result))
3026 return BoolGetDatum(false);
3028 return BoolGetDatum(true);
3033 return BoolGetDatum(false);
3035 else if (DatumGetBool(result))
3036 return BoolGetDatum(false);
3038 return BoolGetDatum(true);
3043 return BoolGetDatum(true);
3045 else if (DatumGetBool(result))
3046 return BoolGetDatum(true);
3048 return BoolGetDatum(false);
3053 return BoolGetDatum(true);
3056 return BoolGetDatum(false);
3057 case IS_NOT_UNKNOWN:
3061 return BoolGetDatum(false);
3064 return BoolGetDatum(true);
3066 elog(ERROR, "unrecognized booltesttype: %d",
3067 (int) btest->booltesttype);
3068 return (Datum) 0; /* keep compiler quiet */
3073 * ExecEvalCoerceToDomain
3075 * Test the provided data against the domain constraint(s). If the data
3076 * passes the constraint specifications, pass it through (return the
3077 * datum) otherwise throw an error.
3080 ExecEvalCoerceToDomain(CoerceToDomainState *cstate, ExprContext *econtext,
3081 bool *isNull, ExprDoneCond *isDone)
3083 CoerceToDomain *ctest = (CoerceToDomain *) cstate->xprstate.expr;
3087 result = ExecEvalExpr(cstate->arg, econtext, isNull, isDone);
3089 if (isDone && *isDone == ExprEndResult)
3090 return result; /* nothing to check */
3092 foreach(l, cstate->constraints)
3094 DomainConstraintState *con = (DomainConstraintState *) lfirst(l);
3096 switch (con->constrainttype)
3098 case DOM_CONSTRAINT_NOTNULL:
3101 (errcode(ERRCODE_NOT_NULL_VIOLATION),
3102 errmsg("domain %s does not allow null values",
3103 format_type_be(ctest->resulttype))));
3105 case DOM_CONSTRAINT_CHECK:
3113 * Set up value to be returned by CoerceToDomainValue
3114 * nodes. We must save and restore prior setting of
3115 * econtext's domainValue fields, in case this node is
3116 * itself within a check expression for another domain.
3118 save_datum = econtext->domainValue_datum;
3119 save_isNull = econtext->domainValue_isNull;
3121 econtext->domainValue_datum = result;
3122 econtext->domainValue_isNull = *isNull;
3124 conResult = ExecEvalExpr(con->check_expr,
3125 econtext, &conIsNull, NULL);
3128 !DatumGetBool(conResult))
3130 (errcode(ERRCODE_CHECK_VIOLATION),
3131 errmsg("value for domain %s violates check constraint \"%s\"",
3132 format_type_be(ctest->resulttype),
3134 econtext->domainValue_datum = save_datum;
3135 econtext->domainValue_isNull = save_isNull;
3140 elog(ERROR, "unrecognized constraint type: %d",
3141 (int) con->constrainttype);
3146 /* If all has gone well (constraints did not fail) return the datum */
3151 * ExecEvalCoerceToDomainValue
3153 * Return the value stored by CoerceToDomain.
3156 ExecEvalCoerceToDomainValue(ExprState *exprstate,
3157 ExprContext *econtext,
3158 bool *isNull, ExprDoneCond *isDone)
3161 *isDone = ExprSingleResult;
3162 *isNull = econtext->domainValue_isNull;
3163 return econtext->domainValue_datum;
3166 /* ----------------------------------------------------------------
3167 * ExecEvalFieldSelect
3169 * Evaluate a FieldSelect node.
3170 * ----------------------------------------------------------------
3173 ExecEvalFieldSelect(FieldSelectState *fstate,
3174 ExprContext *econtext,
3176 ExprDoneCond *isDone)
3178 FieldSelect *fselect = (FieldSelect *) fstate->xprstate.expr;
3181 HeapTupleHeader tuple;
3185 HeapTupleData tmptup;
3187 tupDatum = ExecEvalExpr(fstate->arg, econtext, isNull, isDone);
3189 /* this test covers the isDone exception too: */
3193 tuple = DatumGetHeapTupleHeader(tupDatum);
3195 tupType = HeapTupleHeaderGetTypeId(tuple);
3196 tupTypmod = HeapTupleHeaderGetTypMod(tuple);
3198 /* Lookup tupdesc if first time through or if type changes */
3199 tupDesc = get_cached_rowtype(tupType, tupTypmod,
3200 &fstate->argdesc, econtext);
3203 * heap_getattr needs a HeapTuple not a bare HeapTupleHeader. We set all
3204 * the fields in the struct just in case user tries to inspect system
3207 tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
3208 ItemPointerSetInvalid(&(tmptup.t_self));
3209 tmptup.t_tableOid = InvalidOid;
3210 tmptup.t_data = tuple;
3212 result = heap_getattr(&tmptup,
3219 /* ----------------------------------------------------------------
3220 * ExecEvalFieldStore
3222 * Evaluate a FieldStore node.
3223 * ----------------------------------------------------------------
3226 ExecEvalFieldStore(FieldStoreState *fstate,
3227 ExprContext *econtext,
3229 ExprDoneCond *isDone)
3231 FieldStore *fstore = (FieldStore *) fstate->xprstate.expr;
3242 tupDatum = ExecEvalExpr(fstate->arg, econtext, isNull, isDone);
3244 if (isDone && *isDone == ExprEndResult)
3247 /* Lookup tupdesc if first time through or after rescan */
3248 tupDesc = get_cached_rowtype(fstore->resulttype, -1,
3249 &fstate->argdesc, econtext);
3251 /* Allocate workspace */
3252 values = (Datum *) palloc(tupDesc->natts * sizeof(Datum));
3253 isnull = (bool *) palloc(tupDesc->natts * sizeof(bool));
3258 * heap_deform_tuple needs a HeapTuple not a bare HeapTupleHeader. We
3259 * set all the fields in the struct just in case.
3261 HeapTupleHeader tuphdr;
3262 HeapTupleData tmptup;
3264 tuphdr = DatumGetHeapTupleHeader(tupDatum);
3265 tmptup.t_len = HeapTupleHeaderGetDatumLength(tuphdr);
3266 ItemPointerSetInvalid(&(tmptup.t_self));
3267 tmptup.t_tableOid = InvalidOid;
3268 tmptup.t_data = tuphdr;
3270 heap_deform_tuple(&tmptup, tupDesc, values, isnull);
3274 /* Convert null input tuple into an all-nulls row */
3275 memset(isnull, true, tupDesc->natts * sizeof(bool));
3278 /* Result is never null */
3281 save_datum = econtext->caseValue_datum;
3282 save_isNull = econtext->caseValue_isNull;
3284 forboth(l1, fstate->newvals, l2, fstore->fieldnums)
3286 ExprState *newval = (ExprState *) lfirst(l1);
3287 AttrNumber fieldnum = lfirst_int(l2);
3289 Assert(fieldnum > 0 && fieldnum <= tupDesc->natts);
3292 * Use the CaseTestExpr mechanism to pass down the old value of the
3293 * field being replaced; this is useful in case we have a nested field
3294 * update situation. It's safe to reuse the CASE mechanism because
3295 * there cannot be a CASE between here and where the value would be
3298 econtext->caseValue_datum = values[fieldnum - 1];
3299 econtext->caseValue_isNull = isnull[fieldnum - 1];
3301 values[fieldnum - 1] = ExecEvalExpr(newval,
3303 &isnull[fieldnum - 1],
3307 econtext->caseValue_datum = save_datum;
3308 econtext->caseValue_isNull = save_isNull;
3310 tuple = heap_form_tuple(tupDesc, values, isnull);
3315 return HeapTupleGetDatum(tuple);
3318 /* ----------------------------------------------------------------
3319 * ExecEvalRelabelType
3321 * Evaluate a RelabelType node.
3322 * ----------------------------------------------------------------
3325 ExecEvalRelabelType(GenericExprState *exprstate,
3326 ExprContext *econtext,
3327 bool *isNull, ExprDoneCond *isDone)
3329 return ExecEvalExpr(exprstate->arg, econtext, isNull, isDone);
3334 * ExecEvalExprSwitchContext
3336 * Same as ExecEvalExpr, but get into the right allocation context explicitly.
3339 ExecEvalExprSwitchContext(ExprState *expression,
3340 ExprContext *econtext,
3342 ExprDoneCond *isDone)
3345 MemoryContext oldContext;
3347 oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
3348 retDatum = ExecEvalExpr(expression, econtext, isNull, isDone);
3349 MemoryContextSwitchTo(oldContext);
3355 * ExecInitExpr: prepare an expression tree for execution
3357 * This function builds and returns an ExprState tree paralleling the given
3358 * Expr node tree. The ExprState tree can then be handed to ExecEvalExpr
3359 * for execution. Because the Expr tree itself is read-only as far as
3360 * ExecInitExpr and ExecEvalExpr are concerned, several different executions
3361 * of the same plan tree can occur concurrently.
3363 * This must be called in a memory context that will last as long as repeated
3364 * executions of the expression are needed. Typically the context will be
3365 * the same as the per-query context of the associated ExprContext.
3367 * Any Aggref and SubPlan nodes found in the tree are added to the lists
3368 * of such nodes held by the parent PlanState. Otherwise, we do very little
3369 * initialization here other than building the state-node tree. Any nontrivial
3370 * work associated with initializing runtime info for a node should happen
3371 * during the first actual evaluation of that node. (This policy lets us
3372 * avoid work if the node is never actually evaluated.)
3374 * Note: there is no ExecEndExpr function; we assume that any resource
3375 * cleanup needed will be handled by just releasing the memory context
3376 * in which the state tree is built. Functions that require additional
3377 * cleanup work can register a shutdown callback in the ExprContext.
3379 * 'node' is the root of the expression tree to examine
3380 * 'parent' is the PlanState node that owns the expression.
3382 * 'parent' may be NULL if we are preparing an expression that is not
3383 * associated with a plan tree. (If so, it can't have aggs or subplans.)
3384 * This case should usually come through ExecPrepareExpr, not directly here.
3387 ExecInitExpr(Expr *node, PlanState *parent)
3394 /* Guard against stack overflow due to overly complex expressions */
3395 check_stack_depth();
3397 switch (nodeTag(node))
3401 Var *var = (Var *) node;
3403 state = (ExprState *) makeNode(ExprState);
3404 if (var->varattno != InvalidAttrNumber)
3405 state->evalfunc = ExecEvalVar;
3407 state->evalfunc = ExecEvalWholeRowVar;
3411 state = (ExprState *) makeNode(ExprState);
3412 state->evalfunc = ExecEvalConst;
3415 state = (ExprState *) makeNode(ExprState);
3416 state->evalfunc = ExecEvalParam;
3418 case T_CoerceToDomainValue:
3419 state = (ExprState *) makeNode(ExprState);
3420 state->evalfunc = ExecEvalCoerceToDomainValue;
3422 case T_CaseTestExpr:
3423 state = (ExprState *) makeNode(ExprState);
3424 state->evalfunc = ExecEvalCaseTestExpr;
3428 Aggref *aggref = (Aggref *) node;
3429 AggrefExprState *astate = makeNode(AggrefExprState);
3431 astate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalAggref;
3432 if (parent && IsA(parent, AggState))
3434 AggState *aggstate = (AggState *) parent;
3437 aggstate->aggs = lcons(astate, aggstate->aggs);
3438 naggs = ++aggstate->numaggs;
3440 astate->args = (List *) ExecInitExpr((Expr *) aggref->args,
3444 * Complain if the aggregate's arguments contain any
3445 * aggregates; nested agg functions are semantically
3446 * nonsensical. (This should have been caught earlier,
3447 * but we defend against it here anyway.)
3449 if (naggs != aggstate->numaggs)
3451 (errcode(ERRCODE_GROUPING_ERROR),
3452 errmsg("aggregate function calls may not be nested")));
3456 /* planner messed up */
3457 elog(ERROR, "aggref found in non-Agg plan node");
3459 state = (ExprState *) astate;
3464 ArrayRef *aref = (ArrayRef *) node;
3465 ArrayRefExprState *astate = makeNode(ArrayRefExprState);
3467 astate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalArrayRef;
3468 astate->refupperindexpr = (List *)
3469 ExecInitExpr((Expr *) aref->refupperindexpr, parent);
3470 astate->reflowerindexpr = (List *)
3471 ExecInitExpr((Expr *) aref->reflowerindexpr, parent);
3472 astate->refexpr = ExecInitExpr(aref->refexpr, parent);
3473 astate->refassgnexpr = ExecInitExpr(aref->refassgnexpr,
3475 /* do one-time catalog lookups for type info */
3476 astate->refattrlength = get_typlen(aref->refarraytype);
3477 get_typlenbyvalalign(aref->refelemtype,
3478 &astate->refelemlength,
3479 &astate->refelembyval,
3480 &astate->refelemalign);
3481 state = (ExprState *) astate;
3486 FuncExpr *funcexpr = (FuncExpr *) node;
3487 FuncExprState *fstate = makeNode(FuncExprState);
3489 fstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalFunc;
3490 fstate->args = (List *)
3491 ExecInitExpr((Expr *) funcexpr->args, parent);
3492 fstate->func.fn_oid = InvalidOid; /* not initialized */
3493 state = (ExprState *) fstate;
3498 OpExpr *opexpr = (OpExpr *) node;
3499 FuncExprState *fstate = makeNode(FuncExprState);
3501 fstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalOper;
3502 fstate->args = (List *)
3503 ExecInitExpr((Expr *) opexpr->args, parent);
3504 fstate->func.fn_oid = InvalidOid; /* not initialized */
3505 state = (ExprState *) fstate;
3508 case T_DistinctExpr:
3510 DistinctExpr *distinctexpr = (DistinctExpr *) node;
3511 FuncExprState *fstate = makeNode(FuncExprState);
3513 fstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalDistinct;
3514 fstate->args = (List *)
3515 ExecInitExpr((Expr *) distinctexpr->args, parent);
3516 fstate->func.fn_oid = InvalidOid; /* not initialized */
3517 state = (ExprState *) fstate;
3520 case T_ScalarArrayOpExpr:
3522 ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) node;
3523 ScalarArrayOpExprState *sstate = makeNode(ScalarArrayOpExprState);
3525 sstate->fxprstate.xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalScalarArrayOp;
3526 sstate->fxprstate.args = (List *)
3527 ExecInitExpr((Expr *) opexpr->args, parent);
3528 sstate->fxprstate.func.fn_oid = InvalidOid; /* not initialized */
3529 sstate->element_type = InvalidOid; /* ditto */
3530 state = (ExprState *) sstate;
3535 BoolExpr *boolexpr = (BoolExpr *) node;
3536 BoolExprState *bstate = makeNode(BoolExprState);
3538 switch (boolexpr->boolop)
3541 bstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalAnd;
3544 bstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalOr;
3547 bstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalNot;
3550 elog(ERROR, "unrecognized boolop: %d",
3551 (int) boolexpr->boolop);
3554 bstate->args = (List *)
3555 ExecInitExpr((Expr *) boolexpr->args, parent);
3556 state = (ExprState *) bstate;
3561 /* Keep this in sync with ExecInitExprInitPlan, below */
3562 SubPlan *subplan = (SubPlan *) node;
3563 SubPlanState *sstate = makeNode(SubPlanState);
3565 sstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecSubPlan;
3568 elog(ERROR, "SubPlan found with no parent plan");
3571 * Here we just add the SubPlanState nodes to parent->subPlan.
3572 * The subplans will be initialized later.
3574 parent->subPlan = lcons(sstate, parent->subPlan);
3575 sstate->sub_estate = NULL;
3576 sstate->planstate = NULL;
3579 ExecInitExpr((Expr *) subplan->testexpr, parent);
3580 sstate->args = (List *)
3581 ExecInitExpr((Expr *) subplan->args, parent);
3583 state = (ExprState *) sstate;
3588 FieldSelect *fselect = (FieldSelect *) node;
3589 FieldSelectState *fstate = makeNode(FieldSelectState);
3591 fstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalFieldSelect;
3592 fstate->arg = ExecInitExpr(fselect->arg, parent);
3593 fstate->argdesc = NULL;
3594 state = (ExprState *) fstate;
3599 FieldStore *fstore = (FieldStore *) node;
3600 FieldStoreState *fstate = makeNode(FieldStoreState);
3602 fstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalFieldStore;
3603 fstate->arg = ExecInitExpr(fstore->arg, parent);
3604 fstate->newvals = (List *) ExecInitExpr((Expr *) fstore->newvals, parent);
3605 fstate->argdesc = NULL;
3606 state = (ExprState *) fstate;
3611 RelabelType *relabel = (RelabelType *) node;
3612 GenericExprState *gstate = makeNode(GenericExprState);
3614 gstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalRelabelType;
3615 gstate->arg = ExecInitExpr(relabel->arg, parent);
3616 state = (ExprState *) gstate;
3619 case T_ConvertRowtypeExpr:
3621 ConvertRowtypeExpr *convert = (ConvertRowtypeExpr *) node;
3622 ConvertRowtypeExprState *cstate = makeNode(ConvertRowtypeExprState);
3624 cstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalConvertRowtype;
3625 cstate->arg = ExecInitExpr(convert->arg, parent);
3626 state = (ExprState *) cstate;
3631 CaseExpr *caseexpr = (CaseExpr *) node;
3632 CaseExprState *cstate = makeNode(CaseExprState);
3633 List *outlist = NIL;
3636 cstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalCase;
3637 cstate->arg = ExecInitExpr(caseexpr->arg, parent);
3638 foreach(l, caseexpr->args)
3640 CaseWhen *when = (CaseWhen *) lfirst(l);
3641 CaseWhenState *wstate = makeNode(CaseWhenState);
3643 Assert(IsA(when, CaseWhen));
3644 wstate->xprstate.evalfunc = NULL; /* not used */
3645 wstate->xprstate.expr = (Expr *) when;
3646 wstate->expr = ExecInitExpr(when->expr, parent);
3647 wstate->result = ExecInitExpr(when->result, parent);
3648 outlist = lappend(outlist, wstate);
3650 cstate->args = outlist;
3651 cstate->defresult = ExecInitExpr(caseexpr->defresult, parent);
3652 state = (ExprState *) cstate;
3657 ArrayExpr *arrayexpr = (ArrayExpr *) node;
3658 ArrayExprState *astate = makeNode(ArrayExprState);
3659 List *outlist = NIL;
3662 astate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalArray;
3663 foreach(l, arrayexpr->elements)
3665 Expr *e = (Expr *) lfirst(l);
3668 estate = ExecInitExpr(e, parent);
3669 outlist = lappend(outlist, estate);
3671 astate->elements = outlist;
3672 /* do one-time catalog lookup for type info */
3673 get_typlenbyvalalign(arrayexpr->element_typeid,
3674 &astate->elemlength,
3676 &astate->elemalign);
3677 state = (ExprState *) astate;
3682 RowExpr *rowexpr = (RowExpr *) node;
3683 RowExprState *rstate = makeNode(RowExprState);
3684 Form_pg_attribute *attrs;
3685 List *outlist = NIL;
3689 rstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalRow;
3690 /* Build tupdesc to describe result tuples */
3691 if (rowexpr->row_typeid == RECORDOID)
3693 /* generic record, use runtime type assignment */
3694 rstate->tupdesc = ExecTypeFromExprList(rowexpr->args);
3695 BlessTupleDesc(rstate->tupdesc);
3696 /* we won't need to redo this at runtime */
3700 /* it's been cast to a named type, use that */
3701 rstate->tupdesc = lookup_rowtype_tupdesc_copy(rowexpr->row_typeid, -1);
3703 /* Set up evaluation, skipping any deleted columns */
3704 Assert(list_length(rowexpr->args) <= rstate->tupdesc->natts);
3705 attrs = rstate->tupdesc->attrs;
3707 foreach(l, rowexpr->args)
3709 Expr *e = (Expr *) lfirst(l);
3712 if (!attrs[i]->attisdropped)
3715 * Guard against ALTER COLUMN TYPE on rowtype since
3716 * the RowExpr was created. XXX should we check
3717 * typmod too? Not sure we can be sure it'll be the
3720 if (exprType((Node *) e) != attrs[i]->atttypid)
3722 (errcode(ERRCODE_DATATYPE_MISMATCH),
3723 errmsg("ROW() column has type %s instead of type %s",
3724 format_type_be(exprType((Node *) e)),
3725 format_type_be(attrs[i]->atttypid))));
3730 * Ignore original expression and insert a NULL. We
3731 * don't really care what type of NULL it is, so
3732 * always make an int4 NULL.
3734 e = (Expr *) makeNullConst(INT4OID);
3736 estate = ExecInitExpr(e, parent);
3737 outlist = lappend(outlist, estate);
3740 rstate->args = outlist;
3741 state = (ExprState *) rstate;
3744 case T_RowCompareExpr:
3746 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
3747 RowCompareExprState *rstate = makeNode(RowCompareExprState);
3748 int nopers = list_length(rcexpr->opnos);
3754 rstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalRowCompare;
3755 Assert(list_length(rcexpr->largs) == nopers);
3757 foreach(l, rcexpr->largs)
3759 Expr *e = (Expr *) lfirst(l);
3762 estate = ExecInitExpr(e, parent);
3763 outlist = lappend(outlist, estate);
3765 rstate->largs = outlist;
3766 Assert(list_length(rcexpr->rargs) == nopers);
3768 foreach(l, rcexpr->rargs)
3770 Expr *e = (Expr *) lfirst(l);
3773 estate = ExecInitExpr(e, parent);
3774 outlist = lappend(outlist, estate);
3776 rstate->rargs = outlist;
3777 Assert(list_length(rcexpr->opfamilies) == nopers);
3778 rstate->funcs = (FmgrInfo *) palloc(nopers * sizeof(FmgrInfo));
3780 forboth(l, rcexpr->opnos, l2, rcexpr->opfamilies)
3782 Oid opno = lfirst_oid(l);
3783 Oid opfamily = lfirst_oid(l2);
3790 get_op_opfamily_properties(opno, opfamily,
3795 proc = get_opfamily_proc(opfamily,
3801 * If we enforced permissions checks on index support
3802 * functions, we'd need to make a check here. But the
3803 * index support machinery doesn't do that, and neither
3806 fmgr_info(proc, &(rstate->funcs[i]));
3809 state = (ExprState *) rstate;
3812 case T_CoalesceExpr:
3814 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
3815 CoalesceExprState *cstate = makeNode(CoalesceExprState);
3816 List *outlist = NIL;
3819 cstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalCoalesce;
3820 foreach(l, coalesceexpr->args)
3822 Expr *e = (Expr *) lfirst(l);
3825 estate = ExecInitExpr(e, parent);
3826 outlist = lappend(outlist, estate);
3828 cstate->args = outlist;
3829 state = (ExprState *) cstate;
3834 MinMaxExpr *minmaxexpr = (MinMaxExpr *) node;
3835 MinMaxExprState *mstate = makeNode(MinMaxExprState);
3836 List *outlist = NIL;
3838 TypeCacheEntry *typentry;
3840 mstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalMinMax;
3841 foreach(l, minmaxexpr->args)
3843 Expr *e = (Expr *) lfirst(l);
3846 estate = ExecInitExpr(e, parent);
3847 outlist = lappend(outlist, estate);
3849 mstate->args = outlist;
3850 /* Look up the btree comparison function for the datatype */
3851 typentry = lookup_type_cache(minmaxexpr->minmaxtype,
3852 TYPECACHE_CMP_PROC);
3853 if (!OidIsValid(typentry->cmp_proc))
3855 (errcode(ERRCODE_UNDEFINED_FUNCTION),
3856 errmsg("could not identify a comparison function for type %s",
3857 format_type_be(minmaxexpr->minmaxtype))));
3860 * If we enforced permissions checks on index support
3861 * functions, we'd need to make a check here. But the index
3862 * support machinery doesn't do that, and neither does this
3865 fmgr_info(typentry->cmp_proc, &(mstate->cfunc));
3866 state = (ExprState *) mstate;
3871 XmlExpr *xexpr = (XmlExpr *) node;
3872 XmlExprState *xstate = makeNode(XmlExprState);
3877 xstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalXml;
3878 xstate->named_outfuncs = (FmgrInfo *)
3879 palloc0(list_length(xexpr->named_args) * sizeof(FmgrInfo));
3882 foreach(arg, xexpr->named_args)
3884 Expr *e = (Expr *) lfirst(arg);
3889 estate = ExecInitExpr(e, parent);
3890 outlist = lappend(outlist, estate);
3892 getTypeOutputInfo(exprType((Node *) e),
3893 &typOutFunc, &typIsVarlena);
3894 fmgr_info(typOutFunc, &xstate->named_outfuncs[i]);
3897 xstate->named_args = outlist;
3900 foreach(arg, xexpr->args)
3902 Expr *e = (Expr *) lfirst(arg);
3905 estate = ExecInitExpr(e, parent);
3906 outlist = lappend(outlist, estate);
3908 xstate->args = outlist;
3910 state = (ExprState *) xstate;
3915 NullIfExpr *nullifexpr = (NullIfExpr *) node;
3916 FuncExprState *fstate = makeNode(FuncExprState);
3918 fstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalNullIf;
3919 fstate->args = (List *)
3920 ExecInitExpr((Expr *) nullifexpr->args, parent);
3921 fstate->func.fn_oid = InvalidOid; /* not initialized */
3922 state = (ExprState *) fstate;
3927 NullTest *ntest = (NullTest *) node;
3928 NullTestState *nstate = makeNode(NullTestState);
3930 nstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalNullTest;
3931 nstate->arg = ExecInitExpr(ntest->arg, parent);
3932 nstate->argisrow = type_is_rowtype(exprType((Node *) ntest->arg));
3933 nstate->argdesc = NULL;
3934 state = (ExprState *) nstate;
3939 BooleanTest *btest = (BooleanTest *) node;
3940 GenericExprState *gstate = makeNode(GenericExprState);
3942 gstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalBooleanTest;
3943 gstate->arg = ExecInitExpr(btest->arg, parent);
3944 state = (ExprState *) gstate;
3947 case T_CoerceToDomain:
3949 CoerceToDomain *ctest = (CoerceToDomain *) node;
3950 CoerceToDomainState *cstate = makeNode(CoerceToDomainState);
3952 cstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalCoerceToDomain;
3953 cstate->arg = ExecInitExpr(ctest->arg, parent);
3954 cstate->constraints = GetDomainConstraints(ctest->resulttype);
3955 state = (ExprState *) cstate;
3960 TargetEntry *tle = (TargetEntry *) node;
3961 GenericExprState *gstate = makeNode(GenericExprState);
3963 gstate->xprstate.evalfunc = NULL; /* not used */
3964 gstate->arg = ExecInitExpr(tle->expr, parent);
3965 state = (ExprState *) gstate;
3970 List *outlist = NIL;
3973 foreach(l, (List *) node)
3975 outlist = lappend(outlist,
3976 ExecInitExpr((Expr *) lfirst(l),
3979 /* Don't fall through to the "common" code below */
3980 return (ExprState *) outlist;
3983 elog(ERROR, "unrecognized node type: %d",
3984 (int) nodeTag(node));
3985 state = NULL; /* keep compiler quiet */
3989 /* Common code for all state-node types */
3996 * ExecInitExprInitPlan --- initialize a subplan expr that's being handled
3997 * as an InitPlan. This is identical to ExecInitExpr's handling of a regular
3998 * subplan expr, except we do NOT want to add the node to the parent's
4002 ExecInitExprInitPlan(SubPlan *node, PlanState *parent)
4004 SubPlanState *sstate = makeNode(SubPlanState);
4007 elog(ERROR, "SubPlan found with no parent plan");
4009 /* The subplan's state will be initialized later */
4010 sstate->sub_estate = NULL;
4011 sstate->planstate = NULL;
4013 sstate->testexpr = ExecInitExpr((Expr *) node->testexpr, parent);
4014 sstate->args = (List *) ExecInitExpr((Expr *) node->args, parent);
4016 sstate->xprstate.expr = (Expr *) node;
4022 * ExecPrepareExpr --- initialize for expression execution outside a normal
4023 * Plan tree context.
4025 * This differs from ExecInitExpr in that we don't assume the caller is
4026 * already running in the EState's per-query context. Also, we apply
4027 * fix_opfuncids() to the passed expression tree to be sure it is ready
4028 * to run. (In ordinary Plan trees the planner will have fixed opfuncids,
4029 * but callers outside the executor will not have done this.)
4032 ExecPrepareExpr(Expr *node, EState *estate)
4035 MemoryContext oldcontext;
4037 fix_opfuncids((Node *) node);
4039 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
4041 result = ExecInitExpr(node, NULL);
4043 MemoryContextSwitchTo(oldcontext);
4049 /* ----------------------------------------------------------------
4050 * ExecQual / ExecTargetList / ExecProject
4051 * ----------------------------------------------------------------
4054 /* ----------------------------------------------------------------
4057 * Evaluates a conjunctive boolean expression (qual list) and
4058 * returns true iff none of the subexpressions are false.
4059 * (We also return true if the list is empty.)
4061 * If some of the subexpressions yield NULL but none yield FALSE,
4062 * then the result of the conjunction is NULL (ie, unknown)
4063 * according to three-valued boolean logic. In this case,
4064 * we return the value specified by the "resultForNull" parameter.
4066 * Callers evaluating WHERE clauses should pass resultForNull=FALSE,
4067 * since SQL specifies that tuples with null WHERE results do not
4068 * get selected. On the other hand, callers evaluating constraint
4069 * conditions should pass resultForNull=TRUE, since SQL also specifies
4070 * that NULL constraint conditions are not failures.
4072 * NOTE: it would not be correct to use this routine to evaluate an
4073 * AND subclause of a boolean expression; for that purpose, a NULL
4074 * result must be returned as NULL so that it can be properly treated
4075 * in the next higher operator (cf. ExecEvalAnd and ExecEvalOr).
4076 * This routine is only used in contexts where a complete expression
4077 * is being evaluated and we know that NULL can be treated the same
4078 * as one boolean result or the other.
4080 * ----------------------------------------------------------------
4083 ExecQual(List *qual, ExprContext *econtext, bool resultForNull)
4086 MemoryContext oldContext;
4092 EV_printf("ExecQual: qual is ");
4093 EV_nodeDisplay(qual);
4099 * Run in short-lived per-tuple context while computing expressions.
4101 oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
4104 * Evaluate the qual conditions one at a time. If we find a FALSE result,
4105 * we can stop evaluating and return FALSE --- the AND result must be
4106 * FALSE. Also, if we find a NULL result when resultForNull is FALSE, we
4107 * can stop and return FALSE --- the AND result must be FALSE or NULL in
4108 * that case, and the caller doesn't care which.
4110 * If we get to the end of the list, we can return TRUE. This will happen
4111 * when the AND result is indeed TRUE, or when the AND result is NULL (one
4112 * or more NULL subresult, with all the rest TRUE) and the caller has
4113 * specified resultForNull = TRUE.
4119 ExprState *clause = (ExprState *) lfirst(l);
4123 expr_value = ExecEvalExpr(clause, econtext, &isNull, NULL);
4127 if (resultForNull == false)
4129 result = false; /* treat NULL as FALSE */
4135 if (!DatumGetBool(expr_value))
4137 result = false; /* definitely FALSE */
4143 MemoryContextSwitchTo(oldContext);
4149 * Number of items in a tlist (including any resjunk items!)
4152 ExecTargetListLength(List *targetlist)
4154 /* This used to be more complex, but fjoins are dead */
4155 return list_length(targetlist);
4159 * Number of items in a tlist, not including any resjunk items
4162 ExecCleanTargetListLength(List *targetlist)
4167 foreach(tl, targetlist)
4169 TargetEntry *curTle = (TargetEntry *) lfirst(tl);
4171 Assert(IsA(curTle, TargetEntry));
4172 if (!curTle->resjunk)
4180 * Evaluates a targetlist with respect to the given
4181 * expression context. Returns TRUE if we were able to create
4182 * a result, FALSE if we have exhausted a set-valued expression.
4184 * Results are stored into the passed values and isnull arrays.
4185 * The caller must provide an itemIsDone array that persists across calls.
4187 * As with ExecEvalExpr, the caller should pass isDone = NULL if not
4188 * prepared to deal with sets of result tuples. Otherwise, a return
4189 * of *isDone = ExprMultipleResult signifies a set element, and a return
4190 * of *isDone = ExprEndResult signifies end of the set of tuple.
4193 ExecTargetList(List *targetlist,
4194 ExprContext *econtext,
4197 ExprDoneCond *itemIsDone,
4198 ExprDoneCond *isDone)
4200 MemoryContext oldContext;
4205 * Run in short-lived per-tuple context while computing expressions.
4207 oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
4210 * evaluate all the expressions in the target list
4213 *isDone = ExprSingleResult; /* until proven otherwise */
4215 haveDoneSets = false; /* any exhausted set exprs in tlist? */
4217 foreach(tl, targetlist)
4219 GenericExprState *gstate = (GenericExprState *) lfirst(tl);
4220 TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr;
4221 AttrNumber resind = tle->resno - 1;
4223 values[resind] = ExecEvalExpr(gstate->arg,
4226 &itemIsDone[resind]);
4228 if (itemIsDone[resind] != ExprSingleResult)
4230 /* We have a set-valued expression in the tlist */
4233 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4234 errmsg("set-valued function called in context that cannot accept a set")));
4235 if (itemIsDone[resind] == ExprMultipleResult)
4237 /* we have undone sets in the tlist, set flag */
4238 *isDone = ExprMultipleResult;
4242 /* we have done sets in the tlist, set flag for that */
4243 haveDoneSets = true;
4251 * note: can't get here unless we verified isDone != NULL
4253 if (*isDone == ExprSingleResult)
4256 * all sets are done, so report that tlist expansion is complete.
4258 *isDone = ExprEndResult;
4259 MemoryContextSwitchTo(oldContext);
4265 * We have some done and some undone sets. Restart the done ones
4266 * so that we can deliver a tuple (if possible).
4268 foreach(tl, targetlist)
4270 GenericExprState *gstate = (GenericExprState *) lfirst(tl);
4271 TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr;
4272 AttrNumber resind = tle->resno - 1;
4274 if (itemIsDone[resind] == ExprEndResult)
4276 values[resind] = ExecEvalExpr(gstate->arg,
4279 &itemIsDone[resind]);
4281 if (itemIsDone[resind] == ExprEndResult)
4284 * Oh dear, this item is returning an empty set. Guess
4285 * we can't make a tuple after all.
4287 *isDone = ExprEndResult;
4294 * If we cannot make a tuple because some sets are empty, we still
4295 * have to cycle the nonempty sets to completion, else resources
4296 * will not be released from subplans etc.
4298 * XXX is that still necessary?
4300 if (*isDone == ExprEndResult)
4302 foreach(tl, targetlist)
4304 GenericExprState *gstate = (GenericExprState *) lfirst(tl);
4305 TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr;
4306 AttrNumber resind = tle->resno - 1;
4308 while (itemIsDone[resind] == ExprMultipleResult)
4310 values[resind] = ExecEvalExpr(gstate->arg,
4313 &itemIsDone[resind]);
4317 MemoryContextSwitchTo(oldContext);
4323 /* Report success */
4324 MemoryContextSwitchTo(oldContext);
4331 * Evaluates a simple-Variable-list projection.
4333 * Results are stored into the passed values and isnull arrays.
4336 ExecVariableList(ProjectionInfo *projInfo,
4340 ExprContext *econtext = projInfo->pi_exprContext;
4341 int *varSlotOffsets = projInfo->pi_varSlotOffsets;
4342 int *varNumbers = projInfo->pi_varNumbers;
4346 * Force extraction of all input values that we need.
4348 if (projInfo->pi_lastInnerVar > 0)
4349 slot_getsomeattrs(econtext->ecxt_innertuple,
4350 projInfo->pi_lastInnerVar);
4351 if (projInfo->pi_lastOuterVar > 0)
4352 slot_getsomeattrs(econtext->ecxt_outertuple,
4353 projInfo->pi_lastOuterVar);
4354 if (projInfo->pi_lastScanVar > 0)
4355 slot_getsomeattrs(econtext->ecxt_scantuple,
4356 projInfo->pi_lastScanVar);
4359 * Assign to result by direct extraction of fields from source slots ... a
4360 * mite ugly, but fast ...
4362 for (i = list_length(projInfo->pi_targetlist) - 1; i >= 0; i--)
4364 char *slotptr = ((char *) econtext) + varSlotOffsets[i];
4365 TupleTableSlot *varSlot = *((TupleTableSlot **) slotptr);
4366 int varNumber = varNumbers[i] - 1;
4368 values[i] = varSlot->tts_values[varNumber];
4369 isnull[i] = varSlot->tts_isnull[varNumber];
4376 * projects a tuple based on projection info and stores
4377 * it in the previously specified tuple table slot.
4379 * Note: the result is always a virtual tuple; therefore it
4380 * may reference the contents of the exprContext's scan tuples
4381 * and/or temporary results constructed in the exprContext.
4382 * If the caller wishes the result to be valid longer than that
4383 * data will be valid, he must call ExecMaterializeSlot on the
4387 ExecProject(ProjectionInfo *projInfo, ExprDoneCond *isDone)
4389 TupleTableSlot *slot;
4394 Assert(projInfo != NULL);
4397 * get the projection info we want
4399 slot = projInfo->pi_slot;
4402 * Clear any former contents of the result slot. This makes it safe for
4403 * us to use the slot's Datum/isnull arrays as workspace. (Also, we can
4404 * return the slot as-is if we decide no rows can be projected.)
4406 ExecClearTuple(slot);
4409 * form a new result tuple (if possible); if successful, mark the result
4410 * slot as containing a valid virtual tuple
4412 if (projInfo->pi_isVarList)
4414 /* simple Var list: this always succeeds with one result row */
4416 *isDone = ExprSingleResult;
4417 ExecVariableList(projInfo,
4420 ExecStoreVirtualTuple(slot);
4424 if (ExecTargetList(projInfo->pi_targetlist,
4425 projInfo->pi_exprContext,
4428 projInfo->pi_itemIsDone,
4430 ExecStoreVirtualTuple(slot);