]> granicus.if.org Git - postgresql/blob - src/backend/executor/execQual.c
cc165006f5c55808fddb40d4613e2ffac583741b
[postgresql] / src / backend / executor / execQual.c
1 /*-------------------------------------------------------------------------
2  *
3  * execQual.c
4  *        Routines to evaluate qualification and targetlist expressions
5  *
6  * Portions Copyright (c) 1996-2007, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $PostgreSQL: pgsql/src/backend/executor/execQual.c,v 1.222 2007/09/06 17:31:58 tgl Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15 /*
16  *       INTERFACE ROUTINES
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
21  *
22  *       NOTES
23  *              The more heavily used ExecEvalExpr routines, such as ExecEvalVar(),
24  *              are hotspots. Making these faster will speed up the entire system.
25  *
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
30  *
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
34  *              to gain speed.
35  */
36
37 #include "postgres.h"
38
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"
45 #include "funcapi.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"
56
57
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);
158
159
160 /* ----------------------------------------------------------------
161  *              ExecEvalExpr routines
162  *
163  *              Recursively evaluate a targetlist or qualification expression.
164  *
165  * Each of the following routines having the signature
166  *              Datum ExecEvalFoo(ExprState *expression,
167  *                                                ExprContext *econtext,
168  *                                                bool *isNull,
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.)
175  *
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!
181  *
182  *
183  * All these functions share this calling convention:
184  *
185  * Inputs:
186  *              expression: the expression state tree to evaluate
187  *              econtext: evaluation context information
188  *
189  * Outputs:
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
194  *
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.
209  *
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  * ----------------------------------------------------------------
216  */
217
218
219 /*----------
220  *        ExecEvalArrayRef
221  *
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).
225  *
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.
228  *
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).
234  *----------
235  */
236 static Datum
237 ExecEvalArrayRef(ArrayRefExprState *astate,
238                                  ExprContext *econtext,
239                                  bool *isNull,
240                                  ExprDoneCond *isDone)
241 {
242         ArrayRef   *arrayRef = (ArrayRef *) astate->xprstate.expr;
243         ArrayType  *array_source;
244         ArrayType  *resultArray;
245         bool            isAssignment = (arrayRef->refassgnexpr != NULL);
246         bool            eisnull;
247         ListCell   *l;
248         int                     i = 0,
249                                 j = 0;
250         IntArray        upper,
251                                 lower;
252         int                *lIndex;
253
254         array_source = (ArrayType *)
255                 DatumGetPointer(ExecEvalExpr(astate->refexpr,
256                                                                          econtext,
257                                                                          isNull,
258                                                                          isDone));
259
260         /*
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.
263          */
264         if (*isNull)
265         {
266                 if (isDone && *isDone == ExprEndResult)
267                         return (Datum) NULL;    /* end of set result */
268                 if (!isAssignment)
269                         return (Datum) NULL;
270         }
271
272         foreach(l, astate->refupperindexpr)
273         {
274                 ExprState  *eltstate = (ExprState *) lfirst(l);
275
276                 if (i >= MAXDIM)
277                         ereport(ERROR,
278                                         (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
279                                          errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
280                                                         i, MAXDIM)));
281
282                 upper.indx[i++] = DatumGetInt32(ExecEvalExpr(eltstate,
283                                                                                                          econtext,
284                                                                                                          &eisnull,
285                                                                                                          NULL));
286                 /* If any index expr yields NULL, result is NULL or error */
287                 if (eisnull)
288                 {
289                         if (isAssignment)
290                                 ereport(ERROR,
291                                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
292                                   errmsg("array subscript in assignment must not be null")));
293                         *isNull = true;
294                         return (Datum) NULL;
295                 }
296         }
297
298         if (astate->reflowerindexpr != NIL)
299         {
300                 foreach(l, astate->reflowerindexpr)
301                 {
302                         ExprState  *eltstate = (ExprState *) lfirst(l);
303
304                         if (j >= MAXDIM)
305                                 ereport(ERROR,
306                                                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
307                                                  errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
308                                                                 i, MAXDIM)));
309
310                         lower.indx[j++] = DatumGetInt32(ExecEvalExpr(eltstate,
311                                                                                                                  econtext,
312                                                                                                                  &eisnull,
313                                                                                                                  NULL));
314                         /* If any index expr yields NULL, result is NULL or error */
315                         if (eisnull)
316                         {
317                                 if (isAssignment)
318                                         ereport(ERROR,
319                                                         (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
320                                                          errmsg("array subscript in assignment must not be null")));
321                                 *isNull = true;
322                                 return (Datum) NULL;
323                         }
324                 }
325                 /* this can't happen unless parser messed up */
326                 if (i != j)
327                         elog(ERROR, "upper and lower index lists are not same length");
328                 lIndex = lower.indx;
329         }
330         else
331                 lIndex = NULL;
332
333         if (isAssignment)
334         {
335                 Datum           sourceData;
336
337                 /*
338                  * Evaluate the value to be assigned into the array.
339                  *
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.
346                  */
347                 sourceData = ExecEvalExpr(astate->refassgnexpr,
348                                                                   econtext,
349                                                                   &eisnull,
350                                                                   NULL);
351
352                 /*
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.
356                  */
357                 if (astate->refattrlength > 0)  /* fixed-length array? */
358                         if (eisnull || *isNull)
359                                 return PointerGetDatum(array_source);
360
361                 /*
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.
366                  */
367                 if (*isNull)
368                 {
369                         array_source = construct_empty_array(arrayRef->refelemtype);
370                         *isNull = false;
371                 }
372
373                 if (lIndex == NULL)
374                         resultArray = array_set(array_source, i,
375                                                                         upper.indx,
376                                                                         sourceData,
377                                                                         eisnull,
378                                                                         astate->refattrlength,
379                                                                         astate->refelemlength,
380                                                                         astate->refelembyval,
381                                                                         astate->refelemalign);
382                 else
383                         resultArray = array_set_slice(array_source, i,
384                                                                                   upper.indx, lower.indx,
385                                                                    (ArrayType *) DatumGetPointer(sourceData),
386                                                                                   eisnull,
387                                                                                   astate->refattrlength,
388                                                                                   astate->refelemlength,
389                                                                                   astate->refelembyval,
390                                                                                   astate->refelemalign);
391                 return PointerGetDatum(resultArray);
392         }
393
394         if (lIndex == NULL)
395                 return array_ref(array_source, i, upper.indx,
396                                                  astate->refattrlength,
397                                                  astate->refelemlength,
398                                                  astate->refelembyval,
399                                                  astate->refelemalign,
400                                                  isNull);
401         else
402         {
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);
410         }
411 }
412
413
414 /* ----------------------------------------------------------------
415  *              ExecEvalAggref
416  *
417  *              Returns a Datum whose value is the value of the precomputed
418  *              aggregate found in the given expression context.
419  * ----------------------------------------------------------------
420  */
421 static Datum
422 ExecEvalAggref(AggrefExprState *aggref, ExprContext *econtext,
423                            bool *isNull, ExprDoneCond *isDone)
424 {
425         if (isDone)
426                 *isDone = ExprSingleResult;
427
428         if (econtext->ecxt_aggvalues == NULL)           /* safety check */
429                 elog(ERROR, "no aggregates in this expression context");
430
431         *isNull = econtext->ecxt_aggnulls[aggref->aggno];
432         return econtext->ecxt_aggvalues[aggref->aggno];
433 }
434
435 /* ----------------------------------------------------------------
436  *              ExecEvalVar
437  *
438  *              Returns a Datum whose value is the value of a range
439  *              variable with respect to given expression context.
440  *
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  * ----------------------------------------------------------------
446  */
447 static Datum
448 ExecEvalVar(ExprState *exprstate, ExprContext *econtext,
449                         bool *isNull, ExprDoneCond *isDone)
450 {
451         Var                *variable = (Var *) exprstate->expr;
452         TupleTableSlot *slot;
453         AttrNumber      attnum;
454
455         if (isDone)
456                 *isDone = ExprSingleResult;
457
458         /*
459          * Get the input slot and attribute number we want
460          *
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
464          * original tuple).
465          */
466         attnum = variable->varattno;
467
468         switch (variable->varno)
469         {
470                 case INNER:                             /* get the tuple from the inner node */
471                         slot = econtext->ecxt_innertuple;
472                         Assert(attnum > 0);
473                         break;
474
475                 case OUTER:                             /* get the tuple from the outer node */
476                         slot = econtext->ecxt_outertuple;
477                         Assert(attnum > 0);
478                         break;
479
480                 default:                                /* get the tuple from the relation being
481                                                                  * scanned */
482                         slot = econtext->ecxt_scantuple;
483                         break;
484         }
485
486         if (attnum != InvalidAttrNumber)
487         {
488                 /*
489                  * Scalar variable case.
490                  *
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
493                  * is the possibility of an attribute having been changed in type
494                  * since the plan tree was created.  Ideally the plan would get
495                  * invalidated and not re-used, but until that day arrives, we need
496                  * defenses.  Fortunately it's sufficient to check once on the first
497                  * time through.
498                  *
499                  * Note: we allow a reference to a dropped attribute.  slot_getattr
500                  * will force a NULL result in such cases.
501                  *
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
504                  * been generated by ExecTypeFromTL(), and that can't guarantee to
505                  * generate an accurate typmod in all cases, because some expression
506                  * node types don't carry typmod.
507                  */
508                 if (attnum > 0)
509                 {
510                         TupleDesc       slot_tupdesc = slot->tts_tupleDescriptor;
511                         Form_pg_attribute attr;
512
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);
516
517                         attr = slot_tupdesc->attrs[attnum - 1];
518
519                         /* can't check type if dropped, since atttypid is probably 0 */
520                         if (!attr->attisdropped)
521                         {
522                                 if (variable->vartype != attr->atttypid)
523                                         ereport(ERROR,
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))));
528                         }
529                 }
530
531                 /* Skip the checking on future executions of node */
532                 exprstate->evalfunc = ExecEvalScalarVar;
533
534                 /* Fetch the value from the slot */
535                 return slot_getattr(slot, attnum, isNull);
536         }
537         else
538         {
539                 /*
540                  * Whole-row variable.
541                  *
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.
545                  *
546                  * If the Var identifies a named composite type, we must check that
547                  * the actual tuple type is compatible with it.
548                  */
549                 TupleDesc       slot_tupdesc = slot->tts_tupleDescriptor;
550                 bool            needslow = false;
551
552                 if (variable->vartype == RECORDOID)
553                 {
554                         if (slot_tupdesc->tdtypeid == RECORDOID &&
555                                 slot_tupdesc->tdtypmod < 0)
556                                 assign_record_type_typmod(slot_tupdesc);
557                 }
558                 else
559                 {
560                         TupleDesc       var_tupdesc;
561                         int                     i;
562
563                         /*
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
576                          * rid of them in the eventual output tuples.
577                          */
578                         var_tupdesc = lookup_rowtype_tupdesc(variable->vartype, -1);
579
580                         if (var_tupdesc->natts > slot_tupdesc->natts)
581                                 ereport(ERROR,
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)
587                                 needslow = true;
588
589                         for (i = 0; i < var_tupdesc->natts; i++)
590                         {
591                                 Form_pg_attribute vattr = var_tupdesc->attrs[i];
592                                 Form_pg_attribute sattr = slot_tupdesc->attrs[i];
593
594                                 if (vattr->atttypid == sattr->atttypid)
595                                         continue;                       /* no worries */
596                                 if (!vattr->attisdropped)
597                                         ereport(ERROR,
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),
602                                                                            i + 1,
603                                                                            format_type_be(vattr->atttypid))));
604
605                                 if (vattr->attlen != sattr->attlen ||
606                                         vattr->attalign != sattr->attalign)
607                                         ereport(ERROR,
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.",
611                                                                            i + 1)));
612                         }
613
614                         ReleaseTupleDesc(var_tupdesc);
615                 }
616
617                 /* Skip the checking on future executions of node */
618                 if (needslow)
619                         exprstate->evalfunc = ExecEvalWholeRowSlow;
620                 else
621                         exprstate->evalfunc = ExecEvalWholeRowVar;
622
623                 /* Fetch the value */
624                 return ExecEvalWholeRowVar(exprstate, econtext, isNull, isDone);
625         }
626 }
627
628 /* ----------------------------------------------------------------
629  *              ExecEvalScalarVar
630  *
631  *              Returns a Datum for a scalar variable.
632  * ----------------------------------------------------------------
633  */
634 static Datum
635 ExecEvalScalarVar(ExprState *exprstate, ExprContext *econtext,
636                                   bool *isNull, ExprDoneCond *isDone)
637 {
638         Var                *variable = (Var *) exprstate->expr;
639         TupleTableSlot *slot;
640         AttrNumber      attnum;
641
642         if (isDone)
643                 *isDone = ExprSingleResult;
644
645         /* Get the input slot and attribute number we want */
646         switch (variable->varno)
647         {
648                 case INNER:                             /* get the tuple from the inner node */
649                         slot = econtext->ecxt_innertuple;
650                         break;
651
652                 case OUTER:                             /* get the tuple from the outer node */
653                         slot = econtext->ecxt_outertuple;
654                         break;
655
656                 default:                                /* get the tuple from the relation being
657                                                                  * scanned */
658                         slot = econtext->ecxt_scantuple;
659                         break;
660         }
661
662         attnum = variable->varattno;
663
664         /* Fetch the value from the slot */
665         return slot_getattr(slot, attnum, isNull);
666 }
667
668 /* ----------------------------------------------------------------
669  *              ExecEvalWholeRowVar
670  *
671  *              Returns a Datum for a whole-row variable.
672  * ----------------------------------------------------------------
673  */
674 static Datum
675 ExecEvalWholeRowVar(ExprState *exprstate, ExprContext *econtext,
676                                         bool *isNull, ExprDoneCond *isDone)
677 {
678         Var                *variable = (Var *) exprstate->expr;
679         TupleTableSlot *slot = econtext->ecxt_scantuple;
680         HeapTuple       tuple;
681         TupleDesc       tupleDesc;
682         HeapTupleHeader dtuple;
683
684         if (isDone)
685                 *isDone = ExprSingleResult;
686         *isNull = false;
687
688         tuple = ExecFetchSlotTuple(slot);
689         tupleDesc = slot->tts_tupleDescriptor;
690
691         /*
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.
694          */
695         dtuple = (HeapTupleHeader) palloc(tuple->t_len);
696         memcpy((char *) dtuple, (char *) tuple->t_data, tuple->t_len);
697
698         HeapTupleHeaderSetDatumLength(dtuple, tuple->t_len);
699
700         /*
701          * If the Var identifies a named composite type, label the tuple with that
702          * type; otherwise use what is in the tupleDesc.
703          */
704         if (variable->vartype != RECORDOID)
705         {
706                 HeapTupleHeaderSetTypeId(dtuple, variable->vartype);
707                 HeapTupleHeaderSetTypMod(dtuple, variable->vartypmod);
708         }
709         else
710         {
711                 HeapTupleHeaderSetTypeId(dtuple, tupleDesc->tdtypeid);
712                 HeapTupleHeaderSetTypMod(dtuple, tupleDesc->tdtypmod);
713         }
714
715         return PointerGetDatum(dtuple);
716 }
717
718 /* ----------------------------------------------------------------
719  *              ExecEvalWholeRowSlow
720  *
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  * ----------------------------------------------------------------
724  */
725 static Datum
726 ExecEvalWholeRowSlow(ExprState *exprstate, ExprContext *econtext,
727                                          bool *isNull, ExprDoneCond *isDone)
728 {
729         Var                *variable = (Var *) exprstate->expr;
730         TupleTableSlot *slot = econtext->ecxt_scantuple;
731         HeapTuple       tuple;
732         TupleDesc       var_tupdesc;
733         HeapTupleHeader dtuple;
734
735         if (isDone)
736                 *isDone = ExprSingleResult;
737         *isNull = false;
738
739         /*
740          * Currently, the only case handled here is stripping of trailing
741          * resjunk fields, which we do in a slightly chintzy way by just
742          * adjusting the tuple's natts header field.  Possibly there will someday
743          * be a need for more-extensive rearrangements, in which case it'd
744          * be worth disassembling and reassembling the tuple (perhaps use a
745          * JunkFilter for that?)
746          */
747         Assert(variable->vartype != RECORDOID);
748         var_tupdesc = lookup_rowtype_tupdesc(variable->vartype, -1);
749
750         tuple = ExecFetchSlotTuple(slot);
751
752         /*
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.
756          */
757         dtuple = (HeapTupleHeader) palloc(tuple->t_len);
758         memcpy((char *) dtuple, (char *) tuple->t_data, tuple->t_len);
759
760         HeapTupleHeaderSetDatumLength(dtuple, tuple->t_len);
761         HeapTupleHeaderSetTypeId(dtuple, variable->vartype);
762         HeapTupleHeaderSetTypMod(dtuple, variable->vartypmod);
763
764         Assert(HeapTupleHeaderGetNatts(dtuple) >= var_tupdesc->natts);
765         HeapTupleHeaderSetNatts(dtuple, var_tupdesc->natts);
766
767         ReleaseTupleDesc(var_tupdesc);
768
769         return PointerGetDatum(dtuple);
770 }
771
772 /* ----------------------------------------------------------------
773  *              ExecEvalConst
774  *
775  *              Returns the value of a constant.
776  *
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  * ----------------------------------------------------------------
781  */
782 static Datum
783 ExecEvalConst(ExprState *exprstate, ExprContext *econtext,
784                           bool *isNull, ExprDoneCond *isDone)
785 {
786         Const      *con = (Const *) exprstate->expr;
787
788         if (isDone)
789                 *isDone = ExprSingleResult;
790
791         *isNull = con->constisnull;
792         return con->constvalue;
793 }
794
795 /* ----------------------------------------------------------------
796  *              ExecEvalParam
797  *
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  * ----------------------------------------------------------------
803  */
804 static Datum
805 ExecEvalParam(ExprState *exprstate, ExprContext *econtext,
806                           bool *isNull, ExprDoneCond *isDone)
807 {
808         Param      *expression = (Param *) exprstate->expr;
809         int                     thisParamId = expression->paramid;
810
811         if (isDone)
812                 *isDone = ExprSingleResult;
813
814         if (expression->paramkind == PARAM_EXEC)
815         {
816                 /*
817                  * PARAM_EXEC params (internal executor parameters) are stored in the
818                  * ecxt_param_exec_vals array, and can be accessed by array index.
819                  */
820                 ParamExecData *prm;
821
822                 prm = &(econtext->ecxt_param_exec_vals[thisParamId]);
823                 if (prm->execPlan != NULL)
824                 {
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);
829                 }
830                 *isNull = prm->isnull;
831                 return prm->value;
832         }
833         else
834         {
835                 /*
836                  * PARAM_EXTERN parameters must be sought in ecxt_param_list_info.
837                  */
838                 ParamListInfo paramInfo = econtext->ecxt_param_list_info;
839
840                 Assert(expression->paramkind == PARAM_EXTERN);
841                 if (paramInfo &&
842                         thisParamId > 0 && thisParamId <= paramInfo->numParams)
843                 {
844                         ParamExternData *prm = &paramInfo->params[thisParamId - 1];
845
846                         if (OidIsValid(prm->ptype))
847                         {
848                                 Assert(prm->ptype == expression->paramtype);
849                                 *isNull = prm->isnull;
850                                 return prm->value;
851                         }
852                 }
853                 ereport(ERROR,
854                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
855                                  errmsg("no value found for parameter %d", thisParamId)));
856                 return (Datum) 0;               /* keep compiler quiet */
857         }
858 }
859
860
861 /* ----------------------------------------------------------------
862  *              ExecEvalOper / ExecEvalFunc support routines
863  * ----------------------------------------------------------------
864  */
865
866 /*
867  *              GetAttributeByName
868  *              GetAttributeByNum
869  *
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.
876  */
877 Datum
878 GetAttributeByNum(HeapTupleHeader tuple,
879                                   AttrNumber attrno,
880                                   bool *isNull)
881 {
882         Datum           result;
883         Oid                     tupType;
884         int32           tupTypmod;
885         TupleDesc       tupDesc;
886         HeapTupleData tmptup;
887
888         if (!AttributeNumberIsValid(attrno))
889                 elog(ERROR, "invalid attribute number %d", attrno);
890
891         if (isNull == NULL)
892                 elog(ERROR, "a NULL isNull pointer was passed");
893
894         if (tuple == NULL)
895         {
896                 /* Kinda bogus but compatible with old behavior... */
897                 *isNull = true;
898                 return (Datum) 0;
899         }
900
901         tupType = HeapTupleHeaderGetTypeId(tuple);
902         tupTypmod = HeapTupleHeaderGetTypMod(tuple);
903         tupDesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
904
905         /*
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
908          * columns.
909          */
910         tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
911         ItemPointerSetInvalid(&(tmptup.t_self));
912         tmptup.t_tableOid = InvalidOid;
913         tmptup.t_data = tuple;
914
915         result = heap_getattr(&tmptup,
916                                                   attrno,
917                                                   tupDesc,
918                                                   isNull);
919
920         ReleaseTupleDesc(tupDesc);
921
922         return result;
923 }
924
925 Datum
926 GetAttributeByName(HeapTupleHeader tuple, const char *attname, bool *isNull)
927 {
928         AttrNumber      attrno;
929         Datum           result;
930         Oid                     tupType;
931         int32           tupTypmod;
932         TupleDesc       tupDesc;
933         HeapTupleData tmptup;
934         int                     i;
935
936         if (attname == NULL)
937                 elog(ERROR, "invalid attribute name");
938
939         if (isNull == NULL)
940                 elog(ERROR, "a NULL isNull pointer was passed");
941
942         if (tuple == NULL)
943         {
944                 /* Kinda bogus but compatible with old behavior... */
945                 *isNull = true;
946                 return (Datum) 0;
947         }
948
949         tupType = HeapTupleHeaderGetTypeId(tuple);
950         tupTypmod = HeapTupleHeaderGetTypMod(tuple);
951         tupDesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
952
953         attrno = InvalidAttrNumber;
954         for (i = 0; i < tupDesc->natts; i++)
955         {
956                 if (namestrcmp(&(tupDesc->attrs[i]->attname), attname) == 0)
957                 {
958                         attrno = tupDesc->attrs[i]->attnum;
959                         break;
960                 }
961         }
962
963         if (attrno == InvalidAttrNumber)
964                 elog(ERROR, "attribute \"%s\" does not exist", attname);
965
966         /*
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
969          * columns.
970          */
971         tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
972         ItemPointerSetInvalid(&(tmptup.t_self));
973         tmptup.t_tableOid = InvalidOid;
974         tmptup.t_data = tuple;
975
976         result = heap_getattr(&tmptup,
977                                                   attrno,
978                                                   tupDesc,
979                                                   isNull);
980
981         ReleaseTupleDesc(tupDesc);
982
983         return result;
984 }
985
986 /*
987  * init_fcache - initialize a FuncExprState node during first use
988  */
989 void
990 init_fcache(Oid foid, FuncExprState *fcache, MemoryContext fcacheCxt)
991 {
992         AclResult       aclresult;
993
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));
998
999         /*
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?
1004          */
1005         if (list_length(fcache->args) > FUNC_MAX_ARGS)
1006                 ereport(ERROR,
1007                                 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
1008                                  errmsg("cannot pass more than %d arguments to a function",
1009                                                 FUNC_MAX_ARGS)));
1010
1011         /* Set up the primary fmgr lookup information */
1012         fmgr_info_cxt(foid, &(fcache->func), fcacheCxt);
1013
1014         /* Initialize additional info */
1015         fcache->setArgsValid = false;
1016         fcache->shutdown_reg = false;
1017         fcache->func.fn_expr = (Node *) fcache->xprstate.expr;
1018 }
1019
1020 /*
1021  * callback function in case a FuncExpr returning a set needs to be shut down
1022  * before it has been run to completion
1023  */
1024 static void
1025 ShutdownFuncExpr(Datum arg)
1026 {
1027         FuncExprState *fcache = (FuncExprState *) DatumGetPointer(arg);
1028
1029         /* Clear any active set-argument state */
1030         fcache->setArgsValid = false;
1031
1032         /* execUtils will deregister the callback... */
1033         fcache->shutdown_reg = false;
1034 }
1035
1036 /*
1037  * get_cached_rowtype: utility function to lookup a rowtype tupdesc
1038  *
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
1043  *
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
1047  */
1048 static TupleDesc
1049 get_cached_rowtype(Oid type_id, int32 typmod,
1050                                    TupleDesc *cache_field, ExprContext *econtext)
1051 {
1052         TupleDesc       tupDesc = *cache_field;
1053
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)
1058         {
1059                 tupDesc = lookup_rowtype_tupdesc(type_id, typmod);
1060
1061                 if (*cache_field)
1062                 {
1063                         /* Release old tupdesc; but callback is already registered */
1064                         ReleaseTupleDesc(*cache_field);
1065                 }
1066                 else
1067                 {
1068                         /* Need to register shutdown callback to release tupdesc */
1069                         RegisterExprContextCallback(econtext,
1070                                                                                 ShutdownTupleDescRef,
1071                                                                                 PointerGetDatum(cache_field));
1072                 }
1073                 *cache_field = tupDesc;
1074         }
1075         return tupDesc;
1076 }
1077
1078 /*
1079  * Callback function to release a tupdesc refcount at expression tree shutdown
1080  */
1081 static void
1082 ShutdownTupleDescRef(Datum arg)
1083 {
1084         TupleDesc  *cache_field = (TupleDesc *) DatumGetPointer(arg);
1085
1086         if (*cache_field)
1087                 ReleaseTupleDesc(*cache_field);
1088         *cache_field = NULL;
1089 }
1090
1091 /*
1092  * Evaluate arguments for a function.
1093  */
1094 static ExprDoneCond
1095 ExecEvalFuncArgs(FunctionCallInfo fcinfo,
1096                                  List *argList,
1097                                  ExprContext *econtext)
1098 {
1099         ExprDoneCond argIsDone;
1100         int                     i;
1101         ListCell   *arg;
1102
1103         argIsDone = ExprSingleResult;           /* default assumption */
1104
1105         i = 0;
1106         foreach(arg, argList)
1107         {
1108                 ExprState  *argstate = (ExprState *) lfirst(arg);
1109                 ExprDoneCond thisArgIsDone;
1110
1111                 fcinfo->arg[i] = ExecEvalExpr(argstate,
1112                                                                           econtext,
1113                                                                           &fcinfo->argnull[i],
1114                                                                           &thisArgIsDone);
1115
1116                 if (thisArgIsDone != ExprSingleResult)
1117                 {
1118                         /*
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.
1122                          */
1123                         if (argIsDone != ExprSingleResult)
1124                                 ereport(ERROR,
1125                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1126                                                  errmsg("functions and operators can take at most one set argument")));
1127                         argIsDone = thisArgIsDone;
1128                 }
1129                 i++;
1130         }
1131
1132         fcinfo->nargs = i;
1133
1134         return argIsDone;
1135 }
1136
1137 /*
1138  *              ExecMakeFunctionResult
1139  *
1140  * Evaluate the arguments to a function and then the function itself.
1141  */
1142 Datum
1143 ExecMakeFunctionResult(FuncExprState *fcache,
1144                                            ExprContext *econtext,
1145                                            bool *isNull,
1146                                            ExprDoneCond *isDone)
1147 {
1148         List       *arguments = fcache->args;
1149         Datum           result;
1150         FunctionCallInfoData fcinfo;
1151         ReturnSetInfo rsinfo;           /* for functions returning sets */
1152         ExprDoneCond argDone;
1153         bool            hasSetArg;
1154         int                     i;
1155
1156         /* Guard against stack overflow due to overly complex expressions */
1157         check_stack_depth();
1158
1159         /*
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.
1164          */
1165         if (!fcache->setArgsValid)
1166         {
1167                 /* Need to prep callinfo structure */
1168                 InitFunctionCallInfoData(fcinfo, &(fcache->func), 0, NULL, NULL);
1169                 argDone = ExecEvalFuncArgs(&fcinfo, arguments, econtext);
1170                 if (argDone == ExprEndResult)
1171                 {
1172                         /* input is an empty set, so return an empty set. */
1173                         *isNull = true;
1174                         if (isDone)
1175                                 *isDone = ExprEndResult;
1176                         else
1177                                 ereport(ERROR,
1178                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1179                                                  errmsg("set-valued function called in context that cannot accept a set")));
1180                         return (Datum) 0;
1181                 }
1182                 hasSetArg = (argDone != ExprSingleResult);
1183         }
1184         else
1185         {
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;
1191         }
1192
1193         /*
1194          * If function returns set, prepare a resultinfo node for communication
1195          */
1196         if (fcache->func.fn_retset)
1197         {
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;
1207         }
1208
1209         /*
1210          * now return the value gotten by calling the function manager, passing
1211          * the function the evaluated parameter values.
1212          */
1213         if (fcache->func.fn_retset || hasSetArg)
1214         {
1215                 /*
1216                  * We need to return a set result.      Complain if caller not ready to
1217                  * accept one.
1218                  */
1219                 if (isDone == NULL)
1220                         ereport(ERROR,
1221                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1222                                          errmsg("set-valued function called in context that cannot accept a set")));
1223
1224                 /*
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.
1231                  */
1232                 for (;;)
1233                 {
1234                         /*
1235                          * If function is strict, and there are any NULL arguments, skip
1236                          * calling the function (at least for this set of args).
1237                          */
1238                         bool            callit = true;
1239
1240                         if (fcache->func.fn_strict)
1241                         {
1242                                 for (i = 0; i < fcinfo.nargs; i++)
1243                                 {
1244                                         if (fcinfo.argnull[i])
1245                                         {
1246                                                 callit = false;
1247                                                 break;
1248                                         }
1249                                 }
1250                         }
1251
1252                         if (callit)
1253                         {
1254                                 fcinfo.isnull = false;
1255                                 rsinfo.isDone = ExprSingleResult;
1256                                 result = FunctionCallInvoke(&fcinfo);
1257                                 *isNull = fcinfo.isnull;
1258                                 *isDone = rsinfo.isDone;
1259                         }
1260                         else
1261                         {
1262                                 result = (Datum) 0;
1263                                 *isNull = true;
1264                                 *isDone = ExprEndResult;
1265                         }
1266
1267                         if (*isDone != ExprEndResult)
1268                         {
1269                                 /*
1270                                  * Got a result from current argument.  If function itself
1271                                  * returns set, save the current argument values to re-use on
1272                                  * the next call.
1273                                  */
1274                                 if (fcache->func.fn_retset && *isDone == ExprMultipleResult)
1275                                 {
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)
1281                                         {
1282                                                 RegisterExprContextCallback(econtext,
1283                                                                                                         ShutdownFuncExpr,
1284                                                                                                         PointerGetDatum(fcache));
1285                                                 fcache->shutdown_reg = true;
1286                                         }
1287                                 }
1288
1289                                 /*
1290                                  * Make sure we say we are returning a set, even if the
1291                                  * function itself doesn't return sets.
1292                                  */
1293                                 if (hasSetArg)
1294                                         *isDone = ExprMultipleResult;
1295                                 break;
1296                         }
1297
1298                         /* Else, done with this argument */
1299                         if (!hasSetArg)
1300                                 break;                  /* input not a set, so done */
1301
1302                         /* Re-eval args to get the next element of the input set */
1303                         argDone = ExecEvalFuncArgs(&fcinfo, arguments, econtext);
1304
1305                         if (argDone != ExprMultipleResult)
1306                         {
1307                                 /* End of argument set, so we're done. */
1308                                 *isNull = true;
1309                                 *isDone = ExprEndResult;
1310                                 result = (Datum) 0;
1311                                 break;
1312                         }
1313
1314                         /*
1315                          * If we reach here, loop around to run the function on the new
1316                          * argument.
1317                          */
1318                 }
1319         }
1320         else
1321         {
1322                 /*
1323                  * Non-set case: much easier.
1324                  *
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
1328                  * first time.
1329                  */
1330                 fcache->xprstate.evalfunc = (ExprStateEvalFunc) ExecMakeFunctionResultNoSets;
1331
1332                 if (isDone)
1333                         *isDone = ExprSingleResult;
1334
1335                 /*
1336                  * If function is strict, and there are any NULL arguments, skip
1337                  * calling the function and return NULL.
1338                  */
1339                 if (fcache->func.fn_strict)
1340                 {
1341                         for (i = 0; i < fcinfo.nargs; i++)
1342                         {
1343                                 if (fcinfo.argnull[i])
1344                                 {
1345                                         *isNull = true;
1346                                         return (Datum) 0;
1347                                 }
1348                         }
1349                 }
1350                 fcinfo.isnull = false;
1351                 result = FunctionCallInvoke(&fcinfo);
1352                 *isNull = fcinfo.isnull;
1353         }
1354
1355         return result;
1356 }
1357
1358 /*
1359  *              ExecMakeFunctionResultNoSets
1360  *
1361  * Simplified version of ExecMakeFunctionResult that can only handle
1362  * non-set cases.  Hand-tuned for speed.
1363  */
1364 static Datum
1365 ExecMakeFunctionResultNoSets(FuncExprState *fcache,
1366                                                          ExprContext *econtext,
1367                                                          bool *isNull,
1368                                                          ExprDoneCond *isDone)
1369 {
1370         ListCell   *arg;
1371         Datum           result;
1372         FunctionCallInfoData fcinfo;
1373         int                     i;
1374
1375         /* Guard against stack overflow due to overly complex expressions */
1376         check_stack_depth();
1377
1378         if (isDone)
1379                 *isDone = ExprSingleResult;
1380
1381         /* inlined, simplified version of ExecEvalFuncArgs */
1382         i = 0;
1383         foreach(arg, fcache->args)
1384         {
1385                 ExprState  *argstate = (ExprState *) lfirst(arg);
1386
1387                 fcinfo.arg[i] = ExecEvalExpr(argstate,
1388                                                                          econtext,
1389                                                                          &fcinfo.argnull[i],
1390                                                                          NULL);
1391                 i++;
1392         }
1393
1394         InitFunctionCallInfoData(fcinfo, &(fcache->func), i, NULL, NULL);
1395
1396         /*
1397          * If function is strict, and there are any NULL arguments, skip calling
1398          * the function and return NULL.
1399          */
1400         if (fcache->func.fn_strict)
1401         {
1402                 while (--i >= 0)
1403                 {
1404                         if (fcinfo.argnull[i])
1405                         {
1406                                 *isNull = true;
1407                                 return (Datum) 0;
1408                         }
1409                 }
1410         }
1411         /* fcinfo.isnull = false; */    /* handled by InitFunctionCallInfoData */
1412         result = FunctionCallInvoke(&fcinfo);
1413         *isNull = fcinfo.isnull;
1414
1415         return result;
1416 }
1417
1418
1419 /*
1420  *              ExecMakeTableFunctionResult
1421  *
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.
1425  */
1426 Tuplestorestate *
1427 ExecMakeTableFunctionResult(ExprState *funcexpr,
1428                                                         ExprContext *econtext,
1429                                                         TupleDesc expectedDesc,
1430                                                         TupleDesc *returnDesc)
1431 {
1432         Tuplestorestate *tupstore = NULL;
1433         TupleDesc       tupdesc = NULL;
1434         Oid                     funcrettype;
1435         bool            returnsTuple;
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;
1444
1445         callerContext = CurrentMemoryContext;
1446
1447         funcrettype = exprType((Node *) funcexpr->expr);
1448
1449         returnsTuple = type_is_rowtype(funcrettype);
1450
1451         /*
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.
1457          */
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;
1467
1468         /*
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.
1477          */
1478         if (funcexpr && IsA(funcexpr, FuncExprState) &&
1479                 IsA(funcexpr->expr, FuncExpr))
1480         {
1481                 FuncExprState *fcache = (FuncExprState *) funcexpr;
1482                 ExprDoneCond argDone;
1483
1484                 /*
1485                  * This path is similar to ExecMakeFunctionResult.
1486                  */
1487                 direct_function_call = true;
1488
1489                 /*
1490                  * Initialize function cache if first time through
1491                  */
1492                 if (fcache->func.fn_oid == InvalidOid)
1493                 {
1494                         FuncExpr   *func = (FuncExpr *) fcache->xprstate.expr;
1495
1496                         init_fcache(func->funcid, fcache, econtext->ecxt_per_query_memory);
1497                 }
1498                 returnsSet = fcache->func.fn_retset;
1499
1500                 /*
1501                  * Evaluate the function's argument list.
1502                  *
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?
1507                  */
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)
1512                         ereport(ERROR,
1513                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1514                                          errmsg("set-valued function called in context that cannot accept a set")));
1515
1516                 /*
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).
1520                  */
1521                 if (fcache->func.fn_strict)
1522                 {
1523                         int                     i;
1524
1525                         for (i = 0; i < fcinfo.nargs; i++)
1526                         {
1527                                 if (fcinfo.argnull[i])
1528                                         goto no_function_result;
1529                         }
1530                 }
1531         }
1532         else
1533         {
1534                 /* Treat funcexpr as a generic expression */
1535                 direct_function_call = false;
1536         }
1537
1538         /*
1539          * Switch to short-lived context for calling the function or expression.
1540          */
1541         MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
1542
1543         /*
1544          * Loop to handle the ValuePerCall protocol (which is also the same
1545          * behavior needed in the generic ExecEvalExpr path).
1546          */
1547         for (;;)
1548         {
1549                 Datum           result;
1550                 HeapTuple       tuple;
1551
1552                 CHECK_FOR_INTERRUPTS();
1553
1554                 /*
1555                  * reset per-tuple memory context before each call of the function or
1556                  * expression. This cleans up any local memory the function may leak
1557                  * when called.
1558                  */
1559                 ResetExprContext(econtext);
1560
1561                 /* Call the function or expression one time */
1562                 if (direct_function_call)
1563                 {
1564                         fcinfo.isnull = false;
1565                         rsinfo.isDone = ExprSingleResult;
1566                         result = FunctionCallInvoke(&fcinfo);
1567                 }
1568                 else
1569                 {
1570                         result = ExecEvalExpr(funcexpr, econtext,
1571                                                                   &fcinfo.isnull, &rsinfo.isDone);
1572                 }
1573
1574                 /* Which protocol does function want to use? */
1575                 if (rsinfo.returnMode == SFRM_ValuePerCall)
1576                 {
1577                         /*
1578                          * Check for end of result set.
1579                          */
1580                         if (rsinfo.isDone == ExprEndResult)
1581                                 break;
1582
1583                         /*
1584                          * Can't do anything very useful with NULL rowtype values. For a
1585                          * function returning set, we consider this a protocol violation
1586                          * (but another alternative would be to just ignore the result and
1587                          * "continue" to get another row).      For a function not returning
1588                          * set, we fall out of the loop; we'll cons up an all-nulls result
1589                          * row below.
1590                          */
1591                         if (returnsTuple && fcinfo.isnull)
1592                         {
1593                                 if (!returnsSet)
1594                                         break;
1595                                 ereport(ERROR,
1596                                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1597                                                  errmsg("function returning set of rows cannot return null value")));
1598                         }
1599
1600                         /*
1601                          * If first time through, build tupdesc and tuplestore for result
1602                          */
1603                         if (first_time)
1604                         {
1605                                 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1606                                 if (returnsTuple)
1607                                 {
1608                                         /*
1609                                          * Use the type info embedded in the rowtype Datum to look
1610                                          * up the needed tupdesc.  Make a copy for the query.
1611                                          */
1612                                         HeapTupleHeader td;
1613
1614                                         td = DatumGetHeapTupleHeader(result);
1615                                         tupdesc = lookup_rowtype_tupdesc_copy(HeapTupleHeaderGetTypeId(td),
1616                                                                                            HeapTupleHeaderGetTypMod(td));
1617                                 }
1618                                 else
1619                                 {
1620                                         /*
1621                                          * Scalar type, so make a single-column descriptor
1622                                          */
1623                                         tupdesc = CreateTemplateTupleDesc(1, false);
1624                                         TupleDescInitEntry(tupdesc,
1625                                                                            (AttrNumber) 1,
1626                                                                            "column",
1627                                                                            funcrettype,
1628                                                                            -1,
1629                                                                            0);
1630                                 }
1631                                 tupstore = tuplestore_begin_heap(true, false, work_mem);
1632                                 MemoryContextSwitchTo(oldcontext);
1633                                 rsinfo.setResult = tupstore;
1634                                 rsinfo.setDesc = tupdesc;
1635                         }
1636
1637                         /*
1638                          * Store current resultset item.
1639                          */
1640                         if (returnsTuple)
1641                         {
1642                                 HeapTupleHeader td;
1643
1644                                 td = DatumGetHeapTupleHeader(result);
1645
1646                                 /*
1647                                  * tuplestore_puttuple needs a HeapTuple not a bare
1648                                  * HeapTupleHeader, but it doesn't need all the fields.
1649                                  */
1650                                 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
1651                                 tmptup.t_data = td;
1652                                 tuple = &tmptup;
1653                         }
1654                         else
1655                         {
1656                                 tuple = heap_form_tuple(tupdesc, &result, &fcinfo.isnull);
1657                         }
1658
1659                         oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1660                         tuplestore_puttuple(tupstore, tuple);
1661                         MemoryContextSwitchTo(oldcontext);
1662
1663                         /*
1664                          * Are we done?
1665                          */
1666                         if (rsinfo.isDone != ExprMultipleResult)
1667                                 break;
1668                 }
1669                 else if (rsinfo.returnMode == SFRM_Materialize)
1670                 {
1671                         /* check we're on the same page as the function author */
1672                         if (!first_time || rsinfo.isDone != ExprSingleResult)
1673                                 ereport(ERROR,
1674                                                 (errcode(ERRCODE_E_R_I_E_SRF_PROTOCOL_VIOLATED),
1675                                                  errmsg("table-function protocol for materialize mode was not followed")));
1676                         /* Done evaluating the set result */
1677                         break;
1678                 }
1679                 else
1680                         ereport(ERROR,
1681                                         (errcode(ERRCODE_E_R_I_E_SRF_PROTOCOL_VIOLATED),
1682                                          errmsg("unrecognized table-function returnMode: %d",
1683                                                         (int) rsinfo.returnMode)));
1684
1685                 first_time = false;
1686         }
1687
1688 no_function_result:
1689
1690         /*
1691          * If we got nothing from the function (ie, an empty-set or NULL result),
1692          * we have to create the tuplestore to return, and if it's a
1693          * non-set-returning function then insert a single all-nulls row.
1694          */
1695         if (rsinfo.setResult == NULL)
1696         {
1697                 MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1698                 tupstore = tuplestore_begin_heap(true, false, work_mem);
1699                 rsinfo.setResult = tupstore;
1700                 if (!returnsSet)
1701                 {
1702                         int                     natts = expectedDesc->natts;
1703                         Datum      *nulldatums;
1704                         bool       *nullflags;
1705                         HeapTuple       tuple;
1706
1707                         MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
1708                         nulldatums = (Datum *) palloc0(natts * sizeof(Datum));
1709                         nullflags = (bool *) palloc(natts * sizeof(bool));
1710                         memset(nullflags, true, natts * sizeof(bool));
1711                         tuple = heap_form_tuple(expectedDesc, nulldatums, nullflags);
1712                         MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1713                         tuplestore_puttuple(tupstore, tuple);
1714                 }
1715         }
1716
1717         MemoryContextSwitchTo(callerContext);
1718
1719         /* The returned pointers are those in rsinfo */
1720         *returnDesc = rsinfo.setDesc;
1721         return rsinfo.setResult;
1722 }
1723
1724
1725 /* ----------------------------------------------------------------
1726  *              ExecEvalFunc
1727  *              ExecEvalOper
1728  *
1729  *              Evaluate the functional result of a list of arguments by calling the
1730  *              function manager.
1731  * ----------------------------------------------------------------
1732  */
1733
1734 /* ----------------------------------------------------------------
1735  *              ExecEvalFunc
1736  * ----------------------------------------------------------------
1737  */
1738 static Datum
1739 ExecEvalFunc(FuncExprState *fcache,
1740                          ExprContext *econtext,
1741                          bool *isNull,
1742                          ExprDoneCond *isDone)
1743 {
1744         /* This is called only the first time through */
1745         FuncExpr   *func = (FuncExpr *) fcache->xprstate.expr;
1746
1747         /* Initialize function lookup info */
1748         init_fcache(func->funcid, fcache, econtext->ecxt_per_query_memory);
1749
1750         /* Go directly to ExecMakeFunctionResult on subsequent uses */
1751         fcache->xprstate.evalfunc = (ExprStateEvalFunc) ExecMakeFunctionResult;
1752
1753         return ExecMakeFunctionResult(fcache, econtext, isNull, isDone);
1754 }
1755
1756 /* ----------------------------------------------------------------
1757  *              ExecEvalOper
1758  * ----------------------------------------------------------------
1759  */
1760 static Datum
1761 ExecEvalOper(FuncExprState *fcache,
1762                          ExprContext *econtext,
1763                          bool *isNull,
1764                          ExprDoneCond *isDone)
1765 {
1766         /* This is called only the first time through */
1767         OpExpr     *op = (OpExpr *) fcache->xprstate.expr;
1768
1769         /* Initialize function lookup info */
1770         init_fcache(op->opfuncid, fcache, econtext->ecxt_per_query_memory);
1771
1772         /* Go directly to ExecMakeFunctionResult on subsequent uses */
1773         fcache->xprstate.evalfunc = (ExprStateEvalFunc) ExecMakeFunctionResult;
1774
1775         return ExecMakeFunctionResult(fcache, econtext, isNull, isDone);
1776 }
1777
1778 /* ----------------------------------------------------------------
1779  *              ExecEvalDistinct
1780  *
1781  * IS DISTINCT FROM must evaluate arguments to determine whether
1782  * they are NULL; if either is NULL then the result is already
1783  * known. If neither is NULL, then proceed to evaluate the
1784  * function. Note that this is *always* derived from the equals
1785  * operator, but since we need special processing of the arguments
1786  * we can not simply reuse ExecEvalOper() or ExecEvalFunc().
1787  * ----------------------------------------------------------------
1788  */
1789 static Datum
1790 ExecEvalDistinct(FuncExprState *fcache,
1791                                  ExprContext *econtext,
1792                                  bool *isNull,
1793                                  ExprDoneCond *isDone)
1794 {
1795         Datum           result;
1796         FunctionCallInfoData fcinfo;
1797         ExprDoneCond argDone;
1798         List       *argList;
1799
1800         /* Set default values for result flags: non-null, not a set result */
1801         *isNull = false;
1802         if (isDone)
1803                 *isDone = ExprSingleResult;
1804
1805         /*
1806          * Initialize function cache if first time through
1807          */
1808         if (fcache->func.fn_oid == InvalidOid)
1809         {
1810                 DistinctExpr *op = (DistinctExpr *) fcache->xprstate.expr;
1811
1812                 init_fcache(op->opfuncid, fcache, econtext->ecxt_per_query_memory);
1813                 Assert(!fcache->func.fn_retset);
1814         }
1815
1816         /*
1817          * extract info from fcache
1818          */
1819         argList = fcache->args;
1820
1821         /* Need to prep callinfo structure */
1822         InitFunctionCallInfoData(fcinfo, &(fcache->func), 0, NULL, NULL);
1823         argDone = ExecEvalFuncArgs(&fcinfo, argList, econtext);
1824         if (argDone != ExprSingleResult)
1825                 ereport(ERROR,
1826                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1827                                  errmsg("IS DISTINCT FROM does not support set arguments")));
1828         Assert(fcinfo.nargs == 2);
1829
1830         if (fcinfo.argnull[0] && fcinfo.argnull[1])
1831         {
1832                 /* Both NULL? Then is not distinct... */
1833                 result = BoolGetDatum(FALSE);
1834         }
1835         else if (fcinfo.argnull[0] || fcinfo.argnull[1])
1836         {
1837                 /* Only one is NULL? Then is distinct... */
1838                 result = BoolGetDatum(TRUE);
1839         }
1840         else
1841         {
1842                 fcinfo.isnull = false;
1843                 result = FunctionCallInvoke(&fcinfo);
1844                 *isNull = fcinfo.isnull;
1845                 /* Must invert result of "=" */
1846                 result = BoolGetDatum(!DatumGetBool(result));
1847         }
1848
1849         return result;
1850 }
1851
1852 /*
1853  * ExecEvalScalarArrayOp
1854  *
1855  * Evaluate "scalar op ANY/ALL (array)".  The operator always yields boolean,
1856  * and we combine the results across all array elements using OR and AND
1857  * (for ANY and ALL respectively).      Of course we short-circuit as soon as
1858  * the result is known.
1859  */
1860 static Datum
1861 ExecEvalScalarArrayOp(ScalarArrayOpExprState *sstate,
1862                                           ExprContext *econtext,
1863                                           bool *isNull, ExprDoneCond *isDone)
1864 {
1865         ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) sstate->fxprstate.xprstate.expr;
1866         bool            useOr = opexpr->useOr;
1867         ArrayType  *arr;
1868         int                     nitems;
1869         Datum           result;
1870         bool            resultnull;
1871         FunctionCallInfoData fcinfo;
1872         ExprDoneCond argDone;
1873         int                     i;
1874         int16           typlen;
1875         bool            typbyval;
1876         char            typalign;
1877         char       *s;
1878         bits8      *bitmap;
1879         int                     bitmask;
1880
1881         /* Set default values for result flags: non-null, not a set result */
1882         *isNull = false;
1883         if (isDone)
1884                 *isDone = ExprSingleResult;
1885
1886         /*
1887          * Initialize function cache if first time through
1888          */
1889         if (sstate->fxprstate.func.fn_oid == InvalidOid)
1890         {
1891                 init_fcache(opexpr->opfuncid, &sstate->fxprstate,
1892                                         econtext->ecxt_per_query_memory);
1893                 Assert(!sstate->fxprstate.func.fn_retset);
1894         }
1895
1896         /* Need to prep callinfo structure */
1897         InitFunctionCallInfoData(fcinfo, &(sstate->fxprstate.func), 0, NULL, NULL);
1898         argDone = ExecEvalFuncArgs(&fcinfo, sstate->fxprstate.args, econtext);
1899         if (argDone != ExprSingleResult)
1900                 ereport(ERROR,
1901                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1902                            errmsg("op ANY/ALL (array) does not support set arguments")));
1903         Assert(fcinfo.nargs == 2);
1904
1905         /*
1906          * If the array is NULL then we return NULL --- it's not very meaningful
1907          * to do anything else, even if the operator isn't strict.
1908          */
1909         if (fcinfo.argnull[1])
1910         {
1911                 *isNull = true;
1912                 return (Datum) 0;
1913         }
1914         /* Else okay to fetch and detoast the array */
1915         arr = DatumGetArrayTypeP(fcinfo.arg[1]);
1916
1917         /*
1918          * If the array is empty, we return either FALSE or TRUE per the useOr
1919          * flag.  This is correct even if the scalar is NULL; since we would
1920          * evaluate the operator zero times, it matters not whether it would want
1921          * to return NULL.
1922          */
1923         nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr));
1924         if (nitems <= 0)
1925                 return BoolGetDatum(!useOr);
1926
1927         /*
1928          * If the scalar is NULL, and the function is strict, return NULL; no
1929          * point in iterating the loop.
1930          */
1931         if (fcinfo.argnull[0] && sstate->fxprstate.func.fn_strict)
1932         {
1933                 *isNull = true;
1934                 return (Datum) 0;
1935         }
1936
1937         /*
1938          * We arrange to look up info about the element type only once per series
1939          * of calls, assuming the element type doesn't change underneath us.
1940          */
1941         if (sstate->element_type != ARR_ELEMTYPE(arr))
1942         {
1943                 get_typlenbyvalalign(ARR_ELEMTYPE(arr),
1944                                                          &sstate->typlen,
1945                                                          &sstate->typbyval,
1946                                                          &sstate->typalign);
1947                 sstate->element_type = ARR_ELEMTYPE(arr);
1948         }
1949         typlen = sstate->typlen;
1950         typbyval = sstate->typbyval;
1951         typalign = sstate->typalign;
1952
1953         result = BoolGetDatum(!useOr);
1954         resultnull = false;
1955
1956         /* Loop over the array elements */
1957         s = (char *) ARR_DATA_PTR(arr);
1958         bitmap = ARR_NULLBITMAP(arr);
1959         bitmask = 1;
1960
1961         for (i = 0; i < nitems; i++)
1962         {
1963                 Datum           elt;
1964                 Datum           thisresult;
1965
1966                 /* Get array element, checking for NULL */
1967                 if (bitmap && (*bitmap & bitmask) == 0)
1968                 {
1969                         fcinfo.arg[1] = (Datum) 0;
1970                         fcinfo.argnull[1] = true;
1971                 }
1972                 else
1973                 {
1974                         elt = fetch_att(s, typbyval, typlen);
1975                         s = att_addlength_pointer(s, typlen, s);
1976                         s = (char *) att_align_nominal(s, typalign);
1977                         fcinfo.arg[1] = elt;
1978                         fcinfo.argnull[1] = false;
1979                 }
1980
1981                 /* Call comparison function */
1982                 if (fcinfo.argnull[1] && sstate->fxprstate.func.fn_strict)
1983                 {
1984                         fcinfo.isnull = true;
1985                         thisresult = (Datum) 0;
1986                 }
1987                 else
1988                 {
1989                         fcinfo.isnull = false;
1990                         thisresult = FunctionCallInvoke(&fcinfo);
1991                 }
1992
1993                 /* Combine results per OR or AND semantics */
1994                 if (fcinfo.isnull)
1995                         resultnull = true;
1996                 else if (useOr)
1997                 {
1998                         if (DatumGetBool(thisresult))
1999                         {
2000                                 result = BoolGetDatum(true);
2001                                 resultnull = false;
2002                                 break;                  /* needn't look at any more elements */
2003                         }
2004                 }
2005                 else
2006                 {
2007                         if (!DatumGetBool(thisresult))
2008                         {
2009                                 result = BoolGetDatum(false);
2010                                 resultnull = false;
2011                                 break;                  /* needn't look at any more elements */
2012                         }
2013                 }
2014
2015                 /* advance bitmap pointer if any */
2016                 if (bitmap)
2017                 {
2018                         bitmask <<= 1;
2019                         if (bitmask == 0x100)
2020                         {
2021                                 bitmap++;
2022                                 bitmask = 1;
2023                         }
2024                 }
2025         }
2026
2027         *isNull = resultnull;
2028         return result;
2029 }
2030
2031 /* ----------------------------------------------------------------
2032  *              ExecEvalNot
2033  *              ExecEvalOr
2034  *              ExecEvalAnd
2035  *
2036  *              Evaluate boolean expressions, with appropriate short-circuiting.
2037  *
2038  *              The query planner reformulates clause expressions in the
2039  *              qualification to conjunctive normal form.  If we ever get
2040  *              an AND to evaluate, we can be sure that it's not a top-level
2041  *              clause in the qualification, but appears lower (as a function
2042  *              argument, for example), or in the target list.  Not that you
2043  *              need to know this, mind you...
2044  * ----------------------------------------------------------------
2045  */
2046 static Datum
2047 ExecEvalNot(BoolExprState *notclause, ExprContext *econtext,
2048                         bool *isNull, ExprDoneCond *isDone)
2049 {
2050         ExprState  *clause = linitial(notclause->args);
2051         Datum           expr_value;
2052
2053         if (isDone)
2054                 *isDone = ExprSingleResult;
2055
2056         expr_value = ExecEvalExpr(clause, econtext, isNull, NULL);
2057
2058         /*
2059          * if the expression evaluates to null, then we just cascade the null back
2060          * to whoever called us.
2061          */
2062         if (*isNull)
2063                 return expr_value;
2064
2065         /*
2066          * evaluation of 'not' is simple.. expr is false, then return 'true' and
2067          * vice versa.
2068          */
2069         return BoolGetDatum(!DatumGetBool(expr_value));
2070 }
2071
2072 /* ----------------------------------------------------------------
2073  *              ExecEvalOr
2074  * ----------------------------------------------------------------
2075  */
2076 static Datum
2077 ExecEvalOr(BoolExprState *orExpr, ExprContext *econtext,
2078                    bool *isNull, ExprDoneCond *isDone)
2079 {
2080         List       *clauses = orExpr->args;
2081         ListCell   *clause;
2082         bool            AnyNull;
2083
2084         if (isDone)
2085                 *isDone = ExprSingleResult;
2086
2087         AnyNull = false;
2088
2089         /*
2090          * If any of the clauses is TRUE, the OR result is TRUE regardless of the
2091          * states of the rest of the clauses, so we can stop evaluating and return
2092          * TRUE immediately.  If none are TRUE and one or more is NULL, we return
2093          * NULL; otherwise we return FALSE.  This makes sense when you interpret
2094          * NULL as "don't know": if we have a TRUE then the OR is TRUE even if we
2095          * aren't sure about some of the other inputs. If all the known inputs are
2096          * FALSE, but we have one or more "don't knows", then we have to report
2097          * that we "don't know" what the OR's result should be --- perhaps one of
2098          * the "don't knows" would have been TRUE if we'd known its value.  Only
2099          * when all the inputs are known to be FALSE can we state confidently that
2100          * the OR's result is FALSE.
2101          */
2102         foreach(clause, clauses)
2103         {
2104                 ExprState  *clausestate = (ExprState *) lfirst(clause);
2105                 Datum           clause_value;
2106
2107                 clause_value = ExecEvalExpr(clausestate, econtext, isNull, NULL);
2108
2109                 /*
2110                  * if we have a non-null true result, then return it.
2111                  */
2112                 if (*isNull)
2113                         AnyNull = true;         /* remember we got a null */
2114                 else if (DatumGetBool(clause_value))
2115                         return clause_value;
2116         }
2117
2118         /* AnyNull is true if at least one clause evaluated to NULL */
2119         *isNull = AnyNull;
2120         return BoolGetDatum(false);
2121 }
2122
2123 /* ----------------------------------------------------------------
2124  *              ExecEvalAnd
2125  * ----------------------------------------------------------------
2126  */
2127 static Datum
2128 ExecEvalAnd(BoolExprState *andExpr, ExprContext *econtext,
2129                         bool *isNull, ExprDoneCond *isDone)
2130 {
2131         List       *clauses = andExpr->args;
2132         ListCell   *clause;
2133         bool            AnyNull;
2134
2135         if (isDone)
2136                 *isDone = ExprSingleResult;
2137
2138         AnyNull = false;
2139
2140         /*
2141          * If any of the clauses is FALSE, the AND result is FALSE regardless of
2142          * the states of the rest of the clauses, so we can stop evaluating and
2143          * return FALSE immediately.  If none are FALSE and one or more is NULL,
2144          * we return NULL; otherwise we return TRUE.  This makes sense when you
2145          * interpret NULL as "don't know", using the same sort of reasoning as for
2146          * OR, above.
2147          */
2148
2149         foreach(clause, clauses)
2150         {
2151                 ExprState  *clausestate = (ExprState *) lfirst(clause);
2152                 Datum           clause_value;
2153
2154                 clause_value = ExecEvalExpr(clausestate, econtext, isNull, NULL);
2155
2156                 /*
2157                  * if we have a non-null false result, then return it.
2158                  */
2159                 if (*isNull)
2160                         AnyNull = true;         /* remember we got a null */
2161                 else if (!DatumGetBool(clause_value))
2162                         return clause_value;
2163         }
2164
2165         /* AnyNull is true if at least one clause evaluated to NULL */
2166         *isNull = AnyNull;
2167         return BoolGetDatum(!AnyNull);
2168 }
2169
2170 /* ----------------------------------------------------------------
2171  *              ExecEvalConvertRowtype
2172  *
2173  *              Evaluate a rowtype coercion operation.  This may require
2174  *              rearranging field positions.
2175  * ----------------------------------------------------------------
2176  */
2177 static Datum
2178 ExecEvalConvertRowtype(ConvertRowtypeExprState *cstate,
2179                                            ExprContext *econtext,
2180                                            bool *isNull, ExprDoneCond *isDone)
2181 {
2182         ConvertRowtypeExpr *convert = (ConvertRowtypeExpr *) cstate->xprstate.expr;
2183         HeapTuple       result;
2184         Datum           tupDatum;
2185         HeapTupleHeader tuple;
2186         HeapTupleData tmptup;
2187         AttrNumber *attrMap;
2188         Datum      *invalues;
2189         bool       *inisnull;
2190         Datum      *outvalues;
2191         bool       *outisnull;
2192         int                     i;
2193         int                     outnatts;
2194
2195         tupDatum = ExecEvalExpr(cstate->arg, econtext, isNull, isDone);
2196
2197         /* this test covers the isDone exception too: */
2198         if (*isNull)
2199                 return tupDatum;
2200
2201         tuple = DatumGetHeapTupleHeader(tupDatum);
2202
2203         /* Lookup tupdescs if first time through or after rescan */
2204         if (cstate->indesc == NULL)
2205                 get_cached_rowtype(exprType((Node *) convert->arg), -1,
2206                                                    &cstate->indesc, econtext);
2207         if (cstate->outdesc == NULL)
2208                 get_cached_rowtype(convert->resulttype, -1,
2209                                                    &cstate->outdesc, econtext);
2210
2211         Assert(HeapTupleHeaderGetTypeId(tuple) == cstate->indesc->tdtypeid);
2212         Assert(HeapTupleHeaderGetTypMod(tuple) == cstate->indesc->tdtypmod);
2213
2214         /* if first time through, initialize */
2215         if (cstate->attrMap == NULL)
2216         {
2217                 MemoryContext old_cxt;
2218                 int                     n;
2219
2220                 /* allocate state in long-lived memory context */
2221                 old_cxt = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
2222
2223                 /* prepare map from old to new attribute numbers */
2224                 n = cstate->outdesc->natts;
2225                 cstate->attrMap = (AttrNumber *) palloc0(n * sizeof(AttrNumber));
2226                 for (i = 0; i < n; i++)
2227                 {
2228                         Form_pg_attribute att = cstate->outdesc->attrs[i];
2229                         char       *attname;
2230                         Oid                     atttypid;
2231                         int32           atttypmod;
2232                         int                     j;
2233
2234                         if (att->attisdropped)
2235                                 continue;               /* attrMap[i] is already 0 */
2236                         attname = NameStr(att->attname);
2237                         atttypid = att->atttypid;
2238                         atttypmod = att->atttypmod;
2239                         for (j = 0; j < cstate->indesc->natts; j++)
2240                         {
2241                                 att = cstate->indesc->attrs[j];
2242                                 if (att->attisdropped)
2243                                         continue;
2244                                 if (strcmp(attname, NameStr(att->attname)) == 0)
2245                                 {
2246                                         /* Found it, check type */
2247                                         if (atttypid != att->atttypid || atttypmod != att->atttypmod)
2248                                                 elog(ERROR, "attribute \"%s\" of type %s does not match corresponding attribute of type %s",
2249                                                          attname,
2250                                                          format_type_be(cstate->indesc->tdtypeid),
2251                                                          format_type_be(cstate->outdesc->tdtypeid));
2252                                         cstate->attrMap[i] = (AttrNumber) (j + 1);
2253                                         break;
2254                                 }
2255                         }
2256                         if (cstate->attrMap[i] == 0)
2257                                 elog(ERROR, "attribute \"%s\" of type %s does not exist",
2258                                          attname,
2259                                          format_type_be(cstate->indesc->tdtypeid));
2260                 }
2261                 /* preallocate workspace for Datum arrays */
2262                 n = cstate->indesc->natts + 1;  /* +1 for NULL */
2263                 cstate->invalues = (Datum *) palloc(n * sizeof(Datum));
2264                 cstate->inisnull = (bool *) palloc(n * sizeof(bool));
2265                 n = cstate->outdesc->natts;
2266                 cstate->outvalues = (Datum *) palloc(n * sizeof(Datum));
2267                 cstate->outisnull = (bool *) palloc(n * sizeof(bool));
2268
2269                 MemoryContextSwitchTo(old_cxt);
2270         }
2271
2272         attrMap = cstate->attrMap;
2273         invalues = cstate->invalues;
2274         inisnull = cstate->inisnull;
2275         outvalues = cstate->outvalues;
2276         outisnull = cstate->outisnull;
2277         outnatts = cstate->outdesc->natts;
2278
2279         /*
2280          * heap_deform_tuple needs a HeapTuple not a bare HeapTupleHeader.
2281          */
2282         tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
2283         tmptup.t_data = tuple;
2284
2285         /*
2286          * Extract all the values of the old tuple, offsetting the arrays so that
2287          * invalues[0] is NULL and invalues[1] is the first source attribute; this
2288          * exactly matches the numbering convention in attrMap.
2289          */
2290         heap_deform_tuple(&tmptup, cstate->indesc, invalues + 1, inisnull + 1);
2291         invalues[0] = (Datum) 0;
2292         inisnull[0] = true;
2293
2294         /*
2295          * Transpose into proper fields of the new tuple.
2296          */
2297         for (i = 0; i < outnatts; i++)
2298         {
2299                 int                     j = attrMap[i];
2300
2301                 outvalues[i] = invalues[j];
2302                 outisnull[i] = inisnull[j];
2303         }
2304
2305         /*
2306          * Now form the new tuple.
2307          */
2308         result = heap_form_tuple(cstate->outdesc, outvalues, outisnull);
2309
2310         return HeapTupleGetDatum(result);
2311 }
2312
2313 /* ----------------------------------------------------------------
2314  *              ExecEvalCase
2315  *
2316  *              Evaluate a CASE clause. Will have boolean expressions
2317  *              inside the WHEN clauses, and will have expressions
2318  *              for results.
2319  *              - thomas 1998-11-09
2320  * ----------------------------------------------------------------
2321  */
2322 static Datum
2323 ExecEvalCase(CaseExprState *caseExpr, ExprContext *econtext,
2324                          bool *isNull, ExprDoneCond *isDone)
2325 {
2326         List       *clauses = caseExpr->args;
2327         ListCell   *clause;
2328         Datum           save_datum;
2329         bool            save_isNull;
2330
2331         if (isDone)
2332                 *isDone = ExprSingleResult;
2333
2334         /*
2335          * If there's a test expression, we have to evaluate it and save the value
2336          * where the CaseTestExpr placeholders can find it. We must save and
2337          * restore prior setting of econtext's caseValue fields, in case this node
2338          * is itself within a larger CASE.
2339          */
2340         save_datum = econtext->caseValue_datum;
2341         save_isNull = econtext->caseValue_isNull;
2342
2343         if (caseExpr->arg)
2344         {
2345                 econtext->caseValue_datum = ExecEvalExpr(caseExpr->arg,
2346                                                                                                  econtext,
2347                                                                                                  &econtext->caseValue_isNull,
2348                                                                                                  NULL);
2349         }
2350
2351         /*
2352          * we evaluate each of the WHEN clauses in turn, as soon as one is true we
2353          * return the corresponding result. If none are true then we return the
2354          * value of the default clause, or NULL if there is none.
2355          */
2356         foreach(clause, clauses)
2357         {
2358                 CaseWhenState *wclause = lfirst(clause);
2359                 Datum           clause_value;
2360
2361                 clause_value = ExecEvalExpr(wclause->expr,
2362                                                                         econtext,
2363                                                                         isNull,
2364                                                                         NULL);
2365
2366                 /*
2367                  * if we have a true test, then we return the result, since the case
2368                  * statement is satisfied.      A NULL result from the test is not
2369                  * considered true.
2370                  */
2371                 if (DatumGetBool(clause_value) && !*isNull)
2372                 {
2373                         econtext->caseValue_datum = save_datum;
2374                         econtext->caseValue_isNull = save_isNull;
2375                         return ExecEvalExpr(wclause->result,
2376                                                                 econtext,
2377                                                                 isNull,
2378                                                                 isDone);
2379                 }
2380         }
2381
2382         econtext->caseValue_datum = save_datum;
2383         econtext->caseValue_isNull = save_isNull;
2384
2385         if (caseExpr->defresult)
2386         {
2387                 return ExecEvalExpr(caseExpr->defresult,
2388                                                         econtext,
2389                                                         isNull,
2390                                                         isDone);
2391         }
2392
2393         *isNull = true;
2394         return (Datum) 0;
2395 }
2396
2397 /*
2398  * ExecEvalCaseTestExpr
2399  *
2400  * Return the value stored by CASE.
2401  */
2402 static Datum
2403 ExecEvalCaseTestExpr(ExprState *exprstate,
2404                                          ExprContext *econtext,
2405                                          bool *isNull, ExprDoneCond *isDone)
2406 {
2407         if (isDone)
2408                 *isDone = ExprSingleResult;
2409         *isNull = econtext->caseValue_isNull;
2410         return econtext->caseValue_datum;
2411 }
2412
2413 /* ----------------------------------------------------------------
2414  *              ExecEvalArray - ARRAY[] expressions
2415  * ----------------------------------------------------------------
2416  */
2417 static Datum
2418 ExecEvalArray(ArrayExprState *astate, ExprContext *econtext,
2419                           bool *isNull, ExprDoneCond *isDone)
2420 {
2421         ArrayExpr  *arrayExpr = (ArrayExpr *) astate->xprstate.expr;
2422         ArrayType  *result;
2423         ListCell   *element;
2424         Oid                     element_type = arrayExpr->element_typeid;
2425         int                     ndims = 0;
2426         int                     dims[MAXDIM];
2427         int                     lbs[MAXDIM];
2428
2429         /* Set default values for result flags: non-null, not a set result */
2430         *isNull = false;
2431         if (isDone)
2432                 *isDone = ExprSingleResult;
2433
2434         if (!arrayExpr->multidims)
2435         {
2436                 /* Elements are presumably of scalar type */
2437                 int                     nelems;
2438                 Datum      *dvalues;
2439                 bool       *dnulls;
2440                 int                     i = 0;
2441
2442                 ndims = 1;
2443                 nelems = list_length(astate->elements);
2444
2445                 /* Shouldn't happen here, but if length is 0, return empty array */
2446                 if (nelems == 0)
2447                         return PointerGetDatum(construct_empty_array(element_type));
2448
2449                 dvalues = (Datum *) palloc(nelems * sizeof(Datum));
2450                 dnulls = (bool *) palloc(nelems * sizeof(bool));
2451
2452                 /* loop through and build array of datums */
2453                 foreach(element, astate->elements)
2454                 {
2455                         ExprState  *e = (ExprState *) lfirst(element);
2456
2457                         dvalues[i] = ExecEvalExpr(e, econtext, &dnulls[i], NULL);
2458                         i++;
2459                 }
2460
2461                 /* setup for 1-D array of the given length */
2462                 dims[0] = nelems;
2463                 lbs[0] = 1;
2464
2465                 result = construct_md_array(dvalues, dnulls, ndims, dims, lbs,
2466                                                                         element_type,
2467                                                                         astate->elemlength,
2468                                                                         astate->elembyval,
2469                                                                         astate->elemalign);
2470         }
2471         else
2472         {
2473                 /* Must be nested array expressions */
2474                 int                     nbytes = 0;
2475                 int                     nitems = 0;
2476                 int                     outer_nelems = 0;
2477                 int                     elem_ndims = 0;
2478                 int                *elem_dims = NULL;
2479                 int                *elem_lbs = NULL;
2480                 bool            firstone = true;
2481                 bool            havenulls = false;
2482                 bool            haveempty = false;
2483                 char      **subdata;
2484                 bits8     **subbitmaps;
2485                 int                *subbytes;
2486                 int                *subnitems;
2487                 int                     i;
2488                 int32           dataoffset;
2489                 char       *dat;
2490                 int                     iitem;
2491
2492                 i = list_length(astate->elements);
2493                 subdata = (char **) palloc(i * sizeof(char *));
2494                 subbitmaps = (bits8 **) palloc(i * sizeof(bits8 *));
2495                 subbytes = (int *) palloc(i * sizeof(int));
2496                 subnitems = (int *) palloc(i * sizeof(int));
2497
2498                 /* loop through and get data area from each element */
2499                 foreach(element, astate->elements)
2500                 {
2501                         ExprState  *e = (ExprState *) lfirst(element);
2502                         bool            eisnull;
2503                         Datum           arraydatum;
2504                         ArrayType  *array;
2505                         int                     this_ndims;
2506
2507                         arraydatum = ExecEvalExpr(e, econtext, &eisnull, NULL);
2508                         /* temporarily ignore null subarrays */
2509                         if (eisnull)
2510                         {
2511                                 haveempty = true;
2512                                 continue;
2513                         }
2514
2515                         array = DatumGetArrayTypeP(arraydatum);
2516
2517                         /* run-time double-check on element type */
2518                         if (element_type != ARR_ELEMTYPE(array))
2519                                 ereport(ERROR,
2520                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
2521                                                  errmsg("cannot merge incompatible arrays"),
2522                                                  errdetail("Array with element type %s cannot be "
2523                                                  "included in ARRAY construct with element type %s.",
2524                                                                    format_type_be(ARR_ELEMTYPE(array)),
2525                                                                    format_type_be(element_type))));
2526
2527                         this_ndims = ARR_NDIM(array);
2528                         /* temporarily ignore zero-dimensional subarrays */
2529                         if (this_ndims <= 0)
2530                         {
2531                                 haveempty = true;
2532                                 continue;
2533                         }
2534
2535                         if (firstone)
2536                         {
2537                                 /* Get sub-array details from first member */
2538                                 elem_ndims = this_ndims;
2539                                 ndims = elem_ndims + 1;
2540                                 if (ndims <= 0 || ndims > MAXDIM)
2541                                         ereport(ERROR,
2542                                                         (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
2543                                                   errmsg("number of array dimensions (%d) exceeds " \
2544                                                                  "the maximum allowed (%d)", ndims, MAXDIM)));
2545
2546                                 elem_dims = (int *) palloc(elem_ndims * sizeof(int));
2547                                 memcpy(elem_dims, ARR_DIMS(array), elem_ndims * sizeof(int));
2548                                 elem_lbs = (int *) palloc(elem_ndims * sizeof(int));
2549                                 memcpy(elem_lbs, ARR_LBOUND(array), elem_ndims * sizeof(int));
2550
2551                                 firstone = false;
2552                         }
2553                         else
2554                         {
2555                                 /* Check other sub-arrays are compatible */
2556                                 if (elem_ndims != this_ndims ||
2557                                         memcmp(elem_dims, ARR_DIMS(array),
2558                                                    elem_ndims * sizeof(int)) != 0 ||
2559                                         memcmp(elem_lbs, ARR_LBOUND(array),
2560                                                    elem_ndims * sizeof(int)) != 0)
2561                                         ereport(ERROR,
2562                                                         (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2563                                                          errmsg("multidimensional arrays must have array "
2564                                                                         "expressions with matching dimensions")));
2565                         }
2566
2567                         subdata[outer_nelems] = ARR_DATA_PTR(array);
2568                         subbitmaps[outer_nelems] = ARR_NULLBITMAP(array);
2569                         subbytes[outer_nelems] = ARR_SIZE(array) - ARR_DATA_OFFSET(array);
2570                         nbytes += subbytes[outer_nelems];
2571                         subnitems[outer_nelems] = ArrayGetNItems(this_ndims,
2572                                                                                                          ARR_DIMS(array));
2573                         nitems += subnitems[outer_nelems];
2574                         havenulls |= ARR_HASNULL(array);
2575                         outer_nelems++;
2576                 }
2577
2578                 /*
2579                  * If all items were null or empty arrays, return an empty array;
2580                  * otherwise, if some were and some weren't, raise error.  (Note:
2581                  * we must special-case this somehow to avoid trying to generate
2582                  * a 1-D array formed from empty arrays.  It's not ideal...)
2583                  */
2584                 if (haveempty)
2585                 {
2586                         if (ndims == 0)         /* didn't find any nonempty array */
2587                                 return PointerGetDatum(construct_empty_array(element_type));
2588                         ereport(ERROR,
2589                                         (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2590                                          errmsg("multidimensional arrays must have array "
2591                                                         "expressions with matching dimensions")));
2592                 }
2593
2594                 /* setup for multi-D array */
2595                 dims[0] = outer_nelems;
2596                 lbs[0] = 1;
2597                 for (i = 1; i < ndims; i++)
2598                 {
2599                         dims[i] = elem_dims[i - 1];
2600                         lbs[i] = elem_lbs[i - 1];
2601                 }
2602
2603                 if (havenulls)
2604                 {
2605                         dataoffset = ARR_OVERHEAD_WITHNULLS(ndims, nitems);
2606                         nbytes += dataoffset;
2607                 }
2608                 else
2609                 {
2610                         dataoffset = 0;         /* marker for no null bitmap */
2611                         nbytes += ARR_OVERHEAD_NONULLS(ndims);
2612                 }
2613
2614                 result = (ArrayType *) palloc(nbytes);
2615                 SET_VARSIZE(result, nbytes);
2616                 result->ndim = ndims;
2617                 result->dataoffset = dataoffset;
2618                 result->elemtype = element_type;
2619                 memcpy(ARR_DIMS(result), dims, ndims * sizeof(int));
2620                 memcpy(ARR_LBOUND(result), lbs, ndims * sizeof(int));
2621
2622                 dat = ARR_DATA_PTR(result);
2623                 iitem = 0;
2624                 for (i = 0; i < outer_nelems; i++)
2625                 {
2626                         memcpy(dat, subdata[i], subbytes[i]);
2627                         dat += subbytes[i];
2628                         if (havenulls)
2629                                 array_bitmap_copy(ARR_NULLBITMAP(result), iitem,
2630                                                                   subbitmaps[i], 0,
2631                                                                   subnitems[i]);
2632                         iitem += subnitems[i];
2633                 }
2634         }
2635
2636         return PointerGetDatum(result);
2637 }
2638
2639 /* ----------------------------------------------------------------
2640  *              ExecEvalRow - ROW() expressions
2641  * ----------------------------------------------------------------
2642  */
2643 static Datum
2644 ExecEvalRow(RowExprState *rstate,
2645                         ExprContext *econtext,
2646                         bool *isNull, ExprDoneCond *isDone)
2647 {
2648         HeapTuple       tuple;
2649         Datum      *values;
2650         bool       *isnull;
2651         int                     natts;
2652         ListCell   *arg;
2653         int                     i;
2654
2655         /* Set default values for result flags: non-null, not a set result */
2656         *isNull = false;
2657         if (isDone)
2658                 *isDone = ExprSingleResult;
2659
2660         /* Allocate workspace */
2661         natts = rstate->tupdesc->natts;
2662         values = (Datum *) palloc0(natts * sizeof(Datum));
2663         isnull = (bool *) palloc(natts * sizeof(bool));
2664
2665         /* preset to nulls in case rowtype has some later-added columns */
2666         memset(isnull, true, natts * sizeof(bool));
2667
2668         /* Evaluate field values */
2669         i = 0;
2670         foreach(arg, rstate->args)
2671         {
2672                 ExprState  *e = (ExprState *) lfirst(arg);
2673
2674                 values[i] = ExecEvalExpr(e, econtext, &isnull[i], NULL);
2675                 i++;
2676         }
2677
2678         tuple = heap_form_tuple(rstate->tupdesc, values, isnull);
2679
2680         pfree(values);
2681         pfree(isnull);
2682
2683         return HeapTupleGetDatum(tuple);
2684 }
2685
2686 /* ----------------------------------------------------------------
2687  *              ExecEvalRowCompare - ROW() comparison-op ROW()
2688  * ----------------------------------------------------------------
2689  */
2690 static Datum
2691 ExecEvalRowCompare(RowCompareExprState *rstate,
2692                                    ExprContext *econtext,
2693                                    bool *isNull, ExprDoneCond *isDone)
2694 {
2695         bool            result;
2696         RowCompareType rctype = ((RowCompareExpr *) rstate->xprstate.expr)->rctype;
2697         int32           cmpresult = 0;
2698         ListCell   *l;
2699         ListCell   *r;
2700         int                     i;
2701
2702         if (isDone)
2703                 *isDone = ExprSingleResult;
2704         *isNull = true;                         /* until we get a result */
2705
2706         i = 0;
2707         forboth(l, rstate->largs, r, rstate->rargs)
2708         {
2709                 ExprState  *le = (ExprState *) lfirst(l);
2710                 ExprState  *re = (ExprState *) lfirst(r);
2711                 FunctionCallInfoData locfcinfo;
2712
2713                 InitFunctionCallInfoData(locfcinfo, &(rstate->funcs[i]), 2,
2714                                                                  NULL, NULL);
2715                 locfcinfo.arg[0] = ExecEvalExpr(le, econtext,
2716                                                                                 &locfcinfo.argnull[0], NULL);
2717                 locfcinfo.arg[1] = ExecEvalExpr(re, econtext,
2718                                                                                 &locfcinfo.argnull[1], NULL);
2719                 if (rstate->funcs[i].fn_strict &&
2720                         (locfcinfo.argnull[0] || locfcinfo.argnull[1]))
2721                         return (Datum) 0;       /* force NULL result */
2722                 locfcinfo.isnull = false;
2723                 cmpresult = DatumGetInt32(FunctionCallInvoke(&locfcinfo));
2724                 if (locfcinfo.isnull)
2725                         return (Datum) 0;       /* force NULL result */
2726                 if (cmpresult != 0)
2727                         break;                          /* no need to compare remaining columns */
2728                 i++;
2729         }
2730
2731         switch (rctype)
2732         {
2733                         /* EQ and NE cases aren't allowed here */
2734                 case ROWCOMPARE_LT:
2735                         result = (cmpresult < 0);
2736                         break;
2737                 case ROWCOMPARE_LE:
2738                         result = (cmpresult <= 0);
2739                         break;
2740                 case ROWCOMPARE_GE:
2741                         result = (cmpresult >= 0);
2742                         break;
2743                 case ROWCOMPARE_GT:
2744                         result = (cmpresult > 0);
2745                         break;
2746                 default:
2747                         elog(ERROR, "unrecognized RowCompareType: %d", (int) rctype);
2748                         result = 0;                     /* keep compiler quiet */
2749                         break;
2750         }
2751
2752         *isNull = false;
2753         return BoolGetDatum(result);
2754 }
2755
2756 /* ----------------------------------------------------------------
2757  *              ExecEvalCoalesce
2758  * ----------------------------------------------------------------
2759  */
2760 static Datum
2761 ExecEvalCoalesce(CoalesceExprState *coalesceExpr, ExprContext *econtext,
2762                                  bool *isNull, ExprDoneCond *isDone)
2763 {
2764         ListCell   *arg;
2765
2766         if (isDone)
2767                 *isDone = ExprSingleResult;
2768
2769         /* Simply loop through until something NOT NULL is found */
2770         foreach(arg, coalesceExpr->args)
2771         {
2772                 ExprState  *e = (ExprState *) lfirst(arg);
2773                 Datum           value;
2774
2775                 value = ExecEvalExpr(e, econtext, isNull, NULL);
2776                 if (!*isNull)
2777                         return value;
2778         }
2779
2780         /* Else return NULL */
2781         *isNull = true;
2782         return (Datum) 0;
2783 }
2784
2785 /* ----------------------------------------------------------------
2786  *              ExecEvalMinMax
2787  * ----------------------------------------------------------------
2788  */
2789 static Datum
2790 ExecEvalMinMax(MinMaxExprState *minmaxExpr, ExprContext *econtext,
2791                            bool *isNull, ExprDoneCond *isDone)
2792 {
2793         Datum           result = (Datum) 0;
2794         MinMaxOp        op = ((MinMaxExpr *) minmaxExpr->xprstate.expr)->op;
2795         FunctionCallInfoData locfcinfo;
2796         ListCell   *arg;
2797
2798         if (isDone)
2799                 *isDone = ExprSingleResult;
2800         *isNull = true;                         /* until we get a result */
2801
2802         InitFunctionCallInfoData(locfcinfo, &minmaxExpr->cfunc, 2, NULL, NULL);
2803         locfcinfo.argnull[0] = false;
2804         locfcinfo.argnull[1] = false;
2805
2806         foreach(arg, minmaxExpr->args)
2807         {
2808                 ExprState  *e = (ExprState *) lfirst(arg);
2809                 Datum           value;
2810                 bool            valueIsNull;
2811                 int32           cmpresult;
2812
2813                 value = ExecEvalExpr(e, econtext, &valueIsNull, NULL);
2814                 if (valueIsNull)
2815                         continue;                       /* ignore NULL inputs */
2816
2817                 if (*isNull)
2818                 {
2819                         /* first nonnull input, adopt value */
2820                         result = value;
2821                         *isNull = false;
2822                 }
2823                 else
2824                 {
2825                         /* apply comparison function */
2826                         locfcinfo.arg[0] = result;
2827                         locfcinfo.arg[1] = value;
2828                         locfcinfo.isnull = false;
2829                         cmpresult = DatumGetInt32(FunctionCallInvoke(&locfcinfo));
2830                         if (locfcinfo.isnull)           /* probably should not happen */
2831                                 continue;
2832                         if (cmpresult > 0 && op == IS_LEAST)
2833                                 result = value;
2834                         else if (cmpresult < 0 && op == IS_GREATEST)
2835                                 result = value;
2836                 }
2837         }
2838
2839         return result;
2840 }
2841
2842 /* ----------------------------------------------------------------
2843  *              ExecEvalXml
2844  * ----------------------------------------------------------------
2845  */
2846 static Datum
2847 ExecEvalXml(XmlExprState *xmlExpr, ExprContext *econtext,
2848                         bool *isNull, ExprDoneCond *isDone)
2849 {
2850         XmlExpr            *xexpr = (XmlExpr *) xmlExpr->xprstate.expr;
2851         text               *result;
2852         StringInfoData  buf;
2853         Datum                   value;
2854         bool                    isnull;
2855         ListCell           *arg;
2856         ListCell   *narg;
2857         int                     i;
2858
2859         if (isDone)
2860                 *isDone = ExprSingleResult;
2861         *isNull = true;                         /* until we get a result */
2862
2863         switch (xexpr->op)
2864         {
2865                 case IS_XMLCONCAT:
2866                         {
2867                                 List *values = NIL;
2868
2869                                 foreach(arg, xmlExpr->args)
2870                                 {
2871                                         ExprState       *e = (ExprState *) lfirst(arg);
2872
2873                                         value = ExecEvalExpr(e, econtext, &isnull, NULL);
2874                                         if (!isnull)
2875                                                 values = lappend(values, DatumGetPointer(value));
2876                                 }
2877
2878                                 if (list_length(values) > 0)
2879                                 {
2880                                         *isNull = false;
2881                                         return PointerGetDatum(xmlconcat(values));
2882                                 }
2883                         }
2884                         break;
2885
2886                 case IS_XMLFOREST:
2887                         initStringInfo(&buf);
2888                         i = 0;
2889                         forboth(arg, xmlExpr->named_args, narg, xexpr->arg_names)
2890                         {
2891                                 ExprState       *e = (ExprState *) lfirst(arg);
2892                                 char    *argname = strVal(lfirst(narg));
2893
2894                                 value = ExecEvalExpr(e, econtext, &isnull, NULL);
2895                                 if (!isnull)
2896                                 {
2897                                         appendStringInfo(&buf, "<%s>%s</%s>",
2898                                                                          argname,
2899                                                                          map_sql_value_to_xml_value(value, exprType((Node *) e->expr)),
2900                                                                          argname);
2901                                         *isNull = false;
2902                                 }
2903                                 i++;
2904                         }
2905                         break;
2906
2907                         /* The remaining cases don't need to set up buf */
2908                 case IS_XMLELEMENT:
2909                         *isNull = false;
2910                         return PointerGetDatum(xmlelement(xmlExpr, econtext));
2911                         break;
2912
2913                 case IS_XMLPARSE:
2914                         {
2915                                 ExprState       *e;
2916                                 text        *data;
2917                                 bool            preserve_whitespace;
2918
2919                                 /* arguments are known to be text, bool */
2920                                 Assert(list_length(xmlExpr->args) == 2);
2921
2922                                 e = (ExprState *) linitial(xmlExpr->args);
2923                                 value = ExecEvalExpr(e, econtext, &isnull, NULL);
2924                                 if (isnull)
2925                                         return (Datum) 0;
2926                                 data = DatumGetTextP(value);
2927
2928                                 e = (ExprState *) lsecond(xmlExpr->args);
2929                                 value = ExecEvalExpr(e, econtext, &isnull, NULL);
2930                                 if (isnull)             /* probably can't happen */
2931                                         return (Datum) 0;
2932                                 preserve_whitespace = DatumGetBool(value);
2933
2934                                 *isNull = false;
2935
2936                                 return PointerGetDatum(xmlparse(data,
2937                                                                                                 xexpr->xmloption,
2938                                                                                                 preserve_whitespace));
2939                         }
2940                         break;
2941
2942                 case IS_XMLPI:
2943                         {
2944                                 ExprState       *e;
2945                                 text        *arg;
2946
2947                                 /* optional argument is known to be text */
2948                                 Assert(list_length(xmlExpr->args) <= 1);
2949
2950                                 if (xmlExpr->args)
2951                                 {
2952                                         e = (ExprState *) linitial(xmlExpr->args);
2953                                         value = ExecEvalExpr(e, econtext, &isnull, NULL);
2954                                         if (isnull)
2955                                                 arg = NULL;
2956                                         else
2957                                                 arg = DatumGetTextP(value);
2958                                 }
2959                                 else
2960                                 {
2961                                         arg = NULL;
2962                                         isnull = false;
2963                                 }
2964
2965                                 return PointerGetDatum(xmlpi(xexpr->name, arg, isnull, isNull));
2966                         }
2967                         break;
2968
2969                 case IS_XMLROOT:
2970                         {
2971                                 ExprState       *e;
2972                                 xmltype         *data;
2973                                 text            *version;
2974                                 int                     standalone;
2975
2976                                 /* arguments are known to be xml, text, int */
2977                                 Assert(list_length(xmlExpr->args) == 3);
2978
2979                                 e = (ExprState *) linitial(xmlExpr->args);
2980                                 value = ExecEvalExpr(e, econtext, &isnull, NULL);
2981                                 if (isnull)
2982                                         return (Datum) 0;
2983                                 data = DatumGetXmlP(value);
2984
2985                                 e = (ExprState *) lsecond(xmlExpr->args);
2986                                 value = ExecEvalExpr(e, econtext, &isnull, NULL);
2987                                 if (isnull)
2988                                         version = NULL;
2989                                 else
2990                                         version = DatumGetTextP(value);
2991
2992                                 e = (ExprState *) lthird(xmlExpr->args);
2993                                 value = ExecEvalExpr(e, econtext, &isnull, NULL);
2994                                 standalone = DatumGetInt32(value);
2995
2996                                 *isNull = false;
2997
2998                                 return PointerGetDatum(xmlroot(data,
2999                                                                                            version,
3000                                                                                            standalone));
3001                         }
3002                         break;
3003
3004                 case IS_XMLSERIALIZE:
3005                         {
3006                                 ExprState       *e;
3007
3008                                 /* argument type is known to be xml */
3009                                 Assert(list_length(xmlExpr->args) == 1);
3010
3011                                 e = (ExprState *) linitial(xmlExpr->args);
3012                                 value = ExecEvalExpr(e, econtext, &isnull, NULL);
3013                                 if (isnull)
3014                                         return (Datum) 0;
3015
3016                                 *isNull = false;
3017
3018                                 return PointerGetDatum(xmltotext_with_xmloption(DatumGetXmlP(value), xexpr->xmloption));
3019                         }
3020                         break;
3021
3022                 case IS_DOCUMENT:
3023                         {
3024                                 ExprState       *e;
3025
3026                                 /* optional argument is known to be xml */
3027                                 Assert(list_length(xmlExpr->args) == 1);
3028
3029                                 e = (ExprState *) linitial(xmlExpr->args);
3030                                 value = ExecEvalExpr(e, econtext, &isnull, NULL);
3031                                 if (isnull)
3032                                         return (Datum) 0;
3033                                 else
3034                                 {
3035                                         *isNull = false;
3036                                         return BoolGetDatum(xml_is_document(DatumGetXmlP(value)));
3037                                 }
3038                         }
3039                         break;
3040         }
3041
3042         if (*isNull)
3043                 result = NULL;
3044         else
3045         {
3046                 int             len = buf.len + VARHDRSZ;
3047
3048                 result = palloc(len);
3049                 SET_VARSIZE(result, len);
3050                 memcpy(VARDATA(result), buf.data, buf.len);
3051         }
3052
3053         pfree(buf.data);
3054         return PointerGetDatum(result);
3055 }
3056
3057 /* ----------------------------------------------------------------
3058  *              ExecEvalNullIf
3059  *
3060  * Note that this is *always* derived from the equals operator,
3061  * but since we need special processing of the arguments
3062  * we can not simply reuse ExecEvalOper() or ExecEvalFunc().
3063  * ----------------------------------------------------------------
3064  */
3065 static Datum
3066 ExecEvalNullIf(FuncExprState *nullIfExpr,
3067                            ExprContext *econtext,
3068                            bool *isNull, ExprDoneCond *isDone)
3069 {
3070         Datum           result;
3071         FunctionCallInfoData fcinfo;
3072         ExprDoneCond argDone;
3073         List       *argList;
3074
3075         if (isDone)
3076                 *isDone = ExprSingleResult;
3077
3078         /*
3079          * Initialize function cache if first time through
3080          */
3081         if (nullIfExpr->func.fn_oid == InvalidOid)
3082         {
3083                 NullIfExpr *op = (NullIfExpr *) nullIfExpr->xprstate.expr;
3084
3085                 init_fcache(op->opfuncid, nullIfExpr, econtext->ecxt_per_query_memory);
3086                 Assert(!nullIfExpr->func.fn_retset);
3087         }
3088
3089         /*
3090          * extract info from nullIfExpr
3091          */
3092         argList = nullIfExpr->args;
3093
3094         /* Need to prep callinfo structure */
3095         InitFunctionCallInfoData(fcinfo, &(nullIfExpr->func), 0, NULL, NULL);
3096         argDone = ExecEvalFuncArgs(&fcinfo, argList, econtext);
3097         if (argDone != ExprSingleResult)
3098                 ereport(ERROR,
3099                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
3100                                  errmsg("NULLIF does not support set arguments")));
3101         Assert(fcinfo.nargs == 2);
3102
3103         /* if either argument is NULL they can't be equal */
3104         if (!fcinfo.argnull[0] && !fcinfo.argnull[1])
3105         {
3106                 fcinfo.isnull = false;
3107                 result = FunctionCallInvoke(&fcinfo);
3108                 /* if the arguments are equal return null */
3109                 if (!fcinfo.isnull && DatumGetBool(result))
3110                 {
3111                         *isNull = true;
3112                         return (Datum) 0;
3113                 }
3114         }
3115
3116         /* else return first argument */
3117         *isNull = fcinfo.argnull[0];
3118         return fcinfo.arg[0];
3119 }
3120
3121 /* ----------------------------------------------------------------
3122  *              ExecEvalNullTest
3123  *
3124  *              Evaluate a NullTest node.
3125  * ----------------------------------------------------------------
3126  */
3127 static Datum
3128 ExecEvalNullTest(NullTestState *nstate,
3129                                  ExprContext *econtext,
3130                                  bool *isNull,
3131                                  ExprDoneCond *isDone)
3132 {
3133         NullTest   *ntest = (NullTest *) nstate->xprstate.expr;
3134         Datum           result;
3135
3136         result = ExecEvalExpr(nstate->arg, econtext, isNull, isDone);
3137
3138         if (isDone && *isDone == ExprEndResult)
3139                 return result;                  /* nothing to check */
3140
3141         if (nstate->argisrow && !(*isNull))
3142         {
3143                 HeapTupleHeader tuple;
3144                 Oid                     tupType;
3145                 int32           tupTypmod;
3146                 TupleDesc       tupDesc;
3147                 HeapTupleData tmptup;
3148                 int                     att;
3149
3150                 tuple = DatumGetHeapTupleHeader(result);
3151
3152                 tupType = HeapTupleHeaderGetTypeId(tuple);
3153                 tupTypmod = HeapTupleHeaderGetTypMod(tuple);
3154
3155                 /* Lookup tupdesc if first time through or if type changes */
3156                 tupDesc = get_cached_rowtype(tupType, tupTypmod,
3157                                                                          &nstate->argdesc, econtext);
3158
3159                 /*
3160                  * heap_attisnull needs a HeapTuple not a bare HeapTupleHeader.
3161                  */
3162                 tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
3163                 tmptup.t_data = tuple;
3164
3165                 for (att = 1; att <= tupDesc->natts; att++)
3166                 {
3167                         /* ignore dropped columns */
3168                         if (tupDesc->attrs[att - 1]->attisdropped)
3169                                 continue;
3170                         if (heap_attisnull(&tmptup, att))
3171                         {
3172                                 /* null field disproves IS NOT NULL */
3173                                 if (ntest->nulltesttype == IS_NOT_NULL)
3174                                         return BoolGetDatum(false);
3175                         }
3176                         else
3177                         {
3178                                 /* non-null field disproves IS NULL */
3179                                 if (ntest->nulltesttype == IS_NULL)
3180                                         return BoolGetDatum(false);
3181                         }
3182                 }
3183
3184                 return BoolGetDatum(true);
3185         }
3186         else
3187         {
3188                 /* Simple scalar-argument case, or a null rowtype datum */
3189                 switch (ntest->nulltesttype)
3190                 {
3191                         case IS_NULL:
3192                                 if (*isNull)
3193                                 {
3194                                         *isNull = false;
3195                                         return BoolGetDatum(true);
3196                                 }
3197                                 else
3198                                         return BoolGetDatum(false);
3199                         case IS_NOT_NULL:
3200                                 if (*isNull)
3201                                 {
3202                                         *isNull = false;
3203                                         return BoolGetDatum(false);
3204                                 }
3205                                 else
3206                                         return BoolGetDatum(true);
3207                         default:
3208                                 elog(ERROR, "unrecognized nulltesttype: %d",
3209                                          (int) ntest->nulltesttype);
3210                                 return (Datum) 0;               /* keep compiler quiet */
3211                 }
3212         }
3213 }
3214
3215 /* ----------------------------------------------------------------
3216  *              ExecEvalBooleanTest
3217  *
3218  *              Evaluate a BooleanTest node.
3219  * ----------------------------------------------------------------
3220  */
3221 static Datum
3222 ExecEvalBooleanTest(GenericExprState *bstate,
3223                                         ExprContext *econtext,
3224                                         bool *isNull,
3225                                         ExprDoneCond *isDone)
3226 {
3227         BooleanTest *btest = (BooleanTest *) bstate->xprstate.expr;
3228         Datum           result;
3229
3230         result = ExecEvalExpr(bstate->arg, econtext, isNull, isDone);
3231
3232         if (isDone && *isDone == ExprEndResult)
3233                 return result;                  /* nothing to check */
3234
3235         switch (btest->booltesttype)
3236         {
3237                 case IS_TRUE:
3238                         if (*isNull)
3239                         {
3240                                 *isNull = false;
3241                                 return BoolGetDatum(false);
3242                         }
3243                         else if (DatumGetBool(result))
3244                                 return BoolGetDatum(true);
3245                         else
3246                                 return BoolGetDatum(false);
3247                 case IS_NOT_TRUE:
3248                         if (*isNull)
3249                         {
3250                                 *isNull = false;
3251                                 return BoolGetDatum(true);
3252                         }
3253                         else if (DatumGetBool(result))
3254                                 return BoolGetDatum(false);
3255                         else
3256                                 return BoolGetDatum(true);
3257                 case IS_FALSE:
3258                         if (*isNull)
3259                         {
3260                                 *isNull = false;
3261                                 return BoolGetDatum(false);
3262                         }
3263                         else if (DatumGetBool(result))
3264                                 return BoolGetDatum(false);
3265                         else
3266                                 return BoolGetDatum(true);
3267                 case IS_NOT_FALSE:
3268                         if (*isNull)
3269                         {
3270                                 *isNull = false;
3271                                 return BoolGetDatum(true);
3272                         }
3273                         else if (DatumGetBool(result))
3274                                 return BoolGetDatum(true);
3275                         else
3276                                 return BoolGetDatum(false);
3277                 case IS_UNKNOWN:
3278                         if (*isNull)
3279                         {
3280                                 *isNull = false;
3281                                 return BoolGetDatum(true);
3282                         }
3283                         else
3284                                 return BoolGetDatum(false);
3285                 case IS_NOT_UNKNOWN:
3286                         if (*isNull)
3287                         {
3288                                 *isNull = false;
3289                                 return BoolGetDatum(false);
3290                         }
3291                         else
3292                                 return BoolGetDatum(true);
3293                 default:
3294                         elog(ERROR, "unrecognized booltesttype: %d",
3295                                  (int) btest->booltesttype);
3296                         return (Datum) 0;       /* keep compiler quiet */
3297         }
3298 }
3299
3300 /*
3301  * ExecEvalCoerceToDomain
3302  *
3303  * Test the provided data against the domain constraint(s).  If the data
3304  * passes the constraint specifications, pass it through (return the
3305  * datum) otherwise throw an error.
3306  */
3307 static Datum
3308 ExecEvalCoerceToDomain(CoerceToDomainState *cstate, ExprContext *econtext,
3309                                            bool *isNull, ExprDoneCond *isDone)
3310 {
3311         CoerceToDomain *ctest = (CoerceToDomain *) cstate->xprstate.expr;
3312         Datum           result;
3313         ListCell   *l;
3314
3315         result = ExecEvalExpr(cstate->arg, econtext, isNull, isDone);
3316
3317         if (isDone && *isDone == ExprEndResult)
3318                 return result;                  /* nothing to check */
3319
3320         foreach(l, cstate->constraints)
3321         {
3322                 DomainConstraintState *con = (DomainConstraintState *) lfirst(l);
3323
3324                 switch (con->constrainttype)
3325                 {
3326                         case DOM_CONSTRAINT_NOTNULL:
3327                                 if (*isNull)
3328                                         ereport(ERROR,
3329                                                         (errcode(ERRCODE_NOT_NULL_VIOLATION),
3330                                                          errmsg("domain %s does not allow null values",
3331                                                                         format_type_be(ctest->resulttype))));
3332                                 break;
3333                         case DOM_CONSTRAINT_CHECK:
3334                                 {
3335                                         Datum           conResult;
3336                                         bool            conIsNull;
3337                                         Datum           save_datum;
3338                                         bool            save_isNull;
3339
3340                                         /*
3341                                          * Set up value to be returned by CoerceToDomainValue
3342                                          * nodes. We must save and restore prior setting of
3343                                          * econtext's domainValue fields, in case this node is
3344                                          * itself within a check expression for another domain.
3345                                          */
3346                                         save_datum = econtext->domainValue_datum;
3347                                         save_isNull = econtext->domainValue_isNull;
3348
3349                                         econtext->domainValue_datum = result;
3350                                         econtext->domainValue_isNull = *isNull;
3351
3352                                         conResult = ExecEvalExpr(con->check_expr,
3353                                                                                          econtext, &conIsNull, NULL);
3354
3355                                         if (!conIsNull &&
3356                                                 !DatumGetBool(conResult))
3357                                                 ereport(ERROR,
3358                                                                 (errcode(ERRCODE_CHECK_VIOLATION),
3359                                                                  errmsg("value for domain %s violates check constraint \"%s\"",
3360                                                                                 format_type_be(ctest->resulttype),
3361                                                                                 con->name)));
3362                                         econtext->domainValue_datum = save_datum;
3363                                         econtext->domainValue_isNull = save_isNull;
3364
3365                                         break;
3366                                 }
3367                         default:
3368                                 elog(ERROR, "unrecognized constraint type: %d",
3369                                          (int) con->constrainttype);
3370                                 break;
3371                 }
3372         }
3373
3374         /* If all has gone well (constraints did not fail) return the datum */
3375         return result;
3376 }
3377
3378 /*
3379  * ExecEvalCoerceToDomainValue
3380  *
3381  * Return the value stored by CoerceToDomain.
3382  */
3383 static Datum
3384 ExecEvalCoerceToDomainValue(ExprState *exprstate,
3385                                                         ExprContext *econtext,
3386                                                         bool *isNull, ExprDoneCond *isDone)
3387 {
3388         if (isDone)
3389                 *isDone = ExprSingleResult;
3390         *isNull = econtext->domainValue_isNull;
3391         return econtext->domainValue_datum;
3392 }
3393
3394 /* ----------------------------------------------------------------
3395  *              ExecEvalFieldSelect
3396  *
3397  *              Evaluate a FieldSelect node.
3398  * ----------------------------------------------------------------
3399  */
3400 static Datum
3401 ExecEvalFieldSelect(FieldSelectState *fstate,
3402                                         ExprContext *econtext,
3403                                         bool *isNull,
3404                                         ExprDoneCond *isDone)
3405 {
3406         FieldSelect *fselect = (FieldSelect *) fstate->xprstate.expr;
3407         AttrNumber      fieldnum = fselect->fieldnum;
3408         Datum           result;
3409         Datum           tupDatum;
3410         HeapTupleHeader tuple;
3411         Oid                     tupType;
3412         int32           tupTypmod;
3413         TupleDesc       tupDesc;
3414         Form_pg_attribute attr;
3415         HeapTupleData tmptup;
3416
3417         tupDatum = ExecEvalExpr(fstate->arg, econtext, isNull, isDone);
3418
3419         /* this test covers the isDone exception too: */
3420         if (*isNull)
3421                 return tupDatum;
3422
3423         tuple = DatumGetHeapTupleHeader(tupDatum);
3424
3425         tupType = HeapTupleHeaderGetTypeId(tuple);
3426         tupTypmod = HeapTupleHeaderGetTypMod(tuple);
3427
3428         /* Lookup tupdesc if first time through or if type changes */
3429         tupDesc = get_cached_rowtype(tupType, tupTypmod,
3430                                                                  &fstate->argdesc, econtext);
3431
3432         /* Check for dropped column, and force a NULL result if so */
3433         if (fieldnum <= 0 ||
3434                 fieldnum > tupDesc->natts)      /* should never happen */
3435                                 elog(ERROR, "attribute number %d exceeds number of columns %d",
3436                                          fieldnum, tupDesc->natts);
3437         attr = tupDesc->attrs[fieldnum - 1];
3438         if (attr->attisdropped)
3439         {
3440                 *isNull = true;
3441                 return (Datum) 0;
3442         }
3443
3444         /* Check for type mismatch --- possible after ALTER COLUMN TYPE? */
3445         /* As in ExecEvalVar, we should but can't check typmod */
3446         if (fselect->resulttype != attr->atttypid)
3447                 ereport(ERROR,
3448                                 (errmsg("attribute %d has wrong type", fieldnum),
3449                                  errdetail("Table has type %s, but query expects %s.",
3450                                                    format_type_be(attr->atttypid),
3451                                                    format_type_be(fselect->resulttype))));
3452
3453         /*
3454          * heap_getattr needs a HeapTuple not a bare HeapTupleHeader.  We set all
3455          * the fields in the struct just in case user tries to inspect system
3456          * columns.
3457          */
3458         tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
3459         ItemPointerSetInvalid(&(tmptup.t_self));
3460         tmptup.t_tableOid = InvalidOid;
3461         tmptup.t_data = tuple;
3462
3463         result = heap_getattr(&tmptup,
3464                                                   fieldnum,
3465                                                   tupDesc,
3466                                                   isNull);
3467         return result;
3468 }
3469
3470 /* ----------------------------------------------------------------
3471  *              ExecEvalFieldStore
3472  *
3473  *              Evaluate a FieldStore node.
3474  * ----------------------------------------------------------------
3475  */
3476 static Datum
3477 ExecEvalFieldStore(FieldStoreState *fstate,
3478                                    ExprContext *econtext,
3479                                    bool *isNull,
3480                                    ExprDoneCond *isDone)
3481 {
3482         FieldStore *fstore = (FieldStore *) fstate->xprstate.expr;
3483         HeapTuple       tuple;
3484         Datum           tupDatum;
3485         TupleDesc       tupDesc;
3486         Datum      *values;
3487         bool       *isnull;
3488         Datum           save_datum;
3489         bool            save_isNull;
3490         ListCell   *l1,
3491                            *l2;
3492
3493         tupDatum = ExecEvalExpr(fstate->arg, econtext, isNull, isDone);
3494
3495         if (isDone && *isDone == ExprEndResult)
3496                 return tupDatum;
3497
3498         /* Lookup tupdesc if first time through or after rescan */
3499         tupDesc = get_cached_rowtype(fstore->resulttype, -1,
3500                                                                  &fstate->argdesc, econtext);
3501
3502         /* Allocate workspace */
3503         values = (Datum *) palloc(tupDesc->natts * sizeof(Datum));
3504         isnull = (bool *) palloc(tupDesc->natts * sizeof(bool));
3505
3506         if (!*isNull)
3507         {
3508                 /*
3509                  * heap_deform_tuple needs a HeapTuple not a bare HeapTupleHeader. We
3510                  * set all the fields in the struct just in case.
3511                  */
3512                 HeapTupleHeader tuphdr;
3513                 HeapTupleData tmptup;
3514
3515                 tuphdr = DatumGetHeapTupleHeader(tupDatum);
3516                 tmptup.t_len = HeapTupleHeaderGetDatumLength(tuphdr);
3517                 ItemPointerSetInvalid(&(tmptup.t_self));
3518                 tmptup.t_tableOid = InvalidOid;
3519                 tmptup.t_data = tuphdr;
3520
3521                 heap_deform_tuple(&tmptup, tupDesc, values, isnull);
3522         }
3523         else
3524         {
3525                 /* Convert null input tuple into an all-nulls row */
3526                 memset(isnull, true, tupDesc->natts * sizeof(bool));
3527         }
3528
3529         /* Result is never null */
3530         *isNull = false;
3531
3532         save_datum = econtext->caseValue_datum;
3533         save_isNull = econtext->caseValue_isNull;
3534
3535         forboth(l1, fstate->newvals, l2, fstore->fieldnums)
3536         {
3537                 ExprState  *newval = (ExprState *) lfirst(l1);
3538                 AttrNumber      fieldnum = lfirst_int(l2);
3539
3540                 Assert(fieldnum > 0 && fieldnum <= tupDesc->natts);
3541
3542                 /*
3543                  * Use the CaseTestExpr mechanism to pass down the old value of the
3544                  * field being replaced; this is useful in case we have a nested field
3545                  * update situation.  It's safe to reuse the CASE mechanism because
3546                  * there cannot be a CASE between here and where the value would be
3547                  * needed.
3548                  */
3549                 econtext->caseValue_datum = values[fieldnum - 1];
3550                 econtext->caseValue_isNull = isnull[fieldnum - 1];
3551
3552                 values[fieldnum - 1] = ExecEvalExpr(newval,
3553                                                                                         econtext,
3554                                                                                         &isnull[fieldnum - 1],
3555                                                                                         NULL);
3556         }
3557
3558         econtext->caseValue_datum = save_datum;
3559         econtext->caseValue_isNull = save_isNull;
3560
3561         tuple = heap_form_tuple(tupDesc, values, isnull);
3562
3563         pfree(values);
3564         pfree(isnull);
3565
3566         return HeapTupleGetDatum(tuple);
3567 }
3568
3569 /* ----------------------------------------------------------------
3570  *              ExecEvalRelabelType
3571  *
3572  *              Evaluate a RelabelType node.
3573  * ----------------------------------------------------------------
3574  */
3575 static Datum
3576 ExecEvalRelabelType(GenericExprState *exprstate,
3577                                         ExprContext *econtext,
3578                                         bool *isNull, ExprDoneCond *isDone)
3579 {
3580         return ExecEvalExpr(exprstate->arg, econtext, isNull, isDone);
3581 }
3582
3583 /* ----------------------------------------------------------------
3584  *              ExecEvalCoerceViaIO
3585  *
3586  *              Evaluate a CoerceViaIO node.
3587  * ----------------------------------------------------------------
3588  */
3589 static Datum
3590 ExecEvalCoerceViaIO(CoerceViaIOState *iostate,
3591                                         ExprContext *econtext,
3592                                         bool *isNull, ExprDoneCond *isDone)
3593 {
3594         Datum           result;
3595         Datum           inputval;
3596         char       *string;
3597
3598         inputval = ExecEvalExpr(iostate->arg, econtext, isNull, isDone);
3599
3600         if (isDone && *isDone == ExprEndResult)
3601                 return inputval;                /* nothing to do */
3602
3603         if (*isNull)
3604                 string = NULL;                  /* output functions are not called on nulls */
3605         else
3606                 string = OutputFunctionCall(&iostate->outfunc, inputval);
3607
3608         result = InputFunctionCall(&iostate->infunc,
3609                                                            string,
3610                                                            iostate->intypioparam,
3611                                                            -1);
3612
3613         /* The input function cannot change the null/not-null status */
3614         return result;
3615 }
3616
3617 /* ----------------------------------------------------------------
3618  *              ExecEvalArrayCoerceExpr
3619  *
3620  *              Evaluate an ArrayCoerceExpr node.
3621  * ----------------------------------------------------------------
3622  */
3623 static Datum
3624 ExecEvalArrayCoerceExpr(ArrayCoerceExprState *astate,
3625                                                 ExprContext *econtext,
3626                                                 bool *isNull, ExprDoneCond *isDone)
3627 {
3628         ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) astate->xprstate.expr;
3629         Datum           result;
3630         ArrayType  *array;
3631         FunctionCallInfoData locfcinfo;
3632
3633         result = ExecEvalExpr(astate->arg, econtext, isNull, isDone);
3634
3635         if (isDone && *isDone == ExprEndResult)
3636                 return result;                  /* nothing to do */
3637         if (*isNull)
3638                 return result;                  /* nothing to do */
3639
3640         /*
3641          * If it's binary-compatible, modify the element type in the array header,
3642          * but otherwise leave the array as we received it.
3643          */
3644         if (!OidIsValid(acoerce->elemfuncid))
3645         {
3646                 /* Detoast input array if necessary, and copy in any case */
3647                 array = DatumGetArrayTypePCopy(result);
3648                 ARR_ELEMTYPE(array) = astate->resultelemtype;
3649                 PG_RETURN_ARRAYTYPE_P(array);
3650         }
3651
3652         /* Detoast input array if necessary, but don't make a useless copy */
3653         array = DatumGetArrayTypeP(result);
3654
3655         /* Initialize function cache if first time through */
3656         if (astate->elemfunc.fn_oid == InvalidOid)
3657         {
3658                 AclResult       aclresult;
3659
3660                 /* Check permission to call function */
3661                 aclresult = pg_proc_aclcheck(acoerce->elemfuncid, GetUserId(),
3662                                                                          ACL_EXECUTE);
3663                 if (aclresult != ACLCHECK_OK)
3664                         aclcheck_error(aclresult, ACL_KIND_PROC,
3665                                                    get_func_name(acoerce->elemfuncid));
3666
3667                 /* Set up the primary fmgr lookup information */
3668                 fmgr_info_cxt(acoerce->elemfuncid, &(astate->elemfunc),
3669                                           econtext->ecxt_per_query_memory);
3670
3671                 /* Initialize additional info */
3672                 astate->elemfunc.fn_expr = (Node *) acoerce;
3673         }
3674
3675         /*
3676          * Use array_map to apply the function to each array element.
3677          *
3678          * We pass on the desttypmod and isExplicit flags whether or not the
3679          * function wants them.
3680          */
3681         InitFunctionCallInfoData(locfcinfo, &(astate->elemfunc), 3,
3682                                                          NULL, NULL);
3683         locfcinfo.arg[0] = PointerGetDatum(array);
3684         locfcinfo.arg[1] = Int32GetDatum(acoerce->resulttypmod);
3685         locfcinfo.arg[2] = BoolGetDatum(acoerce->isExplicit);
3686         locfcinfo.argnull[0] = false;
3687         locfcinfo.argnull[1] = false;
3688         locfcinfo.argnull[2] = false;
3689
3690         return array_map(&locfcinfo, ARR_ELEMTYPE(array), astate->resultelemtype,
3691                                          astate->amstate);
3692 }
3693
3694 /* ----------------------------------------------------------------
3695  *              ExecEvalCurrentOfExpr
3696  *
3697  * Normally, the planner will convert CURRENT OF into a TidScan qualification,
3698  * but we have plain execQual support in case it doesn't.
3699  * ----------------------------------------------------------------
3700  */
3701 static Datum
3702 ExecEvalCurrentOfExpr(ExprState *exprstate, ExprContext *econtext,
3703                                           bool *isNull, ExprDoneCond *isDone)
3704 {
3705         CurrentOfExpr *cexpr = (CurrentOfExpr *) exprstate->expr;
3706         bool    result;
3707         bool    lisnull;
3708         Oid             tableoid;
3709         ItemPointer tuple_tid;
3710         ItemPointerData cursor_tid;
3711
3712         if (isDone)
3713                 *isDone = ExprSingleResult;
3714         *isNull = false;
3715
3716         Assert(cexpr->cvarno != INNER);
3717         Assert(cexpr->cvarno != OUTER);
3718         Assert(!TupIsNull(econtext->ecxt_scantuple));
3719         /* Use slot_getattr to catch any possible mistakes */
3720         tableoid = DatumGetObjectId(slot_getattr(econtext->ecxt_scantuple,
3721                                                                                          TableOidAttributeNumber,
3722                                                                                          &lisnull));
3723         Assert(!lisnull);
3724         tuple_tid = (ItemPointer)
3725                 DatumGetPointer(slot_getattr(econtext->ecxt_scantuple,
3726                                                                          SelfItemPointerAttributeNumber,
3727                                                                          &lisnull));
3728         Assert(!lisnull);
3729
3730         if (execCurrentOf(cexpr, econtext, tableoid, &cursor_tid))
3731                 result = ItemPointerEquals(&cursor_tid, tuple_tid);
3732         else
3733                 result = false;
3734
3735         return BoolGetDatum(result);
3736 }
3737
3738
3739 /*
3740  * ExecEvalExprSwitchContext
3741  *
3742  * Same as ExecEvalExpr, but get into the right allocation context explicitly.
3743  */
3744 Datum
3745 ExecEvalExprSwitchContext(ExprState *expression,
3746                                                   ExprContext *econtext,
3747                                                   bool *isNull,
3748                                                   ExprDoneCond *isDone)
3749 {
3750         Datum           retDatum;
3751         MemoryContext oldContext;
3752
3753         oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
3754         retDatum = ExecEvalExpr(expression, econtext, isNull, isDone);
3755         MemoryContextSwitchTo(oldContext);
3756         return retDatum;
3757 }
3758
3759
3760 /*
3761  * ExecInitExpr: prepare an expression tree for execution
3762  *
3763  * This function builds and returns an ExprState tree paralleling the given
3764  * Expr node tree.      The ExprState tree can then be handed to ExecEvalExpr
3765  * for execution.  Because the Expr tree itself is read-only as far as
3766  * ExecInitExpr and ExecEvalExpr are concerned, several different executions
3767  * of the same plan tree can occur concurrently.
3768  *
3769  * This must be called in a memory context that will last as long as repeated
3770  * executions of the expression are needed.  Typically the context will be
3771  * the same as the per-query context of the associated ExprContext.
3772  *
3773  * Any Aggref and SubPlan nodes found in the tree are added to the lists
3774  * of such nodes held by the parent PlanState.  Otherwise, we do very little
3775  * initialization here other than building the state-node tree.  Any nontrivial
3776  * work associated with initializing runtime info for a node should happen
3777  * during the first actual evaluation of that node.  (This policy lets us
3778  * avoid work if the node is never actually evaluated.)
3779  *
3780  * Note: there is no ExecEndExpr function; we assume that any resource
3781  * cleanup needed will be handled by just releasing the memory context
3782  * in which the state tree is built.  Functions that require additional
3783  * cleanup work can register a shutdown callback in the ExprContext.
3784  *
3785  *      'node' is the root of the expression tree to examine
3786  *      'parent' is the PlanState node that owns the expression.
3787  *
3788  * 'parent' may be NULL if we are preparing an expression that is not
3789  * associated with a plan tree.  (If so, it can't have aggs or subplans.)
3790  * This case should usually come through ExecPrepareExpr, not directly here.
3791  */
3792 ExprState *
3793 ExecInitExpr(Expr *node, PlanState *parent)
3794 {
3795         ExprState  *state;
3796
3797         if (node == NULL)
3798                 return NULL;
3799
3800         /* Guard against stack overflow due to overly complex expressions */
3801         check_stack_depth();
3802
3803         switch (nodeTag(node))
3804         {
3805                 case T_Var:
3806                         state = (ExprState *) makeNode(ExprState);
3807                         state->evalfunc = ExecEvalVar;
3808                         break;
3809                 case T_Const:
3810                         state = (ExprState *) makeNode(ExprState);
3811                         state->evalfunc = ExecEvalConst;
3812                         break;
3813                 case T_Param:
3814                         state = (ExprState *) makeNode(ExprState);
3815                         state->evalfunc = ExecEvalParam;
3816                         break;
3817                 case T_CoerceToDomainValue:
3818                         state = (ExprState *) makeNode(ExprState);
3819                         state->evalfunc = ExecEvalCoerceToDomainValue;
3820                         break;
3821                 case T_CaseTestExpr:
3822                         state = (ExprState *) makeNode(ExprState);
3823                         state->evalfunc = ExecEvalCaseTestExpr;
3824                         break;
3825                 case T_Aggref:
3826                         {
3827                                 Aggref     *aggref = (Aggref *) node;
3828                                 AggrefExprState *astate = makeNode(AggrefExprState);
3829
3830                                 astate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalAggref;
3831                                 if (parent && IsA(parent, AggState))
3832                                 {
3833                                         AggState   *aggstate = (AggState *) parent;
3834                                         int                     naggs;
3835
3836                                         aggstate->aggs = lcons(astate, aggstate->aggs);
3837                                         naggs = ++aggstate->numaggs;
3838
3839                                         astate->args = (List *) ExecInitExpr((Expr *) aggref->args,
3840                                                                                                                  parent);
3841
3842                                         /*
3843                                          * Complain if the aggregate's arguments contain any
3844                                          * aggregates; nested agg functions are semantically
3845                                          * nonsensical.  (This should have been caught earlier,
3846                                          * but we defend against it here anyway.)
3847                                          */
3848                                         if (naggs != aggstate->numaggs)
3849                                                 ereport(ERROR,
3850                                                                 (errcode(ERRCODE_GROUPING_ERROR),
3851                                                                  errmsg("aggregate function calls cannot be nested")));
3852                                 }
3853                                 else
3854                                 {
3855                                         /* planner messed up */
3856                                         elog(ERROR, "aggref found in non-Agg plan node");
3857                                 }
3858                                 state = (ExprState *) astate;
3859                         }
3860                         break;
3861                 case T_ArrayRef:
3862                         {
3863                                 ArrayRef   *aref = (ArrayRef *) node;
3864                                 ArrayRefExprState *astate = makeNode(ArrayRefExprState);
3865
3866                                 astate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalArrayRef;
3867                                 astate->refupperindexpr = (List *)
3868                                         ExecInitExpr((Expr *) aref->refupperindexpr, parent);
3869                                 astate->reflowerindexpr = (List *)
3870                                         ExecInitExpr((Expr *) aref->reflowerindexpr, parent);
3871                                 astate->refexpr = ExecInitExpr(aref->refexpr, parent);
3872                                 astate->refassgnexpr = ExecInitExpr(aref->refassgnexpr,
3873                                                                                                         parent);
3874                                 /* do one-time catalog lookups for type info */
3875                                 astate->refattrlength = get_typlen(aref->refarraytype);
3876                                 get_typlenbyvalalign(aref->refelemtype,
3877                                                                          &astate->refelemlength,
3878                                                                          &astate->refelembyval,
3879                                                                          &astate->refelemalign);
3880                                 state = (ExprState *) astate;
3881                         }
3882                         break;
3883                 case T_FuncExpr:
3884                         {
3885                                 FuncExpr   *funcexpr = (FuncExpr *) node;
3886                                 FuncExprState *fstate = makeNode(FuncExprState);
3887
3888                                 fstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalFunc;
3889                                 fstate->args = (List *)
3890                                         ExecInitExpr((Expr *) funcexpr->args, parent);
3891                                 fstate->func.fn_oid = InvalidOid;               /* not initialized */
3892                                 state = (ExprState *) fstate;
3893                         }
3894                         break;
3895                 case T_OpExpr:
3896                         {
3897                                 OpExpr     *opexpr = (OpExpr *) node;
3898                                 FuncExprState *fstate = makeNode(FuncExprState);
3899
3900                                 fstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalOper;
3901                                 fstate->args = (List *)
3902                                         ExecInitExpr((Expr *) opexpr->args, parent);
3903                                 fstate->func.fn_oid = InvalidOid;               /* not initialized */
3904                                 state = (ExprState *) fstate;
3905                         }
3906                         break;
3907                 case T_DistinctExpr:
3908                         {
3909                                 DistinctExpr *distinctexpr = (DistinctExpr *) node;
3910                                 FuncExprState *fstate = makeNode(FuncExprState);
3911
3912                                 fstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalDistinct;
3913                                 fstate->args = (List *)
3914                                         ExecInitExpr((Expr *) distinctexpr->args, parent);
3915                                 fstate->func.fn_oid = InvalidOid;               /* not initialized */
3916                                 state = (ExprState *) fstate;
3917                         }
3918                         break;
3919                 case T_ScalarArrayOpExpr:
3920                         {
3921                                 ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) node;
3922                                 ScalarArrayOpExprState *sstate = makeNode(ScalarArrayOpExprState);
3923
3924                                 sstate->fxprstate.xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalScalarArrayOp;
3925                                 sstate->fxprstate.args = (List *)
3926                                         ExecInitExpr((Expr *) opexpr->args, parent);
3927                                 sstate->fxprstate.func.fn_oid = InvalidOid;             /* not initialized */
3928                                 sstate->element_type = InvalidOid;              /* ditto */
3929                                 state = (ExprState *) sstate;
3930                         }
3931                         break;
3932                 case T_BoolExpr:
3933                         {
3934                                 BoolExpr   *boolexpr = (BoolExpr *) node;
3935                                 BoolExprState *bstate = makeNode(BoolExprState);
3936
3937                                 switch (boolexpr->boolop)
3938                                 {
3939                                         case AND_EXPR:
3940                                                 bstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalAnd;
3941                                                 break;
3942                                         case OR_EXPR:
3943                                                 bstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalOr;
3944                                                 break;
3945                                         case NOT_EXPR:
3946                                                 bstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalNot;
3947                                                 break;
3948                                         default:
3949                                                 elog(ERROR, "unrecognized boolop: %d",
3950                                                          (int) boolexpr->boolop);
3951                                                 break;
3952                                 }
3953                                 bstate->args = (List *)
3954                                         ExecInitExpr((Expr *) boolexpr->args, parent);
3955                                 state = (ExprState *) bstate;
3956                         }
3957                         break;
3958                 case T_SubPlan:
3959                         {
3960                                 SubPlan    *subplan = (SubPlan *) node;
3961                                 SubPlanState *sstate;
3962
3963                                 if (!parent)
3964                                         elog(ERROR, "SubPlan found with no parent plan");
3965
3966                                 sstate = ExecInitSubPlan(subplan, parent);
3967
3968                                 /* Add SubPlanState nodes to parent->subPlan */
3969                                 parent->subPlan = lcons(sstate, parent->subPlan);
3970
3971                                 state = (ExprState *) sstate;
3972                         }
3973                         break;
3974                 case T_FieldSelect:
3975                         {
3976                                 FieldSelect *fselect = (FieldSelect *) node;
3977                                 FieldSelectState *fstate = makeNode(FieldSelectState);
3978
3979                                 fstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalFieldSelect;
3980                                 fstate->arg = ExecInitExpr(fselect->arg, parent);
3981                                 fstate->argdesc = NULL;
3982                                 state = (ExprState *) fstate;
3983                         }
3984                         break;
3985                 case T_FieldStore:
3986                         {
3987                                 FieldStore *fstore = (FieldStore *) node;
3988                                 FieldStoreState *fstate = makeNode(FieldStoreState);
3989
3990                                 fstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalFieldStore;
3991                                 fstate->arg = ExecInitExpr(fstore->arg, parent);
3992                                 fstate->newvals = (List *) ExecInitExpr((Expr *) fstore->newvals, parent);
3993                                 fstate->argdesc = NULL;
3994                                 state = (ExprState *) fstate;
3995                         }
3996                         break;
3997                 case T_RelabelType:
3998                         {
3999                                 RelabelType *relabel = (RelabelType *) node;
4000                                 GenericExprState *gstate = makeNode(GenericExprState);
4001
4002                                 gstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalRelabelType;
4003                                 gstate->arg = ExecInitExpr(relabel->arg, parent);
4004                                 state = (ExprState *) gstate;
4005                         }
4006                         break;
4007                 case T_CoerceViaIO:
4008                         {
4009                                 CoerceViaIO *iocoerce = (CoerceViaIO *) node;
4010                                 CoerceViaIOState *iostate = makeNode(CoerceViaIOState);
4011                                 Oid             iofunc;
4012                                 bool    typisvarlena;
4013
4014                                 iostate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalCoerceViaIO;
4015                                 iostate->arg = ExecInitExpr(iocoerce->arg, parent);
4016                                 /* lookup the result type's input function */
4017                                 getTypeInputInfo(iocoerce->resulttype, &iofunc,
4018                                                                  &iostate->intypioparam);
4019                                 fmgr_info(iofunc, &iostate->infunc);
4020                                 /* lookup the input type's output function */
4021                                 getTypeOutputInfo(exprType((Node *) iocoerce->arg),
4022                                                                   &iofunc, &typisvarlena);
4023                                 fmgr_info(iofunc, &iostate->outfunc);
4024                                 state = (ExprState *) iostate;
4025                         }
4026                         break;
4027                 case T_ArrayCoerceExpr:
4028                         {
4029                                 ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
4030                                 ArrayCoerceExprState *astate = makeNode(ArrayCoerceExprState);
4031
4032                                 astate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalArrayCoerceExpr;
4033                                 astate->arg = ExecInitExpr(acoerce->arg, parent);
4034                                 astate->resultelemtype = get_element_type(acoerce->resulttype);
4035                                 if (astate->resultelemtype == InvalidOid)
4036                                         ereport(ERROR,
4037                                                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4038                                                          errmsg("target type is not an array")));
4039                                 /* Arrays over domains aren't supported yet */
4040                                 Assert(getBaseType(astate->resultelemtype) ==
4041                                            astate->resultelemtype);
4042                                 astate->elemfunc.fn_oid = InvalidOid;   /* not initialized */
4043                                 astate->amstate = (ArrayMapState *) palloc0(sizeof(ArrayMapState));
4044                                 state = (ExprState *) astate;
4045                         }
4046                         break;
4047                 case T_ConvertRowtypeExpr:
4048                         {
4049                                 ConvertRowtypeExpr *convert = (ConvertRowtypeExpr *) node;
4050                                 ConvertRowtypeExprState *cstate = makeNode(ConvertRowtypeExprState);
4051
4052                                 cstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalConvertRowtype;
4053                                 cstate->arg = ExecInitExpr(convert->arg, parent);
4054                                 state = (ExprState *) cstate;
4055                         }
4056                         break;
4057                 case T_CaseExpr:
4058                         {
4059                                 CaseExpr   *caseexpr = (CaseExpr *) node;
4060                                 CaseExprState *cstate = makeNode(CaseExprState);
4061                                 List       *outlist = NIL;
4062                                 ListCell   *l;
4063
4064                                 cstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalCase;
4065                                 cstate->arg = ExecInitExpr(caseexpr->arg, parent);
4066                                 foreach(l, caseexpr->args)
4067                                 {
4068                                         CaseWhen   *when = (CaseWhen *) lfirst(l);
4069                                         CaseWhenState *wstate = makeNode(CaseWhenState);
4070
4071                                         Assert(IsA(when, CaseWhen));
4072                                         wstate->xprstate.evalfunc = NULL;       /* not used */
4073                                         wstate->xprstate.expr = (Expr *) when;
4074                                         wstate->expr = ExecInitExpr(when->expr, parent);
4075                                         wstate->result = ExecInitExpr(when->result, parent);
4076                                         outlist = lappend(outlist, wstate);
4077                                 }
4078                                 cstate->args = outlist;
4079                                 cstate->defresult = ExecInitExpr(caseexpr->defresult, parent);
4080                                 state = (ExprState *) cstate;
4081                         }
4082                         break;
4083                 case T_ArrayExpr:
4084                         {
4085                                 ArrayExpr  *arrayexpr = (ArrayExpr *) node;
4086                                 ArrayExprState *astate = makeNode(ArrayExprState);
4087                                 List       *outlist = NIL;
4088                                 ListCell   *l;
4089
4090                                 astate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalArray;
4091                                 foreach(l, arrayexpr->elements)
4092                                 {
4093                                         Expr       *e = (Expr *) lfirst(l);
4094                                         ExprState  *estate;
4095
4096                                         estate = ExecInitExpr(e, parent);
4097                                         outlist = lappend(outlist, estate);
4098                                 }
4099                                 astate->elements = outlist;
4100                                 /* do one-time catalog lookup for type info */
4101                                 get_typlenbyvalalign(arrayexpr->element_typeid,
4102                                                                          &astate->elemlength,
4103                                                                          &astate->elembyval,
4104                                                                          &astate->elemalign);
4105                                 state = (ExprState *) astate;
4106                         }
4107                         break;
4108                 case T_RowExpr:
4109                         {
4110                                 RowExpr    *rowexpr = (RowExpr *) node;
4111                                 RowExprState *rstate = makeNode(RowExprState);
4112                                 Form_pg_attribute *attrs;
4113                                 List       *outlist = NIL;
4114                                 ListCell   *l;
4115                                 int                     i;
4116
4117                                 rstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalRow;
4118                                 /* Build tupdesc to describe result tuples */
4119                                 if (rowexpr->row_typeid == RECORDOID)
4120                                 {
4121                                         /* generic record, use runtime type assignment */
4122                                         rstate->tupdesc = ExecTypeFromExprList(rowexpr->args);
4123                                         BlessTupleDesc(rstate->tupdesc);
4124                                         /* we won't need to redo this at runtime */
4125                                 }
4126                                 else
4127                                 {
4128                                         /* it's been cast to a named type, use that */
4129                                         rstate->tupdesc = lookup_rowtype_tupdesc_copy(rowexpr->row_typeid, -1);
4130                                 }
4131                                 /* Set up evaluation, skipping any deleted columns */
4132                                 Assert(list_length(rowexpr->args) <= rstate->tupdesc->natts);
4133                                 attrs = rstate->tupdesc->attrs;
4134                                 i = 0;
4135                                 foreach(l, rowexpr->args)
4136                                 {
4137                                         Expr       *e = (Expr *) lfirst(l);
4138                                         ExprState  *estate;
4139
4140                                         if (!attrs[i]->attisdropped)
4141                                         {
4142                                                 /*
4143                                                  * Guard against ALTER COLUMN TYPE on rowtype since
4144                                                  * the RowExpr was created.  XXX should we check
4145                                                  * typmod too?  Not sure we can be sure it'll be the
4146                                                  * same.
4147                                                  */
4148                                                 if (exprType((Node *) e) != attrs[i]->atttypid)
4149                                                         ereport(ERROR,
4150                                                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
4151                                                                          errmsg("ROW() column has type %s instead of type %s",
4152                                                                                 format_type_be(exprType((Node *) e)),
4153                                                                            format_type_be(attrs[i]->atttypid))));
4154                                         }
4155                                         else
4156                                         {
4157                                                 /*
4158                                                  * Ignore original expression and insert a NULL. We
4159                                                  * don't really care what type of NULL it is, so
4160                                                  * always make an int4 NULL.
4161                                                  */
4162                                                 e = (Expr *) makeNullConst(INT4OID, -1);
4163                                         }
4164                                         estate = ExecInitExpr(e, parent);
4165                                         outlist = lappend(outlist, estate);
4166                                         i++;
4167                                 }
4168                                 rstate->args = outlist;
4169                                 state = (ExprState *) rstate;
4170                         }
4171                         break;
4172                 case T_RowCompareExpr:
4173                         {
4174                                 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
4175                                 RowCompareExprState *rstate = makeNode(RowCompareExprState);
4176                                 int                     nopers = list_length(rcexpr->opnos);
4177                                 List       *outlist;
4178                                 ListCell   *l;
4179                                 ListCell   *l2;
4180                                 int                     i;
4181
4182                                 rstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalRowCompare;
4183                                 Assert(list_length(rcexpr->largs) == nopers);
4184                                 outlist = NIL;
4185                                 foreach(l, rcexpr->largs)
4186                                 {
4187                                         Expr       *e = (Expr *) lfirst(l);
4188                                         ExprState  *estate;
4189
4190                                         estate = ExecInitExpr(e, parent);
4191                                         outlist = lappend(outlist, estate);
4192                                 }
4193                                 rstate->largs = outlist;
4194                                 Assert(list_length(rcexpr->rargs) == nopers);
4195                                 outlist = NIL;
4196                                 foreach(l, rcexpr->rargs)
4197                                 {
4198                                         Expr       *e = (Expr *) lfirst(l);
4199                                         ExprState  *estate;
4200
4201                                         estate = ExecInitExpr(e, parent);
4202                                         outlist = lappend(outlist, estate);
4203                                 }
4204                                 rstate->rargs = outlist;
4205                                 Assert(list_length(rcexpr->opfamilies) == nopers);
4206                                 rstate->funcs = (FmgrInfo *) palloc(nopers * sizeof(FmgrInfo));
4207                                 i = 0;
4208                                 forboth(l, rcexpr->opnos, l2, rcexpr->opfamilies)
4209                                 {
4210                                         Oid                     opno = lfirst_oid(l);
4211                                         Oid                     opfamily = lfirst_oid(l2);
4212                                         int                     strategy;
4213                                         Oid                     lefttype;
4214                                         Oid                     righttype;
4215                                         bool            recheck;
4216                                         Oid                     proc;
4217
4218                                         get_op_opfamily_properties(opno, opfamily,
4219                                                                                            &strategy,
4220                                                                                            &lefttype,
4221                                                                                            &righttype,
4222                                                                                            &recheck);
4223                                         proc = get_opfamily_proc(opfamily,
4224                                                                                          lefttype,
4225                                                                                          righttype,
4226                                                                                          BTORDER_PROC);
4227
4228                                         /*
4229                                          * If we enforced permissions checks on index support
4230                                          * functions, we'd need to make a check here.  But the
4231                                          * index support machinery doesn't do that, and neither
4232                                          * does this code.
4233                                          */
4234                                         fmgr_info(proc, &(rstate->funcs[i]));
4235                                         i++;
4236                                 }
4237                                 state = (ExprState *) rstate;
4238                         }
4239                         break;
4240                 case T_CoalesceExpr:
4241                         {
4242                                 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
4243                                 CoalesceExprState *cstate = makeNode(CoalesceExprState);
4244                                 List       *outlist = NIL;
4245                                 ListCell   *l;
4246
4247                                 cstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalCoalesce;
4248                                 foreach(l, coalesceexpr->args)
4249                                 {
4250                                         Expr       *e = (Expr *) lfirst(l);
4251                                         ExprState  *estate;
4252
4253                                         estate = ExecInitExpr(e, parent);
4254                                         outlist = lappend(outlist, estate);
4255                                 }
4256                                 cstate->args = outlist;
4257                                 state = (ExprState *) cstate;
4258                         }
4259                         break;
4260                 case T_MinMaxExpr:
4261                         {
4262                                 MinMaxExpr *minmaxexpr = (MinMaxExpr *) node;
4263                                 MinMaxExprState *mstate = makeNode(MinMaxExprState);
4264                                 List       *outlist = NIL;
4265                                 ListCell   *l;
4266                                 TypeCacheEntry *typentry;
4267
4268                                 mstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalMinMax;
4269                                 foreach(l, minmaxexpr->args)
4270                                 {
4271                                         Expr       *e = (Expr *) lfirst(l);
4272                                         ExprState  *estate;
4273
4274                                         estate = ExecInitExpr(e, parent);
4275                                         outlist = lappend(outlist, estate);
4276                                 }
4277                                 mstate->args = outlist;
4278                                 /* Look up the btree comparison function for the datatype */
4279                                 typentry = lookup_type_cache(minmaxexpr->minmaxtype,
4280                                                                                          TYPECACHE_CMP_PROC);
4281                                 if (!OidIsValid(typentry->cmp_proc))
4282                                         ereport(ERROR,
4283                                                         (errcode(ERRCODE_UNDEFINED_FUNCTION),
4284                                                          errmsg("could not identify a comparison function for type %s",
4285                                                                         format_type_be(minmaxexpr->minmaxtype))));
4286
4287                                 /*
4288                                  * If we enforced permissions checks on index support
4289                                  * functions, we'd need to make a check here.  But the index
4290                                  * support machinery doesn't do that, and neither does this
4291                                  * code.
4292                                  */
4293                                 fmgr_info(typentry->cmp_proc, &(mstate->cfunc));
4294                                 state = (ExprState *) mstate;
4295                         }
4296                         break;
4297                 case T_XmlExpr:
4298                         {
4299                                 XmlExpr                 *xexpr = (XmlExpr *) node;
4300                                 XmlExprState    *xstate = makeNode(XmlExprState);
4301                                 List                    *outlist;
4302                                 ListCell                *arg;
4303                                 int                             i;
4304
4305                                 xstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalXml;
4306                                 xstate->named_outfuncs = (FmgrInfo *)
4307                                         palloc0(list_length(xexpr->named_args) * sizeof(FmgrInfo));
4308                                 outlist = NIL;
4309                                 i = 0;
4310                                 foreach(arg, xexpr->named_args)
4311                                 {
4312                                         Expr            *e = (Expr *) lfirst(arg);
4313                                         ExprState       *estate;
4314                                         Oid                     typOutFunc;
4315                                         bool            typIsVarlena;
4316
4317                                         estate = ExecInitExpr(e, parent);
4318                                         outlist = lappend(outlist, estate);
4319
4320                                         getTypeOutputInfo(exprType((Node *) e),
4321                                                                           &typOutFunc, &typIsVarlena);
4322                                         fmgr_info(typOutFunc, &xstate->named_outfuncs[i]);
4323                                         i++;
4324                                 }
4325                                 xstate->named_args = outlist;
4326
4327                                 outlist = NIL;
4328                                 foreach(arg, xexpr->args)
4329                                 {
4330                                         Expr            *e = (Expr *) lfirst(arg);
4331                                         ExprState       *estate;
4332
4333                                         estate = ExecInitExpr(e, parent);
4334                                         outlist = lappend(outlist, estate);
4335                                 }
4336                                 xstate->args = outlist;
4337
4338                                 state = (ExprState *) xstate;
4339                         }
4340                         break;
4341                 case T_NullIfExpr:
4342                         {
4343                                 NullIfExpr *nullifexpr = (NullIfExpr *) node;
4344                                 FuncExprState *fstate = makeNode(FuncExprState);
4345
4346                                 fstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalNullIf;
4347                                 fstate->args = (List *)
4348                                         ExecInitExpr((Expr *) nullifexpr->args, parent);
4349                                 fstate->func.fn_oid = InvalidOid;               /* not initialized */
4350                                 state = (ExprState *) fstate;
4351                         }
4352                         break;
4353                 case T_NullTest:
4354                         {
4355                                 NullTest   *ntest = (NullTest *) node;
4356                                 NullTestState *nstate = makeNode(NullTestState);
4357
4358                                 nstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalNullTest;
4359                                 nstate->arg = ExecInitExpr(ntest->arg, parent);
4360                                 nstate->argisrow = type_is_rowtype(exprType((Node *) ntest->arg));
4361                                 nstate->argdesc = NULL;
4362                                 state = (ExprState *) nstate;
4363                         }
4364                         break;
4365                 case T_BooleanTest:
4366                         {
4367                                 BooleanTest *btest = (BooleanTest *) node;
4368                                 GenericExprState *gstate = makeNode(GenericExprState);
4369
4370                                 gstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalBooleanTest;
4371                                 gstate->arg = ExecInitExpr(btest->arg, parent);
4372                                 state = (ExprState *) gstate;
4373                         }
4374                         break;
4375                 case T_CoerceToDomain:
4376                         {
4377                                 CoerceToDomain *ctest = (CoerceToDomain *) node;
4378                                 CoerceToDomainState *cstate = makeNode(CoerceToDomainState);
4379
4380                                 cstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalCoerceToDomain;
4381                                 cstate->arg = ExecInitExpr(ctest->arg, parent);
4382                                 cstate->constraints = GetDomainConstraints(ctest->resulttype);
4383                                 state = (ExprState *) cstate;
4384                         }
4385                         break;
4386                 case T_CurrentOfExpr:
4387                         state = (ExprState *) makeNode(ExprState);
4388                         state->evalfunc = ExecEvalCurrentOfExpr;
4389                         break;
4390                 case T_TargetEntry:
4391                         {
4392                                 TargetEntry *tle = (TargetEntry *) node;
4393                                 GenericExprState *gstate = makeNode(GenericExprState);
4394
4395                                 gstate->xprstate.evalfunc = NULL;               /* not used */
4396                                 gstate->arg = ExecInitExpr(tle->expr, parent);
4397                                 state = (ExprState *) gstate;
4398                         }
4399                         break;
4400                 case T_List:
4401                         {
4402                                 List       *outlist = NIL;
4403                                 ListCell   *l;
4404
4405                                 foreach(l, (List *) node)
4406                                 {
4407                                         outlist = lappend(outlist,
4408                                                                           ExecInitExpr((Expr *) lfirst(l),
4409                                                                                                    parent));
4410                                 }
4411                                 /* Don't fall through to the "common" code below */
4412                                 return (ExprState *) outlist;
4413                         }
4414                 default:
4415                         elog(ERROR, "unrecognized node type: %d",
4416                                  (int) nodeTag(node));
4417                         state = NULL;           /* keep compiler quiet */
4418                         break;
4419         }
4420
4421         /* Common code for all state-node types */
4422         state->expr = node;
4423
4424         return state;
4425 }
4426
4427 /*
4428  * ExecPrepareExpr --- initialize for expression execution outside a normal
4429  * Plan tree context.
4430  *
4431  * This differs from ExecInitExpr in that we don't assume the caller is
4432  * already running in the EState's per-query context.  Also, we apply
4433  * fix_opfuncids() to the passed expression tree to be sure it is ready
4434  * to run.      (In ordinary Plan trees the planner will have fixed opfuncids,
4435  * but callers outside the executor will not have done this.)
4436  */
4437 ExprState *
4438 ExecPrepareExpr(Expr *node, EState *estate)
4439 {
4440         ExprState  *result;
4441         MemoryContext oldcontext;
4442
4443         fix_opfuncids((Node *) node);
4444
4445         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
4446
4447         result = ExecInitExpr(node, NULL);
4448
4449         MemoryContextSwitchTo(oldcontext);
4450
4451         return result;
4452 }
4453
4454
4455 /* ----------------------------------------------------------------
4456  *                                       ExecQual / ExecTargetList / ExecProject
4457  * ----------------------------------------------------------------
4458  */
4459
4460 /* ----------------------------------------------------------------
4461  *              ExecQual
4462  *
4463  *              Evaluates a conjunctive boolean expression (qual list) and
4464  *              returns true iff none of the subexpressions are false.
4465  *              (We also return true if the list is empty.)
4466  *
4467  *      If some of the subexpressions yield NULL but none yield FALSE,
4468  *      then the result of the conjunction is NULL (ie, unknown)
4469  *      according to three-valued boolean logic.  In this case,
4470  *      we return the value specified by the "resultForNull" parameter.
4471  *
4472  *      Callers evaluating WHERE clauses should pass resultForNull=FALSE,
4473  *      since SQL specifies that tuples with null WHERE results do not
4474  *      get selected.  On the other hand, callers evaluating constraint
4475  *      conditions should pass resultForNull=TRUE, since SQL also specifies
4476  *      that NULL constraint conditions are not failures.
4477  *
4478  *      NOTE: it would not be correct to use this routine to evaluate an
4479  *      AND subclause of a boolean expression; for that purpose, a NULL
4480  *      result must be returned as NULL so that it can be properly treated
4481  *      in the next higher operator (cf. ExecEvalAnd and ExecEvalOr).
4482  *      This routine is only used in contexts where a complete expression
4483  *      is being evaluated and we know that NULL can be treated the same
4484  *      as one boolean result or the other.
4485  *
4486  * ----------------------------------------------------------------
4487  */
4488 bool
4489 ExecQual(List *qual, ExprContext *econtext, bool resultForNull)
4490 {
4491         bool            result;
4492         MemoryContext oldContext;
4493         ListCell   *l;
4494
4495         /*
4496          * debugging stuff
4497          */
4498         EV_printf("ExecQual: qual is ");
4499         EV_nodeDisplay(qual);
4500         EV_printf("\n");
4501
4502         IncrProcessed();
4503
4504         /*
4505          * Run in short-lived per-tuple context while computing expressions.
4506          */
4507         oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
4508
4509         /*
4510          * Evaluate the qual conditions one at a time.  If we find a FALSE result,
4511          * we can stop evaluating and return FALSE --- the AND result must be
4512          * FALSE.  Also, if we find a NULL result when resultForNull is FALSE, we
4513          * can stop and return FALSE --- the AND result must be FALSE or NULL in
4514          * that case, and the caller doesn't care which.
4515          *
4516          * If we get to the end of the list, we can return TRUE.  This will happen
4517          * when the AND result is indeed TRUE, or when the AND result is NULL (one
4518          * or more NULL subresult, with all the rest TRUE) and the caller has
4519          * specified resultForNull = TRUE.
4520          */
4521         result = true;
4522
4523         foreach(l, qual)
4524         {
4525                 ExprState  *clause = (ExprState *) lfirst(l);
4526                 Datum           expr_value;
4527                 bool            isNull;
4528
4529                 expr_value = ExecEvalExpr(clause, econtext, &isNull, NULL);
4530
4531                 if (isNull)
4532                 {
4533                         if (resultForNull == false)
4534                         {
4535                                 result = false; /* treat NULL as FALSE */
4536                                 break;
4537                         }
4538                 }
4539                 else
4540                 {
4541                         if (!DatumGetBool(expr_value))
4542                         {
4543                                 result = false; /* definitely FALSE */
4544                                 break;
4545                         }
4546                 }
4547         }
4548
4549         MemoryContextSwitchTo(oldContext);
4550
4551         return result;
4552 }
4553
4554 /*
4555  * Number of items in a tlist (including any resjunk items!)
4556  */
4557 int
4558 ExecTargetListLength(List *targetlist)
4559 {
4560         /* This used to be more complex, but fjoins are dead */
4561         return list_length(targetlist);
4562 }
4563
4564 /*
4565  * Number of items in a tlist, not including any resjunk items
4566  */
4567 int
4568 ExecCleanTargetListLength(List *targetlist)
4569 {
4570         int                     len = 0;
4571         ListCell   *tl;
4572
4573         foreach(tl, targetlist)
4574         {
4575                 TargetEntry *curTle = (TargetEntry *) lfirst(tl);
4576
4577                 Assert(IsA(curTle, TargetEntry));
4578                 if (!curTle->resjunk)
4579                         len++;
4580         }
4581         return len;
4582 }
4583
4584 /*
4585  * ExecTargetList
4586  *              Evaluates a targetlist with respect to the given
4587  *              expression context.  Returns TRUE if we were able to create
4588  *              a result, FALSE if we have exhausted a set-valued expression.
4589  *
4590  * Results are stored into the passed values and isnull arrays.
4591  * The caller must provide an itemIsDone array that persists across calls.
4592  *
4593  * As with ExecEvalExpr, the caller should pass isDone = NULL if not
4594  * prepared to deal with sets of result tuples.  Otherwise, a return
4595  * of *isDone = ExprMultipleResult signifies a set element, and a return
4596  * of *isDone = ExprEndResult signifies end of the set of tuple.
4597  */
4598 static bool
4599 ExecTargetList(List *targetlist,
4600                            ExprContext *econtext,
4601                            Datum *values,
4602                            bool *isnull,
4603                            ExprDoneCond *itemIsDone,
4604                            ExprDoneCond *isDone)
4605 {
4606         MemoryContext oldContext;
4607         ListCell   *tl;
4608         bool            haveDoneSets;
4609
4610         /*
4611          * Run in short-lived per-tuple context while computing expressions.
4612          */
4613         oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
4614
4615         /*
4616          * evaluate all the expressions in the target list
4617          */
4618         if (isDone)
4619                 *isDone = ExprSingleResult;             /* until proven otherwise */
4620
4621         haveDoneSets = false;           /* any exhausted set exprs in tlist? */
4622
4623         foreach(tl, targetlist)
4624         {
4625                 GenericExprState *gstate = (GenericExprState *) lfirst(tl);
4626                 TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr;
4627                 AttrNumber      resind = tle->resno - 1;
4628
4629                 values[resind] = ExecEvalExpr(gstate->arg,
4630                                                                           econtext,
4631                                                                           &isnull[resind],
4632                                                                           &itemIsDone[resind]);
4633
4634                 if (itemIsDone[resind] != ExprSingleResult)
4635                 {
4636                         /* We have a set-valued expression in the tlist */
4637                         if (isDone == NULL)
4638                                 ereport(ERROR,
4639                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4640                                                  errmsg("set-valued function called in context that cannot accept a set")));
4641                         if (itemIsDone[resind] == ExprMultipleResult)
4642                         {
4643                                 /* we have undone sets in the tlist, set flag */
4644                                 *isDone = ExprMultipleResult;
4645                         }
4646                         else
4647                         {
4648                                 /* we have done sets in the tlist, set flag for that */
4649                                 haveDoneSets = true;
4650                         }
4651                 }
4652         }
4653
4654         if (haveDoneSets)
4655         {
4656                 /*
4657                  * note: can't get here unless we verified isDone != NULL
4658                  */
4659                 if (*isDone == ExprSingleResult)
4660                 {
4661                         /*
4662                          * all sets are done, so report that tlist expansion is complete.
4663                          */
4664                         *isDone = ExprEndResult;
4665                         MemoryContextSwitchTo(oldContext);
4666                         return false;
4667                 }
4668                 else
4669                 {
4670                         /*
4671                          * We have some done and some undone sets.      Restart the done ones
4672                          * so that we can deliver a tuple (if possible).
4673                          */
4674                         foreach(tl, targetlist)
4675                         {
4676                                 GenericExprState *gstate = (GenericExprState *) lfirst(tl);
4677                                 TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr;
4678                                 AttrNumber      resind = tle->resno - 1;
4679
4680                                 if (itemIsDone[resind] == ExprEndResult)
4681                                 {
4682                                         values[resind] = ExecEvalExpr(gstate->arg,
4683                                                                                                   econtext,
4684                                                                                                   &isnull[resind],
4685                                                                                                   &itemIsDone[resind]);
4686
4687                                         if (itemIsDone[resind] == ExprEndResult)
4688                                         {
4689                                                 /*
4690                                                  * Oh dear, this item is returning an empty set. Guess
4691                                                  * we can't make a tuple after all.
4692                                                  */
4693                                                 *isDone = ExprEndResult;
4694                                                 break;
4695                                         }
4696                                 }
4697                         }
4698
4699                         /*
4700                          * If we cannot make a tuple because some sets are empty, we still
4701                          * have to cycle the nonempty sets to completion, else resources
4702                          * will not be released from subplans etc.
4703                          *
4704                          * XXX is that still necessary?
4705                          */
4706                         if (*isDone == ExprEndResult)
4707                         {
4708                                 foreach(tl, targetlist)
4709                                 {
4710                                         GenericExprState *gstate = (GenericExprState *) lfirst(tl);
4711                                         TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr;
4712                                         AttrNumber      resind = tle->resno - 1;
4713
4714                                         while (itemIsDone[resind] == ExprMultipleResult)
4715                                         {
4716                                                 values[resind] = ExecEvalExpr(gstate->arg,
4717                                                                                                           econtext,
4718                                                                                                           &isnull[resind],
4719                                                                                                           &itemIsDone[resind]);
4720                                         }
4721                                 }
4722
4723                                 MemoryContextSwitchTo(oldContext);
4724                                 return false;
4725                         }
4726                 }
4727         }
4728
4729         /* Report success */
4730         MemoryContextSwitchTo(oldContext);
4731
4732         return true;
4733 }
4734
4735 /*
4736  * ExecVariableList
4737  *              Evaluates a simple-Variable-list projection.
4738  *
4739  * Results are stored into the passed values and isnull arrays.
4740  */
4741 static void
4742 ExecVariableList(ProjectionInfo *projInfo,
4743                                  Datum *values,
4744                                  bool *isnull)
4745 {
4746         ExprContext *econtext = projInfo->pi_exprContext;
4747         int                *varSlotOffsets = projInfo->pi_varSlotOffsets;
4748         int                *varNumbers = projInfo->pi_varNumbers;
4749         int                     i;
4750
4751         /*
4752          * Force extraction of all input values that we need.
4753          */
4754         if (projInfo->pi_lastInnerVar > 0)
4755                 slot_getsomeattrs(econtext->ecxt_innertuple,
4756                                                   projInfo->pi_lastInnerVar);
4757         if (projInfo->pi_lastOuterVar > 0)
4758                 slot_getsomeattrs(econtext->ecxt_outertuple,
4759                                                   projInfo->pi_lastOuterVar);
4760         if (projInfo->pi_lastScanVar > 0)
4761                 slot_getsomeattrs(econtext->ecxt_scantuple,
4762                                                   projInfo->pi_lastScanVar);
4763
4764         /*
4765          * Assign to result by direct extraction of fields from source slots ... a
4766          * mite ugly, but fast ...
4767          */
4768         for (i = list_length(projInfo->pi_targetlist) - 1; i >= 0; i--)
4769         {
4770                 char       *slotptr = ((char *) econtext) + varSlotOffsets[i];
4771                 TupleTableSlot *varSlot = *((TupleTableSlot **) slotptr);
4772                 int                     varNumber = varNumbers[i] - 1;
4773
4774                 values[i] = varSlot->tts_values[varNumber];
4775                 isnull[i] = varSlot->tts_isnull[varNumber];
4776         }
4777 }
4778
4779 /*
4780  * ExecProject
4781  *
4782  *              projects a tuple based on projection info and stores
4783  *              it in the previously specified tuple table slot.
4784  *
4785  *              Note: the result is always a virtual tuple; therefore it
4786  *              may reference the contents of the exprContext's scan tuples
4787  *              and/or temporary results constructed in the exprContext.
4788  *              If the caller wishes the result to be valid longer than that
4789  *              data will be valid, he must call ExecMaterializeSlot on the
4790  *              result slot.
4791  */
4792 TupleTableSlot *
4793 ExecProject(ProjectionInfo *projInfo, ExprDoneCond *isDone)
4794 {
4795         TupleTableSlot *slot;
4796
4797         /*
4798          * sanity checks
4799          */
4800         Assert(projInfo != NULL);
4801
4802         /*
4803          * get the projection info we want
4804          */
4805         slot = projInfo->pi_slot;
4806
4807         /*
4808          * Clear any former contents of the result slot.  This makes it safe for
4809          * us to use the slot's Datum/isnull arrays as workspace. (Also, we can
4810          * return the slot as-is if we decide no rows can be projected.)
4811          */
4812         ExecClearTuple(slot);
4813
4814         /*
4815          * form a new result tuple (if possible); if successful, mark the result
4816          * slot as containing a valid virtual tuple
4817          */
4818         if (projInfo->pi_isVarList)
4819         {
4820                 /* simple Var list: this always succeeds with one result row */
4821                 if (isDone)
4822                         *isDone = ExprSingleResult;
4823                 ExecVariableList(projInfo,
4824                                                  slot->tts_values,
4825                                                  slot->tts_isnull);
4826                 ExecStoreVirtualTuple(slot);
4827         }
4828         else
4829         {
4830                 if (ExecTargetList(projInfo->pi_targetlist,
4831                                                    projInfo->pi_exprContext,
4832                                                    slot->tts_values,
4833                                                    slot->tts_isnull,
4834                                                    projInfo->pi_itemIsDone,
4835                                                    isDone))
4836                         ExecStoreVirtualTuple(slot);
4837         }
4838
4839         return slot;
4840 }