1 /*-------------------------------------------------------------------------
4 * Routines to evaluate qualification and targetlist expressions
6 * Portions Copyright (c) 1996-2008, 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.229 2008/04/13 20:51:20 tgl Exp $
13 *-------------------------------------------------------------------------
17 * ExecEvalExpr - (now a macro) evaluate an expression, return a datum
18 * ExecEvalExprSwitchContext - same, but switch into eval memory context
19 * ExecQual - return true/false if qualification is satisfied
20 * ExecProject - form a new tuple by projecting the given tuple
23 * The more heavily used ExecEvalExpr routines, such as ExecEvalVar(),
24 * are hotspots. Making these faster will speed up the entire system.
26 * ExecProject() is used to make tuple projections. Rather then
27 * trying to speed it up, the execution plan should be pre-processed
28 * to facilitate attribute sharing between nodes wherever possible,
29 * instead of doing needless copying. -cim 5/31/91
31 * During expression evaluation, we check_stack_depth only in
32 * ExecMakeFunctionResult rather than at every single node. This
33 * is a compromise that trades off precision of the stack limit setting
39 #include "access/heapam.h"
40 #include "access/nbtree.h"
41 #include "catalog/pg_type.h"
42 #include "commands/typecmds.h"
43 #include "executor/execdebug.h"
44 #include "executor/nodeSubplan.h"
46 #include "miscadmin.h"
47 #include "nodes/makefuncs.h"
48 #include "optimizer/planmain.h"
49 #include "parser/parse_expr.h"
50 #include "utils/acl.h"
51 #include "utils/builtins.h"
52 #include "utils/lsyscache.h"
53 #include "utils/memutils.h"
54 #include "utils/typcache.h"
55 #include "utils/xml.h"
58 /* static function decls */
59 static Datum ExecEvalArrayRef(ArrayRefExprState *astate,
60 ExprContext *econtext,
61 bool *isNull, ExprDoneCond *isDone);
62 static Datum ExecEvalAggref(AggrefExprState *aggref,
63 ExprContext *econtext,
64 bool *isNull, ExprDoneCond *isDone);
65 static Datum ExecEvalVar(ExprState *exprstate, ExprContext *econtext,
66 bool *isNull, ExprDoneCond *isDone);
67 static Datum ExecEvalScalarVar(ExprState *exprstate, ExprContext *econtext,
68 bool *isNull, ExprDoneCond *isDone);
69 static Datum ExecEvalWholeRowVar(ExprState *exprstate, ExprContext *econtext,
70 bool *isNull, ExprDoneCond *isDone);
71 static Datum ExecEvalWholeRowSlow(ExprState *exprstate, ExprContext *econtext,
72 bool *isNull, ExprDoneCond *isDone);
73 static Datum ExecEvalConst(ExprState *exprstate, ExprContext *econtext,
74 bool *isNull, ExprDoneCond *isDone);
75 static Datum ExecEvalParam(ExprState *exprstate, ExprContext *econtext,
76 bool *isNull, ExprDoneCond *isDone);
77 static void ShutdownFuncExpr(Datum arg);
78 static TupleDesc get_cached_rowtype(Oid type_id, int32 typmod,
79 TupleDesc *cache_field, ExprContext *econtext);
80 static void ShutdownTupleDescRef(Datum arg);
81 static ExprDoneCond ExecEvalFuncArgs(FunctionCallInfo fcinfo,
82 List *argList, ExprContext *econtext);
83 static Datum ExecMakeFunctionResultNoSets(FuncExprState *fcache,
84 ExprContext *econtext,
85 bool *isNull, ExprDoneCond *isDone);
86 static Datum ExecEvalFunc(FuncExprState *fcache, ExprContext *econtext,
87 bool *isNull, ExprDoneCond *isDone);
88 static Datum ExecEvalOper(FuncExprState *fcache, ExprContext *econtext,
89 bool *isNull, ExprDoneCond *isDone);
90 static Datum ExecEvalDistinct(FuncExprState *fcache, ExprContext *econtext,
91 bool *isNull, ExprDoneCond *isDone);
92 static Datum ExecEvalScalarArrayOp(ScalarArrayOpExprState *sstate,
93 ExprContext *econtext,
94 bool *isNull, ExprDoneCond *isDone);
95 static Datum ExecEvalNot(BoolExprState *notclause, ExprContext *econtext,
96 bool *isNull, ExprDoneCond *isDone);
97 static Datum ExecEvalOr(BoolExprState *orExpr, ExprContext *econtext,
98 bool *isNull, ExprDoneCond *isDone);
99 static Datum ExecEvalAnd(BoolExprState *andExpr, ExprContext *econtext,
100 bool *isNull, ExprDoneCond *isDone);
101 static Datum ExecEvalConvertRowtype(ConvertRowtypeExprState *cstate,
102 ExprContext *econtext,
103 bool *isNull, ExprDoneCond *isDone);
104 static Datum ExecEvalCase(CaseExprState *caseExpr, ExprContext *econtext,
105 bool *isNull, ExprDoneCond *isDone);
106 static Datum ExecEvalCaseTestExpr(ExprState *exprstate,
107 ExprContext *econtext,
108 bool *isNull, ExprDoneCond *isDone);
109 static Datum ExecEvalArray(ArrayExprState *astate,
110 ExprContext *econtext,
111 bool *isNull, ExprDoneCond *isDone);
112 static Datum ExecEvalRow(RowExprState *rstate,
113 ExprContext *econtext,
114 bool *isNull, ExprDoneCond *isDone);
115 static Datum ExecEvalRowCompare(RowCompareExprState *rstate,
116 ExprContext *econtext,
117 bool *isNull, ExprDoneCond *isDone);
118 static Datum ExecEvalCoalesce(CoalesceExprState *coalesceExpr,
119 ExprContext *econtext,
120 bool *isNull, ExprDoneCond *isDone);
121 static Datum ExecEvalMinMax(MinMaxExprState *minmaxExpr,
122 ExprContext *econtext,
123 bool *isNull, ExprDoneCond *isDone);
124 static Datum ExecEvalXml(XmlExprState *xmlExpr, ExprContext *econtext,
125 bool *isNull, ExprDoneCond *isDone);
126 static Datum ExecEvalNullIf(FuncExprState *nullIfExpr,
127 ExprContext *econtext,
128 bool *isNull, ExprDoneCond *isDone);
129 static Datum ExecEvalNullTest(NullTestState *nstate,
130 ExprContext *econtext,
131 bool *isNull, ExprDoneCond *isDone);
132 static Datum ExecEvalBooleanTest(GenericExprState *bstate,
133 ExprContext *econtext,
134 bool *isNull, ExprDoneCond *isDone);
135 static Datum ExecEvalCoerceToDomain(CoerceToDomainState *cstate,
136 ExprContext *econtext,
137 bool *isNull, ExprDoneCond *isDone);
138 static Datum ExecEvalCoerceToDomainValue(ExprState *exprstate,
139 ExprContext *econtext,
140 bool *isNull, ExprDoneCond *isDone);
141 static Datum ExecEvalFieldSelect(FieldSelectState *fstate,
142 ExprContext *econtext,
143 bool *isNull, ExprDoneCond *isDone);
144 static Datum ExecEvalFieldStore(FieldStoreState *fstate,
145 ExprContext *econtext,
146 bool *isNull, ExprDoneCond *isDone);
147 static Datum ExecEvalRelabelType(GenericExprState *exprstate,
148 ExprContext *econtext,
149 bool *isNull, ExprDoneCond *isDone);
150 static Datum ExecEvalCoerceViaIO(CoerceViaIOState *iostate,
151 ExprContext *econtext,
152 bool *isNull, ExprDoneCond *isDone);
153 static Datum ExecEvalArrayCoerceExpr(ArrayCoerceExprState *astate,
154 ExprContext *econtext,
155 bool *isNull, ExprDoneCond *isDone);
156 static Datum ExecEvalCurrentOfExpr(ExprState *exprstate, ExprContext *econtext,
157 bool *isNull, ExprDoneCond *isDone);
160 /* ----------------------------------------------------------------
161 * ExecEvalExpr routines
163 * Recursively evaluate a targetlist or qualification expression.
165 * Each of the following routines having the signature
166 * Datum ExecEvalFoo(ExprState *expression,
167 * ExprContext *econtext,
169 * ExprDoneCond *isDone);
170 * is responsible for evaluating one type or subtype of ExprState node.
171 * They are normally called via the ExecEvalExpr macro, which makes use of
172 * the function pointer set up when the ExprState node was built by
173 * ExecInitExpr. (In some cases, we change this pointer later to avoid
174 * re-executing one-time overhead.)
176 * Note: for notational simplicity we declare these functions as taking the
177 * specific type of ExprState that they work on. This requires casting when
178 * assigning the function pointer in ExecInitExpr. Be careful that the
179 * function signature is declared correctly, because the cast suppresses
180 * automatic checking!
183 * All these functions share this calling convention:
186 * expression: the expression state tree to evaluate
187 * econtext: evaluation context information
190 * return value: Datum value of result
191 * *isNull: set to TRUE if result is NULL (actual return value is
192 * meaningless if so); set to FALSE if non-null result
193 * *isDone: set to indicator of set-result status
195 * A caller that can only accept a singleton (non-set) result should pass
196 * NULL for isDone; if the expression computes a set result then an error
197 * will be reported via ereport. If the caller does pass an isDone pointer
198 * then *isDone is set to one of these three states:
199 * ExprSingleResult singleton result (not a set)
200 * ExprMultipleResult return value is one element of a set
201 * ExprEndResult there are no more elements in the set
202 * When ExprMultipleResult is returned, the caller should invoke
203 * ExecEvalExpr() repeatedly until ExprEndResult is returned. ExprEndResult
204 * is returned after the last real set element. For convenience isNull will
205 * always be set TRUE when ExprEndResult is returned, but this should not be
206 * taken as indicating a NULL element of the set. Note that these return
207 * conventions allow us to distinguish among a singleton NULL, a NULL element
208 * of a set, and an empty set.
210 * The caller should already have switched into the temporary memory
211 * context econtext->ecxt_per_tuple_memory. The convenience entry point
212 * ExecEvalExprSwitchContext() is provided for callers who don't prefer to
213 * do the switch in an outer loop. We do not do the switch in these routines
214 * because it'd be a waste of cycles during nested expression evaluation.
215 * ----------------------------------------------------------------
222 * This function takes an ArrayRef and returns the extracted Datum
223 * if it's a simple reference, or the modified array value if it's
224 * an array assignment (i.e., array element or slice insertion).
226 * NOTE: if we get a NULL result from a subscript expression, we return NULL
227 * when it's an array reference, or raise an error when it's an assignment.
229 * NOTE: we deliberately refrain from applying DatumGetArrayTypeP() here,
230 * even though that might seem natural, because this code needs to support
231 * both varlena arrays and fixed-length array types. DatumGetArrayTypeP()
232 * only works for the varlena kind. The routines we call in arrayfuncs.c
233 * have to know the difference (that's what they need refattrlength for).
237 ExecEvalArrayRef(ArrayRefExprState *astate,
238 ExprContext *econtext,
240 ExprDoneCond *isDone)
242 ArrayRef *arrayRef = (ArrayRef *) astate->xprstate.expr;
243 ArrayType *array_source;
244 ArrayType *resultArray;
245 bool isAssignment = (arrayRef->refassgnexpr != NULL);
254 array_source = (ArrayType *)
255 DatumGetPointer(ExecEvalExpr(astate->refexpr,
261 * If refexpr yields NULL, and it's a fetch, then result is NULL. In the
262 * assignment case, we'll cons up something below.
266 if (isDone && *isDone == ExprEndResult)
267 return (Datum) NULL; /* end of set result */
272 foreach(l, astate->refupperindexpr)
274 ExprState *eltstate = (ExprState *) lfirst(l);
278 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
279 errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
282 upper.indx[i++] = DatumGetInt32(ExecEvalExpr(eltstate,
286 /* If any index expr yields NULL, result is NULL or error */
291 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
292 errmsg("array subscript in assignment must not be null")));
298 if (astate->reflowerindexpr != NIL)
300 foreach(l, astate->reflowerindexpr)
302 ExprState *eltstate = (ExprState *) lfirst(l);
306 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
307 errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
310 lower.indx[j++] = DatumGetInt32(ExecEvalExpr(eltstate,
314 /* If any index expr yields NULL, result is NULL or error */
319 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
320 errmsg("array subscript in assignment must not be null")));
325 /* this can't happen unless parser messed up */
327 elog(ERROR, "upper and lower index lists are not same length");
338 * Evaluate the value to be assigned into the array.
340 * XXX At some point we'll need to look into making the old value of
341 * the array element available via CaseTestExpr, as is done by
342 * ExecEvalFieldStore. This is not needed now but will be needed to
343 * support arrays of composite types; in an assignment to a field of
344 * an array member, the parser would generate a FieldStore that
345 * expects to fetch its input tuple via CaseTestExpr.
347 sourceData = ExecEvalExpr(astate->refassgnexpr,
353 * For an assignment to a fixed-length array type, both the original
354 * array and the value to be assigned into it must be non-NULL, else
355 * we punt and return the original array.
357 if (astate->refattrlength > 0) /* fixed-length array? */
358 if (eisnull || *isNull)
359 return PointerGetDatum(array_source);
362 * For assignment to varlena arrays, we handle a NULL original array
363 * by substituting an empty (zero-dimensional) array; insertion of the
364 * new element will result in a singleton array value. It does not
365 * matter whether the new element is NULL.
369 array_source = construct_empty_array(arrayRef->refelemtype);
374 resultArray = array_set(array_source, i,
378 astate->refattrlength,
379 astate->refelemlength,
380 astate->refelembyval,
381 astate->refelemalign);
383 resultArray = array_set_slice(array_source, i,
384 upper.indx, lower.indx,
385 (ArrayType *) DatumGetPointer(sourceData),
387 astate->refattrlength,
388 astate->refelemlength,
389 astate->refelembyval,
390 astate->refelemalign);
391 return PointerGetDatum(resultArray);
395 return array_ref(array_source, i, upper.indx,
396 astate->refattrlength,
397 astate->refelemlength,
398 astate->refelembyval,
399 astate->refelemalign,
403 resultArray = array_get_slice(array_source, i,
404 upper.indx, lower.indx,
405 astate->refattrlength,
406 astate->refelemlength,
407 astate->refelembyval,
408 astate->refelemalign);
409 return PointerGetDatum(resultArray);
414 /* ----------------------------------------------------------------
417 * Returns a Datum whose value is the value of the precomputed
418 * aggregate found in the given expression context.
419 * ----------------------------------------------------------------
422 ExecEvalAggref(AggrefExprState *aggref, ExprContext *econtext,
423 bool *isNull, ExprDoneCond *isDone)
426 *isDone = ExprSingleResult;
428 if (econtext->ecxt_aggvalues == NULL) /* safety check */
429 elog(ERROR, "no aggregates in this expression context");
431 *isNull = econtext->ecxt_aggnulls[aggref->aggno];
432 return econtext->ecxt_aggvalues[aggref->aggno];
435 /* ----------------------------------------------------------------
438 * Returns a Datum whose value is the value of a range
439 * variable with respect to given expression context.
441 * Note: ExecEvalVar is executed only the first time through in a given plan;
442 * it changes the ExprState's function pointer to pass control directly to
443 * ExecEvalScalarVar, ExecEvalWholeRowVar, or ExecEvalWholeRowSlow after
444 * making one-time checks.
445 * ----------------------------------------------------------------
448 ExecEvalVar(ExprState *exprstate, ExprContext *econtext,
449 bool *isNull, ExprDoneCond *isDone)
451 Var *variable = (Var *) exprstate->expr;
452 TupleTableSlot *slot;
456 *isDone = ExprSingleResult;
459 * Get the input slot and attribute number we want
461 * The asserts check that references to system attributes only appear at
462 * the level of a relation scan; at higher levels, system attributes must
463 * be treated as ordinary variables (since we no longer have access to the
466 attnum = variable->varattno;
468 switch (variable->varno)
470 case INNER: /* get the tuple from the inner node */
471 slot = econtext->ecxt_innertuple;
475 case OUTER: /* get the tuple from the outer node */
476 slot = econtext->ecxt_outertuple;
480 default: /* get the tuple from the relation being
482 slot = econtext->ecxt_scantuple;
486 if (attnum != InvalidAttrNumber)
489 * Scalar variable case.
491 * If it's a user attribute, check validity (bogus system attnums will
492 * be caught inside slot_getattr). What we have to check for here is
493 * the possibility of an attribute having been changed in type since
494 * the plan tree was created. Ideally the plan would get invalidated
495 * and not re-used, but until that day arrives, we need defenses.
496 * Fortunately it's sufficient to check once on the first time
499 * Note: we allow a reference to a dropped attribute. slot_getattr
500 * will force a NULL result in such cases.
502 * Note: ideally we'd check typmod as well as typid, but that seems
503 * impractical at the moment: in many cases the tupdesc will have been
504 * generated by ExecTypeFromTL(), and that can't guarantee to generate
505 * an accurate typmod in all cases, because some expression node types
506 * don't carry typmod.
510 TupleDesc slot_tupdesc = slot->tts_tupleDescriptor;
511 Form_pg_attribute attr;
513 if (attnum > slot_tupdesc->natts) /* should never happen */
514 elog(ERROR, "attribute number %d exceeds number of columns %d",
515 attnum, slot_tupdesc->natts);
517 attr = slot_tupdesc->attrs[attnum - 1];
519 /* can't check type if dropped, since atttypid is probably 0 */
520 if (!attr->attisdropped)
522 if (variable->vartype != attr->atttypid)
524 (errmsg("attribute %d has wrong type", attnum),
525 errdetail("Table has type %s, but query expects %s.",
526 format_type_be(attr->atttypid),
527 format_type_be(variable->vartype))));
531 /* Skip the checking on future executions of node */
532 exprstate->evalfunc = ExecEvalScalarVar;
534 /* Fetch the value from the slot */
535 return slot_getattr(slot, attnum, isNull);
540 * Whole-row variable.
542 * If it's a RECORD Var, we'll use the slot's type ID info. It's
543 * likely that the slot's type is also RECORD; if so, make sure it's
544 * been "blessed", so that the Datum can be interpreted later.
546 * If the Var identifies a named composite type, we must check that
547 * the actual tuple type is compatible with it.
549 TupleDesc slot_tupdesc = slot->tts_tupleDescriptor;
550 bool needslow = false;
552 if (variable->vartype == RECORDOID)
554 if (slot_tupdesc->tdtypeid == RECORDOID &&
555 slot_tupdesc->tdtypmod < 0)
556 assign_record_type_typmod(slot_tupdesc);
560 TupleDesc var_tupdesc;
564 * We really only care about number of attributes and data type.
565 * Also, we can ignore type mismatch on columns that are dropped
566 * in the destination type, so long as the physical storage
567 * matches. This is helpful in some cases involving out-of-date
568 * cached plans. Also, we have to allow the case that the slot
569 * has more columns than the Var's type, because we might be
570 * looking at the output of a subplan that includes resjunk
571 * columns. (XXX it would be nice to verify that the extra
572 * columns are all marked resjunk, but we haven't got access to
573 * the subplan targetlist here...) Resjunk columns should always
574 * be at the end of a targetlist, so it's sufficient to ignore
575 * them here; but we need to use ExecEvalWholeRowSlow to get rid
576 * of them in the eventual output tuples.
578 var_tupdesc = lookup_rowtype_tupdesc(variable->vartype, -1);
580 if (var_tupdesc->natts > slot_tupdesc->natts)
582 (errcode(ERRCODE_DATATYPE_MISMATCH),
583 errmsg("table row type and query-specified row type do not match"),
584 errdetail("Table row contains %d attributes, but query expects %d.",
585 slot_tupdesc->natts, var_tupdesc->natts)));
586 else if (var_tupdesc->natts < slot_tupdesc->natts)
589 for (i = 0; i < var_tupdesc->natts; i++)
591 Form_pg_attribute vattr = var_tupdesc->attrs[i];
592 Form_pg_attribute sattr = slot_tupdesc->attrs[i];
594 if (vattr->atttypid == sattr->atttypid)
595 continue; /* no worries */
596 if (!vattr->attisdropped)
598 (errcode(ERRCODE_DATATYPE_MISMATCH),
599 errmsg("table row type and query-specified row type do not match"),
600 errdetail("Table has type %s at ordinal position %d, but query expects %s.",
601 format_type_be(sattr->atttypid),
603 format_type_be(vattr->atttypid))));
605 if (vattr->attlen != sattr->attlen ||
606 vattr->attalign != sattr->attalign)
608 (errcode(ERRCODE_DATATYPE_MISMATCH),
609 errmsg("table row type and query-specified row type do not match"),
610 errdetail("Physical storage mismatch on dropped attribute at ordinal position %d.",
614 ReleaseTupleDesc(var_tupdesc);
617 /* Skip the checking on future executions of node */
619 exprstate->evalfunc = ExecEvalWholeRowSlow;
621 exprstate->evalfunc = ExecEvalWholeRowVar;
623 /* Fetch the value */
624 return ExecEvalWholeRowVar(exprstate, econtext, isNull, isDone);
628 /* ----------------------------------------------------------------
631 * Returns a Datum for a scalar variable.
632 * ----------------------------------------------------------------
635 ExecEvalScalarVar(ExprState *exprstate, ExprContext *econtext,
636 bool *isNull, ExprDoneCond *isDone)
638 Var *variable = (Var *) exprstate->expr;
639 TupleTableSlot *slot;
643 *isDone = ExprSingleResult;
645 /* Get the input slot and attribute number we want */
646 switch (variable->varno)
648 case INNER: /* get the tuple from the inner node */
649 slot = econtext->ecxt_innertuple;
652 case OUTER: /* get the tuple from the outer node */
653 slot = econtext->ecxt_outertuple;
656 default: /* get the tuple from the relation being
658 slot = econtext->ecxt_scantuple;
662 attnum = variable->varattno;
664 /* Fetch the value from the slot */
665 return slot_getattr(slot, attnum, isNull);
668 /* ----------------------------------------------------------------
669 * ExecEvalWholeRowVar
671 * Returns a Datum for a whole-row variable.
672 * ----------------------------------------------------------------
675 ExecEvalWholeRowVar(ExprState *exprstate, ExprContext *econtext,
676 bool *isNull, ExprDoneCond *isDone)
678 Var *variable = (Var *) exprstate->expr;
679 TupleTableSlot *slot = econtext->ecxt_scantuple;
682 HeapTupleHeader dtuple;
685 *isDone = ExprSingleResult;
688 tuple = ExecFetchSlotTuple(slot);
689 tupleDesc = slot->tts_tupleDescriptor;
692 * We have to make a copy of the tuple so we can safely insert the Datum
693 * overhead fields, which are not set in on-disk tuples.
695 dtuple = (HeapTupleHeader) palloc(tuple->t_len);
696 memcpy((char *) dtuple, (char *) tuple->t_data, tuple->t_len);
698 HeapTupleHeaderSetDatumLength(dtuple, tuple->t_len);
701 * If the Var identifies a named composite type, label the tuple with that
702 * type; otherwise use what is in the tupleDesc.
704 if (variable->vartype != RECORDOID)
706 HeapTupleHeaderSetTypeId(dtuple, variable->vartype);
707 HeapTupleHeaderSetTypMod(dtuple, variable->vartypmod);
711 HeapTupleHeaderSetTypeId(dtuple, tupleDesc->tdtypeid);
712 HeapTupleHeaderSetTypMod(dtuple, tupleDesc->tdtypmod);
715 return PointerGetDatum(dtuple);
718 /* ----------------------------------------------------------------
719 * ExecEvalWholeRowSlow
721 * Returns a Datum for a whole-row variable, in the "slow" case where
722 * we can't just copy the subplan's output.
723 * ----------------------------------------------------------------
726 ExecEvalWholeRowSlow(ExprState *exprstate, ExprContext *econtext,
727 bool *isNull, ExprDoneCond *isDone)
729 Var *variable = (Var *) exprstate->expr;
730 TupleTableSlot *slot = econtext->ecxt_scantuple;
732 TupleDesc var_tupdesc;
733 HeapTupleHeader dtuple;
736 *isDone = ExprSingleResult;
740 * Currently, the only case handled here is stripping of trailing resjunk
741 * fields, which we do in a slightly chintzy way by just adjusting the
742 * tuple's natts header field. Possibly there will someday be a need for
743 * more-extensive rearrangements, in which case it'd be worth
744 * disassembling and reassembling the tuple (perhaps use a JunkFilter for
747 Assert(variable->vartype != RECORDOID);
748 var_tupdesc = lookup_rowtype_tupdesc(variable->vartype, -1);
750 tuple = ExecFetchSlotTuple(slot);
753 * We have to make a copy of the tuple so we can safely insert the Datum
754 * overhead fields, which are not set in on-disk tuples; not to mention
755 * fooling with its natts field.
757 dtuple = (HeapTupleHeader) palloc(tuple->t_len);
758 memcpy((char *) dtuple, (char *) tuple->t_data, tuple->t_len);
760 HeapTupleHeaderSetDatumLength(dtuple, tuple->t_len);
761 HeapTupleHeaderSetTypeId(dtuple, variable->vartype);
762 HeapTupleHeaderSetTypMod(dtuple, variable->vartypmod);
764 Assert(HeapTupleHeaderGetNatts(dtuple) >= var_tupdesc->natts);
765 HeapTupleHeaderSetNatts(dtuple, var_tupdesc->natts);
767 ReleaseTupleDesc(var_tupdesc);
769 return PointerGetDatum(dtuple);
772 /* ----------------------------------------------------------------
775 * Returns the value of a constant.
777 * Note that for pass-by-ref datatypes, we return a pointer to the
778 * actual constant node. This is one of the reasons why functions
779 * must treat their input arguments as read-only.
780 * ----------------------------------------------------------------
783 ExecEvalConst(ExprState *exprstate, ExprContext *econtext,
784 bool *isNull, ExprDoneCond *isDone)
786 Const *con = (Const *) exprstate->expr;
789 *isDone = ExprSingleResult;
791 *isNull = con->constisnull;
792 return con->constvalue;
795 /* ----------------------------------------------------------------
798 * Returns the value of a parameter. A param node contains
799 * something like ($.name) and the expression context contains
800 * the current parameter bindings (name = "sam") (age = 34)...
801 * so our job is to find and return the appropriate datum ("sam").
802 * ----------------------------------------------------------------
805 ExecEvalParam(ExprState *exprstate, ExprContext *econtext,
806 bool *isNull, ExprDoneCond *isDone)
808 Param *expression = (Param *) exprstate->expr;
809 int thisParamId = expression->paramid;
812 *isDone = ExprSingleResult;
814 if (expression->paramkind == PARAM_EXEC)
817 * PARAM_EXEC params (internal executor parameters) are stored in the
818 * ecxt_param_exec_vals array, and can be accessed by array index.
822 prm = &(econtext->ecxt_param_exec_vals[thisParamId]);
823 if (prm->execPlan != NULL)
825 /* Parameter not evaluated yet, so go do it */
826 ExecSetParamPlan(prm->execPlan, econtext);
827 /* ExecSetParamPlan should have processed this param... */
828 Assert(prm->execPlan == NULL);
830 *isNull = prm->isnull;
836 * PARAM_EXTERN parameters must be sought in ecxt_param_list_info.
838 ParamListInfo paramInfo = econtext->ecxt_param_list_info;
840 Assert(expression->paramkind == PARAM_EXTERN);
842 thisParamId > 0 && thisParamId <= paramInfo->numParams)
844 ParamExternData *prm = ¶mInfo->params[thisParamId - 1];
846 if (OidIsValid(prm->ptype))
848 Assert(prm->ptype == expression->paramtype);
849 *isNull = prm->isnull;
854 (errcode(ERRCODE_UNDEFINED_OBJECT),
855 errmsg("no value found for parameter %d", thisParamId)));
856 return (Datum) 0; /* keep compiler quiet */
861 /* ----------------------------------------------------------------
862 * ExecEvalOper / ExecEvalFunc support routines
863 * ----------------------------------------------------------------
870 * These functions return the value of the requested attribute
871 * out of the given tuple Datum.
872 * C functions which take a tuple as an argument are expected
873 * to use these. Ex: overpaid(EMP) might call GetAttributeByNum().
874 * Note: these are actually rather slow because they do a typcache
875 * lookup on each call.
878 GetAttributeByNum(HeapTupleHeader tuple,
886 HeapTupleData tmptup;
888 if (!AttributeNumberIsValid(attrno))
889 elog(ERROR, "invalid attribute number %d", attrno);
892 elog(ERROR, "a NULL isNull pointer was passed");
896 /* Kinda bogus but compatible with old behavior... */
901 tupType = HeapTupleHeaderGetTypeId(tuple);
902 tupTypmod = HeapTupleHeaderGetTypMod(tuple);
903 tupDesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
906 * heap_getattr needs a HeapTuple not a bare HeapTupleHeader. We set all
907 * the fields in the struct just in case user tries to inspect system
910 tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
911 ItemPointerSetInvalid(&(tmptup.t_self));
912 tmptup.t_tableOid = InvalidOid;
913 tmptup.t_data = tuple;
915 result = heap_getattr(&tmptup,
920 ReleaseTupleDesc(tupDesc);
926 GetAttributeByName(HeapTupleHeader tuple, const char *attname, bool *isNull)
933 HeapTupleData tmptup;
937 elog(ERROR, "invalid attribute name");
940 elog(ERROR, "a NULL isNull pointer was passed");
944 /* Kinda bogus but compatible with old behavior... */
949 tupType = HeapTupleHeaderGetTypeId(tuple);
950 tupTypmod = HeapTupleHeaderGetTypMod(tuple);
951 tupDesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
953 attrno = InvalidAttrNumber;
954 for (i = 0; i < tupDesc->natts; i++)
956 if (namestrcmp(&(tupDesc->attrs[i]->attname), attname) == 0)
958 attrno = tupDesc->attrs[i]->attnum;
963 if (attrno == InvalidAttrNumber)
964 elog(ERROR, "attribute \"%s\" does not exist", attname);
967 * heap_getattr needs a HeapTuple not a bare HeapTupleHeader. We set all
968 * the fields in the struct just in case user tries to inspect system
971 tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
972 ItemPointerSetInvalid(&(tmptup.t_self));
973 tmptup.t_tableOid = InvalidOid;
974 tmptup.t_data = tuple;
976 result = heap_getattr(&tmptup,
981 ReleaseTupleDesc(tupDesc);
987 * init_fcache - initialize a FuncExprState node during first use
990 init_fcache(Oid foid, FuncExprState *fcache, MemoryContext fcacheCxt)
994 /* Check permission to call function */
995 aclresult = pg_proc_aclcheck(foid, GetUserId(), ACL_EXECUTE);
996 if (aclresult != ACLCHECK_OK)
997 aclcheck_error(aclresult, ACL_KIND_PROC, get_func_name(foid));
1000 * Safety check on nargs. Under normal circumstances this should never
1001 * fail, as parser should check sooner. But possibly it might fail if
1002 * server has been compiled with FUNC_MAX_ARGS smaller than some functions
1003 * declared in pg_proc?
1005 if (list_length(fcache->args) > FUNC_MAX_ARGS)
1007 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
1008 errmsg("cannot pass more than %d arguments to a function",
1011 /* Set up the primary fmgr lookup information */
1012 fmgr_info_cxt(foid, &(fcache->func), fcacheCxt);
1014 /* Initialize additional info */
1015 fcache->setArgsValid = false;
1016 fcache->shutdown_reg = false;
1017 fcache->func.fn_expr = (Node *) fcache->xprstate.expr;
1021 * callback function in case a FuncExpr returning a set needs to be shut down
1022 * before it has been run to completion
1025 ShutdownFuncExpr(Datum arg)
1027 FuncExprState *fcache = (FuncExprState *) DatumGetPointer(arg);
1029 /* Clear any active set-argument state */
1030 fcache->setArgsValid = false;
1032 /* execUtils will deregister the callback... */
1033 fcache->shutdown_reg = false;
1037 * get_cached_rowtype: utility function to lookup a rowtype tupdesc
1039 * type_id, typmod: identity of the rowtype
1040 * cache_field: where to cache the TupleDesc pointer in expression state node
1041 * (field must be initialized to NULL)
1042 * econtext: expression context we are executing in
1044 * NOTE: because the shutdown callback will be called during plan rescan,
1045 * must be prepared to re-do this during any node execution; cannot call
1046 * just once during expression initialization
1049 get_cached_rowtype(Oid type_id, int32 typmod,
1050 TupleDesc *cache_field, ExprContext *econtext)
1052 TupleDesc tupDesc = *cache_field;
1054 /* Do lookup if no cached value or if requested type changed */
1055 if (tupDesc == NULL ||
1056 type_id != tupDesc->tdtypeid ||
1057 typmod != tupDesc->tdtypmod)
1059 tupDesc = lookup_rowtype_tupdesc(type_id, typmod);
1063 /* Release old tupdesc; but callback is already registered */
1064 ReleaseTupleDesc(*cache_field);
1068 /* Need to register shutdown callback to release tupdesc */
1069 RegisterExprContextCallback(econtext,
1070 ShutdownTupleDescRef,
1071 PointerGetDatum(cache_field));
1073 *cache_field = tupDesc;
1079 * Callback function to release a tupdesc refcount at expression tree shutdown
1082 ShutdownTupleDescRef(Datum arg)
1084 TupleDesc *cache_field = (TupleDesc *) DatumGetPointer(arg);
1087 ReleaseTupleDesc(*cache_field);
1088 *cache_field = NULL;
1092 * Evaluate arguments for a function.
1095 ExecEvalFuncArgs(FunctionCallInfo fcinfo,
1097 ExprContext *econtext)
1099 ExprDoneCond argIsDone;
1103 argIsDone = ExprSingleResult; /* default assumption */
1106 foreach(arg, argList)
1108 ExprState *argstate = (ExprState *) lfirst(arg);
1109 ExprDoneCond thisArgIsDone;
1111 fcinfo->arg[i] = ExecEvalExpr(argstate,
1113 &fcinfo->argnull[i],
1116 if (thisArgIsDone != ExprSingleResult)
1119 * We allow only one argument to have a set value; we'd need much
1120 * more complexity to keep track of multiple set arguments (cf.
1121 * ExecTargetList) and it doesn't seem worth it.
1123 if (argIsDone != ExprSingleResult)
1125 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1126 errmsg("functions and operators can take at most one set argument")));
1127 argIsDone = thisArgIsDone;
1138 * ExecMakeFunctionResult
1140 * Evaluate the arguments to a function and then the function itself.
1143 ExecMakeFunctionResult(FuncExprState *fcache,
1144 ExprContext *econtext,
1146 ExprDoneCond *isDone)
1148 List *arguments = fcache->args;
1150 FunctionCallInfoData fcinfo;
1151 ReturnSetInfo rsinfo; /* for functions returning sets */
1152 ExprDoneCond argDone;
1156 /* Guard against stack overflow due to overly complex expressions */
1157 check_stack_depth();
1160 * arguments is a list of expressions to evaluate before passing to the
1161 * function manager. We skip the evaluation if it was already done in the
1162 * previous call (ie, we are continuing the evaluation of a set-valued
1163 * function). Otherwise, collect the current argument values into fcinfo.
1165 if (!fcache->setArgsValid)
1167 /* Need to prep callinfo structure */
1168 InitFunctionCallInfoData(fcinfo, &(fcache->func), 0, NULL, NULL);
1169 argDone = ExecEvalFuncArgs(&fcinfo, arguments, econtext);
1170 if (argDone == ExprEndResult)
1172 /* input is an empty set, so return an empty set. */
1175 *isDone = ExprEndResult;
1178 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1179 errmsg("set-valued function called in context that cannot accept a set")));
1182 hasSetArg = (argDone != ExprSingleResult);
1186 /* Copy callinfo from previous evaluation */
1187 memcpy(&fcinfo, &fcache->setArgs, sizeof(fcinfo));
1188 hasSetArg = fcache->setHasSetArg;
1189 /* Reset flag (we may set it again below) */
1190 fcache->setArgsValid = false;
1194 * If function returns set, prepare a resultinfo node for communication
1196 if (fcache->func.fn_retset)
1198 fcinfo.resultinfo = (Node *) &rsinfo;
1199 rsinfo.type = T_ReturnSetInfo;
1200 rsinfo.econtext = econtext;
1201 rsinfo.expectedDesc = NULL;
1202 rsinfo.allowedModes = (int) SFRM_ValuePerCall;
1203 rsinfo.returnMode = SFRM_ValuePerCall;
1204 /* isDone is filled below */
1205 rsinfo.setResult = NULL;
1206 rsinfo.setDesc = NULL;
1210 * now return the value gotten by calling the function manager, passing
1211 * the function the evaluated parameter values.
1213 if (fcache->func.fn_retset || hasSetArg)
1216 * We need to return a set result. Complain if caller not ready to
1221 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1222 errmsg("set-valued function called in context that cannot accept a set")));
1225 * This loop handles the situation where we have both a set argument
1226 * and a set-valued function. Once we have exhausted the function's
1227 * value(s) for a particular argument value, we have to get the next
1228 * argument value and start the function over again. We might have to
1229 * do it more than once, if the function produces an empty result set
1230 * for a particular input value.
1235 * If function is strict, and there are any NULL arguments, skip
1236 * calling the function (at least for this set of args).
1240 if (fcache->func.fn_strict)
1242 for (i = 0; i < fcinfo.nargs; i++)
1244 if (fcinfo.argnull[i])
1254 fcinfo.isnull = false;
1255 rsinfo.isDone = ExprSingleResult;
1256 result = FunctionCallInvoke(&fcinfo);
1257 *isNull = fcinfo.isnull;
1258 *isDone = rsinfo.isDone;
1264 *isDone = ExprEndResult;
1267 if (*isDone != ExprEndResult)
1270 * Got a result from current argument. If function itself
1271 * returns set, save the current argument values to re-use on
1274 if (fcache->func.fn_retset && *isDone == ExprMultipleResult)
1276 memcpy(&fcache->setArgs, &fcinfo, sizeof(fcinfo));
1277 fcache->setHasSetArg = hasSetArg;
1278 fcache->setArgsValid = true;
1279 /* Register cleanup callback if we didn't already */
1280 if (!fcache->shutdown_reg)
1282 RegisterExprContextCallback(econtext,
1284 PointerGetDatum(fcache));
1285 fcache->shutdown_reg = true;
1290 * Make sure we say we are returning a set, even if the
1291 * function itself doesn't return sets.
1294 *isDone = ExprMultipleResult;
1298 /* Else, done with this argument */
1300 break; /* input not a set, so done */
1302 /* Re-eval args to get the next element of the input set */
1303 argDone = ExecEvalFuncArgs(&fcinfo, arguments, econtext);
1305 if (argDone != ExprMultipleResult)
1307 /* End of argument set, so we're done. */
1309 *isDone = ExprEndResult;
1315 * If we reach here, loop around to run the function on the new
1323 * Non-set case: much easier.
1325 * We change the ExprState function pointer to use the simpler
1326 * ExecMakeFunctionResultNoSets on subsequent calls. This amounts to
1327 * assuming that no argument can return a set if it didn't do so the
1330 fcache->xprstate.evalfunc = (ExprStateEvalFunc) ExecMakeFunctionResultNoSets;
1333 *isDone = ExprSingleResult;
1336 * If function is strict, and there are any NULL arguments, skip
1337 * calling the function and return NULL.
1339 if (fcache->func.fn_strict)
1341 for (i = 0; i < fcinfo.nargs; i++)
1343 if (fcinfo.argnull[i])
1350 fcinfo.isnull = false;
1351 result = FunctionCallInvoke(&fcinfo);
1352 *isNull = fcinfo.isnull;
1359 * ExecMakeFunctionResultNoSets
1361 * Simplified version of ExecMakeFunctionResult that can only handle
1362 * non-set cases. Hand-tuned for speed.
1365 ExecMakeFunctionResultNoSets(FuncExprState *fcache,
1366 ExprContext *econtext,
1368 ExprDoneCond *isDone)
1372 FunctionCallInfoData fcinfo;
1375 /* Guard against stack overflow due to overly complex expressions */
1376 check_stack_depth();
1379 *isDone = ExprSingleResult;
1381 /* inlined, simplified version of ExecEvalFuncArgs */
1383 foreach(arg, fcache->args)
1385 ExprState *argstate = (ExprState *) lfirst(arg);
1387 fcinfo.arg[i] = ExecEvalExpr(argstate,
1394 InitFunctionCallInfoData(fcinfo, &(fcache->func), i, NULL, NULL);
1397 * If function is strict, and there are any NULL arguments, skip calling
1398 * the function and return NULL.
1400 if (fcache->func.fn_strict)
1404 if (fcinfo.argnull[i])
1411 /* fcinfo.isnull = false; */ /* handled by InitFunctionCallInfoData */
1412 result = FunctionCallInvoke(&fcinfo);
1413 *isNull = fcinfo.isnull;
1420 * ExecMakeTableFunctionResult
1422 * Evaluate a table function, producing a materialized result in a Tuplestore
1423 * object. *returnDesc is set to the tupledesc actually returned by the
1424 * function, or NULL if it didn't provide one.
1427 ExecMakeTableFunctionResult(ExprState *funcexpr,
1428 ExprContext *econtext,
1429 TupleDesc expectedDesc,
1430 TupleDesc *returnDesc)
1432 Tuplestorestate *tupstore = NULL;
1433 TupleDesc tupdesc = NULL;
1436 bool returnsSet = false;
1437 FunctionCallInfoData fcinfo;
1438 ReturnSetInfo rsinfo;
1439 HeapTupleData tmptup;
1440 MemoryContext callerContext;
1441 MemoryContext oldcontext;
1442 bool direct_function_call;
1443 bool first_time = true;
1445 callerContext = CurrentMemoryContext;
1447 funcrettype = exprType((Node *) funcexpr->expr);
1449 returnsTuple = type_is_rowtype(funcrettype);
1452 * Prepare a resultinfo node for communication. We always do this even if
1453 * not expecting a set result, so that we can pass expectedDesc. In the
1454 * generic-expression case, the expression doesn't actually get to see the
1455 * resultinfo, but set it up anyway because we use some of the fields as
1456 * our own state variables.
1458 InitFunctionCallInfoData(fcinfo, NULL, 0, NULL, (Node *) &rsinfo);
1459 rsinfo.type = T_ReturnSetInfo;
1460 rsinfo.econtext = econtext;
1461 rsinfo.expectedDesc = expectedDesc;
1462 rsinfo.allowedModes = (int) (SFRM_ValuePerCall | SFRM_Materialize);
1463 rsinfo.returnMode = SFRM_ValuePerCall;
1464 /* isDone is filled below */
1465 rsinfo.setResult = NULL;
1466 rsinfo.setDesc = NULL;
1469 * Normally the passed expression tree will be a FuncExprState, since the
1470 * grammar only allows a function call at the top level of a table
1471 * function reference. However, if the function doesn't return set then
1472 * the planner might have replaced the function call via constant-folding
1473 * or inlining. So if we see any other kind of expression node, execute
1474 * it via the general ExecEvalExpr() code; the only difference is that we
1475 * don't get a chance to pass a special ReturnSetInfo to any functions
1476 * buried in the expression.
1478 if (funcexpr && IsA(funcexpr, FuncExprState) &&
1479 IsA(funcexpr->expr, FuncExpr))
1481 FuncExprState *fcache = (FuncExprState *) funcexpr;
1482 ExprDoneCond argDone;
1485 * This path is similar to ExecMakeFunctionResult.
1487 direct_function_call = true;
1490 * Initialize function cache if first time through
1492 if (fcache->func.fn_oid == InvalidOid)
1494 FuncExpr *func = (FuncExpr *) fcache->xprstate.expr;
1496 init_fcache(func->funcid, fcache, econtext->ecxt_per_query_memory);
1498 returnsSet = fcache->func.fn_retset;
1501 * Evaluate the function's argument list.
1503 * Note: ideally, we'd do this in the per-tuple context, but then the
1504 * argument values would disappear when we reset the context in the
1505 * inner loop. So do it in caller context. Perhaps we should make a
1506 * separate context just to hold the evaluated arguments?
1508 fcinfo.flinfo = &(fcache->func);
1509 argDone = ExecEvalFuncArgs(&fcinfo, fcache->args, econtext);
1510 /* We don't allow sets in the arguments of the table function */
1511 if (argDone != ExprSingleResult)
1513 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1514 errmsg("set-valued function called in context that cannot accept a set")));
1517 * If function is strict, and there are any NULL arguments, skip
1518 * calling the function and act like it returned NULL (or an empty
1519 * set, in the returns-set case).
1521 if (fcache->func.fn_strict)
1525 for (i = 0; i < fcinfo.nargs; i++)
1527 if (fcinfo.argnull[i])
1528 goto no_function_result;
1534 /* Treat funcexpr as a generic expression */
1535 direct_function_call = false;
1539 * Switch to short-lived context for calling the function or expression.
1541 MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
1544 * Loop to handle the ValuePerCall protocol (which is also the same
1545 * behavior needed in the generic ExecEvalExpr path).
1551 CHECK_FOR_INTERRUPTS();
1554 * reset per-tuple memory context before each call of the function or
1555 * expression. This cleans up any local memory the function may leak
1558 ResetExprContext(econtext);
1560 /* Call the function or expression one time */
1561 if (direct_function_call)
1563 fcinfo.isnull = false;
1564 rsinfo.isDone = ExprSingleResult;
1565 result = FunctionCallInvoke(&fcinfo);
1569 result = ExecEvalExpr(funcexpr, econtext,
1570 &fcinfo.isnull, &rsinfo.isDone);
1573 /* Which protocol does function want to use? */
1574 if (rsinfo.returnMode == SFRM_ValuePerCall)
1577 * Check for end of result set.
1579 if (rsinfo.isDone == ExprEndResult)
1583 * Can't do anything very useful with NULL rowtype values. For a
1584 * function returning set, we consider this a protocol violation
1585 * (but another alternative would be to just ignore the result and
1586 * "continue" to get another row). For a function not returning
1587 * set, we fall out of the loop; we'll cons up an all-nulls result
1590 if (returnsTuple && fcinfo.isnull)
1595 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1596 errmsg("function returning set of rows cannot return null value")));
1600 * If first time through, build tupdesc and tuplestore for result
1604 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1608 * Use the type info embedded in the rowtype Datum to look
1609 * up the needed tupdesc. Make a copy for the query.
1613 td = DatumGetHeapTupleHeader(result);
1614 tupdesc = lookup_rowtype_tupdesc_copy(HeapTupleHeaderGetTypeId(td),
1615 HeapTupleHeaderGetTypMod(td));
1620 * Scalar type, so make a single-column descriptor
1622 tupdesc = CreateTemplateTupleDesc(1, false);
1623 TupleDescInitEntry(tupdesc,
1630 tupstore = tuplestore_begin_heap(true, false, work_mem);
1631 MemoryContextSwitchTo(oldcontext);
1632 rsinfo.setResult = tupstore;
1633 rsinfo.setDesc = tupdesc;
1637 * Store current resultset item.
1643 td = DatumGetHeapTupleHeader(result);
1646 * tuplestore_puttuple needs a HeapTuple not a bare
1647 * HeapTupleHeader, but it doesn't need all the fields.
1649 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
1652 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1653 tuplestore_puttuple(tupstore, &tmptup);
1657 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1658 tuplestore_putvalues(tupstore, tupdesc, &result, &fcinfo.isnull);
1660 MemoryContextSwitchTo(oldcontext);
1665 if (rsinfo.isDone != ExprMultipleResult)
1668 else if (rsinfo.returnMode == SFRM_Materialize)
1670 /* check we're on the same page as the function author */
1671 if (!first_time || rsinfo.isDone != ExprSingleResult)
1673 (errcode(ERRCODE_E_R_I_E_SRF_PROTOCOL_VIOLATED),
1674 errmsg("table-function protocol for materialize mode was not followed")));
1675 /* Done evaluating the set result */
1680 (errcode(ERRCODE_E_R_I_E_SRF_PROTOCOL_VIOLATED),
1681 errmsg("unrecognized table-function returnMode: %d",
1682 (int) rsinfo.returnMode)));
1690 * If we got nothing from the function (ie, an empty-set or NULL result),
1691 * we have to create the tuplestore to return, and if it's a
1692 * non-set-returning function then insert a single all-nulls row.
1694 if (rsinfo.setResult == NULL)
1696 MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1697 tupstore = tuplestore_begin_heap(true, false, work_mem);
1698 rsinfo.setResult = tupstore;
1701 int natts = expectedDesc->natts;
1705 MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
1706 nulldatums = (Datum *) palloc0(natts * sizeof(Datum));
1707 nullflags = (bool *) palloc(natts * sizeof(bool));
1708 memset(nullflags, true, natts * sizeof(bool));
1709 MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1710 tuplestore_putvalues(tupstore, expectedDesc, nulldatums, nullflags);
1714 MemoryContextSwitchTo(callerContext);
1716 /* The returned pointers are those in rsinfo */
1717 *returnDesc = rsinfo.setDesc;
1718 return rsinfo.setResult;
1722 /* ----------------------------------------------------------------
1726 * Evaluate the functional result of a list of arguments by calling the
1728 * ----------------------------------------------------------------
1731 /* ----------------------------------------------------------------
1733 * ----------------------------------------------------------------
1736 ExecEvalFunc(FuncExprState *fcache,
1737 ExprContext *econtext,
1739 ExprDoneCond *isDone)
1741 /* This is called only the first time through */
1742 FuncExpr *func = (FuncExpr *) fcache->xprstate.expr;
1744 /* Initialize function lookup info */
1745 init_fcache(func->funcid, fcache, econtext->ecxt_per_query_memory);
1747 /* Go directly to ExecMakeFunctionResult on subsequent uses */
1748 fcache->xprstate.evalfunc = (ExprStateEvalFunc) ExecMakeFunctionResult;
1750 return ExecMakeFunctionResult(fcache, econtext, isNull, isDone);
1753 /* ----------------------------------------------------------------
1755 * ----------------------------------------------------------------
1758 ExecEvalOper(FuncExprState *fcache,
1759 ExprContext *econtext,
1761 ExprDoneCond *isDone)
1763 /* This is called only the first time through */
1764 OpExpr *op = (OpExpr *) fcache->xprstate.expr;
1766 /* Initialize function lookup info */
1767 init_fcache(op->opfuncid, fcache, econtext->ecxt_per_query_memory);
1769 /* Go directly to ExecMakeFunctionResult on subsequent uses */
1770 fcache->xprstate.evalfunc = (ExprStateEvalFunc) ExecMakeFunctionResult;
1772 return ExecMakeFunctionResult(fcache, econtext, isNull, isDone);
1775 /* ----------------------------------------------------------------
1778 * IS DISTINCT FROM must evaluate arguments to determine whether
1779 * they are NULL; if either is NULL then the result is already
1780 * known. If neither is NULL, then proceed to evaluate the
1781 * function. Note that this is *always* derived from the equals
1782 * operator, but since we need special processing of the arguments
1783 * we can not simply reuse ExecEvalOper() or ExecEvalFunc().
1784 * ----------------------------------------------------------------
1787 ExecEvalDistinct(FuncExprState *fcache,
1788 ExprContext *econtext,
1790 ExprDoneCond *isDone)
1793 FunctionCallInfoData fcinfo;
1794 ExprDoneCond argDone;
1797 /* Set default values for result flags: non-null, not a set result */
1800 *isDone = ExprSingleResult;
1803 * Initialize function cache if first time through
1805 if (fcache->func.fn_oid == InvalidOid)
1807 DistinctExpr *op = (DistinctExpr *) fcache->xprstate.expr;
1809 init_fcache(op->opfuncid, fcache, econtext->ecxt_per_query_memory);
1810 Assert(!fcache->func.fn_retset);
1814 * extract info from fcache
1816 argList = fcache->args;
1818 /* Need to prep callinfo structure */
1819 InitFunctionCallInfoData(fcinfo, &(fcache->func), 0, NULL, NULL);
1820 argDone = ExecEvalFuncArgs(&fcinfo, argList, econtext);
1821 if (argDone != ExprSingleResult)
1823 (errcode(ERRCODE_DATATYPE_MISMATCH),
1824 errmsg("IS DISTINCT FROM does not support set arguments")));
1825 Assert(fcinfo.nargs == 2);
1827 if (fcinfo.argnull[0] && fcinfo.argnull[1])
1829 /* Both NULL? Then is not distinct... */
1830 result = BoolGetDatum(FALSE);
1832 else if (fcinfo.argnull[0] || fcinfo.argnull[1])
1834 /* Only one is NULL? Then is distinct... */
1835 result = BoolGetDatum(TRUE);
1839 fcinfo.isnull = false;
1840 result = FunctionCallInvoke(&fcinfo);
1841 *isNull = fcinfo.isnull;
1842 /* Must invert result of "=" */
1843 result = BoolGetDatum(!DatumGetBool(result));
1850 * ExecEvalScalarArrayOp
1852 * Evaluate "scalar op ANY/ALL (array)". The operator always yields boolean,
1853 * and we combine the results across all array elements using OR and AND
1854 * (for ANY and ALL respectively). Of course we short-circuit as soon as
1855 * the result is known.
1858 ExecEvalScalarArrayOp(ScalarArrayOpExprState *sstate,
1859 ExprContext *econtext,
1860 bool *isNull, ExprDoneCond *isDone)
1862 ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) sstate->fxprstate.xprstate.expr;
1863 bool useOr = opexpr->useOr;
1868 FunctionCallInfoData fcinfo;
1869 ExprDoneCond argDone;
1878 /* Set default values for result flags: non-null, not a set result */
1881 *isDone = ExprSingleResult;
1884 * Initialize function cache if first time through
1886 if (sstate->fxprstate.func.fn_oid == InvalidOid)
1888 init_fcache(opexpr->opfuncid, &sstate->fxprstate,
1889 econtext->ecxt_per_query_memory);
1890 Assert(!sstate->fxprstate.func.fn_retset);
1893 /* Need to prep callinfo structure */
1894 InitFunctionCallInfoData(fcinfo, &(sstate->fxprstate.func), 0, NULL, NULL);
1895 argDone = ExecEvalFuncArgs(&fcinfo, sstate->fxprstate.args, econtext);
1896 if (argDone != ExprSingleResult)
1898 (errcode(ERRCODE_DATATYPE_MISMATCH),
1899 errmsg("op ANY/ALL (array) does not support set arguments")));
1900 Assert(fcinfo.nargs == 2);
1903 * If the array is NULL then we return NULL --- it's not very meaningful
1904 * to do anything else, even if the operator isn't strict.
1906 if (fcinfo.argnull[1])
1911 /* Else okay to fetch and detoast the array */
1912 arr = DatumGetArrayTypeP(fcinfo.arg[1]);
1915 * If the array is empty, we return either FALSE or TRUE per the useOr
1916 * flag. This is correct even if the scalar is NULL; since we would
1917 * evaluate the operator zero times, it matters not whether it would want
1920 nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr));
1922 return BoolGetDatum(!useOr);
1925 * If the scalar is NULL, and the function is strict, return NULL; no
1926 * point in iterating the loop.
1928 if (fcinfo.argnull[0] && sstate->fxprstate.func.fn_strict)
1935 * We arrange to look up info about the element type only once per series
1936 * of calls, assuming the element type doesn't change underneath us.
1938 if (sstate->element_type != ARR_ELEMTYPE(arr))
1940 get_typlenbyvalalign(ARR_ELEMTYPE(arr),
1944 sstate->element_type = ARR_ELEMTYPE(arr);
1946 typlen = sstate->typlen;
1947 typbyval = sstate->typbyval;
1948 typalign = sstate->typalign;
1950 result = BoolGetDatum(!useOr);
1953 /* Loop over the array elements */
1954 s = (char *) ARR_DATA_PTR(arr);
1955 bitmap = ARR_NULLBITMAP(arr);
1958 for (i = 0; i < nitems; i++)
1963 /* Get array element, checking for NULL */
1964 if (bitmap && (*bitmap & bitmask) == 0)
1966 fcinfo.arg[1] = (Datum) 0;
1967 fcinfo.argnull[1] = true;
1971 elt = fetch_att(s, typbyval, typlen);
1972 s = att_addlength_pointer(s, typlen, s);
1973 s = (char *) att_align_nominal(s, typalign);
1974 fcinfo.arg[1] = elt;
1975 fcinfo.argnull[1] = false;
1978 /* Call comparison function */
1979 if (fcinfo.argnull[1] && sstate->fxprstate.func.fn_strict)
1981 fcinfo.isnull = true;
1982 thisresult = (Datum) 0;
1986 fcinfo.isnull = false;
1987 thisresult = FunctionCallInvoke(&fcinfo);
1990 /* Combine results per OR or AND semantics */
1995 if (DatumGetBool(thisresult))
1997 result = BoolGetDatum(true);
1999 break; /* needn't look at any more elements */
2004 if (!DatumGetBool(thisresult))
2006 result = BoolGetDatum(false);
2008 break; /* needn't look at any more elements */
2012 /* advance bitmap pointer if any */
2016 if (bitmask == 0x100)
2024 *isNull = resultnull;
2028 /* ----------------------------------------------------------------
2033 * Evaluate boolean expressions, with appropriate short-circuiting.
2035 * The query planner reformulates clause expressions in the
2036 * qualification to conjunctive normal form. If we ever get
2037 * an AND to evaluate, we can be sure that it's not a top-level
2038 * clause in the qualification, but appears lower (as a function
2039 * argument, for example), or in the target list. Not that you
2040 * need to know this, mind you...
2041 * ----------------------------------------------------------------
2044 ExecEvalNot(BoolExprState *notclause, ExprContext *econtext,
2045 bool *isNull, ExprDoneCond *isDone)
2047 ExprState *clause = linitial(notclause->args);
2051 *isDone = ExprSingleResult;
2053 expr_value = ExecEvalExpr(clause, econtext, isNull, NULL);
2056 * if the expression evaluates to null, then we just cascade the null back
2057 * to whoever called us.
2063 * evaluation of 'not' is simple.. expr is false, then return 'true' and
2066 return BoolGetDatum(!DatumGetBool(expr_value));
2069 /* ----------------------------------------------------------------
2071 * ----------------------------------------------------------------
2074 ExecEvalOr(BoolExprState *orExpr, ExprContext *econtext,
2075 bool *isNull, ExprDoneCond *isDone)
2077 List *clauses = orExpr->args;
2082 *isDone = ExprSingleResult;
2087 * If any of the clauses is TRUE, the OR result is TRUE regardless of the
2088 * states of the rest of the clauses, so we can stop evaluating and return
2089 * TRUE immediately. If none are TRUE and one or more is NULL, we return
2090 * NULL; otherwise we return FALSE. This makes sense when you interpret
2091 * NULL as "don't know": if we have a TRUE then the OR is TRUE even if we
2092 * aren't sure about some of the other inputs. If all the known inputs are
2093 * FALSE, but we have one or more "don't knows", then we have to report
2094 * that we "don't know" what the OR's result should be --- perhaps one of
2095 * the "don't knows" would have been TRUE if we'd known its value. Only
2096 * when all the inputs are known to be FALSE can we state confidently that
2097 * the OR's result is FALSE.
2099 foreach(clause, clauses)
2101 ExprState *clausestate = (ExprState *) lfirst(clause);
2104 clause_value = ExecEvalExpr(clausestate, econtext, isNull, NULL);
2107 * if we have a non-null true result, then return it.
2110 AnyNull = true; /* remember we got a null */
2111 else if (DatumGetBool(clause_value))
2112 return clause_value;
2115 /* AnyNull is true if at least one clause evaluated to NULL */
2117 return BoolGetDatum(false);
2120 /* ----------------------------------------------------------------
2122 * ----------------------------------------------------------------
2125 ExecEvalAnd(BoolExprState *andExpr, ExprContext *econtext,
2126 bool *isNull, ExprDoneCond *isDone)
2128 List *clauses = andExpr->args;
2133 *isDone = ExprSingleResult;
2138 * If any of the clauses is FALSE, the AND result is FALSE regardless of
2139 * the states of the rest of the clauses, so we can stop evaluating and
2140 * return FALSE immediately. If none are FALSE and one or more is NULL,
2141 * we return NULL; otherwise we return TRUE. This makes sense when you
2142 * interpret NULL as "don't know", using the same sort of reasoning as for
2146 foreach(clause, clauses)
2148 ExprState *clausestate = (ExprState *) lfirst(clause);
2151 clause_value = ExecEvalExpr(clausestate, econtext, isNull, NULL);
2154 * if we have a non-null false result, then return it.
2157 AnyNull = true; /* remember we got a null */
2158 else if (!DatumGetBool(clause_value))
2159 return clause_value;
2162 /* AnyNull is true if at least one clause evaluated to NULL */
2164 return BoolGetDatum(!AnyNull);
2167 /* ----------------------------------------------------------------
2168 * ExecEvalConvertRowtype
2170 * Evaluate a rowtype coercion operation. This may require
2171 * rearranging field positions.
2172 * ----------------------------------------------------------------
2175 ExecEvalConvertRowtype(ConvertRowtypeExprState *cstate,
2176 ExprContext *econtext,
2177 bool *isNull, ExprDoneCond *isDone)
2179 ConvertRowtypeExpr *convert = (ConvertRowtypeExpr *) cstate->xprstate.expr;
2182 HeapTupleHeader tuple;
2183 HeapTupleData tmptup;
2184 AttrNumber *attrMap;
2192 tupDatum = ExecEvalExpr(cstate->arg, econtext, isNull, isDone);
2194 /* this test covers the isDone exception too: */
2198 tuple = DatumGetHeapTupleHeader(tupDatum);
2200 /* Lookup tupdescs if first time through or after rescan */
2201 if (cstate->indesc == NULL)
2202 get_cached_rowtype(exprType((Node *) convert->arg), -1,
2203 &cstate->indesc, econtext);
2204 if (cstate->outdesc == NULL)
2205 get_cached_rowtype(convert->resulttype, -1,
2206 &cstate->outdesc, econtext);
2208 Assert(HeapTupleHeaderGetTypeId(tuple) == cstate->indesc->tdtypeid);
2209 Assert(HeapTupleHeaderGetTypMod(tuple) == cstate->indesc->tdtypmod);
2211 /* if first time through, initialize */
2212 if (cstate->attrMap == NULL)
2214 MemoryContext old_cxt;
2217 /* allocate state in long-lived memory context */
2218 old_cxt = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
2220 /* prepare map from old to new attribute numbers */
2221 n = cstate->outdesc->natts;
2222 cstate->attrMap = (AttrNumber *) palloc0(n * sizeof(AttrNumber));
2223 for (i = 0; i < n; i++)
2225 Form_pg_attribute att = cstate->outdesc->attrs[i];
2231 if (att->attisdropped)
2232 continue; /* attrMap[i] is already 0 */
2233 attname = NameStr(att->attname);
2234 atttypid = att->atttypid;
2235 atttypmod = att->atttypmod;
2236 for (j = 0; j < cstate->indesc->natts; j++)
2238 att = cstate->indesc->attrs[j];
2239 if (att->attisdropped)
2241 if (strcmp(attname, NameStr(att->attname)) == 0)
2243 /* Found it, check type */
2244 if (atttypid != att->atttypid || atttypmod != att->atttypmod)
2245 elog(ERROR, "attribute \"%s\" of type %s does not match corresponding attribute of type %s",
2247 format_type_be(cstate->indesc->tdtypeid),
2248 format_type_be(cstate->outdesc->tdtypeid));
2249 cstate->attrMap[i] = (AttrNumber) (j + 1);
2253 if (cstate->attrMap[i] == 0)
2254 elog(ERROR, "attribute \"%s\" of type %s does not exist",
2256 format_type_be(cstate->indesc->tdtypeid));
2258 /* preallocate workspace for Datum arrays */
2259 n = cstate->indesc->natts + 1; /* +1 for NULL */
2260 cstate->invalues = (Datum *) palloc(n * sizeof(Datum));
2261 cstate->inisnull = (bool *) palloc(n * sizeof(bool));
2262 n = cstate->outdesc->natts;
2263 cstate->outvalues = (Datum *) palloc(n * sizeof(Datum));
2264 cstate->outisnull = (bool *) palloc(n * sizeof(bool));
2266 MemoryContextSwitchTo(old_cxt);
2269 attrMap = cstate->attrMap;
2270 invalues = cstate->invalues;
2271 inisnull = cstate->inisnull;
2272 outvalues = cstate->outvalues;
2273 outisnull = cstate->outisnull;
2274 outnatts = cstate->outdesc->natts;
2277 * heap_deform_tuple needs a HeapTuple not a bare HeapTupleHeader.
2279 tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
2280 tmptup.t_data = tuple;
2283 * Extract all the values of the old tuple, offsetting the arrays so that
2284 * invalues[0] is NULL and invalues[1] is the first source attribute; this
2285 * exactly matches the numbering convention in attrMap.
2287 heap_deform_tuple(&tmptup, cstate->indesc, invalues + 1, inisnull + 1);
2288 invalues[0] = (Datum) 0;
2292 * Transpose into proper fields of the new tuple.
2294 for (i = 0; i < outnatts; i++)
2298 outvalues[i] = invalues[j];
2299 outisnull[i] = inisnull[j];
2303 * Now form the new tuple.
2305 result = heap_form_tuple(cstate->outdesc, outvalues, outisnull);
2307 return HeapTupleGetDatum(result);
2310 /* ----------------------------------------------------------------
2313 * Evaluate a CASE clause. Will have boolean expressions
2314 * inside the WHEN clauses, and will have expressions
2316 * - thomas 1998-11-09
2317 * ----------------------------------------------------------------
2320 ExecEvalCase(CaseExprState *caseExpr, ExprContext *econtext,
2321 bool *isNull, ExprDoneCond *isDone)
2323 List *clauses = caseExpr->args;
2329 *isDone = ExprSingleResult;
2332 * If there's a test expression, we have to evaluate it and save the value
2333 * where the CaseTestExpr placeholders can find it. We must save and
2334 * restore prior setting of econtext's caseValue fields, in case this node
2335 * is itself within a larger CASE.
2337 save_datum = econtext->caseValue_datum;
2338 save_isNull = econtext->caseValue_isNull;
2342 econtext->caseValue_datum = ExecEvalExpr(caseExpr->arg,
2344 &econtext->caseValue_isNull,
2349 * we evaluate each of the WHEN clauses in turn, as soon as one is true we
2350 * return the corresponding result. If none are true then we return the
2351 * value of the default clause, or NULL if there is none.
2353 foreach(clause, clauses)
2355 CaseWhenState *wclause = lfirst(clause);
2358 clause_value = ExecEvalExpr(wclause->expr,
2364 * if we have a true test, then we return the result, since the case
2365 * statement is satisfied. A NULL result from the test is not
2368 if (DatumGetBool(clause_value) && !*isNull)
2370 econtext->caseValue_datum = save_datum;
2371 econtext->caseValue_isNull = save_isNull;
2372 return ExecEvalExpr(wclause->result,
2379 econtext->caseValue_datum = save_datum;
2380 econtext->caseValue_isNull = save_isNull;
2382 if (caseExpr->defresult)
2384 return ExecEvalExpr(caseExpr->defresult,
2395 * ExecEvalCaseTestExpr
2397 * Return the value stored by CASE.
2400 ExecEvalCaseTestExpr(ExprState *exprstate,
2401 ExprContext *econtext,
2402 bool *isNull, ExprDoneCond *isDone)
2405 *isDone = ExprSingleResult;
2406 *isNull = econtext->caseValue_isNull;
2407 return econtext->caseValue_datum;
2410 /* ----------------------------------------------------------------
2411 * ExecEvalArray - ARRAY[] expressions
2412 * ----------------------------------------------------------------
2415 ExecEvalArray(ArrayExprState *astate, ExprContext *econtext,
2416 bool *isNull, ExprDoneCond *isDone)
2418 ArrayExpr *arrayExpr = (ArrayExpr *) astate->xprstate.expr;
2421 Oid element_type = arrayExpr->element_typeid;
2426 /* Set default values for result flags: non-null, not a set result */
2429 *isDone = ExprSingleResult;
2431 if (!arrayExpr->multidims)
2433 /* Elements are presumably of scalar type */
2440 nelems = list_length(astate->elements);
2442 /* Shouldn't happen here, but if length is 0, return empty array */
2444 return PointerGetDatum(construct_empty_array(element_type));
2446 dvalues = (Datum *) palloc(nelems * sizeof(Datum));
2447 dnulls = (bool *) palloc(nelems * sizeof(bool));
2449 /* loop through and build array of datums */
2450 foreach(element, astate->elements)
2452 ExprState *e = (ExprState *) lfirst(element);
2454 dvalues[i] = ExecEvalExpr(e, econtext, &dnulls[i], NULL);
2458 /* setup for 1-D array of the given length */
2462 result = construct_md_array(dvalues, dnulls, ndims, dims, lbs,
2470 /* Must be nested array expressions */
2473 int outer_nelems = 0;
2475 int *elem_dims = NULL;
2476 int *elem_lbs = NULL;
2477 bool firstone = true;
2478 bool havenulls = false;
2479 bool haveempty = false;
2489 i = list_length(astate->elements);
2490 subdata = (char **) palloc(i * sizeof(char *));
2491 subbitmaps = (bits8 **) palloc(i * sizeof(bits8 *));
2492 subbytes = (int *) palloc(i * sizeof(int));
2493 subnitems = (int *) palloc(i * sizeof(int));
2495 /* loop through and get data area from each element */
2496 foreach(element, astate->elements)
2498 ExprState *e = (ExprState *) lfirst(element);
2504 arraydatum = ExecEvalExpr(e, econtext, &eisnull, NULL);
2505 /* temporarily ignore null subarrays */
2512 array = DatumGetArrayTypeP(arraydatum);
2514 /* run-time double-check on element type */
2515 if (element_type != ARR_ELEMTYPE(array))
2517 (errcode(ERRCODE_DATATYPE_MISMATCH),
2518 errmsg("cannot merge incompatible arrays"),
2519 errdetail("Array with element type %s cannot be "
2520 "included in ARRAY construct with element type %s.",
2521 format_type_be(ARR_ELEMTYPE(array)),
2522 format_type_be(element_type))));
2524 this_ndims = ARR_NDIM(array);
2525 /* temporarily ignore zero-dimensional subarrays */
2526 if (this_ndims <= 0)
2534 /* Get sub-array details from first member */
2535 elem_ndims = this_ndims;
2536 ndims = elem_ndims + 1;
2537 if (ndims <= 0 || ndims > MAXDIM)
2539 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
2540 errmsg("number of array dimensions (%d) exceeds " \
2541 "the maximum allowed (%d)", ndims, MAXDIM)));
2543 elem_dims = (int *) palloc(elem_ndims * sizeof(int));
2544 memcpy(elem_dims, ARR_DIMS(array), elem_ndims * sizeof(int));
2545 elem_lbs = (int *) palloc(elem_ndims * sizeof(int));
2546 memcpy(elem_lbs, ARR_LBOUND(array), elem_ndims * sizeof(int));
2552 /* Check other sub-arrays are compatible */
2553 if (elem_ndims != this_ndims ||
2554 memcmp(elem_dims, ARR_DIMS(array),
2555 elem_ndims * sizeof(int)) != 0 ||
2556 memcmp(elem_lbs, ARR_LBOUND(array),
2557 elem_ndims * sizeof(int)) != 0)
2559 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2560 errmsg("multidimensional arrays must have array "
2561 "expressions with matching dimensions")));
2564 subdata[outer_nelems] = ARR_DATA_PTR(array);
2565 subbitmaps[outer_nelems] = ARR_NULLBITMAP(array);
2566 subbytes[outer_nelems] = ARR_SIZE(array) - ARR_DATA_OFFSET(array);
2567 nbytes += subbytes[outer_nelems];
2568 subnitems[outer_nelems] = ArrayGetNItems(this_ndims,
2570 nitems += subnitems[outer_nelems];
2571 havenulls |= ARR_HASNULL(array);
2576 * If all items were null or empty arrays, return an empty array;
2577 * otherwise, if some were and some weren't, raise error. (Note: we
2578 * must special-case this somehow to avoid trying to generate a 1-D
2579 * array formed from empty arrays. It's not ideal...)
2583 if (ndims == 0) /* didn't find any nonempty array */
2584 return PointerGetDatum(construct_empty_array(element_type));
2586 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2587 errmsg("multidimensional arrays must have array "
2588 "expressions with matching dimensions")));
2591 /* setup for multi-D array */
2592 dims[0] = outer_nelems;
2594 for (i = 1; i < ndims; i++)
2596 dims[i] = elem_dims[i - 1];
2597 lbs[i] = elem_lbs[i - 1];
2602 dataoffset = ARR_OVERHEAD_WITHNULLS(ndims, nitems);
2603 nbytes += dataoffset;
2607 dataoffset = 0; /* marker for no null bitmap */
2608 nbytes += ARR_OVERHEAD_NONULLS(ndims);
2611 result = (ArrayType *) palloc(nbytes);
2612 SET_VARSIZE(result, nbytes);
2613 result->ndim = ndims;
2614 result->dataoffset = dataoffset;
2615 result->elemtype = element_type;
2616 memcpy(ARR_DIMS(result), dims, ndims * sizeof(int));
2617 memcpy(ARR_LBOUND(result), lbs, ndims * sizeof(int));
2619 dat = ARR_DATA_PTR(result);
2621 for (i = 0; i < outer_nelems; i++)
2623 memcpy(dat, subdata[i], subbytes[i]);
2626 array_bitmap_copy(ARR_NULLBITMAP(result), iitem,
2629 iitem += subnitems[i];
2633 return PointerGetDatum(result);
2636 /* ----------------------------------------------------------------
2637 * ExecEvalRow - ROW() expressions
2638 * ----------------------------------------------------------------
2641 ExecEvalRow(RowExprState *rstate,
2642 ExprContext *econtext,
2643 bool *isNull, ExprDoneCond *isDone)
2652 /* Set default values for result flags: non-null, not a set result */
2655 *isDone = ExprSingleResult;
2657 /* Allocate workspace */
2658 natts = rstate->tupdesc->natts;
2659 values = (Datum *) palloc0(natts * sizeof(Datum));
2660 isnull = (bool *) palloc(natts * sizeof(bool));
2662 /* preset to nulls in case rowtype has some later-added columns */
2663 memset(isnull, true, natts * sizeof(bool));
2665 /* Evaluate field values */
2667 foreach(arg, rstate->args)
2669 ExprState *e = (ExprState *) lfirst(arg);
2671 values[i] = ExecEvalExpr(e, econtext, &isnull[i], NULL);
2675 tuple = heap_form_tuple(rstate->tupdesc, values, isnull);
2680 return HeapTupleGetDatum(tuple);
2683 /* ----------------------------------------------------------------
2684 * ExecEvalRowCompare - ROW() comparison-op ROW()
2685 * ----------------------------------------------------------------
2688 ExecEvalRowCompare(RowCompareExprState *rstate,
2689 ExprContext *econtext,
2690 bool *isNull, ExprDoneCond *isDone)
2693 RowCompareType rctype = ((RowCompareExpr *) rstate->xprstate.expr)->rctype;
2694 int32 cmpresult = 0;
2700 *isDone = ExprSingleResult;
2701 *isNull = true; /* until we get a result */
2704 forboth(l, rstate->largs, r, rstate->rargs)
2706 ExprState *le = (ExprState *) lfirst(l);
2707 ExprState *re = (ExprState *) lfirst(r);
2708 FunctionCallInfoData locfcinfo;
2710 InitFunctionCallInfoData(locfcinfo, &(rstate->funcs[i]), 2,
2712 locfcinfo.arg[0] = ExecEvalExpr(le, econtext,
2713 &locfcinfo.argnull[0], NULL);
2714 locfcinfo.arg[1] = ExecEvalExpr(re, econtext,
2715 &locfcinfo.argnull[1], NULL);
2716 if (rstate->funcs[i].fn_strict &&
2717 (locfcinfo.argnull[0] || locfcinfo.argnull[1]))
2718 return (Datum) 0; /* force NULL result */
2719 locfcinfo.isnull = false;
2720 cmpresult = DatumGetInt32(FunctionCallInvoke(&locfcinfo));
2721 if (locfcinfo.isnull)
2722 return (Datum) 0; /* force NULL result */
2724 break; /* no need to compare remaining columns */
2730 /* EQ and NE cases aren't allowed here */
2732 result = (cmpresult < 0);
2735 result = (cmpresult <= 0);
2738 result = (cmpresult >= 0);
2741 result = (cmpresult > 0);
2744 elog(ERROR, "unrecognized RowCompareType: %d", (int) rctype);
2745 result = 0; /* keep compiler quiet */
2750 return BoolGetDatum(result);
2753 /* ----------------------------------------------------------------
2755 * ----------------------------------------------------------------
2758 ExecEvalCoalesce(CoalesceExprState *coalesceExpr, ExprContext *econtext,
2759 bool *isNull, ExprDoneCond *isDone)
2764 *isDone = ExprSingleResult;
2766 /* Simply loop through until something NOT NULL is found */
2767 foreach(arg, coalesceExpr->args)
2769 ExprState *e = (ExprState *) lfirst(arg);
2772 value = ExecEvalExpr(e, econtext, isNull, NULL);
2777 /* Else return NULL */
2782 /* ----------------------------------------------------------------
2784 * ----------------------------------------------------------------
2787 ExecEvalMinMax(MinMaxExprState *minmaxExpr, ExprContext *econtext,
2788 bool *isNull, ExprDoneCond *isDone)
2790 Datum result = (Datum) 0;
2791 MinMaxOp op = ((MinMaxExpr *) minmaxExpr->xprstate.expr)->op;
2792 FunctionCallInfoData locfcinfo;
2796 *isDone = ExprSingleResult;
2797 *isNull = true; /* until we get a result */
2799 InitFunctionCallInfoData(locfcinfo, &minmaxExpr->cfunc, 2, NULL, NULL);
2800 locfcinfo.argnull[0] = false;
2801 locfcinfo.argnull[1] = false;
2803 foreach(arg, minmaxExpr->args)
2805 ExprState *e = (ExprState *) lfirst(arg);
2810 value = ExecEvalExpr(e, econtext, &valueIsNull, NULL);
2812 continue; /* ignore NULL inputs */
2816 /* first nonnull input, adopt value */
2822 /* apply comparison function */
2823 locfcinfo.arg[0] = result;
2824 locfcinfo.arg[1] = value;
2825 locfcinfo.isnull = false;
2826 cmpresult = DatumGetInt32(FunctionCallInvoke(&locfcinfo));
2827 if (locfcinfo.isnull) /* probably should not happen */
2829 if (cmpresult > 0 && op == IS_LEAST)
2831 else if (cmpresult < 0 && op == IS_GREATEST)
2839 /* ----------------------------------------------------------------
2841 * ----------------------------------------------------------------
2844 ExecEvalXml(XmlExprState *xmlExpr, ExprContext *econtext,
2845 bool *isNull, ExprDoneCond *isDone)
2847 XmlExpr *xexpr = (XmlExpr *) xmlExpr->xprstate.expr;
2857 *isDone = ExprSingleResult;
2858 *isNull = true; /* until we get a result */
2866 foreach(arg, xmlExpr->args)
2868 ExprState *e = (ExprState *) lfirst(arg);
2870 value = ExecEvalExpr(e, econtext, &isnull, NULL);
2872 values = lappend(values, DatumGetPointer(value));
2875 if (list_length(values) > 0)
2878 return PointerGetDatum(xmlconcat(values));
2884 initStringInfo(&buf);
2886 forboth(arg, xmlExpr->named_args, narg, xexpr->arg_names)
2888 ExprState *e = (ExprState *) lfirst(arg);
2889 char *argname = strVal(lfirst(narg));
2891 value = ExecEvalExpr(e, econtext, &isnull, NULL);
2894 appendStringInfo(&buf, "<%s>%s</%s>",
2896 map_sql_value_to_xml_value(value, exprType((Node *) e->expr)),
2904 /* The remaining cases don't need to set up buf */
2907 return PointerGetDatum(xmlelement(xmlExpr, econtext));
2914 bool preserve_whitespace;
2916 /* arguments are known to be text, bool */
2917 Assert(list_length(xmlExpr->args) == 2);
2919 e = (ExprState *) linitial(xmlExpr->args);
2920 value = ExecEvalExpr(e, econtext, &isnull, NULL);
2923 data = DatumGetTextP(value);
2925 e = (ExprState *) lsecond(xmlExpr->args);
2926 value = ExecEvalExpr(e, econtext, &isnull, NULL);
2927 if (isnull) /* probably can't happen */
2929 preserve_whitespace = DatumGetBool(value);
2933 return PointerGetDatum(xmlparse(data,
2935 preserve_whitespace));
2944 /* optional argument is known to be text */
2945 Assert(list_length(xmlExpr->args) <= 1);
2949 e = (ExprState *) linitial(xmlExpr->args);
2950 value = ExecEvalExpr(e, econtext, &isnull, NULL);
2954 arg = DatumGetTextP(value);
2962 return PointerGetDatum(xmlpi(xexpr->name, arg, isnull, isNull));
2973 /* arguments are known to be xml, text, int */
2974 Assert(list_length(xmlExpr->args) == 3);
2976 e = (ExprState *) linitial(xmlExpr->args);
2977 value = ExecEvalExpr(e, econtext, &isnull, NULL);
2980 data = DatumGetXmlP(value);
2982 e = (ExprState *) lsecond(xmlExpr->args);
2983 value = ExecEvalExpr(e, econtext, &isnull, NULL);
2987 version = DatumGetTextP(value);
2989 e = (ExprState *) lthird(xmlExpr->args);
2990 value = ExecEvalExpr(e, econtext, &isnull, NULL);
2991 standalone = DatumGetInt32(value);
2995 return PointerGetDatum(xmlroot(data,
3001 case IS_XMLSERIALIZE:
3005 /* argument type is known to be xml */
3006 Assert(list_length(xmlExpr->args) == 1);
3008 e = (ExprState *) linitial(xmlExpr->args);
3009 value = ExecEvalExpr(e, econtext, &isnull, NULL);
3015 return PointerGetDatum(xmltotext_with_xmloption(DatumGetXmlP(value), xexpr->xmloption));
3023 /* optional argument is known to be xml */
3024 Assert(list_length(xmlExpr->args) == 1);
3026 e = (ExprState *) linitial(xmlExpr->args);
3027 value = ExecEvalExpr(e, econtext, &isnull, NULL);
3033 return BoolGetDatum(xml_is_document(DatumGetXmlP(value)));
3042 result = cstring_to_text_with_len(buf.data, buf.len);
3045 return PointerGetDatum(result);
3048 /* ----------------------------------------------------------------
3051 * Note that this is *always* derived from the equals operator,
3052 * but since we need special processing of the arguments
3053 * we can not simply reuse ExecEvalOper() or ExecEvalFunc().
3054 * ----------------------------------------------------------------
3057 ExecEvalNullIf(FuncExprState *nullIfExpr,
3058 ExprContext *econtext,
3059 bool *isNull, ExprDoneCond *isDone)
3062 FunctionCallInfoData fcinfo;
3063 ExprDoneCond argDone;
3067 *isDone = ExprSingleResult;
3070 * Initialize function cache if first time through
3072 if (nullIfExpr->func.fn_oid == InvalidOid)
3074 NullIfExpr *op = (NullIfExpr *) nullIfExpr->xprstate.expr;
3076 init_fcache(op->opfuncid, nullIfExpr, econtext->ecxt_per_query_memory);
3077 Assert(!nullIfExpr->func.fn_retset);
3081 * extract info from nullIfExpr
3083 argList = nullIfExpr->args;
3085 /* Need to prep callinfo structure */
3086 InitFunctionCallInfoData(fcinfo, &(nullIfExpr->func), 0, NULL, NULL);
3087 argDone = ExecEvalFuncArgs(&fcinfo, argList, econtext);
3088 if (argDone != ExprSingleResult)
3090 (errcode(ERRCODE_DATATYPE_MISMATCH),
3091 errmsg("NULLIF does not support set arguments")));
3092 Assert(fcinfo.nargs == 2);
3094 /* if either argument is NULL they can't be equal */
3095 if (!fcinfo.argnull[0] && !fcinfo.argnull[1])
3097 fcinfo.isnull = false;
3098 result = FunctionCallInvoke(&fcinfo);
3099 /* if the arguments are equal return null */
3100 if (!fcinfo.isnull && DatumGetBool(result))
3107 /* else return first argument */
3108 *isNull = fcinfo.argnull[0];
3109 return fcinfo.arg[0];
3112 /* ----------------------------------------------------------------
3115 * Evaluate a NullTest node.
3116 * ----------------------------------------------------------------
3119 ExecEvalNullTest(NullTestState *nstate,
3120 ExprContext *econtext,
3122 ExprDoneCond *isDone)
3124 NullTest *ntest = (NullTest *) nstate->xprstate.expr;
3127 result = ExecEvalExpr(nstate->arg, econtext, isNull, isDone);
3129 if (isDone && *isDone == ExprEndResult)
3130 return result; /* nothing to check */
3132 if (nstate->argisrow && !(*isNull))
3134 HeapTupleHeader tuple;
3138 HeapTupleData tmptup;
3141 tuple = DatumGetHeapTupleHeader(result);
3143 tupType = HeapTupleHeaderGetTypeId(tuple);
3144 tupTypmod = HeapTupleHeaderGetTypMod(tuple);
3146 /* Lookup tupdesc if first time through or if type changes */
3147 tupDesc = get_cached_rowtype(tupType, tupTypmod,
3148 &nstate->argdesc, econtext);
3151 * heap_attisnull needs a HeapTuple not a bare HeapTupleHeader.
3153 tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
3154 tmptup.t_data = tuple;
3156 for (att = 1; att <= tupDesc->natts; att++)
3158 /* ignore dropped columns */
3159 if (tupDesc->attrs[att - 1]->attisdropped)
3161 if (heap_attisnull(&tmptup, att))
3163 /* null field disproves IS NOT NULL */
3164 if (ntest->nulltesttype == IS_NOT_NULL)
3165 return BoolGetDatum(false);
3169 /* non-null field disproves IS NULL */
3170 if (ntest->nulltesttype == IS_NULL)
3171 return BoolGetDatum(false);
3175 return BoolGetDatum(true);
3179 /* Simple scalar-argument case, or a null rowtype datum */
3180 switch (ntest->nulltesttype)
3186 return BoolGetDatum(true);
3189 return BoolGetDatum(false);
3194 return BoolGetDatum(false);
3197 return BoolGetDatum(true);
3199 elog(ERROR, "unrecognized nulltesttype: %d",
3200 (int) ntest->nulltesttype);
3201 return (Datum) 0; /* keep compiler quiet */
3206 /* ----------------------------------------------------------------
3207 * ExecEvalBooleanTest
3209 * Evaluate a BooleanTest node.
3210 * ----------------------------------------------------------------
3213 ExecEvalBooleanTest(GenericExprState *bstate,
3214 ExprContext *econtext,
3216 ExprDoneCond *isDone)
3218 BooleanTest *btest = (BooleanTest *) bstate->xprstate.expr;
3221 result = ExecEvalExpr(bstate->arg, econtext, isNull, isDone);
3223 if (isDone && *isDone == ExprEndResult)
3224 return result; /* nothing to check */
3226 switch (btest->booltesttype)
3232 return BoolGetDatum(false);
3234 else if (DatumGetBool(result))
3235 return BoolGetDatum(true);
3237 return BoolGetDatum(false);
3242 return BoolGetDatum(true);
3244 else if (DatumGetBool(result))
3245 return BoolGetDatum(false);
3247 return BoolGetDatum(true);
3252 return BoolGetDatum(false);
3254 else if (DatumGetBool(result))
3255 return BoolGetDatum(false);
3257 return BoolGetDatum(true);
3262 return BoolGetDatum(true);
3264 else if (DatumGetBool(result))
3265 return BoolGetDatum(true);
3267 return BoolGetDatum(false);
3272 return BoolGetDatum(true);
3275 return BoolGetDatum(false);
3276 case IS_NOT_UNKNOWN:
3280 return BoolGetDatum(false);
3283 return BoolGetDatum(true);
3285 elog(ERROR, "unrecognized booltesttype: %d",
3286 (int) btest->booltesttype);
3287 return (Datum) 0; /* keep compiler quiet */
3292 * ExecEvalCoerceToDomain
3294 * Test the provided data against the domain constraint(s). If the data
3295 * passes the constraint specifications, pass it through (return the
3296 * datum) otherwise throw an error.
3299 ExecEvalCoerceToDomain(CoerceToDomainState *cstate, ExprContext *econtext,
3300 bool *isNull, ExprDoneCond *isDone)
3302 CoerceToDomain *ctest = (CoerceToDomain *) cstate->xprstate.expr;
3306 result = ExecEvalExpr(cstate->arg, econtext, isNull, isDone);
3308 if (isDone && *isDone == ExprEndResult)
3309 return result; /* nothing to check */
3311 foreach(l, cstate->constraints)
3313 DomainConstraintState *con = (DomainConstraintState *) lfirst(l);
3315 switch (con->constrainttype)
3317 case DOM_CONSTRAINT_NOTNULL:
3320 (errcode(ERRCODE_NOT_NULL_VIOLATION),
3321 errmsg("domain %s does not allow null values",
3322 format_type_be(ctest->resulttype))));
3324 case DOM_CONSTRAINT_CHECK:
3332 * Set up value to be returned by CoerceToDomainValue
3333 * nodes. We must save and restore prior setting of
3334 * econtext's domainValue fields, in case this node is
3335 * itself within a check expression for another domain.
3337 save_datum = econtext->domainValue_datum;
3338 save_isNull = econtext->domainValue_isNull;
3340 econtext->domainValue_datum = result;
3341 econtext->domainValue_isNull = *isNull;
3343 conResult = ExecEvalExpr(con->check_expr,
3344 econtext, &conIsNull, NULL);
3347 !DatumGetBool(conResult))
3349 (errcode(ERRCODE_CHECK_VIOLATION),
3350 errmsg("value for domain %s violates check constraint \"%s\"",
3351 format_type_be(ctest->resulttype),
3353 econtext->domainValue_datum = save_datum;
3354 econtext->domainValue_isNull = save_isNull;
3359 elog(ERROR, "unrecognized constraint type: %d",
3360 (int) con->constrainttype);
3365 /* If all has gone well (constraints did not fail) return the datum */
3370 * ExecEvalCoerceToDomainValue
3372 * Return the value stored by CoerceToDomain.
3375 ExecEvalCoerceToDomainValue(ExprState *exprstate,
3376 ExprContext *econtext,
3377 bool *isNull, ExprDoneCond *isDone)
3380 *isDone = ExprSingleResult;
3381 *isNull = econtext->domainValue_isNull;
3382 return econtext->domainValue_datum;
3385 /* ----------------------------------------------------------------
3386 * ExecEvalFieldSelect
3388 * Evaluate a FieldSelect node.
3389 * ----------------------------------------------------------------
3392 ExecEvalFieldSelect(FieldSelectState *fstate,
3393 ExprContext *econtext,
3395 ExprDoneCond *isDone)
3397 FieldSelect *fselect = (FieldSelect *) fstate->xprstate.expr;
3398 AttrNumber fieldnum = fselect->fieldnum;
3401 HeapTupleHeader tuple;
3405 Form_pg_attribute attr;
3406 HeapTupleData tmptup;
3408 tupDatum = ExecEvalExpr(fstate->arg, econtext, isNull, isDone);
3410 /* this test covers the isDone exception too: */
3414 tuple = DatumGetHeapTupleHeader(tupDatum);
3416 tupType = HeapTupleHeaderGetTypeId(tuple);
3417 tupTypmod = HeapTupleHeaderGetTypMod(tuple);
3419 /* Lookup tupdesc if first time through or if type changes */
3420 tupDesc = get_cached_rowtype(tupType, tupTypmod,
3421 &fstate->argdesc, econtext);
3423 /* Check for dropped column, and force a NULL result if so */
3424 if (fieldnum <= 0 ||
3425 fieldnum > tupDesc->natts) /* should never happen */
3426 elog(ERROR, "attribute number %d exceeds number of columns %d",
3427 fieldnum, tupDesc->natts);
3428 attr = tupDesc->attrs[fieldnum - 1];
3429 if (attr->attisdropped)
3435 /* Check for type mismatch --- possible after ALTER COLUMN TYPE? */
3436 /* As in ExecEvalVar, we should but can't check typmod */
3437 if (fselect->resulttype != attr->atttypid)
3439 (errmsg("attribute %d has wrong type", fieldnum),
3440 errdetail("Table has type %s, but query expects %s.",
3441 format_type_be(attr->atttypid),
3442 format_type_be(fselect->resulttype))));
3445 * heap_getattr needs a HeapTuple not a bare HeapTupleHeader. We set all
3446 * the fields in the struct just in case user tries to inspect system
3449 tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
3450 ItemPointerSetInvalid(&(tmptup.t_self));
3451 tmptup.t_tableOid = InvalidOid;
3452 tmptup.t_data = tuple;
3454 result = heap_getattr(&tmptup,
3461 /* ----------------------------------------------------------------
3462 * ExecEvalFieldStore
3464 * Evaluate a FieldStore node.
3465 * ----------------------------------------------------------------
3468 ExecEvalFieldStore(FieldStoreState *fstate,
3469 ExprContext *econtext,
3471 ExprDoneCond *isDone)
3473 FieldStore *fstore = (FieldStore *) fstate->xprstate.expr;
3484 tupDatum = ExecEvalExpr(fstate->arg, econtext, isNull, isDone);
3486 if (isDone && *isDone == ExprEndResult)
3489 /* Lookup tupdesc if first time through or after rescan */
3490 tupDesc = get_cached_rowtype(fstore->resulttype, -1,
3491 &fstate->argdesc, econtext);
3493 /* Allocate workspace */
3494 values = (Datum *) palloc(tupDesc->natts * sizeof(Datum));
3495 isnull = (bool *) palloc(tupDesc->natts * sizeof(bool));
3500 * heap_deform_tuple needs a HeapTuple not a bare HeapTupleHeader. We
3501 * set all the fields in the struct just in case.
3503 HeapTupleHeader tuphdr;
3504 HeapTupleData tmptup;
3506 tuphdr = DatumGetHeapTupleHeader(tupDatum);
3507 tmptup.t_len = HeapTupleHeaderGetDatumLength(tuphdr);
3508 ItemPointerSetInvalid(&(tmptup.t_self));
3509 tmptup.t_tableOid = InvalidOid;
3510 tmptup.t_data = tuphdr;
3512 heap_deform_tuple(&tmptup, tupDesc, values, isnull);
3516 /* Convert null input tuple into an all-nulls row */
3517 memset(isnull, true, tupDesc->natts * sizeof(bool));
3520 /* Result is never null */
3523 save_datum = econtext->caseValue_datum;
3524 save_isNull = econtext->caseValue_isNull;
3526 forboth(l1, fstate->newvals, l2, fstore->fieldnums)
3528 ExprState *newval = (ExprState *) lfirst(l1);
3529 AttrNumber fieldnum = lfirst_int(l2);
3531 Assert(fieldnum > 0 && fieldnum <= tupDesc->natts);
3534 * Use the CaseTestExpr mechanism to pass down the old value of the
3535 * field being replaced; this is useful in case we have a nested field
3536 * update situation. It's safe to reuse the CASE mechanism because
3537 * there cannot be a CASE between here and where the value would be
3540 econtext->caseValue_datum = values[fieldnum - 1];
3541 econtext->caseValue_isNull = isnull[fieldnum - 1];
3543 values[fieldnum - 1] = ExecEvalExpr(newval,
3545 &isnull[fieldnum - 1],
3549 econtext->caseValue_datum = save_datum;
3550 econtext->caseValue_isNull = save_isNull;
3552 tuple = heap_form_tuple(tupDesc, values, isnull);
3557 return HeapTupleGetDatum(tuple);
3560 /* ----------------------------------------------------------------
3561 * ExecEvalRelabelType
3563 * Evaluate a RelabelType node.
3564 * ----------------------------------------------------------------
3567 ExecEvalRelabelType(GenericExprState *exprstate,
3568 ExprContext *econtext,
3569 bool *isNull, ExprDoneCond *isDone)
3571 return ExecEvalExpr(exprstate->arg, econtext, isNull, isDone);
3574 /* ----------------------------------------------------------------
3575 * ExecEvalCoerceViaIO
3577 * Evaluate a CoerceViaIO node.
3578 * ----------------------------------------------------------------
3581 ExecEvalCoerceViaIO(CoerceViaIOState *iostate,
3582 ExprContext *econtext,
3583 bool *isNull, ExprDoneCond *isDone)
3589 inputval = ExecEvalExpr(iostate->arg, econtext, isNull, isDone);
3591 if (isDone && *isDone == ExprEndResult)
3592 return inputval; /* nothing to do */
3595 string = NULL; /* output functions are not called on nulls */
3597 string = OutputFunctionCall(&iostate->outfunc, inputval);
3599 result = InputFunctionCall(&iostate->infunc,
3601 iostate->intypioparam,
3604 /* The input function cannot change the null/not-null status */
3608 /* ----------------------------------------------------------------
3609 * ExecEvalArrayCoerceExpr
3611 * Evaluate an ArrayCoerceExpr node.
3612 * ----------------------------------------------------------------
3615 ExecEvalArrayCoerceExpr(ArrayCoerceExprState *astate,
3616 ExprContext *econtext,
3617 bool *isNull, ExprDoneCond *isDone)
3619 ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) astate->xprstate.expr;
3622 FunctionCallInfoData locfcinfo;
3624 result = ExecEvalExpr(astate->arg, econtext, isNull, isDone);
3626 if (isDone && *isDone == ExprEndResult)
3627 return result; /* nothing to do */
3629 return result; /* nothing to do */
3632 * If it's binary-compatible, modify the element type in the array header,
3633 * but otherwise leave the array as we received it.
3635 if (!OidIsValid(acoerce->elemfuncid))
3637 /* Detoast input array if necessary, and copy in any case */
3638 array = DatumGetArrayTypePCopy(result);
3639 ARR_ELEMTYPE(array) = astate->resultelemtype;
3640 PG_RETURN_ARRAYTYPE_P(array);
3643 /* Detoast input array if necessary, but don't make a useless copy */
3644 array = DatumGetArrayTypeP(result);
3646 /* Initialize function cache if first time through */
3647 if (astate->elemfunc.fn_oid == InvalidOid)
3649 AclResult aclresult;
3651 /* Check permission to call function */
3652 aclresult = pg_proc_aclcheck(acoerce->elemfuncid, GetUserId(),
3654 if (aclresult != ACLCHECK_OK)
3655 aclcheck_error(aclresult, ACL_KIND_PROC,
3656 get_func_name(acoerce->elemfuncid));
3658 /* Set up the primary fmgr lookup information */
3659 fmgr_info_cxt(acoerce->elemfuncid, &(astate->elemfunc),
3660 econtext->ecxt_per_query_memory);
3662 /* Initialize additional info */
3663 astate->elemfunc.fn_expr = (Node *) acoerce;
3667 * Use array_map to apply the function to each array element.
3669 * We pass on the desttypmod and isExplicit flags whether or not the
3670 * function wants them.
3672 InitFunctionCallInfoData(locfcinfo, &(astate->elemfunc), 3,
3674 locfcinfo.arg[0] = PointerGetDatum(array);
3675 locfcinfo.arg[1] = Int32GetDatum(acoerce->resulttypmod);
3676 locfcinfo.arg[2] = BoolGetDatum(acoerce->isExplicit);
3677 locfcinfo.argnull[0] = false;
3678 locfcinfo.argnull[1] = false;
3679 locfcinfo.argnull[2] = false;
3681 return array_map(&locfcinfo, ARR_ELEMTYPE(array), astate->resultelemtype,
3685 /* ----------------------------------------------------------------
3686 * ExecEvalCurrentOfExpr
3688 * The planner must convert CURRENT OF into a TidScan qualification.
3689 * So, we have to be able to do ExecInitExpr on a CurrentOfExpr,
3690 * but we shouldn't ever actually execute it.
3691 * ----------------------------------------------------------------
3694 ExecEvalCurrentOfExpr(ExprState *exprstate, ExprContext *econtext,
3695 bool *isNull, ExprDoneCond *isDone)
3697 elog(ERROR, "CURRENT OF cannot be executed");
3698 return 0; /* keep compiler quiet */
3703 * ExecEvalExprSwitchContext
3705 * Same as ExecEvalExpr, but get into the right allocation context explicitly.
3708 ExecEvalExprSwitchContext(ExprState *expression,
3709 ExprContext *econtext,
3711 ExprDoneCond *isDone)
3714 MemoryContext oldContext;
3716 oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
3717 retDatum = ExecEvalExpr(expression, econtext, isNull, isDone);
3718 MemoryContextSwitchTo(oldContext);
3724 * ExecInitExpr: prepare an expression tree for execution
3726 * This function builds and returns an ExprState tree paralleling the given
3727 * Expr node tree. The ExprState tree can then be handed to ExecEvalExpr
3728 * for execution. Because the Expr tree itself is read-only as far as
3729 * ExecInitExpr and ExecEvalExpr are concerned, several different executions
3730 * of the same plan tree can occur concurrently.
3732 * This must be called in a memory context that will last as long as repeated
3733 * executions of the expression are needed. Typically the context will be
3734 * the same as the per-query context of the associated ExprContext.
3736 * Any Aggref and SubPlan nodes found in the tree are added to the lists
3737 * of such nodes held by the parent PlanState. Otherwise, we do very little
3738 * initialization here other than building the state-node tree. Any nontrivial
3739 * work associated with initializing runtime info for a node should happen
3740 * during the first actual evaluation of that node. (This policy lets us
3741 * avoid work if the node is never actually evaluated.)
3743 * Note: there is no ExecEndExpr function; we assume that any resource
3744 * cleanup needed will be handled by just releasing the memory context
3745 * in which the state tree is built. Functions that require additional
3746 * cleanup work can register a shutdown callback in the ExprContext.
3748 * 'node' is the root of the expression tree to examine
3749 * 'parent' is the PlanState node that owns the expression.
3751 * 'parent' may be NULL if we are preparing an expression that is not
3752 * associated with a plan tree. (If so, it can't have aggs or subplans.)
3753 * This case should usually come through ExecPrepareExpr, not directly here.
3756 ExecInitExpr(Expr *node, PlanState *parent)
3763 /* Guard against stack overflow due to overly complex expressions */
3764 check_stack_depth();
3766 switch (nodeTag(node))
3769 state = (ExprState *) makeNode(ExprState);
3770 state->evalfunc = ExecEvalVar;
3773 state = (ExprState *) makeNode(ExprState);
3774 state->evalfunc = ExecEvalConst;
3777 state = (ExprState *) makeNode(ExprState);
3778 state->evalfunc = ExecEvalParam;
3780 case T_CoerceToDomainValue:
3781 state = (ExprState *) makeNode(ExprState);
3782 state->evalfunc = ExecEvalCoerceToDomainValue;
3784 case T_CaseTestExpr:
3785 state = (ExprState *) makeNode(ExprState);
3786 state->evalfunc = ExecEvalCaseTestExpr;
3790 Aggref *aggref = (Aggref *) node;
3791 AggrefExprState *astate = makeNode(AggrefExprState);
3793 astate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalAggref;
3794 if (parent && IsA(parent, AggState))
3796 AggState *aggstate = (AggState *) parent;
3799 aggstate->aggs = lcons(astate, aggstate->aggs);
3800 naggs = ++aggstate->numaggs;
3802 astate->args = (List *) ExecInitExpr((Expr *) aggref->args,
3806 * Complain if the aggregate's arguments contain any
3807 * aggregates; nested agg functions are semantically
3808 * nonsensical. (This should have been caught earlier,
3809 * but we defend against it here anyway.)
3811 if (naggs != aggstate->numaggs)
3813 (errcode(ERRCODE_GROUPING_ERROR),
3814 errmsg("aggregate function calls cannot be nested")));
3818 /* planner messed up */
3819 elog(ERROR, "aggref found in non-Agg plan node");
3821 state = (ExprState *) astate;
3826 ArrayRef *aref = (ArrayRef *) node;
3827 ArrayRefExprState *astate = makeNode(ArrayRefExprState);
3829 astate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalArrayRef;
3830 astate->refupperindexpr = (List *)
3831 ExecInitExpr((Expr *) aref->refupperindexpr, parent);
3832 astate->reflowerindexpr = (List *)
3833 ExecInitExpr((Expr *) aref->reflowerindexpr, parent);
3834 astate->refexpr = ExecInitExpr(aref->refexpr, parent);
3835 astate->refassgnexpr = ExecInitExpr(aref->refassgnexpr,
3837 /* do one-time catalog lookups for type info */
3838 astate->refattrlength = get_typlen(aref->refarraytype);
3839 get_typlenbyvalalign(aref->refelemtype,
3840 &astate->refelemlength,
3841 &astate->refelembyval,
3842 &astate->refelemalign);
3843 state = (ExprState *) astate;
3848 FuncExpr *funcexpr = (FuncExpr *) node;
3849 FuncExprState *fstate = makeNode(FuncExprState);
3851 fstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalFunc;
3852 fstate->args = (List *)
3853 ExecInitExpr((Expr *) funcexpr->args, parent);
3854 fstate->func.fn_oid = InvalidOid; /* not initialized */
3855 state = (ExprState *) fstate;
3860 OpExpr *opexpr = (OpExpr *) node;
3861 FuncExprState *fstate = makeNode(FuncExprState);
3863 fstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalOper;
3864 fstate->args = (List *)
3865 ExecInitExpr((Expr *) opexpr->args, parent);
3866 fstate->func.fn_oid = InvalidOid; /* not initialized */
3867 state = (ExprState *) fstate;
3870 case T_DistinctExpr:
3872 DistinctExpr *distinctexpr = (DistinctExpr *) node;
3873 FuncExprState *fstate = makeNode(FuncExprState);
3875 fstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalDistinct;
3876 fstate->args = (List *)
3877 ExecInitExpr((Expr *) distinctexpr->args, parent);
3878 fstate->func.fn_oid = InvalidOid; /* not initialized */
3879 state = (ExprState *) fstate;
3882 case T_ScalarArrayOpExpr:
3884 ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) node;
3885 ScalarArrayOpExprState *sstate = makeNode(ScalarArrayOpExprState);
3887 sstate->fxprstate.xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalScalarArrayOp;
3888 sstate->fxprstate.args = (List *)
3889 ExecInitExpr((Expr *) opexpr->args, parent);
3890 sstate->fxprstate.func.fn_oid = InvalidOid; /* not initialized */
3891 sstate->element_type = InvalidOid; /* ditto */
3892 state = (ExprState *) sstate;
3897 BoolExpr *boolexpr = (BoolExpr *) node;
3898 BoolExprState *bstate = makeNode(BoolExprState);
3900 switch (boolexpr->boolop)
3903 bstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalAnd;
3906 bstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalOr;
3909 bstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalNot;
3912 elog(ERROR, "unrecognized boolop: %d",
3913 (int) boolexpr->boolop);
3916 bstate->args = (List *)
3917 ExecInitExpr((Expr *) boolexpr->args, parent);
3918 state = (ExprState *) bstate;
3923 SubPlan *subplan = (SubPlan *) node;
3924 SubPlanState *sstate;
3927 elog(ERROR, "SubPlan found with no parent plan");
3929 sstate = ExecInitSubPlan(subplan, parent);
3931 /* Add SubPlanState nodes to parent->subPlan */
3932 parent->subPlan = lcons(sstate, parent->subPlan);
3934 state = (ExprState *) sstate;
3939 FieldSelect *fselect = (FieldSelect *) node;
3940 FieldSelectState *fstate = makeNode(FieldSelectState);
3942 fstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalFieldSelect;
3943 fstate->arg = ExecInitExpr(fselect->arg, parent);
3944 fstate->argdesc = NULL;
3945 state = (ExprState *) fstate;
3950 FieldStore *fstore = (FieldStore *) node;
3951 FieldStoreState *fstate = makeNode(FieldStoreState);
3953 fstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalFieldStore;
3954 fstate->arg = ExecInitExpr(fstore->arg, parent);
3955 fstate->newvals = (List *) ExecInitExpr((Expr *) fstore->newvals, parent);
3956 fstate->argdesc = NULL;
3957 state = (ExprState *) fstate;
3962 RelabelType *relabel = (RelabelType *) node;
3963 GenericExprState *gstate = makeNode(GenericExprState);
3965 gstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalRelabelType;
3966 gstate->arg = ExecInitExpr(relabel->arg, parent);
3967 state = (ExprState *) gstate;
3972 CoerceViaIO *iocoerce = (CoerceViaIO *) node;
3973 CoerceViaIOState *iostate = makeNode(CoerceViaIOState);
3977 iostate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalCoerceViaIO;
3978 iostate->arg = ExecInitExpr(iocoerce->arg, parent);
3979 /* lookup the result type's input function */
3980 getTypeInputInfo(iocoerce->resulttype, &iofunc,
3981 &iostate->intypioparam);
3982 fmgr_info(iofunc, &iostate->infunc);
3983 /* lookup the input type's output function */
3984 getTypeOutputInfo(exprType((Node *) iocoerce->arg),
3985 &iofunc, &typisvarlena);
3986 fmgr_info(iofunc, &iostate->outfunc);
3987 state = (ExprState *) iostate;
3990 case T_ArrayCoerceExpr:
3992 ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
3993 ArrayCoerceExprState *astate = makeNode(ArrayCoerceExprState);
3995 astate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalArrayCoerceExpr;
3996 astate->arg = ExecInitExpr(acoerce->arg, parent);
3997 astate->resultelemtype = get_element_type(acoerce->resulttype);
3998 if (astate->resultelemtype == InvalidOid)
4000 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4001 errmsg("target type is not an array")));
4002 /* Arrays over domains aren't supported yet */
4003 Assert(getBaseType(astate->resultelemtype) ==
4004 astate->resultelemtype);
4005 astate->elemfunc.fn_oid = InvalidOid; /* not initialized */
4006 astate->amstate = (ArrayMapState *) palloc0(sizeof(ArrayMapState));
4007 state = (ExprState *) astate;
4010 case T_ConvertRowtypeExpr:
4012 ConvertRowtypeExpr *convert = (ConvertRowtypeExpr *) node;
4013 ConvertRowtypeExprState *cstate = makeNode(ConvertRowtypeExprState);
4015 cstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalConvertRowtype;
4016 cstate->arg = ExecInitExpr(convert->arg, parent);
4017 state = (ExprState *) cstate;
4022 CaseExpr *caseexpr = (CaseExpr *) node;
4023 CaseExprState *cstate = makeNode(CaseExprState);
4024 List *outlist = NIL;
4027 cstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalCase;
4028 cstate->arg = ExecInitExpr(caseexpr->arg, parent);
4029 foreach(l, caseexpr->args)
4031 CaseWhen *when = (CaseWhen *) lfirst(l);
4032 CaseWhenState *wstate = makeNode(CaseWhenState);
4034 Assert(IsA(when, CaseWhen));
4035 wstate->xprstate.evalfunc = NULL; /* not used */
4036 wstate->xprstate.expr = (Expr *) when;
4037 wstate->expr = ExecInitExpr(when->expr, parent);
4038 wstate->result = ExecInitExpr(when->result, parent);
4039 outlist = lappend(outlist, wstate);
4041 cstate->args = outlist;
4042 cstate->defresult = ExecInitExpr(caseexpr->defresult, parent);
4043 state = (ExprState *) cstate;
4048 ArrayExpr *arrayexpr = (ArrayExpr *) node;
4049 ArrayExprState *astate = makeNode(ArrayExprState);
4050 List *outlist = NIL;
4053 astate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalArray;
4054 foreach(l, arrayexpr->elements)
4056 Expr *e = (Expr *) lfirst(l);
4059 estate = ExecInitExpr(e, parent);
4060 outlist = lappend(outlist, estate);
4062 astate->elements = outlist;
4063 /* do one-time catalog lookup for type info */
4064 get_typlenbyvalalign(arrayexpr->element_typeid,
4065 &astate->elemlength,
4067 &astate->elemalign);
4068 state = (ExprState *) astate;
4073 RowExpr *rowexpr = (RowExpr *) node;
4074 RowExprState *rstate = makeNode(RowExprState);
4075 Form_pg_attribute *attrs;
4076 List *outlist = NIL;
4080 rstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalRow;
4081 /* Build tupdesc to describe result tuples */
4082 if (rowexpr->row_typeid == RECORDOID)
4084 /* generic record, use runtime type assignment */
4085 rstate->tupdesc = ExecTypeFromExprList(rowexpr->args);
4086 BlessTupleDesc(rstate->tupdesc);
4087 /* we won't need to redo this at runtime */
4091 /* it's been cast to a named type, use that */
4092 rstate->tupdesc = lookup_rowtype_tupdesc_copy(rowexpr->row_typeid, -1);
4094 /* Set up evaluation, skipping any deleted columns */
4095 Assert(list_length(rowexpr->args) <= rstate->tupdesc->natts);
4096 attrs = rstate->tupdesc->attrs;
4098 foreach(l, rowexpr->args)
4100 Expr *e = (Expr *) lfirst(l);
4103 if (!attrs[i]->attisdropped)
4106 * Guard against ALTER COLUMN TYPE on rowtype since
4107 * the RowExpr was created. XXX should we check
4108 * typmod too? Not sure we can be sure it'll be the
4111 if (exprType((Node *) e) != attrs[i]->atttypid)
4113 (errcode(ERRCODE_DATATYPE_MISMATCH),
4114 errmsg("ROW() column has type %s instead of type %s",
4115 format_type_be(exprType((Node *) e)),
4116 format_type_be(attrs[i]->atttypid))));
4121 * Ignore original expression and insert a NULL. We
4122 * don't really care what type of NULL it is, so
4123 * always make an int4 NULL.
4125 e = (Expr *) makeNullConst(INT4OID, -1);
4127 estate = ExecInitExpr(e, parent);
4128 outlist = lappend(outlist, estate);
4131 rstate->args = outlist;
4132 state = (ExprState *) rstate;
4135 case T_RowCompareExpr:
4137 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
4138 RowCompareExprState *rstate = makeNode(RowCompareExprState);
4139 int nopers = list_length(rcexpr->opnos);
4145 rstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalRowCompare;
4146 Assert(list_length(rcexpr->largs) == nopers);
4148 foreach(l, rcexpr->largs)
4150 Expr *e = (Expr *) lfirst(l);
4153 estate = ExecInitExpr(e, parent);
4154 outlist = lappend(outlist, estate);
4156 rstate->largs = outlist;
4157 Assert(list_length(rcexpr->rargs) == nopers);
4159 foreach(l, rcexpr->rargs)
4161 Expr *e = (Expr *) lfirst(l);
4164 estate = ExecInitExpr(e, parent);
4165 outlist = lappend(outlist, estate);
4167 rstate->rargs = outlist;
4168 Assert(list_length(rcexpr->opfamilies) == nopers);
4169 rstate->funcs = (FmgrInfo *) palloc(nopers * sizeof(FmgrInfo));
4171 forboth(l, rcexpr->opnos, l2, rcexpr->opfamilies)
4173 Oid opno = lfirst_oid(l);
4174 Oid opfamily = lfirst_oid(l2);
4180 get_op_opfamily_properties(opno, opfamily,
4184 proc = get_opfamily_proc(opfamily,
4190 * If we enforced permissions checks on index support
4191 * functions, we'd need to make a check here. But the
4192 * index support machinery doesn't do that, and neither
4195 fmgr_info(proc, &(rstate->funcs[i]));
4198 state = (ExprState *) rstate;
4201 case T_CoalesceExpr:
4203 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
4204 CoalesceExprState *cstate = makeNode(CoalesceExprState);
4205 List *outlist = NIL;
4208 cstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalCoalesce;
4209 foreach(l, coalesceexpr->args)
4211 Expr *e = (Expr *) lfirst(l);
4214 estate = ExecInitExpr(e, parent);
4215 outlist = lappend(outlist, estate);
4217 cstate->args = outlist;
4218 state = (ExprState *) cstate;
4223 MinMaxExpr *minmaxexpr = (MinMaxExpr *) node;
4224 MinMaxExprState *mstate = makeNode(MinMaxExprState);
4225 List *outlist = NIL;
4227 TypeCacheEntry *typentry;
4229 mstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalMinMax;
4230 foreach(l, minmaxexpr->args)
4232 Expr *e = (Expr *) lfirst(l);
4235 estate = ExecInitExpr(e, parent);
4236 outlist = lappend(outlist, estate);
4238 mstate->args = outlist;
4239 /* Look up the btree comparison function for the datatype */
4240 typentry = lookup_type_cache(minmaxexpr->minmaxtype,
4241 TYPECACHE_CMP_PROC);
4242 if (!OidIsValid(typentry->cmp_proc))
4244 (errcode(ERRCODE_UNDEFINED_FUNCTION),
4245 errmsg("could not identify a comparison function for type %s",
4246 format_type_be(minmaxexpr->minmaxtype))));
4249 * If we enforced permissions checks on index support
4250 * functions, we'd need to make a check here. But the index
4251 * support machinery doesn't do that, and neither does this
4254 fmgr_info(typentry->cmp_proc, &(mstate->cfunc));
4255 state = (ExprState *) mstate;
4260 XmlExpr *xexpr = (XmlExpr *) node;
4261 XmlExprState *xstate = makeNode(XmlExprState);
4266 xstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalXml;
4267 xstate->named_outfuncs = (FmgrInfo *)
4268 palloc0(list_length(xexpr->named_args) * sizeof(FmgrInfo));
4271 foreach(arg, xexpr->named_args)
4273 Expr *e = (Expr *) lfirst(arg);
4278 estate = ExecInitExpr(e, parent);
4279 outlist = lappend(outlist, estate);
4281 getTypeOutputInfo(exprType((Node *) e),
4282 &typOutFunc, &typIsVarlena);
4283 fmgr_info(typOutFunc, &xstate->named_outfuncs[i]);
4286 xstate->named_args = outlist;
4289 foreach(arg, xexpr->args)
4291 Expr *e = (Expr *) lfirst(arg);
4294 estate = ExecInitExpr(e, parent);
4295 outlist = lappend(outlist, estate);
4297 xstate->args = outlist;
4299 state = (ExprState *) xstate;
4304 NullIfExpr *nullifexpr = (NullIfExpr *) node;
4305 FuncExprState *fstate = makeNode(FuncExprState);
4307 fstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalNullIf;
4308 fstate->args = (List *)
4309 ExecInitExpr((Expr *) nullifexpr->args, parent);
4310 fstate->func.fn_oid = InvalidOid; /* not initialized */
4311 state = (ExprState *) fstate;
4316 NullTest *ntest = (NullTest *) node;
4317 NullTestState *nstate = makeNode(NullTestState);
4319 nstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalNullTest;
4320 nstate->arg = ExecInitExpr(ntest->arg, parent);
4321 nstate->argisrow = type_is_rowtype(exprType((Node *) ntest->arg));
4322 nstate->argdesc = NULL;
4323 state = (ExprState *) nstate;
4328 BooleanTest *btest = (BooleanTest *) node;
4329 GenericExprState *gstate = makeNode(GenericExprState);
4331 gstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalBooleanTest;
4332 gstate->arg = ExecInitExpr(btest->arg, parent);
4333 state = (ExprState *) gstate;
4336 case T_CoerceToDomain:
4338 CoerceToDomain *ctest = (CoerceToDomain *) node;
4339 CoerceToDomainState *cstate = makeNode(CoerceToDomainState);
4341 cstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalCoerceToDomain;
4342 cstate->arg = ExecInitExpr(ctest->arg, parent);
4343 cstate->constraints = GetDomainConstraints(ctest->resulttype);
4344 state = (ExprState *) cstate;
4347 case T_CurrentOfExpr:
4348 state = (ExprState *) makeNode(ExprState);
4349 state->evalfunc = ExecEvalCurrentOfExpr;
4353 TargetEntry *tle = (TargetEntry *) node;
4354 GenericExprState *gstate = makeNode(GenericExprState);
4356 gstate->xprstate.evalfunc = NULL; /* not used */
4357 gstate->arg = ExecInitExpr(tle->expr, parent);
4358 state = (ExprState *) gstate;
4363 List *outlist = NIL;
4366 foreach(l, (List *) node)
4368 outlist = lappend(outlist,
4369 ExecInitExpr((Expr *) lfirst(l),
4372 /* Don't fall through to the "common" code below */
4373 return (ExprState *) outlist;
4376 elog(ERROR, "unrecognized node type: %d",
4377 (int) nodeTag(node));
4378 state = NULL; /* keep compiler quiet */
4382 /* Common code for all state-node types */
4389 * ExecPrepareExpr --- initialize for expression execution outside a normal
4390 * Plan tree context.
4392 * This differs from ExecInitExpr in that we don't assume the caller is
4393 * already running in the EState's per-query context. Also, we apply
4394 * fix_opfuncids() to the passed expression tree to be sure it is ready
4395 * to run. (In ordinary Plan trees the planner will have fixed opfuncids,
4396 * but callers outside the executor will not have done this.)
4399 ExecPrepareExpr(Expr *node, EState *estate)
4402 MemoryContext oldcontext;
4404 fix_opfuncids((Node *) node);
4406 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
4408 result = ExecInitExpr(node, NULL);
4410 MemoryContextSwitchTo(oldcontext);
4416 /* ----------------------------------------------------------------
4417 * ExecQual / ExecTargetList / ExecProject
4418 * ----------------------------------------------------------------
4421 /* ----------------------------------------------------------------
4424 * Evaluates a conjunctive boolean expression (qual list) and
4425 * returns true iff none of the subexpressions are false.
4426 * (We also return true if the list is empty.)
4428 * If some of the subexpressions yield NULL but none yield FALSE,
4429 * then the result of the conjunction is NULL (ie, unknown)
4430 * according to three-valued boolean logic. In this case,
4431 * we return the value specified by the "resultForNull" parameter.
4433 * Callers evaluating WHERE clauses should pass resultForNull=FALSE,
4434 * since SQL specifies that tuples with null WHERE results do not
4435 * get selected. On the other hand, callers evaluating constraint
4436 * conditions should pass resultForNull=TRUE, since SQL also specifies
4437 * that NULL constraint conditions are not failures.
4439 * NOTE: it would not be correct to use this routine to evaluate an
4440 * AND subclause of a boolean expression; for that purpose, a NULL
4441 * result must be returned as NULL so that it can be properly treated
4442 * in the next higher operator (cf. ExecEvalAnd and ExecEvalOr).
4443 * This routine is only used in contexts where a complete expression
4444 * is being evaluated and we know that NULL can be treated the same
4445 * as one boolean result or the other.
4447 * ----------------------------------------------------------------
4450 ExecQual(List *qual, ExprContext *econtext, bool resultForNull)
4453 MemoryContext oldContext;
4459 EV_printf("ExecQual: qual is ");
4460 EV_nodeDisplay(qual);
4466 * Run in short-lived per-tuple context while computing expressions.
4468 oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
4471 * Evaluate the qual conditions one at a time. If we find a FALSE result,
4472 * we can stop evaluating and return FALSE --- the AND result must be
4473 * FALSE. Also, if we find a NULL result when resultForNull is FALSE, we
4474 * can stop and return FALSE --- the AND result must be FALSE or NULL in
4475 * that case, and the caller doesn't care which.
4477 * If we get to the end of the list, we can return TRUE. This will happen
4478 * when the AND result is indeed TRUE, or when the AND result is NULL (one
4479 * or more NULL subresult, with all the rest TRUE) and the caller has
4480 * specified resultForNull = TRUE.
4486 ExprState *clause = (ExprState *) lfirst(l);
4490 expr_value = ExecEvalExpr(clause, econtext, &isNull, NULL);
4494 if (resultForNull == false)
4496 result = false; /* treat NULL as FALSE */
4502 if (!DatumGetBool(expr_value))
4504 result = false; /* definitely FALSE */
4510 MemoryContextSwitchTo(oldContext);
4516 * Number of items in a tlist (including any resjunk items!)
4519 ExecTargetListLength(List *targetlist)
4521 /* This used to be more complex, but fjoins are dead */
4522 return list_length(targetlist);
4526 * Number of items in a tlist, not including any resjunk items
4529 ExecCleanTargetListLength(List *targetlist)
4534 foreach(tl, targetlist)
4536 TargetEntry *curTle = (TargetEntry *) lfirst(tl);
4538 Assert(IsA(curTle, TargetEntry));
4539 if (!curTle->resjunk)
4547 * Evaluates a targetlist with respect to the given
4548 * expression context. Returns TRUE if we were able to create
4549 * a result, FALSE if we have exhausted a set-valued expression.
4551 * Results are stored into the passed values and isnull arrays.
4552 * The caller must provide an itemIsDone array that persists across calls.
4554 * As with ExecEvalExpr, the caller should pass isDone = NULL if not
4555 * prepared to deal with sets of result tuples. Otherwise, a return
4556 * of *isDone = ExprMultipleResult signifies a set element, and a return
4557 * of *isDone = ExprEndResult signifies end of the set of tuple.
4560 ExecTargetList(List *targetlist,
4561 ExprContext *econtext,
4564 ExprDoneCond *itemIsDone,
4565 ExprDoneCond *isDone)
4567 MemoryContext oldContext;
4572 * Run in short-lived per-tuple context while computing expressions.
4574 oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
4577 * evaluate all the expressions in the target list
4580 *isDone = ExprSingleResult; /* until proven otherwise */
4582 haveDoneSets = false; /* any exhausted set exprs in tlist? */
4584 foreach(tl, targetlist)
4586 GenericExprState *gstate = (GenericExprState *) lfirst(tl);
4587 TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr;
4588 AttrNumber resind = tle->resno - 1;
4590 values[resind] = ExecEvalExpr(gstate->arg,
4593 &itemIsDone[resind]);
4595 if (itemIsDone[resind] != ExprSingleResult)
4597 /* We have a set-valued expression in the tlist */
4600 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4601 errmsg("set-valued function called in context that cannot accept a set")));
4602 if (itemIsDone[resind] == ExprMultipleResult)
4604 /* we have undone sets in the tlist, set flag */
4605 *isDone = ExprMultipleResult;
4609 /* we have done sets in the tlist, set flag for that */
4610 haveDoneSets = true;
4618 * note: can't get here unless we verified isDone != NULL
4620 if (*isDone == ExprSingleResult)
4623 * all sets are done, so report that tlist expansion is complete.
4625 *isDone = ExprEndResult;
4626 MemoryContextSwitchTo(oldContext);
4632 * We have some done and some undone sets. Restart the done ones
4633 * so that we can deliver a tuple (if possible).
4635 foreach(tl, targetlist)
4637 GenericExprState *gstate = (GenericExprState *) lfirst(tl);
4638 TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr;
4639 AttrNumber resind = tle->resno - 1;
4641 if (itemIsDone[resind] == ExprEndResult)
4643 values[resind] = ExecEvalExpr(gstate->arg,
4646 &itemIsDone[resind]);
4648 if (itemIsDone[resind] == ExprEndResult)
4651 * Oh dear, this item is returning an empty set. Guess
4652 * we can't make a tuple after all.
4654 *isDone = ExprEndResult;
4661 * If we cannot make a tuple because some sets are empty, we still
4662 * have to cycle the nonempty sets to completion, else resources
4663 * will not be released from subplans etc.
4665 * XXX is that still necessary?
4667 if (*isDone == ExprEndResult)
4669 foreach(tl, targetlist)
4671 GenericExprState *gstate = (GenericExprState *) lfirst(tl);
4672 TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr;
4673 AttrNumber resind = tle->resno - 1;
4675 while (itemIsDone[resind] == ExprMultipleResult)
4677 values[resind] = ExecEvalExpr(gstate->arg,
4680 &itemIsDone[resind]);
4684 MemoryContextSwitchTo(oldContext);
4690 /* Report success */
4691 MemoryContextSwitchTo(oldContext);
4698 * Evaluates a simple-Variable-list projection.
4700 * Results are stored into the passed values and isnull arrays.
4703 ExecVariableList(ProjectionInfo *projInfo,
4707 ExprContext *econtext = projInfo->pi_exprContext;
4708 int *varSlotOffsets = projInfo->pi_varSlotOffsets;
4709 int *varNumbers = projInfo->pi_varNumbers;
4713 * Force extraction of all input values that we need.
4715 if (projInfo->pi_lastInnerVar > 0)
4716 slot_getsomeattrs(econtext->ecxt_innertuple,
4717 projInfo->pi_lastInnerVar);
4718 if (projInfo->pi_lastOuterVar > 0)
4719 slot_getsomeattrs(econtext->ecxt_outertuple,
4720 projInfo->pi_lastOuterVar);
4721 if (projInfo->pi_lastScanVar > 0)
4722 slot_getsomeattrs(econtext->ecxt_scantuple,
4723 projInfo->pi_lastScanVar);
4726 * Assign to result by direct extraction of fields from source slots ... a
4727 * mite ugly, but fast ...
4729 for (i = list_length(projInfo->pi_targetlist) - 1; i >= 0; i--)
4731 char *slotptr = ((char *) econtext) + varSlotOffsets[i];
4732 TupleTableSlot *varSlot = *((TupleTableSlot **) slotptr);
4733 int varNumber = varNumbers[i] - 1;
4735 values[i] = varSlot->tts_values[varNumber];
4736 isnull[i] = varSlot->tts_isnull[varNumber];
4743 * projects a tuple based on projection info and stores
4744 * it in the previously specified tuple table slot.
4746 * Note: the result is always a virtual tuple; therefore it
4747 * may reference the contents of the exprContext's scan tuples
4748 * and/or temporary results constructed in the exprContext.
4749 * If the caller wishes the result to be valid longer than that
4750 * data will be valid, he must call ExecMaterializeSlot on the
4754 ExecProject(ProjectionInfo *projInfo, ExprDoneCond *isDone)
4756 TupleTableSlot *slot;
4761 Assert(projInfo != NULL);
4764 * get the projection info we want
4766 slot = projInfo->pi_slot;
4769 * Clear any former contents of the result slot. This makes it safe for
4770 * us to use the slot's Datum/isnull arrays as workspace. (Also, we can
4771 * return the slot as-is if we decide no rows can be projected.)
4773 ExecClearTuple(slot);
4776 * form a new result tuple (if possible); if successful, mark the result
4777 * slot as containing a valid virtual tuple
4779 if (projInfo->pi_isVarList)
4781 /* simple Var list: this always succeeds with one result row */
4783 *isDone = ExprSingleResult;
4784 ExecVariableList(projInfo,
4787 ExecStoreVirtualTuple(slot);
4791 if (ExecTargetList(projInfo->pi_targetlist,
4792 projInfo->pi_exprContext,
4795 projInfo->pi_itemIsDone,
4797 ExecStoreVirtualTuple(slot);