1 /*-------------------------------------------------------------------------
4 * Routines to evaluate qualification and targetlist expressions
6 * Portions Copyright (c) 1996-2006, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/executor/execQual.c,v 1.196 2006/10/06 17:13:59 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"
57 /* static function decls */
58 static Datum ExecEvalArrayRef(ArrayRefExprState *astate,
59 ExprContext *econtext,
60 bool *isNull, ExprDoneCond *isDone);
61 static Datum ExecEvalAggref(AggrefExprState *aggref,
62 ExprContext *econtext,
63 bool *isNull, ExprDoneCond *isDone);
64 static Datum ExecEvalVar(ExprState *exprstate, ExprContext *econtext,
65 bool *isNull, ExprDoneCond *isDone);
66 static Datum ExecEvalWholeRowVar(ExprState *exprstate, ExprContext *econtext,
67 bool *isNull, ExprDoneCond *isDone);
68 static Datum ExecEvalConst(ExprState *exprstate, ExprContext *econtext,
69 bool *isNull, ExprDoneCond *isDone);
70 static Datum ExecEvalParam(ExprState *exprstate, ExprContext *econtext,
71 bool *isNull, ExprDoneCond *isDone);
72 static void ShutdownFuncExpr(Datum arg);
73 static TupleDesc get_cached_rowtype(Oid type_id, int32 typmod,
74 TupleDesc *cache_field, ExprContext *econtext);
75 static void ShutdownTupleDescRef(Datum arg);
76 static ExprDoneCond ExecEvalFuncArgs(FunctionCallInfo fcinfo,
77 List *argList, ExprContext *econtext);
78 static Datum ExecMakeFunctionResultNoSets(FuncExprState *fcache,
79 ExprContext *econtext,
80 bool *isNull, ExprDoneCond *isDone);
81 static Datum ExecEvalFunc(FuncExprState *fcache, ExprContext *econtext,
82 bool *isNull, ExprDoneCond *isDone);
83 static Datum ExecEvalOper(FuncExprState *fcache, ExprContext *econtext,
84 bool *isNull, ExprDoneCond *isDone);
85 static Datum ExecEvalDistinct(FuncExprState *fcache, ExprContext *econtext,
86 bool *isNull, ExprDoneCond *isDone);
87 static Datum ExecEvalScalarArrayOp(ScalarArrayOpExprState *sstate,
88 ExprContext *econtext,
89 bool *isNull, ExprDoneCond *isDone);
90 static Datum ExecEvalNot(BoolExprState *notclause, ExprContext *econtext,
91 bool *isNull, ExprDoneCond *isDone);
92 static Datum ExecEvalOr(BoolExprState *orExpr, ExprContext *econtext,
93 bool *isNull, ExprDoneCond *isDone);
94 static Datum ExecEvalAnd(BoolExprState *andExpr, ExprContext *econtext,
95 bool *isNull, ExprDoneCond *isDone);
96 static Datum ExecEvalConvertRowtype(ConvertRowtypeExprState *cstate,
97 ExprContext *econtext,
98 bool *isNull, ExprDoneCond *isDone);
99 static Datum ExecEvalCase(CaseExprState *caseExpr, ExprContext *econtext,
100 bool *isNull, ExprDoneCond *isDone);
101 static Datum ExecEvalCaseTestExpr(ExprState *exprstate,
102 ExprContext *econtext,
103 bool *isNull, ExprDoneCond *isDone);
104 static Datum ExecEvalArray(ArrayExprState *astate,
105 ExprContext *econtext,
106 bool *isNull, ExprDoneCond *isDone);
107 static Datum ExecEvalRow(RowExprState *rstate,
108 ExprContext *econtext,
109 bool *isNull, ExprDoneCond *isDone);
110 static Datum ExecEvalRowCompare(RowCompareExprState *rstate,
111 ExprContext *econtext,
112 bool *isNull, ExprDoneCond *isDone);
113 static Datum ExecEvalCoalesce(CoalesceExprState *coalesceExpr,
114 ExprContext *econtext,
115 bool *isNull, ExprDoneCond *isDone);
116 static Datum ExecEvalMinMax(MinMaxExprState *minmaxExpr,
117 ExprContext *econtext,
118 bool *isNull, ExprDoneCond *isDone);
119 static Datum ExecEvalNullIf(FuncExprState *nullIfExpr,
120 ExprContext *econtext,
121 bool *isNull, ExprDoneCond *isDone);
122 static Datum ExecEvalNullTest(NullTestState *nstate,
123 ExprContext *econtext,
124 bool *isNull, ExprDoneCond *isDone);
125 static Datum ExecEvalBooleanTest(GenericExprState *bstate,
126 ExprContext *econtext,
127 bool *isNull, ExprDoneCond *isDone);
128 static Datum ExecEvalCoerceToDomain(CoerceToDomainState *cstate,
129 ExprContext *econtext,
130 bool *isNull, ExprDoneCond *isDone);
131 static Datum ExecEvalCoerceToDomainValue(ExprState *exprstate,
132 ExprContext *econtext,
133 bool *isNull, ExprDoneCond *isDone);
134 static Datum ExecEvalFieldSelect(FieldSelectState *fstate,
135 ExprContext *econtext,
136 bool *isNull, ExprDoneCond *isDone);
137 static Datum ExecEvalFieldStore(FieldStoreState *fstate,
138 ExprContext *econtext,
139 bool *isNull, ExprDoneCond *isDone);
140 static Datum ExecEvalRelabelType(GenericExprState *exprstate,
141 ExprContext *econtext,
142 bool *isNull, ExprDoneCond *isDone);
145 /* ----------------------------------------------------------------
146 * ExecEvalExpr routines
148 * Recursively evaluate a targetlist or qualification expression.
150 * Each of the following routines having the signature
151 * Datum ExecEvalFoo(ExprState *expression,
152 * ExprContext *econtext,
154 * ExprDoneCond *isDone);
155 * is responsible for evaluating one type or subtype of ExprState node.
156 * They are normally called via the ExecEvalExpr macro, which makes use of
157 * the function pointer set up when the ExprState node was built by
158 * ExecInitExpr. (In some cases, we change this pointer later to avoid
159 * re-executing one-time overhead.)
161 * Note: for notational simplicity we declare these functions as taking the
162 * specific type of ExprState that they work on. This requires casting when
163 * assigning the function pointer in ExecInitExpr. Be careful that the
164 * function signature is declared correctly, because the cast suppresses
165 * automatic checking!
168 * All these functions share this calling convention:
171 * expression: the expression state tree to evaluate
172 * econtext: evaluation context information
175 * return value: Datum value of result
176 * *isNull: set to TRUE if result is NULL (actual return value is
177 * meaningless if so); set to FALSE if non-null result
178 * *isDone: set to indicator of set-result status
180 * A caller that can only accept a singleton (non-set) result should pass
181 * NULL for isDone; if the expression computes a set result then an error
182 * will be reported via ereport. If the caller does pass an isDone pointer
183 * then *isDone is set to one of these three states:
184 * ExprSingleResult singleton result (not a set)
185 * ExprMultipleResult return value is one element of a set
186 * ExprEndResult there are no more elements in the set
187 * When ExprMultipleResult is returned, the caller should invoke
188 * ExecEvalExpr() repeatedly until ExprEndResult is returned. ExprEndResult
189 * is returned after the last real set element. For convenience isNull will
190 * always be set TRUE when ExprEndResult is returned, but this should not be
191 * taken as indicating a NULL element of the set. Note that these return
192 * conventions allow us to distinguish among a singleton NULL, a NULL element
193 * of a set, and an empty set.
195 * The caller should already have switched into the temporary memory
196 * context econtext->ecxt_per_tuple_memory. The convenience entry point
197 * ExecEvalExprSwitchContext() is provided for callers who don't prefer to
198 * do the switch in an outer loop. We do not do the switch in these routines
199 * because it'd be a waste of cycles during nested expression evaluation.
200 * ----------------------------------------------------------------
207 * This function takes an ArrayRef and returns the extracted Datum
208 * if it's a simple reference, or the modified array value if it's
209 * an array assignment (i.e., array element or slice insertion).
211 * NOTE: if we get a NULL result from a subscript expression, we return NULL
212 * when it's an array reference, or raise an error when it's an assignment.
214 * NOTE: we deliberately refrain from applying DatumGetArrayTypeP() here,
215 * even though that might seem natural, because this code needs to support
216 * both varlena arrays and fixed-length array types. DatumGetArrayTypeP()
217 * only works for the varlena kind. The routines we call in arrayfuncs.c
218 * have to know the difference (that's what they need refattrlength for).
222 ExecEvalArrayRef(ArrayRefExprState *astate,
223 ExprContext *econtext,
225 ExprDoneCond *isDone)
227 ArrayRef *arrayRef = (ArrayRef *) astate->xprstate.expr;
228 ArrayType *array_source;
229 ArrayType *resultArray;
230 bool isAssignment = (arrayRef->refassgnexpr != NULL);
239 array_source = (ArrayType *)
240 DatumGetPointer(ExecEvalExpr(astate->refexpr,
246 * If refexpr yields NULL, and it's a fetch, then result is NULL. In the
247 * assignment case, we'll cons up something below.
251 if (isDone && *isDone == ExprEndResult)
252 return (Datum) NULL; /* end of set result */
257 foreach(l, astate->refupperindexpr)
259 ExprState *eltstate = (ExprState *) lfirst(l);
263 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
264 errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
267 upper.indx[i++] = DatumGetInt32(ExecEvalExpr(eltstate,
271 /* If any index expr yields NULL, result is NULL or error */
276 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
277 errmsg("array subscript in assignment must not be null")));
283 if (astate->reflowerindexpr != NIL)
285 foreach(l, astate->reflowerindexpr)
287 ExprState *eltstate = (ExprState *) lfirst(l);
291 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
292 errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
295 lower.indx[j++] = DatumGetInt32(ExecEvalExpr(eltstate,
299 /* If any index expr yields NULL, result is NULL or error */
304 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
305 errmsg("array subscript in assignment must not be NULL")));
310 /* this can't happen unless parser messed up */
312 elog(ERROR, "upper and lower index lists are not same length");
323 * Evaluate the value to be assigned into the array.
325 * XXX At some point we'll need to look into making the old value of
326 * the array element available via CaseTestExpr, as is done by
327 * ExecEvalFieldStore. This is not needed now but will be needed to
328 * support arrays of composite types; in an assignment to a field of
329 * an array member, the parser would generate a FieldStore that
330 * expects to fetch its input tuple via CaseTestExpr.
332 sourceData = ExecEvalExpr(astate->refassgnexpr,
338 * For an assignment to a fixed-length array type, both the original
339 * array and the value to be assigned into it must be non-NULL, else
340 * we punt and return the original array.
342 if (astate->refattrlength > 0) /* fixed-length array? */
343 if (eisnull || *isNull)
344 return PointerGetDatum(array_source);
347 * For assignment to varlena arrays, we handle a NULL original array
348 * by substituting an empty (zero-dimensional) array; insertion of the
349 * new element will result in a singleton array value. It does not
350 * matter whether the new element is NULL.
354 array_source = construct_empty_array(arrayRef->refelemtype);
359 resultArray = array_set(array_source, i,
363 astate->refattrlength,
364 astate->refelemlength,
365 astate->refelembyval,
366 astate->refelemalign);
368 resultArray = array_set_slice(array_source, i,
369 upper.indx, lower.indx,
370 (ArrayType *) DatumGetPointer(sourceData),
372 astate->refattrlength,
373 astate->refelemlength,
374 astate->refelembyval,
375 astate->refelemalign);
376 return PointerGetDatum(resultArray);
380 return array_ref(array_source, i, upper.indx,
381 astate->refattrlength,
382 astate->refelemlength,
383 astate->refelembyval,
384 astate->refelemalign,
388 resultArray = array_get_slice(array_source, i,
389 upper.indx, lower.indx,
390 astate->refattrlength,
391 astate->refelemlength,
392 astate->refelembyval,
393 astate->refelemalign);
394 return PointerGetDatum(resultArray);
399 /* ----------------------------------------------------------------
402 * Returns a Datum whose value is the value of the precomputed
403 * aggregate found in the given expression context.
404 * ----------------------------------------------------------------
407 ExecEvalAggref(AggrefExprState *aggref, ExprContext *econtext,
408 bool *isNull, ExprDoneCond *isDone)
411 *isDone = ExprSingleResult;
413 if (econtext->ecxt_aggvalues == NULL) /* safety check */
414 elog(ERROR, "no aggregates in this expression context");
416 *isNull = econtext->ecxt_aggnulls[aggref->aggno];
417 return econtext->ecxt_aggvalues[aggref->aggno];
420 /* ----------------------------------------------------------------
423 * Returns a Datum whose value is the value of a range
424 * variable with respect to given expression context.
425 * ----------------------------------------------------------------
428 ExecEvalVar(ExprState *exprstate, ExprContext *econtext,
429 bool *isNull, ExprDoneCond *isDone)
431 Var *variable = (Var *) exprstate->expr;
432 TupleTableSlot *slot;
436 *isDone = ExprSingleResult;
439 * Get the slot and attribute number we want
441 * The asserts check that references to system attributes only appear at
442 * the level of a relation scan; at higher levels, system attributes must
443 * be treated as ordinary variables (since we no longer have access to the
446 attnum = variable->varattno;
448 switch (variable->varno)
450 case INNER: /* get the tuple from the inner node */
451 slot = econtext->ecxt_innertuple;
455 case OUTER: /* get the tuple from the outer node */
456 slot = econtext->ecxt_outertuple;
460 default: /* get the tuple from the relation being
462 slot = econtext->ecxt_scantuple;
466 #ifdef USE_ASSERT_CHECKING
469 * Some checks that are only applied for user attribute numbers (bogus
470 * system attnums will be caught inside slot_getattr).
474 TupleDesc tuple_type = slot->tts_tupleDescriptor;
477 * This assert checks that the attnum is valid.
479 Assert(attnum <= tuple_type->natts);
482 * This assert checks that the datatype the plan expects to get (as
483 * told by our "variable" argument) is in fact the datatype of the
484 * attribute being fetched (as seen in the current context, identified
485 * by our "econtext" argument). Otherwise crashes are likely.
487 * Note that we can't check dropped columns, since their atttypid has
490 Assert(variable->vartype == tuple_type->attrs[attnum - 1]->atttypid ||
491 tuple_type->attrs[attnum - 1]->attisdropped);
493 #endif /* USE_ASSERT_CHECKING */
495 return slot_getattr(slot, attnum, isNull);
498 /* ----------------------------------------------------------------
499 * ExecEvalWholeRowVar
501 * Returns a Datum for a whole-row variable.
503 * This could be folded into ExecEvalVar, but we make it a separate
504 * routine so as not to slow down ExecEvalVar with tests for this
506 * ----------------------------------------------------------------
509 ExecEvalWholeRowVar(ExprState *exprstate, ExprContext *econtext,
510 bool *isNull, ExprDoneCond *isDone)
512 Var *variable = (Var *) exprstate->expr;
513 TupleTableSlot *slot;
516 HeapTupleHeader dtuple;
519 *isDone = ExprSingleResult;
522 Assert(variable->varattno == InvalidAttrNumber);
525 * Whole-row Vars can only appear at the level of a relation scan, never
528 Assert(variable->varno != INNER);
529 Assert(variable->varno != OUTER);
530 slot = econtext->ecxt_scantuple;
532 tuple = ExecFetchSlotTuple(slot);
533 tupleDesc = slot->tts_tupleDescriptor;
536 * We have to make a copy of the tuple so we can safely insert the Datum
537 * overhead fields, which are not set in on-disk tuples.
539 dtuple = (HeapTupleHeader) palloc(tuple->t_len);
540 memcpy((char *) dtuple, (char *) tuple->t_data, tuple->t_len);
542 HeapTupleHeaderSetDatumLength(dtuple, tuple->t_len);
545 * If the Var identifies a named composite type, label the tuple with that
546 * type; otherwise use what is in the tupleDesc.
548 * It's likely that the slot's tupleDesc is a record type; if so, make
549 * sure it's been "blessed", so that the Datum can be interpreted later.
551 if (variable->vartype != RECORDOID)
553 HeapTupleHeaderSetTypeId(dtuple, variable->vartype);
554 HeapTupleHeaderSetTypMod(dtuple, variable->vartypmod);
558 if (tupleDesc->tdtypeid == RECORDOID &&
559 tupleDesc->tdtypmod < 0)
560 assign_record_type_typmod(tupleDesc);
561 HeapTupleHeaderSetTypeId(dtuple, tupleDesc->tdtypeid);
562 HeapTupleHeaderSetTypMod(dtuple, tupleDesc->tdtypmod);
565 return PointerGetDatum(dtuple);
568 /* ----------------------------------------------------------------
571 * Returns the value of a constant.
573 * Note that for pass-by-ref datatypes, we return a pointer to the
574 * actual constant node. This is one of the reasons why functions
575 * must treat their input arguments as read-only.
576 * ----------------------------------------------------------------
579 ExecEvalConst(ExprState *exprstate, ExprContext *econtext,
580 bool *isNull, ExprDoneCond *isDone)
582 Const *con = (Const *) exprstate->expr;
585 *isDone = ExprSingleResult;
587 *isNull = con->constisnull;
588 return con->constvalue;
591 /* ----------------------------------------------------------------
594 * Returns the value of a parameter. A param node contains
595 * something like ($.name) and the expression context contains
596 * the current parameter bindings (name = "sam") (age = 34)...
597 * so our job is to find and return the appropriate datum ("sam").
599 * Q: if we have a parameter ($.foo) without a binding, i.e.
600 * there is no (foo = xxx) in the parameter list info,
601 * is this a fatal error or should this be a "not available"
602 * (in which case we could return NULL)? -cim 10/13/89
603 * ----------------------------------------------------------------
606 ExecEvalParam(ExprState *exprstate, ExprContext *econtext,
607 bool *isNull, ExprDoneCond *isDone)
609 Param *expression = (Param *) exprstate->expr;
610 int thisParamId = expression->paramid;
613 *isDone = ExprSingleResult;
615 if (expression->paramkind == PARAM_EXEC)
618 * PARAM_EXEC params (internal executor parameters) are stored in the
619 * ecxt_param_exec_vals array, and can be accessed by array index.
623 prm = &(econtext->ecxt_param_exec_vals[thisParamId]);
624 if (prm->execPlan != NULL)
626 /* Parameter not evaluated yet, so go do it */
627 ExecSetParamPlan(prm->execPlan, econtext);
628 /* ExecSetParamPlan should have processed this param... */
629 Assert(prm->execPlan == NULL);
631 *isNull = prm->isnull;
637 * PARAM_EXTERN parameters must be sought in ecxt_param_list_info.
639 ParamListInfo paramInfo = econtext->ecxt_param_list_info;
641 Assert(expression->paramkind == PARAM_EXTERN);
643 thisParamId > 0 && thisParamId <= paramInfo->numParams)
645 ParamExternData *prm = ¶mInfo->params[thisParamId - 1];
647 if (OidIsValid(prm->ptype))
649 Assert(prm->ptype == expression->paramtype);
650 *isNull = prm->isnull;
655 (errcode(ERRCODE_UNDEFINED_OBJECT),
656 errmsg("no value found for parameter %d", thisParamId)));
657 return (Datum) 0; /* keep compiler quiet */
662 /* ----------------------------------------------------------------
663 * ExecEvalOper / ExecEvalFunc support routines
664 * ----------------------------------------------------------------
671 * These functions return the value of the requested attribute
672 * out of the given tuple Datum.
673 * C functions which take a tuple as an argument are expected
674 * to use these. Ex: overpaid(EMP) might call GetAttributeByNum().
675 * Note: these are actually rather slow because they do a typcache
676 * lookup on each call.
679 GetAttributeByNum(HeapTupleHeader tuple,
687 HeapTupleData tmptup;
689 if (!AttributeNumberIsValid(attrno))
690 elog(ERROR, "invalid attribute number %d", attrno);
693 elog(ERROR, "a NULL isNull pointer was passed");
697 /* Kinda bogus but compatible with old behavior... */
702 tupType = HeapTupleHeaderGetTypeId(tuple);
703 tupTypmod = HeapTupleHeaderGetTypMod(tuple);
704 tupDesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
707 * heap_getattr needs a HeapTuple not a bare HeapTupleHeader. We set all
708 * the fields in the struct just in case user tries to inspect system
711 tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
712 ItemPointerSetInvalid(&(tmptup.t_self));
713 tmptup.t_tableOid = InvalidOid;
714 tmptup.t_data = tuple;
716 result = heap_getattr(&tmptup,
721 ReleaseTupleDesc(tupDesc);
727 GetAttributeByName(HeapTupleHeader tuple, const char *attname, bool *isNull)
734 HeapTupleData tmptup;
738 elog(ERROR, "invalid attribute name");
741 elog(ERROR, "a NULL isNull pointer was passed");
745 /* Kinda bogus but compatible with old behavior... */
750 tupType = HeapTupleHeaderGetTypeId(tuple);
751 tupTypmod = HeapTupleHeaderGetTypMod(tuple);
752 tupDesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
754 attrno = InvalidAttrNumber;
755 for (i = 0; i < tupDesc->natts; i++)
757 if (namestrcmp(&(tupDesc->attrs[i]->attname), attname) == 0)
759 attrno = tupDesc->attrs[i]->attnum;
764 if (attrno == InvalidAttrNumber)
765 elog(ERROR, "attribute \"%s\" does not exist", attname);
768 * heap_getattr needs a HeapTuple not a bare HeapTupleHeader. We set all
769 * the fields in the struct just in case user tries to inspect system
772 tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
773 ItemPointerSetInvalid(&(tmptup.t_self));
774 tmptup.t_tableOid = InvalidOid;
775 tmptup.t_data = tuple;
777 result = heap_getattr(&tmptup,
782 ReleaseTupleDesc(tupDesc);
788 * init_fcache - initialize a FuncExprState node during first use
791 init_fcache(Oid foid, FuncExprState *fcache, MemoryContext fcacheCxt)
795 /* Check permission to call function */
796 aclresult = pg_proc_aclcheck(foid, GetUserId(), ACL_EXECUTE);
797 if (aclresult != ACLCHECK_OK)
798 aclcheck_error(aclresult, ACL_KIND_PROC, get_func_name(foid));
801 * Safety check on nargs. Under normal circumstances this should never
802 * fail, as parser should check sooner. But possibly it might fail if
803 * server has been compiled with FUNC_MAX_ARGS smaller than some functions
804 * declared in pg_proc?
806 if (list_length(fcache->args) > FUNC_MAX_ARGS)
808 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
809 errmsg("cannot pass more than %d arguments to a function",
812 /* Set up the primary fmgr lookup information */
813 fmgr_info_cxt(foid, &(fcache->func), fcacheCxt);
815 /* Initialize additional info */
816 fcache->setArgsValid = false;
817 fcache->shutdown_reg = false;
818 fcache->func.fn_expr = (Node *) fcache->xprstate.expr;
822 * callback function in case a FuncExpr returning a set needs to be shut down
823 * before it has been run to completion
826 ShutdownFuncExpr(Datum arg)
828 FuncExprState *fcache = (FuncExprState *) DatumGetPointer(arg);
830 /* Clear any active set-argument state */
831 fcache->setArgsValid = false;
833 /* execUtils will deregister the callback... */
834 fcache->shutdown_reg = false;
838 * get_cached_rowtype: utility function to lookup a rowtype tupdesc
840 * type_id, typmod: identity of the rowtype
841 * cache_field: where to cache the TupleDesc pointer in expression state node
842 * (field must be initialized to NULL)
843 * econtext: expression context we are executing in
845 * NOTE: because the shutdown callback will be called during plan rescan,
846 * must be prepared to re-do this during any node execution; cannot call
847 * just once during expression initialization
850 get_cached_rowtype(Oid type_id, int32 typmod,
851 TupleDesc *cache_field, ExprContext *econtext)
853 TupleDesc tupDesc = *cache_field;
855 /* Do lookup if no cached value or if requested type changed */
856 if (tupDesc == NULL ||
857 type_id != tupDesc->tdtypeid ||
858 typmod != tupDesc->tdtypmod)
860 tupDesc = lookup_rowtype_tupdesc(type_id, typmod);
864 /* Release old tupdesc; but callback is already registered */
865 ReleaseTupleDesc(*cache_field);
869 /* Need to register shutdown callback to release tupdesc */
870 RegisterExprContextCallback(econtext,
871 ShutdownTupleDescRef,
872 PointerGetDatum(cache_field));
874 *cache_field = tupDesc;
880 * Callback function to release a tupdesc refcount at expression tree shutdown
883 ShutdownTupleDescRef(Datum arg)
885 TupleDesc *cache_field = (TupleDesc *) DatumGetPointer(arg);
888 ReleaseTupleDesc(*cache_field);
893 * Evaluate arguments for a function.
896 ExecEvalFuncArgs(FunctionCallInfo fcinfo,
898 ExprContext *econtext)
900 ExprDoneCond argIsDone;
904 argIsDone = ExprSingleResult; /* default assumption */
907 foreach(arg, argList)
909 ExprState *argstate = (ExprState *) lfirst(arg);
910 ExprDoneCond thisArgIsDone;
912 fcinfo->arg[i] = ExecEvalExpr(argstate,
917 if (thisArgIsDone != ExprSingleResult)
920 * We allow only one argument to have a set value; we'd need much
921 * more complexity to keep track of multiple set arguments (cf.
922 * ExecTargetList) and it doesn't seem worth it.
924 if (argIsDone != ExprSingleResult)
926 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
927 errmsg("functions and operators can take at most one set argument")));
928 argIsDone = thisArgIsDone;
939 * ExecMakeFunctionResult
941 * Evaluate the arguments to a function and then the function itself.
944 ExecMakeFunctionResult(FuncExprState *fcache,
945 ExprContext *econtext,
947 ExprDoneCond *isDone)
949 List *arguments = fcache->args;
951 FunctionCallInfoData fcinfo;
952 ReturnSetInfo rsinfo; /* for functions returning sets */
953 ExprDoneCond argDone;
957 /* Guard against stack overflow due to overly complex expressions */
961 * arguments is a list of expressions to evaluate before passing to the
962 * function manager. We skip the evaluation if it was already done in the
963 * previous call (ie, we are continuing the evaluation of a set-valued
964 * function). Otherwise, collect the current argument values into fcinfo.
966 if (!fcache->setArgsValid)
968 /* Need to prep callinfo structure */
969 InitFunctionCallInfoData(fcinfo, &(fcache->func), 0, NULL, NULL);
970 argDone = ExecEvalFuncArgs(&fcinfo, arguments, econtext);
971 if (argDone == ExprEndResult)
973 /* input is an empty set, so return an empty set. */
976 *isDone = ExprEndResult;
979 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
980 errmsg("set-valued function called in context that cannot accept a set")));
983 hasSetArg = (argDone != ExprSingleResult);
987 /* Copy callinfo from previous evaluation */
988 memcpy(&fcinfo, &fcache->setArgs, sizeof(fcinfo));
989 hasSetArg = fcache->setHasSetArg;
990 /* Reset flag (we may set it again below) */
991 fcache->setArgsValid = false;
995 * If function returns set, prepare a resultinfo node for communication
997 if (fcache->func.fn_retset)
999 fcinfo.resultinfo = (Node *) &rsinfo;
1000 rsinfo.type = T_ReturnSetInfo;
1001 rsinfo.econtext = econtext;
1002 rsinfo.expectedDesc = NULL;
1003 rsinfo.allowedModes = (int) SFRM_ValuePerCall;
1004 rsinfo.returnMode = SFRM_ValuePerCall;
1005 /* isDone is filled below */
1006 rsinfo.setResult = NULL;
1007 rsinfo.setDesc = NULL;
1011 * now return the value gotten by calling the function manager, passing
1012 * the function the evaluated parameter values.
1014 if (fcache->func.fn_retset || hasSetArg)
1017 * We need to return a set result. Complain if caller not ready to
1022 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1023 errmsg("set-valued function called in context that cannot accept a set")));
1026 * This loop handles the situation where we have both a set argument
1027 * and a set-valued function. Once we have exhausted the function's
1028 * value(s) for a particular argument value, we have to get the next
1029 * argument value and start the function over again. We might have to
1030 * do it more than once, if the function produces an empty result set
1031 * for a particular input value.
1036 * If function is strict, and there are any NULL arguments, skip
1037 * calling the function (at least for this set of args).
1041 if (fcache->func.fn_strict)
1043 for (i = 0; i < fcinfo.nargs; i++)
1045 if (fcinfo.argnull[i])
1055 fcinfo.isnull = false;
1056 rsinfo.isDone = ExprSingleResult;
1057 result = FunctionCallInvoke(&fcinfo);
1058 *isNull = fcinfo.isnull;
1059 *isDone = rsinfo.isDone;
1065 *isDone = ExprEndResult;
1068 if (*isDone != ExprEndResult)
1071 * Got a result from current argument. If function itself
1072 * returns set, save the current argument values to re-use on
1075 if (fcache->func.fn_retset && *isDone == ExprMultipleResult)
1077 memcpy(&fcache->setArgs, &fcinfo, sizeof(fcinfo));
1078 fcache->setHasSetArg = hasSetArg;
1079 fcache->setArgsValid = true;
1080 /* Register cleanup callback if we didn't already */
1081 if (!fcache->shutdown_reg)
1083 RegisterExprContextCallback(econtext,
1085 PointerGetDatum(fcache));
1086 fcache->shutdown_reg = true;
1091 * Make sure we say we are returning a set, even if the
1092 * function itself doesn't return sets.
1095 *isDone = ExprMultipleResult;
1099 /* Else, done with this argument */
1101 break; /* input not a set, so done */
1103 /* Re-eval args to get the next element of the input set */
1104 argDone = ExecEvalFuncArgs(&fcinfo, arguments, econtext);
1106 if (argDone != ExprMultipleResult)
1108 /* End of argument set, so we're done. */
1110 *isDone = ExprEndResult;
1116 * If we reach here, loop around to run the function on the new
1124 * Non-set case: much easier.
1126 * We change the ExprState function pointer to use the simpler
1127 * ExecMakeFunctionResultNoSets on subsequent calls. This amounts to
1128 * assuming that no argument can return a set if it didn't do so the
1131 fcache->xprstate.evalfunc = (ExprStateEvalFunc) ExecMakeFunctionResultNoSets;
1134 *isDone = ExprSingleResult;
1137 * If function is strict, and there are any NULL arguments, skip
1138 * calling the function and return NULL.
1140 if (fcache->func.fn_strict)
1142 for (i = 0; i < fcinfo.nargs; i++)
1144 if (fcinfo.argnull[i])
1151 fcinfo.isnull = false;
1152 result = FunctionCallInvoke(&fcinfo);
1153 *isNull = fcinfo.isnull;
1160 * ExecMakeFunctionResultNoSets
1162 * Simplified version of ExecMakeFunctionResult that can only handle
1163 * non-set cases. Hand-tuned for speed.
1166 ExecMakeFunctionResultNoSets(FuncExprState *fcache,
1167 ExprContext *econtext,
1169 ExprDoneCond *isDone)
1173 FunctionCallInfoData fcinfo;
1176 /* Guard against stack overflow due to overly complex expressions */
1177 check_stack_depth();
1180 *isDone = ExprSingleResult;
1182 /* inlined, simplified version of ExecEvalFuncArgs */
1184 foreach(arg, fcache->args)
1186 ExprState *argstate = (ExprState *) lfirst(arg);
1188 fcinfo.arg[i] = ExecEvalExpr(argstate,
1195 InitFunctionCallInfoData(fcinfo, &(fcache->func), i, NULL, NULL);
1198 * If function is strict, and there are any NULL arguments, skip calling
1199 * the function and return NULL.
1201 if (fcache->func.fn_strict)
1205 if (fcinfo.argnull[i])
1212 /* fcinfo.isnull = false; */ /* handled by InitFunctionCallInfoData */
1213 result = FunctionCallInvoke(&fcinfo);
1214 *isNull = fcinfo.isnull;
1221 * ExecMakeTableFunctionResult
1223 * Evaluate a table function, producing a materialized result in a Tuplestore
1224 * object. *returnDesc is set to the tupledesc actually returned by the
1225 * function, or NULL if it didn't provide one.
1228 ExecMakeTableFunctionResult(ExprState *funcexpr,
1229 ExprContext *econtext,
1230 TupleDesc expectedDesc,
1231 TupleDesc *returnDesc)
1233 Tuplestorestate *tupstore = NULL;
1234 TupleDesc tupdesc = NULL;
1237 bool returnsSet = false;
1238 FunctionCallInfoData fcinfo;
1239 ReturnSetInfo rsinfo;
1240 HeapTupleData tmptup;
1241 MemoryContext callerContext;
1242 MemoryContext oldcontext;
1243 bool direct_function_call;
1244 bool first_time = true;
1246 callerContext = CurrentMemoryContext;
1248 funcrettype = exprType((Node *) funcexpr->expr);
1250 returnsTuple = type_is_rowtype(funcrettype);
1253 * Prepare a resultinfo node for communication. We always do this even if
1254 * not expecting a set result, so that we can pass expectedDesc. In the
1255 * generic-expression case, the expression doesn't actually get to see the
1256 * resultinfo, but set it up anyway because we use some of the fields as
1257 * our own state variables.
1259 InitFunctionCallInfoData(fcinfo, NULL, 0, NULL, (Node *) &rsinfo);
1260 rsinfo.type = T_ReturnSetInfo;
1261 rsinfo.econtext = econtext;
1262 rsinfo.expectedDesc = expectedDesc;
1263 rsinfo.allowedModes = (int) (SFRM_ValuePerCall | SFRM_Materialize);
1264 rsinfo.returnMode = SFRM_ValuePerCall;
1265 /* isDone is filled below */
1266 rsinfo.setResult = NULL;
1267 rsinfo.setDesc = NULL;
1270 * Normally the passed expression tree will be a FuncExprState, since the
1271 * grammar only allows a function call at the top level of a table
1272 * function reference. However, if the function doesn't return set then
1273 * the planner might have replaced the function call via constant-folding
1274 * or inlining. So if we see any other kind of expression node, execute
1275 * it via the general ExecEvalExpr() code; the only difference is that we
1276 * don't get a chance to pass a special ReturnSetInfo to any functions
1277 * buried in the expression.
1279 if (funcexpr && IsA(funcexpr, FuncExprState) &&
1280 IsA(funcexpr->expr, FuncExpr))
1282 FuncExprState *fcache = (FuncExprState *) funcexpr;
1283 ExprDoneCond argDone;
1286 * This path is similar to ExecMakeFunctionResult.
1288 direct_function_call = true;
1291 * Initialize function cache if first time through
1293 if (fcache->func.fn_oid == InvalidOid)
1295 FuncExpr *func = (FuncExpr *) fcache->xprstate.expr;
1297 init_fcache(func->funcid, fcache, econtext->ecxt_per_query_memory);
1299 returnsSet = fcache->func.fn_retset;
1302 * Evaluate the function's argument list.
1304 * Note: ideally, we'd do this in the per-tuple context, but then the
1305 * argument values would disappear when we reset the context in the
1306 * inner loop. So do it in caller context. Perhaps we should make a
1307 * separate context just to hold the evaluated arguments?
1309 fcinfo.flinfo = &(fcache->func);
1310 argDone = ExecEvalFuncArgs(&fcinfo, fcache->args, econtext);
1311 /* We don't allow sets in the arguments of the table function */
1312 if (argDone != ExprSingleResult)
1314 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1315 errmsg("set-valued function called in context that cannot accept a set")));
1318 * If function is strict, and there are any NULL arguments, skip
1319 * calling the function and act like it returned NULL (or an empty
1320 * set, in the returns-set case).
1322 if (fcache->func.fn_strict)
1326 for (i = 0; i < fcinfo.nargs; i++)
1328 if (fcinfo.argnull[i])
1329 goto no_function_result;
1335 /* Treat funcexpr as a generic expression */
1336 direct_function_call = false;
1340 * Switch to short-lived context for calling the function or expression.
1342 MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
1345 * Loop to handle the ValuePerCall protocol (which is also the same
1346 * behavior needed in the generic ExecEvalExpr path).
1353 CHECK_FOR_INTERRUPTS();
1356 * reset per-tuple memory context before each call of the function or
1357 * expression. This cleans up any local memory the function may leak
1360 ResetExprContext(econtext);
1362 /* Call the function or expression one time */
1363 if (direct_function_call)
1365 fcinfo.isnull = false;
1366 rsinfo.isDone = ExprSingleResult;
1367 result = FunctionCallInvoke(&fcinfo);
1371 result = ExecEvalExpr(funcexpr, econtext,
1372 &fcinfo.isnull, &rsinfo.isDone);
1375 /* Which protocol does function want to use? */
1376 if (rsinfo.returnMode == SFRM_ValuePerCall)
1379 * Check for end of result set.
1381 if (rsinfo.isDone == ExprEndResult)
1385 * Can't do anything very useful with NULL rowtype values. For a
1386 * function returning set, we consider this a protocol violation
1387 * (but another alternative would be to just ignore the result and
1388 * "continue" to get another row). For a function not returning
1389 * set, we fall out of the loop; we'll cons up an all-nulls result
1392 if (returnsTuple && fcinfo.isnull)
1397 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1398 errmsg("function returning set of rows cannot return null value")));
1402 * If first time through, build tupdesc and tuplestore for result
1406 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1410 * Use the type info embedded in the rowtype Datum to look
1411 * up the needed tupdesc. Make a copy for the query.
1415 td = DatumGetHeapTupleHeader(result);
1416 tupdesc = lookup_rowtype_tupdesc_copy(HeapTupleHeaderGetTypeId(td),
1417 HeapTupleHeaderGetTypMod(td));
1422 * Scalar type, so make a single-column descriptor
1424 tupdesc = CreateTemplateTupleDesc(1, false);
1425 TupleDescInitEntry(tupdesc,
1432 tupstore = tuplestore_begin_heap(true, false, work_mem);
1433 MemoryContextSwitchTo(oldcontext);
1434 rsinfo.setResult = tupstore;
1435 rsinfo.setDesc = tupdesc;
1439 * Store current resultset item.
1445 td = DatumGetHeapTupleHeader(result);
1448 * tuplestore_puttuple needs a HeapTuple not a bare
1449 * HeapTupleHeader, but it doesn't need all the fields.
1451 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
1457 tuple = heap_form_tuple(tupdesc, &result, &fcinfo.isnull);
1460 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1461 tuplestore_puttuple(tupstore, tuple);
1462 MemoryContextSwitchTo(oldcontext);
1467 if (rsinfo.isDone != ExprMultipleResult)
1470 else if (rsinfo.returnMode == SFRM_Materialize)
1472 /* check we're on the same page as the function author */
1473 if (!first_time || rsinfo.isDone != ExprSingleResult)
1475 (errcode(ERRCODE_E_R_I_E_SRF_PROTOCOL_VIOLATED),
1476 errmsg("table-function protocol for materialize mode was not followed")));
1477 /* Done evaluating the set result */
1482 (errcode(ERRCODE_E_R_I_E_SRF_PROTOCOL_VIOLATED),
1483 errmsg("unrecognized table-function returnMode: %d",
1484 (int) rsinfo.returnMode)));
1492 * If we got nothing from the function (ie, an empty-set or NULL result),
1493 * we have to create the tuplestore to return, and if it's a
1494 * non-set-returning function then insert a single all-nulls row.
1496 if (rsinfo.setResult == NULL)
1498 MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1499 tupstore = tuplestore_begin_heap(true, false, work_mem);
1500 rsinfo.setResult = tupstore;
1503 int natts = expectedDesc->natts;
1508 MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
1509 nulldatums = (Datum *) palloc0(natts * sizeof(Datum));
1510 nullflags = (bool *) palloc(natts * sizeof(bool));
1511 memset(nullflags, true, natts * sizeof(bool));
1512 tuple = heap_form_tuple(expectedDesc, nulldatums, nullflags);
1513 MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1514 tuplestore_puttuple(tupstore, tuple);
1518 MemoryContextSwitchTo(callerContext);
1520 /* The returned pointers are those in rsinfo */
1521 *returnDesc = rsinfo.setDesc;
1522 return rsinfo.setResult;
1526 /* ----------------------------------------------------------------
1530 * Evaluate the functional result of a list of arguments by calling the
1532 * ----------------------------------------------------------------
1535 /* ----------------------------------------------------------------
1537 * ----------------------------------------------------------------
1540 ExecEvalFunc(FuncExprState *fcache,
1541 ExprContext *econtext,
1543 ExprDoneCond *isDone)
1545 /* This is called only the first time through */
1546 FuncExpr *func = (FuncExpr *) fcache->xprstate.expr;
1548 /* Initialize function lookup info */
1549 init_fcache(func->funcid, fcache, econtext->ecxt_per_query_memory);
1551 /* Go directly to ExecMakeFunctionResult on subsequent uses */
1552 fcache->xprstate.evalfunc = (ExprStateEvalFunc) ExecMakeFunctionResult;
1554 return ExecMakeFunctionResult(fcache, econtext, isNull, isDone);
1557 /* ----------------------------------------------------------------
1559 * ----------------------------------------------------------------
1562 ExecEvalOper(FuncExprState *fcache,
1563 ExprContext *econtext,
1565 ExprDoneCond *isDone)
1567 /* This is called only the first time through */
1568 OpExpr *op = (OpExpr *) fcache->xprstate.expr;
1570 /* Initialize function lookup info */
1571 init_fcache(op->opfuncid, fcache, econtext->ecxt_per_query_memory);
1573 /* Go directly to ExecMakeFunctionResult on subsequent uses */
1574 fcache->xprstate.evalfunc = (ExprStateEvalFunc) ExecMakeFunctionResult;
1576 return ExecMakeFunctionResult(fcache, econtext, isNull, isDone);
1579 /* ----------------------------------------------------------------
1582 * IS DISTINCT FROM must evaluate arguments to determine whether
1583 * they are NULL; if either is NULL then the result is already
1584 * known. If neither is NULL, then proceed to evaluate the
1585 * function. Note that this is *always* derived from the equals
1586 * operator, but since we need special processing of the arguments
1587 * we can not simply reuse ExecEvalOper() or ExecEvalFunc().
1588 * ----------------------------------------------------------------
1591 ExecEvalDistinct(FuncExprState *fcache,
1592 ExprContext *econtext,
1594 ExprDoneCond *isDone)
1597 FunctionCallInfoData fcinfo;
1598 ExprDoneCond argDone;
1601 /* Set default values for result flags: non-null, not a set result */
1604 *isDone = ExprSingleResult;
1607 * Initialize function cache if first time through
1609 if (fcache->func.fn_oid == InvalidOid)
1611 DistinctExpr *op = (DistinctExpr *) fcache->xprstate.expr;
1613 init_fcache(op->opfuncid, fcache, econtext->ecxt_per_query_memory);
1614 Assert(!fcache->func.fn_retset);
1618 * extract info from fcache
1620 argList = fcache->args;
1622 /* Need to prep callinfo structure */
1623 InitFunctionCallInfoData(fcinfo, &(fcache->func), 0, NULL, NULL);
1624 argDone = ExecEvalFuncArgs(&fcinfo, argList, econtext);
1625 if (argDone != ExprSingleResult)
1627 (errcode(ERRCODE_DATATYPE_MISMATCH),
1628 errmsg("IS DISTINCT FROM does not support set arguments")));
1629 Assert(fcinfo.nargs == 2);
1631 if (fcinfo.argnull[0] && fcinfo.argnull[1])
1633 /* Both NULL? Then is not distinct... */
1634 result = BoolGetDatum(FALSE);
1636 else if (fcinfo.argnull[0] || fcinfo.argnull[1])
1638 /* Only one is NULL? Then is distinct... */
1639 result = BoolGetDatum(TRUE);
1643 fcinfo.isnull = false;
1644 result = FunctionCallInvoke(&fcinfo);
1645 *isNull = fcinfo.isnull;
1646 /* Must invert result of "=" */
1647 result = BoolGetDatum(!DatumGetBool(result));
1654 * ExecEvalScalarArrayOp
1656 * Evaluate "scalar op ANY/ALL (array)". The operator always yields boolean,
1657 * and we combine the results across all array elements using OR and AND
1658 * (for ANY and ALL respectively). Of course we short-circuit as soon as
1659 * the result is known.
1662 ExecEvalScalarArrayOp(ScalarArrayOpExprState *sstate,
1663 ExprContext *econtext,
1664 bool *isNull, ExprDoneCond *isDone)
1666 ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) sstate->fxprstate.xprstate.expr;
1667 bool useOr = opexpr->useOr;
1672 FunctionCallInfoData fcinfo;
1673 ExprDoneCond argDone;
1682 /* Set default values for result flags: non-null, not a set result */
1685 *isDone = ExprSingleResult;
1688 * Initialize function cache if first time through
1690 if (sstate->fxprstate.func.fn_oid == InvalidOid)
1692 init_fcache(opexpr->opfuncid, &sstate->fxprstate,
1693 econtext->ecxt_per_query_memory);
1694 Assert(!sstate->fxprstate.func.fn_retset);
1697 /* Need to prep callinfo structure */
1698 InitFunctionCallInfoData(fcinfo, &(sstate->fxprstate.func), 0, NULL, NULL);
1699 argDone = ExecEvalFuncArgs(&fcinfo, sstate->fxprstate.args, econtext);
1700 if (argDone != ExprSingleResult)
1702 (errcode(ERRCODE_DATATYPE_MISMATCH),
1703 errmsg("op ANY/ALL (array) does not support set arguments")));
1704 Assert(fcinfo.nargs == 2);
1707 * If the array is NULL then we return NULL --- it's not very meaningful
1708 * to do anything else, even if the operator isn't strict.
1710 if (fcinfo.argnull[1])
1715 /* Else okay to fetch and detoast the array */
1716 arr = DatumGetArrayTypeP(fcinfo.arg[1]);
1719 * If the array is empty, we return either FALSE or TRUE per the useOr
1720 * flag. This is correct even if the scalar is NULL; since we would
1721 * evaluate the operator zero times, it matters not whether it would want
1724 nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr));
1726 return BoolGetDatum(!useOr);
1729 * If the scalar is NULL, and the function is strict, return NULL; no
1730 * point in iterating the loop.
1732 if (fcinfo.argnull[0] && sstate->fxprstate.func.fn_strict)
1739 * We arrange to look up info about the element type only once per series
1740 * of calls, assuming the element type doesn't change underneath us.
1742 if (sstate->element_type != ARR_ELEMTYPE(arr))
1744 get_typlenbyvalalign(ARR_ELEMTYPE(arr),
1748 sstate->element_type = ARR_ELEMTYPE(arr);
1750 typlen = sstate->typlen;
1751 typbyval = sstate->typbyval;
1752 typalign = sstate->typalign;
1754 result = BoolGetDatum(!useOr);
1757 /* Loop over the array elements */
1758 s = (char *) ARR_DATA_PTR(arr);
1759 bitmap = ARR_NULLBITMAP(arr);
1762 for (i = 0; i < nitems; i++)
1767 /* Get array element, checking for NULL */
1768 if (bitmap && (*bitmap & bitmask) == 0)
1770 fcinfo.arg[1] = (Datum) 0;
1771 fcinfo.argnull[1] = true;
1775 elt = fetch_att(s, typbyval, typlen);
1776 s = att_addlength(s, typlen, PointerGetDatum(s));
1777 s = (char *) att_align(s, typalign);
1778 fcinfo.arg[1] = elt;
1779 fcinfo.argnull[1] = false;
1782 /* Call comparison function */
1783 if (fcinfo.argnull[1] && sstate->fxprstate.func.fn_strict)
1785 fcinfo.isnull = true;
1786 thisresult = (Datum) 0;
1790 fcinfo.isnull = false;
1791 thisresult = FunctionCallInvoke(&fcinfo);
1794 /* Combine results per OR or AND semantics */
1799 if (DatumGetBool(thisresult))
1801 result = BoolGetDatum(true);
1803 break; /* needn't look at any more elements */
1808 if (!DatumGetBool(thisresult))
1810 result = BoolGetDatum(false);
1812 break; /* needn't look at any more elements */
1816 /* advance bitmap pointer if any */
1820 if (bitmask == 0x100)
1828 *isNull = resultnull;
1832 /* ----------------------------------------------------------------
1837 * Evaluate boolean expressions, with appropriate short-circuiting.
1839 * The query planner reformulates clause expressions in the
1840 * qualification to conjunctive normal form. If we ever get
1841 * an AND to evaluate, we can be sure that it's not a top-level
1842 * clause in the qualification, but appears lower (as a function
1843 * argument, for example), or in the target list. Not that you
1844 * need to know this, mind you...
1845 * ----------------------------------------------------------------
1848 ExecEvalNot(BoolExprState *notclause, ExprContext *econtext,
1849 bool *isNull, ExprDoneCond *isDone)
1851 ExprState *clause = linitial(notclause->args);
1855 *isDone = ExprSingleResult;
1857 expr_value = ExecEvalExpr(clause, econtext, isNull, NULL);
1860 * if the expression evaluates to null, then we just cascade the null back
1861 * to whoever called us.
1867 * evaluation of 'not' is simple.. expr is false, then return 'true' and
1870 return BoolGetDatum(!DatumGetBool(expr_value));
1873 /* ----------------------------------------------------------------
1875 * ----------------------------------------------------------------
1878 ExecEvalOr(BoolExprState *orExpr, ExprContext *econtext,
1879 bool *isNull, ExprDoneCond *isDone)
1881 List *clauses = orExpr->args;
1886 *isDone = ExprSingleResult;
1891 * If any of the clauses is TRUE, the OR result is TRUE regardless of the
1892 * states of the rest of the clauses, so we can stop evaluating and return
1893 * TRUE immediately. If none are TRUE and one or more is NULL, we return
1894 * NULL; otherwise we return FALSE. This makes sense when you interpret
1895 * NULL as "don't know": if we have a TRUE then the OR is TRUE even if we
1896 * aren't sure about some of the other inputs. If all the known inputs are
1897 * FALSE, but we have one or more "don't knows", then we have to report
1898 * that we "don't know" what the OR's result should be --- perhaps one of
1899 * the "don't knows" would have been TRUE if we'd known its value. Only
1900 * when all the inputs are known to be FALSE can we state confidently that
1901 * the OR's result is FALSE.
1903 foreach(clause, clauses)
1905 ExprState *clausestate = (ExprState *) lfirst(clause);
1908 clause_value = ExecEvalExpr(clausestate, econtext, isNull, NULL);
1911 * if we have a non-null true result, then return it.
1914 AnyNull = true; /* remember we got a null */
1915 else if (DatumGetBool(clause_value))
1916 return clause_value;
1919 /* AnyNull is true if at least one clause evaluated to NULL */
1921 return BoolGetDatum(false);
1924 /* ----------------------------------------------------------------
1926 * ----------------------------------------------------------------
1929 ExecEvalAnd(BoolExprState *andExpr, ExprContext *econtext,
1930 bool *isNull, ExprDoneCond *isDone)
1932 List *clauses = andExpr->args;
1937 *isDone = ExprSingleResult;
1942 * If any of the clauses is FALSE, the AND result is FALSE regardless of
1943 * the states of the rest of the clauses, so we can stop evaluating and
1944 * return FALSE immediately. If none are FALSE and one or more is NULL,
1945 * we return NULL; otherwise we return TRUE. This makes sense when you
1946 * interpret NULL as "don't know", using the same sort of reasoning as for
1950 foreach(clause, clauses)
1952 ExprState *clausestate = (ExprState *) lfirst(clause);
1955 clause_value = ExecEvalExpr(clausestate, econtext, isNull, NULL);
1958 * if we have a non-null false result, then return it.
1961 AnyNull = true; /* remember we got a null */
1962 else if (!DatumGetBool(clause_value))
1963 return clause_value;
1966 /* AnyNull is true if at least one clause evaluated to NULL */
1968 return BoolGetDatum(!AnyNull);
1971 /* ----------------------------------------------------------------
1972 * ExecEvalConvertRowtype
1974 * Evaluate a rowtype coercion operation. This may require
1975 * rearranging field positions.
1976 * ----------------------------------------------------------------
1979 ExecEvalConvertRowtype(ConvertRowtypeExprState *cstate,
1980 ExprContext *econtext,
1981 bool *isNull, ExprDoneCond *isDone)
1983 ConvertRowtypeExpr *convert = (ConvertRowtypeExpr *) cstate->xprstate.expr;
1986 HeapTupleHeader tuple;
1987 HeapTupleData tmptup;
1988 AttrNumber *attrMap;
1996 tupDatum = ExecEvalExpr(cstate->arg, econtext, isNull, isDone);
1998 /* this test covers the isDone exception too: */
2002 tuple = DatumGetHeapTupleHeader(tupDatum);
2004 /* Lookup tupdescs if first time through or after rescan */
2005 if (cstate->indesc == NULL)
2006 get_cached_rowtype(exprType((Node *) convert->arg), -1,
2007 &cstate->indesc, econtext);
2008 if (cstate->outdesc == NULL)
2009 get_cached_rowtype(convert->resulttype, -1,
2010 &cstate->outdesc, econtext);
2012 Assert(HeapTupleHeaderGetTypeId(tuple) == cstate->indesc->tdtypeid);
2013 Assert(HeapTupleHeaderGetTypMod(tuple) == cstate->indesc->tdtypmod);
2015 /* if first time through, initialize */
2016 if (cstate->attrMap == NULL)
2018 MemoryContext old_cxt;
2021 /* allocate state in long-lived memory context */
2022 old_cxt = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
2024 /* prepare map from old to new attribute numbers */
2025 n = cstate->outdesc->natts;
2026 cstate->attrMap = (AttrNumber *) palloc0(n * sizeof(AttrNumber));
2027 for (i = 0; i < n; i++)
2029 Form_pg_attribute att = cstate->outdesc->attrs[i];
2035 if (att->attisdropped)
2036 continue; /* attrMap[i] is already 0 */
2037 attname = NameStr(att->attname);
2038 atttypid = att->atttypid;
2039 atttypmod = att->atttypmod;
2040 for (j = 0; j < cstate->indesc->natts; j++)
2042 att = cstate->indesc->attrs[j];
2043 if (att->attisdropped)
2045 if (strcmp(attname, NameStr(att->attname)) == 0)
2047 /* Found it, check type */
2048 if (atttypid != att->atttypid || atttypmod != att->atttypmod)
2049 elog(ERROR, "attribute \"%s\" of type %s does not match corresponding attribute of type %s",
2051 format_type_be(cstate->indesc->tdtypeid),
2052 format_type_be(cstate->outdesc->tdtypeid));
2053 cstate->attrMap[i] = (AttrNumber) (j + 1);
2057 if (cstate->attrMap[i] == 0)
2058 elog(ERROR, "attribute \"%s\" of type %s does not exist",
2060 format_type_be(cstate->indesc->tdtypeid));
2062 /* preallocate workspace for Datum arrays */
2063 n = cstate->indesc->natts + 1; /* +1 for NULL */
2064 cstate->invalues = (Datum *) palloc(n * sizeof(Datum));
2065 cstate->inisnull = (bool *) palloc(n * sizeof(bool));
2066 n = cstate->outdesc->natts;
2067 cstate->outvalues = (Datum *) palloc(n * sizeof(Datum));
2068 cstate->outisnull = (bool *) palloc(n * sizeof(bool));
2070 MemoryContextSwitchTo(old_cxt);
2073 attrMap = cstate->attrMap;
2074 invalues = cstate->invalues;
2075 inisnull = cstate->inisnull;
2076 outvalues = cstate->outvalues;
2077 outisnull = cstate->outisnull;
2078 outnatts = cstate->outdesc->natts;
2081 * heap_deform_tuple needs a HeapTuple not a bare HeapTupleHeader.
2083 tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
2084 tmptup.t_data = tuple;
2087 * Extract all the values of the old tuple, offsetting the arrays so that
2088 * invalues[0] is NULL and invalues[1] is the first source attribute; this
2089 * exactly matches the numbering convention in attrMap.
2091 heap_deform_tuple(&tmptup, cstate->indesc, invalues + 1, inisnull + 1);
2092 invalues[0] = (Datum) 0;
2096 * Transpose into proper fields of the new tuple.
2098 for (i = 0; i < outnatts; i++)
2102 outvalues[i] = invalues[j];
2103 outisnull[i] = inisnull[j];
2107 * Now form the new tuple.
2109 result = heap_form_tuple(cstate->outdesc, outvalues, outisnull);
2111 return HeapTupleGetDatum(result);
2114 /* ----------------------------------------------------------------
2117 * Evaluate a CASE clause. Will have boolean expressions
2118 * inside the WHEN clauses, and will have expressions
2120 * - thomas 1998-11-09
2121 * ----------------------------------------------------------------
2124 ExecEvalCase(CaseExprState *caseExpr, ExprContext *econtext,
2125 bool *isNull, ExprDoneCond *isDone)
2127 List *clauses = caseExpr->args;
2133 *isDone = ExprSingleResult;
2136 * If there's a test expression, we have to evaluate it and save the value
2137 * where the CaseTestExpr placeholders can find it. We must save and
2138 * restore prior setting of econtext's caseValue fields, in case this node
2139 * is itself within a larger CASE.
2141 save_datum = econtext->caseValue_datum;
2142 save_isNull = econtext->caseValue_isNull;
2146 econtext->caseValue_datum = ExecEvalExpr(caseExpr->arg,
2148 &econtext->caseValue_isNull,
2153 * we evaluate each of the WHEN clauses in turn, as soon as one is true we
2154 * return the corresponding result. If none are true then we return the
2155 * value of the default clause, or NULL if there is none.
2157 foreach(clause, clauses)
2159 CaseWhenState *wclause = lfirst(clause);
2162 clause_value = ExecEvalExpr(wclause->expr,
2168 * if we have a true test, then we return the result, since the case
2169 * statement is satisfied. A NULL result from the test is not
2172 if (DatumGetBool(clause_value) && !*isNull)
2174 econtext->caseValue_datum = save_datum;
2175 econtext->caseValue_isNull = save_isNull;
2176 return ExecEvalExpr(wclause->result,
2183 econtext->caseValue_datum = save_datum;
2184 econtext->caseValue_isNull = save_isNull;
2186 if (caseExpr->defresult)
2188 return ExecEvalExpr(caseExpr->defresult,
2199 * ExecEvalCaseTestExpr
2201 * Return the value stored by CASE.
2204 ExecEvalCaseTestExpr(ExprState *exprstate,
2205 ExprContext *econtext,
2206 bool *isNull, ExprDoneCond *isDone)
2209 *isDone = ExprSingleResult;
2210 *isNull = econtext->caseValue_isNull;
2211 return econtext->caseValue_datum;
2214 /* ----------------------------------------------------------------
2215 * ExecEvalArray - ARRAY[] expressions
2216 * ----------------------------------------------------------------
2219 ExecEvalArray(ArrayExprState *astate, ExprContext *econtext,
2220 bool *isNull, ExprDoneCond *isDone)
2222 ArrayExpr *arrayExpr = (ArrayExpr *) astate->xprstate.expr;
2225 Oid element_type = arrayExpr->element_typeid;
2230 /* Set default values for result flags: non-null, not a set result */
2233 *isDone = ExprSingleResult;
2235 if (!arrayExpr->multidims)
2237 /* Elements are presumably of scalar type */
2244 nelems = list_length(astate->elements);
2246 /* Shouldn't happen here, but if length is 0, return empty array */
2248 return PointerGetDatum(construct_empty_array(element_type));
2250 dvalues = (Datum *) palloc(nelems * sizeof(Datum));
2251 dnulls = (bool *) palloc(nelems * sizeof(bool));
2253 /* loop through and build array of datums */
2254 foreach(element, astate->elements)
2256 ExprState *e = (ExprState *) lfirst(element);
2258 dvalues[i] = ExecEvalExpr(e, econtext, &dnulls[i], NULL);
2262 /* setup for 1-D array of the given length */
2266 result = construct_md_array(dvalues, dnulls, ndims, dims, lbs,
2274 /* Must be nested array expressions */
2277 int outer_nelems = 0;
2279 int *elem_dims = NULL;
2280 int *elem_lbs = NULL;
2281 bool firstone = true;
2282 bool havenulls = false;
2292 i = list_length(astate->elements);
2293 subdata = (char **) palloc(i * sizeof(char *));
2294 subbitmaps = (bits8 **) palloc(i * sizeof(bits8 *));
2295 subbytes = (int *) palloc(i * sizeof(int));
2296 subnitems = (int *) palloc(i * sizeof(int));
2298 /* loop through and get data area from each element */
2299 foreach(element, astate->elements)
2301 ExprState *e = (ExprState *) lfirst(element);
2306 arraydatum = ExecEvalExpr(e, econtext, &eisnull, NULL);
2307 /* ignore null subarrays */
2311 array = DatumGetArrayTypeP(arraydatum);
2313 /* run-time double-check on element type */
2314 if (element_type != ARR_ELEMTYPE(array))
2316 (errcode(ERRCODE_DATATYPE_MISMATCH),
2317 errmsg("cannot merge incompatible arrays"),
2318 errdetail("Array with element type %s cannot be "
2319 "included in ARRAY construct with element type %s.",
2320 format_type_be(ARR_ELEMTYPE(array)),
2321 format_type_be(element_type))));
2325 /* Get sub-array details from first member */
2326 elem_ndims = ARR_NDIM(array);
2327 ndims = elem_ndims + 1;
2328 if (ndims <= 0 || ndims > MAXDIM)
2330 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
2331 errmsg("number of array dimensions (%d) exceeds " \
2332 "the maximum allowed (%d)", ndims, MAXDIM)));
2334 elem_dims = (int *) palloc(elem_ndims * sizeof(int));
2335 memcpy(elem_dims, ARR_DIMS(array), elem_ndims * sizeof(int));
2336 elem_lbs = (int *) palloc(elem_ndims * sizeof(int));
2337 memcpy(elem_lbs, ARR_LBOUND(array), elem_ndims * sizeof(int));
2343 /* Check other sub-arrays are compatible */
2344 if (elem_ndims != ARR_NDIM(array) ||
2345 memcmp(elem_dims, ARR_DIMS(array),
2346 elem_ndims * sizeof(int)) != 0 ||
2347 memcmp(elem_lbs, ARR_LBOUND(array),
2348 elem_ndims * sizeof(int)) != 0)
2350 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2351 errmsg("multidimensional arrays must have array "
2352 "expressions with matching dimensions")));
2355 subdata[outer_nelems] = ARR_DATA_PTR(array);
2356 subbitmaps[outer_nelems] = ARR_NULLBITMAP(array);
2357 subbytes[outer_nelems] = ARR_SIZE(array) - ARR_DATA_OFFSET(array);
2358 nbytes += subbytes[outer_nelems];
2359 subnitems[outer_nelems] = ArrayGetNItems(ARR_NDIM(array),
2361 nitems += subnitems[outer_nelems];
2362 havenulls |= ARR_HASNULL(array);
2366 /* setup for multi-D array */
2367 dims[0] = outer_nelems;
2369 for (i = 1; i < ndims; i++)
2371 dims[i] = elem_dims[i - 1];
2372 lbs[i] = elem_lbs[i - 1];
2377 dataoffset = ARR_OVERHEAD_WITHNULLS(ndims, nitems);
2378 nbytes += dataoffset;
2382 dataoffset = 0; /* marker for no null bitmap */
2383 nbytes += ARR_OVERHEAD_NONULLS(ndims);
2386 result = (ArrayType *) palloc(nbytes);
2387 result->size = nbytes;
2388 result->ndim = ndims;
2389 result->dataoffset = dataoffset;
2390 result->elemtype = element_type;
2391 memcpy(ARR_DIMS(result), dims, ndims * sizeof(int));
2392 memcpy(ARR_LBOUND(result), lbs, ndims * sizeof(int));
2394 dat = ARR_DATA_PTR(result);
2396 for (i = 0; i < outer_nelems; i++)
2398 memcpy(dat, subdata[i], subbytes[i]);
2401 array_bitmap_copy(ARR_NULLBITMAP(result), iitem,
2404 iitem += subnitems[i];
2408 return PointerGetDatum(result);
2411 /* ----------------------------------------------------------------
2412 * ExecEvalRow - ROW() expressions
2413 * ----------------------------------------------------------------
2416 ExecEvalRow(RowExprState *rstate,
2417 ExprContext *econtext,
2418 bool *isNull, ExprDoneCond *isDone)
2427 /* Set default values for result flags: non-null, not a set result */
2430 *isDone = ExprSingleResult;
2432 /* Allocate workspace */
2433 natts = rstate->tupdesc->natts;
2434 values = (Datum *) palloc0(natts * sizeof(Datum));
2435 isnull = (bool *) palloc(natts * sizeof(bool));
2437 /* preset to nulls in case rowtype has some later-added columns */
2438 memset(isnull, true, natts * sizeof(bool));
2440 /* Evaluate field values */
2442 foreach(arg, rstate->args)
2444 ExprState *e = (ExprState *) lfirst(arg);
2446 values[i] = ExecEvalExpr(e, econtext, &isnull[i], NULL);
2450 tuple = heap_form_tuple(rstate->tupdesc, values, isnull);
2455 return HeapTupleGetDatum(tuple);
2458 /* ----------------------------------------------------------------
2459 * ExecEvalRowCompare - ROW() comparison-op ROW()
2460 * ----------------------------------------------------------------
2463 ExecEvalRowCompare(RowCompareExprState *rstate,
2464 ExprContext *econtext,
2465 bool *isNull, ExprDoneCond *isDone)
2468 RowCompareType rctype = ((RowCompareExpr *) rstate->xprstate.expr)->rctype;
2469 int32 cmpresult = 0;
2475 *isDone = ExprSingleResult;
2476 *isNull = true; /* until we get a result */
2479 forboth(l, rstate->largs, r, rstate->rargs)
2481 ExprState *le = (ExprState *) lfirst(l);
2482 ExprState *re = (ExprState *) lfirst(r);
2483 FunctionCallInfoData locfcinfo;
2485 InitFunctionCallInfoData(locfcinfo, &(rstate->funcs[i]), 2,
2487 locfcinfo.arg[0] = ExecEvalExpr(le, econtext,
2488 &locfcinfo.argnull[0], NULL);
2489 locfcinfo.arg[1] = ExecEvalExpr(re, econtext,
2490 &locfcinfo.argnull[1], NULL);
2491 if (rstate->funcs[i].fn_strict &&
2492 (locfcinfo.argnull[0] || locfcinfo.argnull[1]))
2493 return (Datum) 0; /* force NULL result */
2494 locfcinfo.isnull = false;
2495 cmpresult = DatumGetInt32(FunctionCallInvoke(&locfcinfo));
2496 if (locfcinfo.isnull)
2497 return (Datum) 0; /* force NULL result */
2499 break; /* no need to compare remaining columns */
2505 /* EQ and NE cases aren't allowed here */
2507 result = (cmpresult < 0);
2510 result = (cmpresult <= 0);
2513 result = (cmpresult >= 0);
2516 result = (cmpresult > 0);
2519 elog(ERROR, "unrecognized RowCompareType: %d", (int) rctype);
2520 result = 0; /* keep compiler quiet */
2525 return BoolGetDatum(result);
2528 /* ----------------------------------------------------------------
2530 * ----------------------------------------------------------------
2533 ExecEvalCoalesce(CoalesceExprState *coalesceExpr, ExprContext *econtext,
2534 bool *isNull, ExprDoneCond *isDone)
2539 *isDone = ExprSingleResult;
2541 /* Simply loop through until something NOT NULL is found */
2542 foreach(arg, coalesceExpr->args)
2544 ExprState *e = (ExprState *) lfirst(arg);
2547 value = ExecEvalExpr(e, econtext, isNull, NULL);
2552 /* Else return NULL */
2557 /* ----------------------------------------------------------------
2559 * ----------------------------------------------------------------
2562 ExecEvalMinMax(MinMaxExprState *minmaxExpr, ExprContext *econtext,
2563 bool *isNull, ExprDoneCond *isDone)
2565 Datum result = (Datum) 0;
2566 MinMaxOp op = ((MinMaxExpr *) minmaxExpr->xprstate.expr)->op;
2567 FunctionCallInfoData locfcinfo;
2571 *isDone = ExprSingleResult;
2572 *isNull = true; /* until we get a result */
2574 InitFunctionCallInfoData(locfcinfo, &minmaxExpr->cfunc, 2, NULL, NULL);
2575 locfcinfo.argnull[0] = false;
2576 locfcinfo.argnull[1] = false;
2578 foreach(arg, minmaxExpr->args)
2580 ExprState *e = (ExprState *) lfirst(arg);
2585 value = ExecEvalExpr(e, econtext, &valueIsNull, NULL);
2587 continue; /* ignore NULL inputs */
2591 /* first nonnull input, adopt value */
2597 /* apply comparison function */
2598 locfcinfo.arg[0] = result;
2599 locfcinfo.arg[1] = value;
2600 locfcinfo.isnull = false;
2601 cmpresult = DatumGetInt32(FunctionCallInvoke(&locfcinfo));
2602 if (locfcinfo.isnull) /* probably should not happen */
2604 if (cmpresult > 0 && op == IS_LEAST)
2606 else if (cmpresult < 0 && op == IS_GREATEST)
2614 /* ----------------------------------------------------------------
2617 * Note that this is *always* derived from the equals operator,
2618 * but since we need special processing of the arguments
2619 * we can not simply reuse ExecEvalOper() or ExecEvalFunc().
2620 * ----------------------------------------------------------------
2623 ExecEvalNullIf(FuncExprState *nullIfExpr,
2624 ExprContext *econtext,
2625 bool *isNull, ExprDoneCond *isDone)
2628 FunctionCallInfoData fcinfo;
2629 ExprDoneCond argDone;
2633 *isDone = ExprSingleResult;
2636 * Initialize function cache if first time through
2638 if (nullIfExpr->func.fn_oid == InvalidOid)
2640 NullIfExpr *op = (NullIfExpr *) nullIfExpr->xprstate.expr;
2642 init_fcache(op->opfuncid, nullIfExpr, econtext->ecxt_per_query_memory);
2643 Assert(!nullIfExpr->func.fn_retset);
2647 * extract info from nullIfExpr
2649 argList = nullIfExpr->args;
2651 /* Need to prep callinfo structure */
2652 InitFunctionCallInfoData(fcinfo, &(nullIfExpr->func), 0, NULL, NULL);
2653 argDone = ExecEvalFuncArgs(&fcinfo, argList, econtext);
2654 if (argDone != ExprSingleResult)
2656 (errcode(ERRCODE_DATATYPE_MISMATCH),
2657 errmsg("NULLIF does not support set arguments")));
2658 Assert(fcinfo.nargs == 2);
2660 /* if either argument is NULL they can't be equal */
2661 if (!fcinfo.argnull[0] && !fcinfo.argnull[1])
2663 fcinfo.isnull = false;
2664 result = FunctionCallInvoke(&fcinfo);
2665 /* if the arguments are equal return null */
2666 if (!fcinfo.isnull && DatumGetBool(result))
2673 /* else return first argument */
2674 *isNull = fcinfo.argnull[0];
2675 return fcinfo.arg[0];
2678 /* ----------------------------------------------------------------
2681 * Evaluate a NullTest node.
2682 * ----------------------------------------------------------------
2685 ExecEvalNullTest(NullTestState *nstate,
2686 ExprContext *econtext,
2688 ExprDoneCond *isDone)
2690 NullTest *ntest = (NullTest *) nstate->xprstate.expr;
2693 result = ExecEvalExpr(nstate->arg, econtext, isNull, isDone);
2695 if (isDone && *isDone == ExprEndResult)
2696 return result; /* nothing to check */
2698 if (nstate->argisrow && !(*isNull))
2700 HeapTupleHeader tuple;
2704 HeapTupleData tmptup;
2707 tuple = DatumGetHeapTupleHeader(result);
2709 tupType = HeapTupleHeaderGetTypeId(tuple);
2710 tupTypmod = HeapTupleHeaderGetTypMod(tuple);
2712 /* Lookup tupdesc if first time through or if type changes */
2713 tupDesc = get_cached_rowtype(tupType, tupTypmod,
2714 &nstate->argdesc, econtext);
2717 * heap_attisnull needs a HeapTuple not a bare HeapTupleHeader.
2719 tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
2720 tmptup.t_data = tuple;
2722 for (att = 1; att <= tupDesc->natts; att++)
2724 /* ignore dropped columns */
2725 if (tupDesc->attrs[att - 1]->attisdropped)
2727 if (heap_attisnull(&tmptup, att))
2729 /* null field disproves IS NOT NULL */
2730 if (ntest->nulltesttype == IS_NOT_NULL)
2731 return BoolGetDatum(false);
2735 /* non-null field disproves IS NULL */
2736 if (ntest->nulltesttype == IS_NULL)
2737 return BoolGetDatum(false);
2741 return BoolGetDatum(true);
2745 /* Simple scalar-argument case, or a null rowtype datum */
2746 switch (ntest->nulltesttype)
2752 return BoolGetDatum(true);
2755 return BoolGetDatum(false);
2760 return BoolGetDatum(false);
2763 return BoolGetDatum(true);
2765 elog(ERROR, "unrecognized nulltesttype: %d",
2766 (int) ntest->nulltesttype);
2767 return (Datum) 0; /* keep compiler quiet */
2772 /* ----------------------------------------------------------------
2773 * ExecEvalBooleanTest
2775 * Evaluate a BooleanTest node.
2776 * ----------------------------------------------------------------
2779 ExecEvalBooleanTest(GenericExprState *bstate,
2780 ExprContext *econtext,
2782 ExprDoneCond *isDone)
2784 BooleanTest *btest = (BooleanTest *) bstate->xprstate.expr;
2787 result = ExecEvalExpr(bstate->arg, econtext, isNull, isDone);
2789 if (isDone && *isDone == ExprEndResult)
2790 return result; /* nothing to check */
2792 switch (btest->booltesttype)
2798 return BoolGetDatum(false);
2800 else if (DatumGetBool(result))
2801 return BoolGetDatum(true);
2803 return BoolGetDatum(false);
2808 return BoolGetDatum(true);
2810 else if (DatumGetBool(result))
2811 return BoolGetDatum(false);
2813 return BoolGetDatum(true);
2818 return BoolGetDatum(false);
2820 else if (DatumGetBool(result))
2821 return BoolGetDatum(false);
2823 return BoolGetDatum(true);
2828 return BoolGetDatum(true);
2830 else if (DatumGetBool(result))
2831 return BoolGetDatum(true);
2833 return BoolGetDatum(false);
2838 return BoolGetDatum(true);
2841 return BoolGetDatum(false);
2842 case IS_NOT_UNKNOWN:
2846 return BoolGetDatum(false);
2849 return BoolGetDatum(true);
2851 elog(ERROR, "unrecognized booltesttype: %d",
2852 (int) btest->booltesttype);
2853 return (Datum) 0; /* keep compiler quiet */
2858 * ExecEvalCoerceToDomain
2860 * Test the provided data against the domain constraint(s). If the data
2861 * passes the constraint specifications, pass it through (return the
2862 * datum) otherwise throw an error.
2865 ExecEvalCoerceToDomain(CoerceToDomainState *cstate, ExprContext *econtext,
2866 bool *isNull, ExprDoneCond *isDone)
2868 CoerceToDomain *ctest = (CoerceToDomain *) cstate->xprstate.expr;
2872 result = ExecEvalExpr(cstate->arg, econtext, isNull, isDone);
2874 if (isDone && *isDone == ExprEndResult)
2875 return result; /* nothing to check */
2877 foreach(l, cstate->constraints)
2879 DomainConstraintState *con = (DomainConstraintState *) lfirst(l);
2881 switch (con->constrainttype)
2883 case DOM_CONSTRAINT_NOTNULL:
2886 (errcode(ERRCODE_NOT_NULL_VIOLATION),
2887 errmsg("domain %s does not allow null values",
2888 format_type_be(ctest->resulttype))));
2890 case DOM_CONSTRAINT_CHECK:
2898 * Set up value to be returned by CoerceToDomainValue
2899 * nodes. We must save and restore prior setting of
2900 * econtext's domainValue fields, in case this node is
2901 * itself within a check expression for another domain.
2903 save_datum = econtext->domainValue_datum;
2904 save_isNull = econtext->domainValue_isNull;
2906 econtext->domainValue_datum = result;
2907 econtext->domainValue_isNull = *isNull;
2909 conResult = ExecEvalExpr(con->check_expr,
2910 econtext, &conIsNull, NULL);
2913 !DatumGetBool(conResult))
2915 (errcode(ERRCODE_CHECK_VIOLATION),
2916 errmsg("value for domain %s violates check constraint \"%s\"",
2917 format_type_be(ctest->resulttype),
2919 econtext->domainValue_datum = save_datum;
2920 econtext->domainValue_isNull = save_isNull;
2925 elog(ERROR, "unrecognized constraint type: %d",
2926 (int) con->constrainttype);
2931 /* If all has gone well (constraints did not fail) return the datum */
2936 * ExecEvalCoerceToDomainValue
2938 * Return the value stored by CoerceToDomain.
2941 ExecEvalCoerceToDomainValue(ExprState *exprstate,
2942 ExprContext *econtext,
2943 bool *isNull, ExprDoneCond *isDone)
2946 *isDone = ExprSingleResult;
2947 *isNull = econtext->domainValue_isNull;
2948 return econtext->domainValue_datum;
2951 /* ----------------------------------------------------------------
2952 * ExecEvalFieldSelect
2954 * Evaluate a FieldSelect node.
2955 * ----------------------------------------------------------------
2958 ExecEvalFieldSelect(FieldSelectState *fstate,
2959 ExprContext *econtext,
2961 ExprDoneCond *isDone)
2963 FieldSelect *fselect = (FieldSelect *) fstate->xprstate.expr;
2966 HeapTupleHeader tuple;
2970 HeapTupleData tmptup;
2972 tupDatum = ExecEvalExpr(fstate->arg, econtext, isNull, isDone);
2974 /* this test covers the isDone exception too: */
2978 tuple = DatumGetHeapTupleHeader(tupDatum);
2980 tupType = HeapTupleHeaderGetTypeId(tuple);
2981 tupTypmod = HeapTupleHeaderGetTypMod(tuple);
2983 /* Lookup tupdesc if first time through or if type changes */
2984 tupDesc = get_cached_rowtype(tupType, tupTypmod,
2985 &fstate->argdesc, econtext);
2988 * heap_getattr needs a HeapTuple not a bare HeapTupleHeader. We set all
2989 * the fields in the struct just in case user tries to inspect system
2992 tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
2993 ItemPointerSetInvalid(&(tmptup.t_self));
2994 tmptup.t_tableOid = InvalidOid;
2995 tmptup.t_data = tuple;
2997 result = heap_getattr(&tmptup,
3004 /* ----------------------------------------------------------------
3005 * ExecEvalFieldStore
3007 * Evaluate a FieldStore node.
3008 * ----------------------------------------------------------------
3011 ExecEvalFieldStore(FieldStoreState *fstate,
3012 ExprContext *econtext,
3014 ExprDoneCond *isDone)
3016 FieldStore *fstore = (FieldStore *) fstate->xprstate.expr;
3027 tupDatum = ExecEvalExpr(fstate->arg, econtext, isNull, isDone);
3029 if (isDone && *isDone == ExprEndResult)
3032 /* Lookup tupdesc if first time through or after rescan */
3033 tupDesc = get_cached_rowtype(fstore->resulttype, -1,
3034 &fstate->argdesc, econtext);
3036 /* Allocate workspace */
3037 values = (Datum *) palloc(tupDesc->natts * sizeof(Datum));
3038 isnull = (bool *) palloc(tupDesc->natts * sizeof(bool));
3043 * heap_deform_tuple needs a HeapTuple not a bare HeapTupleHeader. We
3044 * set all the fields in the struct just in case.
3046 HeapTupleHeader tuphdr;
3047 HeapTupleData tmptup;
3049 tuphdr = DatumGetHeapTupleHeader(tupDatum);
3050 tmptup.t_len = HeapTupleHeaderGetDatumLength(tuphdr);
3051 ItemPointerSetInvalid(&(tmptup.t_self));
3052 tmptup.t_tableOid = InvalidOid;
3053 tmptup.t_data = tuphdr;
3055 heap_deform_tuple(&tmptup, tupDesc, values, isnull);
3059 /* Convert null input tuple into an all-nulls row */
3060 memset(isnull, true, tupDesc->natts * sizeof(bool));
3063 /* Result is never null */
3066 save_datum = econtext->caseValue_datum;
3067 save_isNull = econtext->caseValue_isNull;
3069 forboth(l1, fstate->newvals, l2, fstore->fieldnums)
3071 ExprState *newval = (ExprState *) lfirst(l1);
3072 AttrNumber fieldnum = lfirst_int(l2);
3074 Assert(fieldnum > 0 && fieldnum <= tupDesc->natts);
3077 * Use the CaseTestExpr mechanism to pass down the old value of the
3078 * field being replaced; this is useful in case we have a nested field
3079 * update situation. It's safe to reuse the CASE mechanism because
3080 * there cannot be a CASE between here and where the value would be
3083 econtext->caseValue_datum = values[fieldnum - 1];
3084 econtext->caseValue_isNull = isnull[fieldnum - 1];
3086 values[fieldnum - 1] = ExecEvalExpr(newval,
3088 &isnull[fieldnum - 1],
3092 econtext->caseValue_datum = save_datum;
3093 econtext->caseValue_isNull = save_isNull;
3095 tuple = heap_form_tuple(tupDesc, values, isnull);
3100 return HeapTupleGetDatum(tuple);
3103 /* ----------------------------------------------------------------
3104 * ExecEvalRelabelType
3106 * Evaluate a RelabelType node.
3107 * ----------------------------------------------------------------
3110 ExecEvalRelabelType(GenericExprState *exprstate,
3111 ExprContext *econtext,
3112 bool *isNull, ExprDoneCond *isDone)
3114 return ExecEvalExpr(exprstate->arg, econtext, isNull, isDone);
3119 * ExecEvalExprSwitchContext
3121 * Same as ExecEvalExpr, but get into the right allocation context explicitly.
3124 ExecEvalExprSwitchContext(ExprState *expression,
3125 ExprContext *econtext,
3127 ExprDoneCond *isDone)
3130 MemoryContext oldContext;
3132 oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
3133 retDatum = ExecEvalExpr(expression, econtext, isNull, isDone);
3134 MemoryContextSwitchTo(oldContext);
3140 * ExecInitExpr: prepare an expression tree for execution
3142 * This function builds and returns an ExprState tree paralleling the given
3143 * Expr node tree. The ExprState tree can then be handed to ExecEvalExpr
3144 * for execution. Because the Expr tree itself is read-only as far as
3145 * ExecInitExpr and ExecEvalExpr are concerned, several different executions
3146 * of the same plan tree can occur concurrently.
3148 * This must be called in a memory context that will last as long as repeated
3149 * executions of the expression are needed. Typically the context will be
3150 * the same as the per-query context of the associated ExprContext.
3152 * Any Aggref and SubPlan nodes found in the tree are added to the lists
3153 * of such nodes held by the parent PlanState. Otherwise, we do very little
3154 * initialization here other than building the state-node tree. Any nontrivial
3155 * work associated with initializing runtime info for a node should happen
3156 * during the first actual evaluation of that node. (This policy lets us
3157 * avoid work if the node is never actually evaluated.)
3159 * Note: there is no ExecEndExpr function; we assume that any resource
3160 * cleanup needed will be handled by just releasing the memory context
3161 * in which the state tree is built. Functions that require additional
3162 * cleanup work can register a shutdown callback in the ExprContext.
3164 * 'node' is the root of the expression tree to examine
3165 * 'parent' is the PlanState node that owns the expression.
3167 * 'parent' may be NULL if we are preparing an expression that is not
3168 * associated with a plan tree. (If so, it can't have aggs or subplans.)
3169 * This case should usually come through ExecPrepareExpr, not directly here.
3172 ExecInitExpr(Expr *node, PlanState *parent)
3179 /* Guard against stack overflow due to overly complex expressions */
3180 check_stack_depth();
3182 switch (nodeTag(node))
3186 Var *var = (Var *) node;
3188 state = (ExprState *) makeNode(ExprState);
3189 if (var->varattno != InvalidAttrNumber)
3190 state->evalfunc = ExecEvalVar;
3192 state->evalfunc = ExecEvalWholeRowVar;
3196 state = (ExprState *) makeNode(ExprState);
3197 state->evalfunc = ExecEvalConst;
3200 state = (ExprState *) makeNode(ExprState);
3201 state->evalfunc = ExecEvalParam;
3203 case T_CoerceToDomainValue:
3204 state = (ExprState *) makeNode(ExprState);
3205 state->evalfunc = ExecEvalCoerceToDomainValue;
3207 case T_CaseTestExpr:
3208 state = (ExprState *) makeNode(ExprState);
3209 state->evalfunc = ExecEvalCaseTestExpr;
3213 Aggref *aggref = (Aggref *) node;
3214 AggrefExprState *astate = makeNode(AggrefExprState);
3216 astate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalAggref;
3217 if (parent && IsA(parent, AggState))
3219 AggState *aggstate = (AggState *) parent;
3222 aggstate->aggs = lcons(astate, aggstate->aggs);
3223 naggs = ++aggstate->numaggs;
3225 astate->args = (List *) ExecInitExpr((Expr *) aggref->args,
3229 * Complain if the aggregate's arguments contain any
3230 * aggregates; nested agg functions are semantically
3231 * nonsensical. (This should have been caught earlier,
3232 * but we defend against it here anyway.)
3234 if (naggs != aggstate->numaggs)
3236 (errcode(ERRCODE_GROUPING_ERROR),
3237 errmsg("aggregate function calls may not be nested")));
3241 /* planner messed up */
3242 elog(ERROR, "aggref found in non-Agg plan node");
3244 state = (ExprState *) astate;
3249 ArrayRef *aref = (ArrayRef *) node;
3250 ArrayRefExprState *astate = makeNode(ArrayRefExprState);
3252 astate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalArrayRef;
3253 astate->refupperindexpr = (List *)
3254 ExecInitExpr((Expr *) aref->refupperindexpr, parent);
3255 astate->reflowerindexpr = (List *)
3256 ExecInitExpr((Expr *) aref->reflowerindexpr, parent);
3257 astate->refexpr = ExecInitExpr(aref->refexpr, parent);
3258 astate->refassgnexpr = ExecInitExpr(aref->refassgnexpr,
3260 /* do one-time catalog lookups for type info */
3261 astate->refattrlength = get_typlen(aref->refarraytype);
3262 get_typlenbyvalalign(aref->refelemtype,
3263 &astate->refelemlength,
3264 &astate->refelembyval,
3265 &astate->refelemalign);
3266 state = (ExprState *) astate;
3271 FuncExpr *funcexpr = (FuncExpr *) node;
3272 FuncExprState *fstate = makeNode(FuncExprState);
3274 fstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalFunc;
3275 fstate->args = (List *)
3276 ExecInitExpr((Expr *) funcexpr->args, parent);
3277 fstate->func.fn_oid = InvalidOid; /* not initialized */
3278 state = (ExprState *) fstate;
3283 OpExpr *opexpr = (OpExpr *) node;
3284 FuncExprState *fstate = makeNode(FuncExprState);
3286 fstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalOper;
3287 fstate->args = (List *)
3288 ExecInitExpr((Expr *) opexpr->args, parent);
3289 fstate->func.fn_oid = InvalidOid; /* not initialized */
3290 state = (ExprState *) fstate;
3293 case T_DistinctExpr:
3295 DistinctExpr *distinctexpr = (DistinctExpr *) node;
3296 FuncExprState *fstate = makeNode(FuncExprState);
3298 fstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalDistinct;
3299 fstate->args = (List *)
3300 ExecInitExpr((Expr *) distinctexpr->args, parent);
3301 fstate->func.fn_oid = InvalidOid; /* not initialized */
3302 state = (ExprState *) fstate;
3305 case T_ScalarArrayOpExpr:
3307 ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) node;
3308 ScalarArrayOpExprState *sstate = makeNode(ScalarArrayOpExprState);
3310 sstate->fxprstate.xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalScalarArrayOp;
3311 sstate->fxprstate.args = (List *)
3312 ExecInitExpr((Expr *) opexpr->args, parent);
3313 sstate->fxprstate.func.fn_oid = InvalidOid; /* not initialized */
3314 sstate->element_type = InvalidOid; /* ditto */
3315 state = (ExprState *) sstate;
3320 BoolExpr *boolexpr = (BoolExpr *) node;
3321 BoolExprState *bstate = makeNode(BoolExprState);
3323 switch (boolexpr->boolop)
3326 bstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalAnd;
3329 bstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalOr;
3332 bstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalNot;
3335 elog(ERROR, "unrecognized boolop: %d",
3336 (int) boolexpr->boolop);
3339 bstate->args = (List *)
3340 ExecInitExpr((Expr *) boolexpr->args, parent);
3341 state = (ExprState *) bstate;
3346 /* Keep this in sync with ExecInitExprInitPlan, below */
3347 SubPlan *subplan = (SubPlan *) node;
3348 SubPlanState *sstate = makeNode(SubPlanState);
3350 sstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecSubPlan;
3353 elog(ERROR, "SubPlan found with no parent plan");
3356 * Here we just add the SubPlanState nodes to parent->subPlan.
3357 * The subplans will be initialized later.
3359 parent->subPlan = lcons(sstate, parent->subPlan);
3360 sstate->sub_estate = NULL;
3361 sstate->planstate = NULL;
3364 ExecInitExpr((Expr *) subplan->testexpr, parent);
3365 sstate->args = (List *)
3366 ExecInitExpr((Expr *) subplan->args, parent);
3368 state = (ExprState *) sstate;
3373 FieldSelect *fselect = (FieldSelect *) node;
3374 FieldSelectState *fstate = makeNode(FieldSelectState);
3376 fstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalFieldSelect;
3377 fstate->arg = ExecInitExpr(fselect->arg, parent);
3378 fstate->argdesc = NULL;
3379 state = (ExprState *) fstate;
3384 FieldStore *fstore = (FieldStore *) node;
3385 FieldStoreState *fstate = makeNode(FieldStoreState);
3387 fstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalFieldStore;
3388 fstate->arg = ExecInitExpr(fstore->arg, parent);
3389 fstate->newvals = (List *) ExecInitExpr((Expr *) fstore->newvals, parent);
3390 fstate->argdesc = NULL;
3391 state = (ExprState *) fstate;
3396 RelabelType *relabel = (RelabelType *) node;
3397 GenericExprState *gstate = makeNode(GenericExprState);
3399 gstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalRelabelType;
3400 gstate->arg = ExecInitExpr(relabel->arg, parent);
3401 state = (ExprState *) gstate;
3404 case T_ConvertRowtypeExpr:
3406 ConvertRowtypeExpr *convert = (ConvertRowtypeExpr *) node;
3407 ConvertRowtypeExprState *cstate = makeNode(ConvertRowtypeExprState);
3409 cstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalConvertRowtype;
3410 cstate->arg = ExecInitExpr(convert->arg, parent);
3411 state = (ExprState *) cstate;
3416 CaseExpr *caseexpr = (CaseExpr *) node;
3417 CaseExprState *cstate = makeNode(CaseExprState);
3418 List *outlist = NIL;
3421 cstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalCase;
3422 cstate->arg = ExecInitExpr(caseexpr->arg, parent);
3423 foreach(l, caseexpr->args)
3425 CaseWhen *when = (CaseWhen *) lfirst(l);
3426 CaseWhenState *wstate = makeNode(CaseWhenState);
3428 Assert(IsA(when, CaseWhen));
3429 wstate->xprstate.evalfunc = NULL; /* not used */
3430 wstate->xprstate.expr = (Expr *) when;
3431 wstate->expr = ExecInitExpr(when->expr, parent);
3432 wstate->result = ExecInitExpr(when->result, parent);
3433 outlist = lappend(outlist, wstate);
3435 cstate->args = outlist;
3436 cstate->defresult = ExecInitExpr(caseexpr->defresult, parent);
3437 state = (ExprState *) cstate;
3442 ArrayExpr *arrayexpr = (ArrayExpr *) node;
3443 ArrayExprState *astate = makeNode(ArrayExprState);
3444 List *outlist = NIL;
3447 astate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalArray;
3448 foreach(l, arrayexpr->elements)
3450 Expr *e = (Expr *) lfirst(l);
3453 estate = ExecInitExpr(e, parent);
3454 outlist = lappend(outlist, estate);
3456 astate->elements = outlist;
3457 /* do one-time catalog lookup for type info */
3458 get_typlenbyvalalign(arrayexpr->element_typeid,
3459 &astate->elemlength,
3461 &astate->elemalign);
3462 state = (ExprState *) astate;
3467 RowExpr *rowexpr = (RowExpr *) node;
3468 RowExprState *rstate = makeNode(RowExprState);
3469 Form_pg_attribute *attrs;
3470 List *outlist = NIL;
3474 rstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalRow;
3475 /* Build tupdesc to describe result tuples */
3476 if (rowexpr->row_typeid == RECORDOID)
3478 /* generic record, use runtime type assignment */
3479 rstate->tupdesc = ExecTypeFromExprList(rowexpr->args);
3480 BlessTupleDesc(rstate->tupdesc);
3481 /* we won't need to redo this at runtime */
3485 /* it's been cast to a named type, use that */
3486 rstate->tupdesc = lookup_rowtype_tupdesc_copy(rowexpr->row_typeid, -1);
3488 /* Set up evaluation, skipping any deleted columns */
3489 Assert(list_length(rowexpr->args) <= rstate->tupdesc->natts);
3490 attrs = rstate->tupdesc->attrs;
3492 foreach(l, rowexpr->args)
3494 Expr *e = (Expr *) lfirst(l);
3497 if (!attrs[i]->attisdropped)
3500 * Guard against ALTER COLUMN TYPE on rowtype since
3501 * the RowExpr was created. XXX should we check
3502 * typmod too? Not sure we can be sure it'll be the
3505 if (exprType((Node *) e) != attrs[i]->atttypid)
3507 (errcode(ERRCODE_DATATYPE_MISMATCH),
3508 errmsg("ROW() column has type %s instead of type %s",
3509 format_type_be(exprType((Node *) e)),
3510 format_type_be(attrs[i]->atttypid))));
3515 * Ignore original expression and insert a NULL. We
3516 * don't really care what type of NULL it is, so
3517 * always make an int4 NULL.
3519 e = (Expr *) makeNullConst(INT4OID);
3521 estate = ExecInitExpr(e, parent);
3522 outlist = lappend(outlist, estate);
3525 rstate->args = outlist;
3526 state = (ExprState *) rstate;
3529 case T_RowCompareExpr:
3531 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
3532 RowCompareExprState *rstate = makeNode(RowCompareExprState);
3533 int nopers = list_length(rcexpr->opnos);
3539 rstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalRowCompare;
3540 Assert(list_length(rcexpr->largs) == nopers);
3542 foreach(l, rcexpr->largs)
3544 Expr *e = (Expr *) lfirst(l);
3547 estate = ExecInitExpr(e, parent);
3548 outlist = lappend(outlist, estate);
3550 rstate->largs = outlist;
3551 Assert(list_length(rcexpr->rargs) == nopers);
3553 foreach(l, rcexpr->rargs)
3555 Expr *e = (Expr *) lfirst(l);
3558 estate = ExecInitExpr(e, parent);
3559 outlist = lappend(outlist, estate);
3561 rstate->rargs = outlist;
3562 Assert(list_length(rcexpr->opclasses) == nopers);
3563 rstate->funcs = (FmgrInfo *) palloc(nopers * sizeof(FmgrInfo));
3565 forboth(l, rcexpr->opnos, l2, rcexpr->opclasses)
3567 Oid opno = lfirst_oid(l);
3568 Oid opclass = lfirst_oid(l2);
3574 get_op_opclass_properties(opno, opclass,
3575 &strategy, &subtype, &recheck);
3576 proc = get_opclass_proc(opclass, subtype, BTORDER_PROC);
3579 * If we enforced permissions checks on index support
3580 * functions, we'd need to make a check here. But the
3581 * index support machinery doesn't do that, and neither
3584 fmgr_info(proc, &(rstate->funcs[i]));
3587 state = (ExprState *) rstate;
3590 case T_CoalesceExpr:
3592 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
3593 CoalesceExprState *cstate = makeNode(CoalesceExprState);
3594 List *outlist = NIL;
3597 cstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalCoalesce;
3598 foreach(l, coalesceexpr->args)
3600 Expr *e = (Expr *) lfirst(l);
3603 estate = ExecInitExpr(e, parent);
3604 outlist = lappend(outlist, estate);
3606 cstate->args = outlist;
3607 state = (ExprState *) cstate;
3612 MinMaxExpr *minmaxexpr = (MinMaxExpr *) node;
3613 MinMaxExprState *mstate = makeNode(MinMaxExprState);
3614 List *outlist = NIL;
3616 TypeCacheEntry *typentry;
3618 mstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalMinMax;
3619 foreach(l, minmaxexpr->args)
3621 Expr *e = (Expr *) lfirst(l);
3624 estate = ExecInitExpr(e, parent);
3625 outlist = lappend(outlist, estate);
3627 mstate->args = outlist;
3628 /* Look up the btree comparison function for the datatype */
3629 typentry = lookup_type_cache(minmaxexpr->minmaxtype,
3630 TYPECACHE_CMP_PROC);
3631 if (!OidIsValid(typentry->cmp_proc))
3633 (errcode(ERRCODE_UNDEFINED_FUNCTION),
3634 errmsg("could not identify a comparison function for type %s",
3635 format_type_be(minmaxexpr->minmaxtype))));
3638 * If we enforced permissions checks on index support
3639 * functions, we'd need to make a check here. But the index
3640 * support machinery doesn't do that, and neither does this
3643 fmgr_info(typentry->cmp_proc, &(mstate->cfunc));
3644 state = (ExprState *) mstate;
3649 NullIfExpr *nullifexpr = (NullIfExpr *) node;
3650 FuncExprState *fstate = makeNode(FuncExprState);
3652 fstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalNullIf;
3653 fstate->args = (List *)
3654 ExecInitExpr((Expr *) nullifexpr->args, parent);
3655 fstate->func.fn_oid = InvalidOid; /* not initialized */
3656 state = (ExprState *) fstate;
3661 NullTest *ntest = (NullTest *) node;
3662 NullTestState *nstate = makeNode(NullTestState);
3664 nstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalNullTest;
3665 nstate->arg = ExecInitExpr(ntest->arg, parent);
3666 nstate->argisrow = type_is_rowtype(exprType((Node *) ntest->arg));
3667 nstate->argdesc = NULL;
3668 state = (ExprState *) nstate;
3673 BooleanTest *btest = (BooleanTest *) node;
3674 GenericExprState *gstate = makeNode(GenericExprState);
3676 gstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalBooleanTest;
3677 gstate->arg = ExecInitExpr(btest->arg, parent);
3678 state = (ExprState *) gstate;
3681 case T_CoerceToDomain:
3683 CoerceToDomain *ctest = (CoerceToDomain *) node;
3684 CoerceToDomainState *cstate = makeNode(CoerceToDomainState);
3686 cstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalCoerceToDomain;
3687 cstate->arg = ExecInitExpr(ctest->arg, parent);
3688 cstate->constraints = GetDomainConstraints(ctest->resulttype);
3689 state = (ExprState *) cstate;
3694 TargetEntry *tle = (TargetEntry *) node;
3695 GenericExprState *gstate = makeNode(GenericExprState);
3697 gstate->xprstate.evalfunc = NULL; /* not used */
3698 gstate->arg = ExecInitExpr(tle->expr, parent);
3699 state = (ExprState *) gstate;
3704 List *outlist = NIL;
3707 foreach(l, (List *) node)
3709 outlist = lappend(outlist,
3710 ExecInitExpr((Expr *) lfirst(l),
3713 /* Don't fall through to the "common" code below */
3714 return (ExprState *) outlist;
3717 elog(ERROR, "unrecognized node type: %d",
3718 (int) nodeTag(node));
3719 state = NULL; /* keep compiler quiet */
3723 /* Common code for all state-node types */
3730 * ExecInitExprInitPlan --- initialize a subplan expr that's being handled
3731 * as an InitPlan. This is identical to ExecInitExpr's handling of a regular
3732 * subplan expr, except we do NOT want to add the node to the parent's
3736 ExecInitExprInitPlan(SubPlan *node, PlanState *parent)
3738 SubPlanState *sstate = makeNode(SubPlanState);
3741 elog(ERROR, "SubPlan found with no parent plan");
3743 /* The subplan's state will be initialized later */
3744 sstate->sub_estate = NULL;
3745 sstate->planstate = NULL;
3747 sstate->testexpr = ExecInitExpr((Expr *) node->testexpr, parent);
3748 sstate->args = (List *) ExecInitExpr((Expr *) node->args, parent);
3750 sstate->xprstate.expr = (Expr *) node;
3756 * ExecPrepareExpr --- initialize for expression execution outside a normal
3757 * Plan tree context.
3759 * This differs from ExecInitExpr in that we don't assume the caller is
3760 * already running in the EState's per-query context. Also, we apply
3761 * fix_opfuncids() to the passed expression tree to be sure it is ready
3762 * to run. (In ordinary Plan trees the planner will have fixed opfuncids,
3763 * but callers outside the executor will not have done this.)
3766 ExecPrepareExpr(Expr *node, EState *estate)
3769 MemoryContext oldcontext;
3771 fix_opfuncids((Node *) node);
3773 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
3775 result = ExecInitExpr(node, NULL);
3777 MemoryContextSwitchTo(oldcontext);
3783 /* ----------------------------------------------------------------
3784 * ExecQual / ExecTargetList / ExecProject
3785 * ----------------------------------------------------------------
3788 /* ----------------------------------------------------------------
3791 * Evaluates a conjunctive boolean expression (qual list) and
3792 * returns true iff none of the subexpressions are false.
3793 * (We also return true if the list is empty.)
3795 * If some of the subexpressions yield NULL but none yield FALSE,
3796 * then the result of the conjunction is NULL (ie, unknown)
3797 * according to three-valued boolean logic. In this case,
3798 * we return the value specified by the "resultForNull" parameter.
3800 * Callers evaluating WHERE clauses should pass resultForNull=FALSE,
3801 * since SQL specifies that tuples with null WHERE results do not
3802 * get selected. On the other hand, callers evaluating constraint
3803 * conditions should pass resultForNull=TRUE, since SQL also specifies
3804 * that NULL constraint conditions are not failures.
3806 * NOTE: it would not be correct to use this routine to evaluate an
3807 * AND subclause of a boolean expression; for that purpose, a NULL
3808 * result must be returned as NULL so that it can be properly treated
3809 * in the next higher operator (cf. ExecEvalAnd and ExecEvalOr).
3810 * This routine is only used in contexts where a complete expression
3811 * is being evaluated and we know that NULL can be treated the same
3812 * as one boolean result or the other.
3814 * ----------------------------------------------------------------
3817 ExecQual(List *qual, ExprContext *econtext, bool resultForNull)
3820 MemoryContext oldContext;
3826 EV_printf("ExecQual: qual is ");
3827 EV_nodeDisplay(qual);
3833 * Run in short-lived per-tuple context while computing expressions.
3835 oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
3838 * Evaluate the qual conditions one at a time. If we find a FALSE result,
3839 * we can stop evaluating and return FALSE --- the AND result must be
3840 * FALSE. Also, if we find a NULL result when resultForNull is FALSE, we
3841 * can stop and return FALSE --- the AND result must be FALSE or NULL in
3842 * that case, and the caller doesn't care which.
3844 * If we get to the end of the list, we can return TRUE. This will happen
3845 * when the AND result is indeed TRUE, or when the AND result is NULL (one
3846 * or more NULL subresult, with all the rest TRUE) and the caller has
3847 * specified resultForNull = TRUE.
3853 ExprState *clause = (ExprState *) lfirst(l);
3857 expr_value = ExecEvalExpr(clause, econtext, &isNull, NULL);
3861 if (resultForNull == false)
3863 result = false; /* treat NULL as FALSE */
3869 if (!DatumGetBool(expr_value))
3871 result = false; /* definitely FALSE */
3877 MemoryContextSwitchTo(oldContext);
3883 * Number of items in a tlist (including any resjunk items!)
3886 ExecTargetListLength(List *targetlist)
3888 /* This used to be more complex, but fjoins are dead */
3889 return list_length(targetlist);
3893 * Number of items in a tlist, not including any resjunk items
3896 ExecCleanTargetListLength(List *targetlist)
3901 foreach(tl, targetlist)
3903 TargetEntry *curTle = (TargetEntry *) lfirst(tl);
3905 Assert(IsA(curTle, TargetEntry));
3906 if (!curTle->resjunk)
3914 * Evaluates a targetlist with respect to the given
3915 * expression context. Returns TRUE if we were able to create
3916 * a result, FALSE if we have exhausted a set-valued expression.
3918 * Results are stored into the passed values and isnull arrays.
3919 * The caller must provide an itemIsDone array that persists across calls.
3921 * As with ExecEvalExpr, the caller should pass isDone = NULL if not
3922 * prepared to deal with sets of result tuples. Otherwise, a return
3923 * of *isDone = ExprMultipleResult signifies a set element, and a return
3924 * of *isDone = ExprEndResult signifies end of the set of tuple.
3927 ExecTargetList(List *targetlist,
3928 ExprContext *econtext,
3931 ExprDoneCond *itemIsDone,
3932 ExprDoneCond *isDone)
3934 MemoryContext oldContext;
3939 * Run in short-lived per-tuple context while computing expressions.
3941 oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
3944 * evaluate all the expressions in the target list
3947 *isDone = ExprSingleResult; /* until proven otherwise */
3949 haveDoneSets = false; /* any exhausted set exprs in tlist? */
3951 foreach(tl, targetlist)
3953 GenericExprState *gstate = (GenericExprState *) lfirst(tl);
3954 TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr;
3955 AttrNumber resind = tle->resno - 1;
3957 values[resind] = ExecEvalExpr(gstate->arg,
3960 &itemIsDone[resind]);
3962 if (itemIsDone[resind] != ExprSingleResult)
3964 /* We have a set-valued expression in the tlist */
3967 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3968 errmsg("set-valued function called in context that cannot accept a set")));
3969 if (itemIsDone[resind] == ExprMultipleResult)
3971 /* we have undone sets in the tlist, set flag */
3972 *isDone = ExprMultipleResult;
3976 /* we have done sets in the tlist, set flag for that */
3977 haveDoneSets = true;
3985 * note: can't get here unless we verified isDone != NULL
3987 if (*isDone == ExprSingleResult)
3990 * all sets are done, so report that tlist expansion is complete.
3992 *isDone = ExprEndResult;
3993 MemoryContextSwitchTo(oldContext);
3999 * We have some done and some undone sets. Restart the done ones
4000 * so that we can deliver a tuple (if possible).
4002 foreach(tl, targetlist)
4004 GenericExprState *gstate = (GenericExprState *) lfirst(tl);
4005 TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr;
4006 AttrNumber resind = tle->resno - 1;
4008 if (itemIsDone[resind] == ExprEndResult)
4010 values[resind] = ExecEvalExpr(gstate->arg,
4013 &itemIsDone[resind]);
4015 if (itemIsDone[resind] == ExprEndResult)
4018 * Oh dear, this item is returning an empty set. Guess
4019 * we can't make a tuple after all.
4021 *isDone = ExprEndResult;
4028 * If we cannot make a tuple because some sets are empty, we still
4029 * have to cycle the nonempty sets to completion, else resources
4030 * will not be released from subplans etc.
4032 * XXX is that still necessary?
4034 if (*isDone == ExprEndResult)
4036 foreach(tl, targetlist)
4038 GenericExprState *gstate = (GenericExprState *) lfirst(tl);
4039 TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr;
4040 AttrNumber resind = tle->resno - 1;
4042 while (itemIsDone[resind] == ExprMultipleResult)
4044 values[resind] = ExecEvalExpr(gstate->arg,
4047 &itemIsDone[resind]);
4051 MemoryContextSwitchTo(oldContext);
4057 /* Report success */
4058 MemoryContextSwitchTo(oldContext);
4065 * Evaluates a simple-Variable-list projection.
4067 * Results are stored into the passed values and isnull arrays.
4070 ExecVariableList(ProjectionInfo *projInfo,
4074 ExprContext *econtext = projInfo->pi_exprContext;
4075 int *varSlotOffsets = projInfo->pi_varSlotOffsets;
4076 int *varNumbers = projInfo->pi_varNumbers;
4080 * Force extraction of all input values that we need.
4082 if (projInfo->pi_lastInnerVar > 0)
4083 slot_getsomeattrs(econtext->ecxt_innertuple,
4084 projInfo->pi_lastInnerVar);
4085 if (projInfo->pi_lastOuterVar > 0)
4086 slot_getsomeattrs(econtext->ecxt_outertuple,
4087 projInfo->pi_lastOuterVar);
4088 if (projInfo->pi_lastScanVar > 0)
4089 slot_getsomeattrs(econtext->ecxt_scantuple,
4090 projInfo->pi_lastScanVar);
4093 * Assign to result by direct extraction of fields from source slots ... a
4094 * mite ugly, but fast ...
4096 for (i = list_length(projInfo->pi_targetlist) - 1; i >= 0; i--)
4098 char *slotptr = ((char *) econtext) + varSlotOffsets[i];
4099 TupleTableSlot *varSlot = *((TupleTableSlot **) slotptr);
4100 int varNumber = varNumbers[i] - 1;
4102 values[i] = varSlot->tts_values[varNumber];
4103 isnull[i] = varSlot->tts_isnull[varNumber];
4110 * projects a tuple based on projection info and stores
4111 * it in the previously specified tuple table slot.
4113 * Note: the result is always a virtual tuple; therefore it
4114 * may reference the contents of the exprContext's scan tuples
4115 * and/or temporary results constructed in the exprContext.
4116 * If the caller wishes the result to be valid longer than that
4117 * data will be valid, he must call ExecMaterializeSlot on the
4121 ExecProject(ProjectionInfo *projInfo, ExprDoneCond *isDone)
4123 TupleTableSlot *slot;
4128 Assert(projInfo != NULL);
4131 * get the projection info we want
4133 slot = projInfo->pi_slot;
4136 * Clear any former contents of the result slot. This makes it safe for
4137 * us to use the slot's Datum/isnull arrays as workspace. (Also, we can
4138 * return the slot as-is if we decide no rows can be projected.)
4140 ExecClearTuple(slot);
4143 * form a new result tuple (if possible); if successful, mark the result
4144 * slot as containing a valid virtual tuple
4146 if (projInfo->pi_isVarList)
4148 /* simple Var list: this always succeeds with one result row */
4150 *isDone = ExprSingleResult;
4151 ExecVariableList(projInfo,
4154 ExecStoreVirtualTuple(slot);
4158 if (ExecTargetList(projInfo->pi_targetlist,
4159 projInfo->pi_exprContext,
4162 projInfo->pi_itemIsDone,
4164 ExecStoreVirtualTuple(slot);