]> granicus.if.org Git - postgresql/blob - src/backend/executor/execQual.c
Repair bug #2694 concerning an ARRAY[] construct whose inputs are empty
[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-2006, 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.197 2006/11/06 18:21:31 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
56
57 /* static function decls */
58 static Datum ExecEvalArrayRef(ArrayRefExprState *astate,
59                                  ExprContext *econtext,
60                                  bool *isNull, ExprDoneCond *isDone);
61 static Datum ExecEvalAggref(AggrefExprState *aggref,
62                            ExprContext *econtext,
63                            bool *isNull, ExprDoneCond *isDone);
64 static Datum ExecEvalVar(ExprState *exprstate, ExprContext *econtext,
65                         bool *isNull, ExprDoneCond *isDone);
66 static Datum ExecEvalWholeRowVar(ExprState *exprstate, ExprContext *econtext,
67                                         bool *isNull, ExprDoneCond *isDone);
68 static Datum ExecEvalConst(ExprState *exprstate, ExprContext *econtext,
69                           bool *isNull, ExprDoneCond *isDone);
70 static Datum ExecEvalParam(ExprState *exprstate, ExprContext *econtext,
71                           bool *isNull, ExprDoneCond *isDone);
72 static void ShutdownFuncExpr(Datum arg);
73 static TupleDesc get_cached_rowtype(Oid type_id, int32 typmod,
74                                    TupleDesc *cache_field, ExprContext *econtext);
75 static void ShutdownTupleDescRef(Datum arg);
76 static ExprDoneCond ExecEvalFuncArgs(FunctionCallInfo fcinfo,
77                                  List *argList, ExprContext *econtext);
78 static Datum ExecMakeFunctionResultNoSets(FuncExprState *fcache,
79                                                          ExprContext *econtext,
80                                                          bool *isNull, ExprDoneCond *isDone);
81 static Datum ExecEvalFunc(FuncExprState *fcache, ExprContext *econtext,
82                          bool *isNull, ExprDoneCond *isDone);
83 static Datum ExecEvalOper(FuncExprState *fcache, ExprContext *econtext,
84                          bool *isNull, ExprDoneCond *isDone);
85 static Datum ExecEvalDistinct(FuncExprState *fcache, ExprContext *econtext,
86                                  bool *isNull, ExprDoneCond *isDone);
87 static Datum ExecEvalScalarArrayOp(ScalarArrayOpExprState *sstate,
88                                           ExprContext *econtext,
89                                           bool *isNull, ExprDoneCond *isDone);
90 static Datum ExecEvalNot(BoolExprState *notclause, ExprContext *econtext,
91                         bool *isNull, ExprDoneCond *isDone);
92 static Datum ExecEvalOr(BoolExprState *orExpr, ExprContext *econtext,
93                    bool *isNull, ExprDoneCond *isDone);
94 static Datum ExecEvalAnd(BoolExprState *andExpr, ExprContext *econtext,
95                         bool *isNull, ExprDoneCond *isDone);
96 static Datum ExecEvalConvertRowtype(ConvertRowtypeExprState *cstate,
97                                            ExprContext *econtext,
98                                            bool *isNull, ExprDoneCond *isDone);
99 static Datum ExecEvalCase(CaseExprState *caseExpr, ExprContext *econtext,
100                          bool *isNull, ExprDoneCond *isDone);
101 static Datum ExecEvalCaseTestExpr(ExprState *exprstate,
102                                          ExprContext *econtext,
103                                          bool *isNull, ExprDoneCond *isDone);
104 static Datum ExecEvalArray(ArrayExprState *astate,
105                           ExprContext *econtext,
106                           bool *isNull, ExprDoneCond *isDone);
107 static Datum ExecEvalRow(RowExprState *rstate,
108                         ExprContext *econtext,
109                         bool *isNull, ExprDoneCond *isDone);
110 static Datum ExecEvalRowCompare(RowCompareExprState *rstate,
111                                    ExprContext *econtext,
112                                    bool *isNull, ExprDoneCond *isDone);
113 static Datum ExecEvalCoalesce(CoalesceExprState *coalesceExpr,
114                                  ExprContext *econtext,
115                                  bool *isNull, ExprDoneCond *isDone);
116 static Datum ExecEvalMinMax(MinMaxExprState *minmaxExpr,
117                            ExprContext *econtext,
118                            bool *isNull, ExprDoneCond *isDone);
119 static Datum ExecEvalNullIf(FuncExprState *nullIfExpr,
120                            ExprContext *econtext,
121                            bool *isNull, ExprDoneCond *isDone);
122 static Datum ExecEvalNullTest(NullTestState *nstate,
123                                  ExprContext *econtext,
124                                  bool *isNull, ExprDoneCond *isDone);
125 static Datum ExecEvalBooleanTest(GenericExprState *bstate,
126                                         ExprContext *econtext,
127                                         bool *isNull, ExprDoneCond *isDone);
128 static Datum ExecEvalCoerceToDomain(CoerceToDomainState *cstate,
129                                            ExprContext *econtext,
130                                            bool *isNull, ExprDoneCond *isDone);
131 static Datum ExecEvalCoerceToDomainValue(ExprState *exprstate,
132                                                         ExprContext *econtext,
133                                                         bool *isNull, ExprDoneCond *isDone);
134 static Datum ExecEvalFieldSelect(FieldSelectState *fstate,
135                                         ExprContext *econtext,
136                                         bool *isNull, ExprDoneCond *isDone);
137 static Datum ExecEvalFieldStore(FieldStoreState *fstate,
138                                    ExprContext *econtext,
139                                    bool *isNull, ExprDoneCond *isDone);
140 static Datum ExecEvalRelabelType(GenericExprState *exprstate,
141                                         ExprContext *econtext,
142                                         bool *isNull, ExprDoneCond *isDone);
143
144
145 /* ----------------------------------------------------------------
146  *              ExecEvalExpr routines
147  *
148  *              Recursively evaluate a targetlist or qualification expression.
149  *
150  * Each of the following routines having the signature
151  *              Datum ExecEvalFoo(ExprState *expression,
152  *                                                ExprContext *econtext,
153  *                                                bool *isNull,
154  *                                                ExprDoneCond *isDone);
155  * is responsible for evaluating one type or subtype of ExprState node.
156  * They are normally called via the ExecEvalExpr macro, which makes use of
157  * the function pointer set up when the ExprState node was built by
158  * ExecInitExpr.  (In some cases, we change this pointer later to avoid
159  * re-executing one-time overhead.)
160  *
161  * Note: for notational simplicity we declare these functions as taking the
162  * specific type of ExprState that they work on.  This requires casting when
163  * assigning the function pointer in ExecInitExpr.      Be careful that the
164  * function signature is declared correctly, because the cast suppresses
165  * automatic checking!
166  *
167  *
168  * All these functions share this calling convention:
169  *
170  * Inputs:
171  *              expression: the expression state tree to evaluate
172  *              econtext: evaluation context information
173  *
174  * Outputs:
175  *              return value: Datum value of result
176  *              *isNull: set to TRUE if result is NULL (actual return value is
177  *                               meaningless if so); set to FALSE if non-null result
178  *              *isDone: set to indicator of set-result status
179  *
180  * A caller that can only accept a singleton (non-set) result should pass
181  * NULL for isDone; if the expression computes a set result then an error
182  * will be reported via ereport.  If the caller does pass an isDone pointer
183  * then *isDone is set to one of these three states:
184  *              ExprSingleResult                singleton result (not a set)
185  *              ExprMultipleResult              return value is one element of a set
186  *              ExprEndResult                   there are no more elements in the set
187  * When ExprMultipleResult is returned, the caller should invoke
188  * ExecEvalExpr() repeatedly until ExprEndResult is returned.  ExprEndResult
189  * is returned after the last real set element.  For convenience isNull will
190  * always be set TRUE when ExprEndResult is returned, but this should not be
191  * taken as indicating a NULL element of the set.  Note that these return
192  * conventions allow us to distinguish among a singleton NULL, a NULL element
193  * of a set, and an empty set.
194  *
195  * The caller should already have switched into the temporary memory
196  * context econtext->ecxt_per_tuple_memory.  The convenience entry point
197  * ExecEvalExprSwitchContext() is provided for callers who don't prefer to
198  * do the switch in an outer loop.      We do not do the switch in these routines
199  * because it'd be a waste of cycles during nested expression evaluation.
200  * ----------------------------------------------------------------
201  */
202
203
204 /*----------
205  *        ExecEvalArrayRef
206  *
207  *         This function takes an ArrayRef and returns the extracted Datum
208  *         if it's a simple reference, or the modified array value if it's
209  *         an array assignment (i.e., array element or slice insertion).
210  *
211  * NOTE: if we get a NULL result from a subscript expression, we return NULL
212  * when it's an array reference, or raise an error when it's an assignment.
213  *
214  * NOTE: we deliberately refrain from applying DatumGetArrayTypeP() here,
215  * even though that might seem natural, because this code needs to support
216  * both varlena arrays and fixed-length array types.  DatumGetArrayTypeP()
217  * only works for the varlena kind.  The routines we call in arrayfuncs.c
218  * have to know the difference (that's what they need refattrlength for).
219  *----------
220  */
221 static Datum
222 ExecEvalArrayRef(ArrayRefExprState *astate,
223                                  ExprContext *econtext,
224                                  bool *isNull,
225                                  ExprDoneCond *isDone)
226 {
227         ArrayRef   *arrayRef = (ArrayRef *) astate->xprstate.expr;
228         ArrayType  *array_source;
229         ArrayType  *resultArray;
230         bool            isAssignment = (arrayRef->refassgnexpr != NULL);
231         bool            eisnull;
232         ListCell   *l;
233         int                     i = 0,
234                                 j = 0;
235         IntArray        upper,
236                                 lower;
237         int                *lIndex;
238
239         array_source = (ArrayType *)
240                 DatumGetPointer(ExecEvalExpr(astate->refexpr,
241                                                                          econtext,
242                                                                          isNull,
243                                                                          isDone));
244
245         /*
246          * If refexpr yields NULL, and it's a fetch, then result is NULL. In the
247          * assignment case, we'll cons up something below.
248          */
249         if (*isNull)
250         {
251                 if (isDone && *isDone == ExprEndResult)
252                         return (Datum) NULL;    /* end of set result */
253                 if (!isAssignment)
254                         return (Datum) NULL;
255         }
256
257         foreach(l, astate->refupperindexpr)
258         {
259                 ExprState  *eltstate = (ExprState *) lfirst(l);
260
261                 if (i >= MAXDIM)
262                         ereport(ERROR,
263                                         (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
264                                          errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
265                                                         i, MAXDIM)));
266
267                 upper.indx[i++] = DatumGetInt32(ExecEvalExpr(eltstate,
268                                                                                                          econtext,
269                                                                                                          &eisnull,
270                                                                                                          NULL));
271                 /* If any index expr yields NULL, result is NULL or error */
272                 if (eisnull)
273                 {
274                         if (isAssignment)
275                                 ereport(ERROR,
276                                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
277                                   errmsg("array subscript in assignment must not be null")));
278                         *isNull = true;
279                         return (Datum) NULL;
280                 }
281         }
282
283         if (astate->reflowerindexpr != NIL)
284         {
285                 foreach(l, astate->reflowerindexpr)
286                 {
287                         ExprState  *eltstate = (ExprState *) lfirst(l);
288
289                         if (j >= MAXDIM)
290                                 ereport(ERROR,
291                                                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
292                                                  errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
293                                                                 i, MAXDIM)));
294
295                         lower.indx[j++] = DatumGetInt32(ExecEvalExpr(eltstate,
296                                                                                                                  econtext,
297                                                                                                                  &eisnull,
298                                                                                                                  NULL));
299                         /* If any index expr yields NULL, result is NULL or error */
300                         if (eisnull)
301                         {
302                                 if (isAssignment)
303                                         ereport(ERROR,
304                                                         (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
305                                                          errmsg("array subscript in assignment must not be NULL")));
306                                 *isNull = true;
307                                 return (Datum) NULL;
308                         }
309                 }
310                 /* this can't happen unless parser messed up */
311                 if (i != j)
312                         elog(ERROR, "upper and lower index lists are not same length");
313                 lIndex = lower.indx;
314         }
315         else
316                 lIndex = NULL;
317
318         if (isAssignment)
319         {
320                 Datum           sourceData;
321
322                 /*
323                  * Evaluate the value to be assigned into the array.
324                  *
325                  * XXX At some point we'll need to look into making the old value of
326                  * the array element available via CaseTestExpr, as is done by
327                  * ExecEvalFieldStore.  This is not needed now but will be needed to
328                  * support arrays of composite types; in an assignment to a field of
329                  * an array member, the parser would generate a FieldStore that
330                  * expects to fetch its input tuple via CaseTestExpr.
331                  */
332                 sourceData = ExecEvalExpr(astate->refassgnexpr,
333                                                                   econtext,
334                                                                   &eisnull,
335                                                                   NULL);
336
337                 /*
338                  * For an assignment to a fixed-length array type, both the original
339                  * array and the value to be assigned into it must be non-NULL, else
340                  * we punt and return the original array.
341                  */
342                 if (astate->refattrlength > 0)  /* fixed-length array? */
343                         if (eisnull || *isNull)
344                                 return PointerGetDatum(array_source);
345
346                 /*
347                  * For assignment to varlena arrays, we handle a NULL original array
348                  * by substituting an empty (zero-dimensional) array; insertion of the
349                  * new element will result in a singleton array value.  It does not
350                  * matter whether the new element is NULL.
351                  */
352                 if (*isNull)
353                 {
354                         array_source = construct_empty_array(arrayRef->refelemtype);
355                         *isNull = false;
356                 }
357
358                 if (lIndex == NULL)
359                         resultArray = array_set(array_source, i,
360                                                                         upper.indx,
361                                                                         sourceData,
362                                                                         eisnull,
363                                                                         astate->refattrlength,
364                                                                         astate->refelemlength,
365                                                                         astate->refelembyval,
366                                                                         astate->refelemalign);
367                 else
368                         resultArray = array_set_slice(array_source, i,
369                                                                                   upper.indx, lower.indx,
370                                                                    (ArrayType *) DatumGetPointer(sourceData),
371                                                                                   eisnull,
372                                                                                   astate->refattrlength,
373                                                                                   astate->refelemlength,
374                                                                                   astate->refelembyval,
375                                                                                   astate->refelemalign);
376                 return PointerGetDatum(resultArray);
377         }
378
379         if (lIndex == NULL)
380                 return array_ref(array_source, i, upper.indx,
381                                                  astate->refattrlength,
382                                                  astate->refelemlength,
383                                                  astate->refelembyval,
384                                                  astate->refelemalign,
385                                                  isNull);
386         else
387         {
388                 resultArray = array_get_slice(array_source, i,
389                                                                           upper.indx, lower.indx,
390                                                                           astate->refattrlength,
391                                                                           astate->refelemlength,
392                                                                           astate->refelembyval,
393                                                                           astate->refelemalign);
394                 return PointerGetDatum(resultArray);
395         }
396 }
397
398
399 /* ----------------------------------------------------------------
400  *              ExecEvalAggref
401  *
402  *              Returns a Datum whose value is the value of the precomputed
403  *              aggregate found in the given expression context.
404  * ----------------------------------------------------------------
405  */
406 static Datum
407 ExecEvalAggref(AggrefExprState *aggref, ExprContext *econtext,
408                            bool *isNull, ExprDoneCond *isDone)
409 {
410         if (isDone)
411                 *isDone = ExprSingleResult;
412
413         if (econtext->ecxt_aggvalues == NULL)           /* safety check */
414                 elog(ERROR, "no aggregates in this expression context");
415
416         *isNull = econtext->ecxt_aggnulls[aggref->aggno];
417         return econtext->ecxt_aggvalues[aggref->aggno];
418 }
419
420 /* ----------------------------------------------------------------
421  *              ExecEvalVar
422  *
423  *              Returns a Datum whose value is the value of a range
424  *              variable with respect to given expression context.
425  * ----------------------------------------------------------------
426  */
427 static Datum
428 ExecEvalVar(ExprState *exprstate, ExprContext *econtext,
429                         bool *isNull, ExprDoneCond *isDone)
430 {
431         Var                *variable = (Var *) exprstate->expr;
432         TupleTableSlot *slot;
433         AttrNumber      attnum;
434
435         if (isDone)
436                 *isDone = ExprSingleResult;
437
438         /*
439          * Get the slot and attribute number we want
440          *
441          * The asserts check that references to system attributes only appear at
442          * the level of a relation scan; at higher levels, system attributes must
443          * be treated as ordinary variables (since we no longer have access to the
444          * original tuple).
445          */
446         attnum = variable->varattno;
447
448         switch (variable->varno)
449         {
450                 case INNER:                             /* get the tuple from the inner node */
451                         slot = econtext->ecxt_innertuple;
452                         Assert(attnum > 0);
453                         break;
454
455                 case OUTER:                             /* get the tuple from the outer node */
456                         slot = econtext->ecxt_outertuple;
457                         Assert(attnum > 0);
458                         break;
459
460                 default:                                /* get the tuple from the relation being
461                                                                  * scanned */
462                         slot = econtext->ecxt_scantuple;
463                         break;
464         }
465
466 #ifdef USE_ASSERT_CHECKING
467
468         /*
469          * Some checks that are only applied for user attribute numbers (bogus
470          * system attnums will be caught inside slot_getattr).
471          */
472         if (attnum > 0)
473         {
474                 TupleDesc       tuple_type = slot->tts_tupleDescriptor;
475
476                 /*
477                  * This assert checks that the attnum is valid.
478                  */
479                 Assert(attnum <= tuple_type->natts);
480
481                 /*
482                  * This assert checks that the datatype the plan expects to get (as
483                  * told by our "variable" argument) is in fact the datatype of the
484                  * attribute being fetched (as seen in the current context, identified
485                  * by our "econtext" argument).  Otherwise crashes are likely.
486                  *
487                  * Note that we can't check dropped columns, since their atttypid has
488                  * been zeroed.
489                  */
490                 Assert(variable->vartype == tuple_type->attrs[attnum - 1]->atttypid ||
491                            tuple_type->attrs[attnum - 1]->attisdropped);
492         }
493 #endif   /* USE_ASSERT_CHECKING */
494
495         return slot_getattr(slot, attnum, isNull);
496 }
497
498 /* ----------------------------------------------------------------
499  *              ExecEvalWholeRowVar
500  *
501  *              Returns a Datum for a whole-row variable.
502  *
503  *              This could be folded into ExecEvalVar, but we make it a separate
504  *              routine so as not to slow down ExecEvalVar with tests for this
505  *              uncommon case.
506  * ----------------------------------------------------------------
507  */
508 static Datum
509 ExecEvalWholeRowVar(ExprState *exprstate, ExprContext *econtext,
510                                         bool *isNull, ExprDoneCond *isDone)
511 {
512         Var                *variable = (Var *) exprstate->expr;
513         TupleTableSlot *slot;
514         HeapTuple       tuple;
515         TupleDesc       tupleDesc;
516         HeapTupleHeader dtuple;
517
518         if (isDone)
519                 *isDone = ExprSingleResult;
520         *isNull = false;
521
522         Assert(variable->varattno == InvalidAttrNumber);
523
524         /*
525          * Whole-row Vars can only appear at the level of a relation scan, never
526          * in a join.
527          */
528         Assert(variable->varno != INNER);
529         Assert(variable->varno != OUTER);
530         slot = econtext->ecxt_scantuple;
531
532         tuple = ExecFetchSlotTuple(slot);
533         tupleDesc = slot->tts_tupleDescriptor;
534
535         /*
536          * We have to make a copy of the tuple so we can safely insert the Datum
537          * overhead fields, which are not set in on-disk tuples.
538          */
539         dtuple = (HeapTupleHeader) palloc(tuple->t_len);
540         memcpy((char *) dtuple, (char *) tuple->t_data, tuple->t_len);
541
542         HeapTupleHeaderSetDatumLength(dtuple, tuple->t_len);
543
544         /*
545          * If the Var identifies a named composite type, label the tuple with that
546          * type; otherwise use what is in the tupleDesc.
547          *
548          * It's likely that the slot's tupleDesc is a record type; if so, make
549          * sure it's been "blessed", so that the Datum can be interpreted later.
550          */
551         if (variable->vartype != RECORDOID)
552         {
553                 HeapTupleHeaderSetTypeId(dtuple, variable->vartype);
554                 HeapTupleHeaderSetTypMod(dtuple, variable->vartypmod);
555         }
556         else
557         {
558                 if (tupleDesc->tdtypeid == RECORDOID &&
559                         tupleDesc->tdtypmod < 0)
560                         assign_record_type_typmod(tupleDesc);
561                 HeapTupleHeaderSetTypeId(dtuple, tupleDesc->tdtypeid);
562                 HeapTupleHeaderSetTypMod(dtuple, tupleDesc->tdtypmod);
563         }
564
565         return PointerGetDatum(dtuple);
566 }
567
568 /* ----------------------------------------------------------------
569  *              ExecEvalConst
570  *
571  *              Returns the value of a constant.
572  *
573  *              Note that for pass-by-ref datatypes, we return a pointer to the
574  *              actual constant node.  This is one of the reasons why functions
575  *              must treat their input arguments as read-only.
576  * ----------------------------------------------------------------
577  */
578 static Datum
579 ExecEvalConst(ExprState *exprstate, ExprContext *econtext,
580                           bool *isNull, ExprDoneCond *isDone)
581 {
582         Const      *con = (Const *) exprstate->expr;
583
584         if (isDone)
585                 *isDone = ExprSingleResult;
586
587         *isNull = con->constisnull;
588         return con->constvalue;
589 }
590
591 /* ----------------------------------------------------------------
592  *              ExecEvalParam
593  *
594  *              Returns the value of a parameter.  A param node contains
595  *              something like ($.name) and the expression context contains
596  *              the current parameter bindings (name = "sam") (age = 34)...
597  *              so our job is to find and return the appropriate datum ("sam").
598  *
599  *              Q: if we have a parameter ($.foo) without a binding, i.e.
600  *                 there is no (foo = xxx) in the parameter list info,
601  *                 is this a fatal error or should this be a "not available"
602  *                 (in which case we could return NULL)?        -cim 10/13/89
603  * ----------------------------------------------------------------
604  */
605 static Datum
606 ExecEvalParam(ExprState *exprstate, ExprContext *econtext,
607                           bool *isNull, ExprDoneCond *isDone)
608 {
609         Param      *expression = (Param *) exprstate->expr;
610         int                     thisParamId = expression->paramid;
611
612         if (isDone)
613                 *isDone = ExprSingleResult;
614
615         if (expression->paramkind == PARAM_EXEC)
616         {
617                 /*
618                  * PARAM_EXEC params (internal executor parameters) are stored in the
619                  * ecxt_param_exec_vals array, and can be accessed by array index.
620                  */
621                 ParamExecData *prm;
622
623                 prm = &(econtext->ecxt_param_exec_vals[thisParamId]);
624                 if (prm->execPlan != NULL)
625                 {
626                         /* Parameter not evaluated yet, so go do it */
627                         ExecSetParamPlan(prm->execPlan, econtext);
628                         /* ExecSetParamPlan should have processed this param... */
629                         Assert(prm->execPlan == NULL);
630                 }
631                 *isNull = prm->isnull;
632                 return prm->value;
633         }
634         else
635         {
636                 /*
637                  * PARAM_EXTERN parameters must be sought in ecxt_param_list_info.
638                  */
639                 ParamListInfo paramInfo = econtext->ecxt_param_list_info;
640
641                 Assert(expression->paramkind == PARAM_EXTERN);
642                 if (paramInfo &&
643                         thisParamId > 0 && thisParamId <= paramInfo->numParams)
644                 {
645                         ParamExternData *prm = &paramInfo->params[thisParamId - 1];
646
647                         if (OidIsValid(prm->ptype))
648                         {
649                                 Assert(prm->ptype == expression->paramtype);
650                                 *isNull = prm->isnull;
651                                 return prm->value;
652                         }
653                 }
654                 ereport(ERROR,
655                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
656                                  errmsg("no value found for parameter %d", thisParamId)));
657                 return (Datum) 0;               /* keep compiler quiet */
658         }
659 }
660
661
662 /* ----------------------------------------------------------------
663  *              ExecEvalOper / ExecEvalFunc support routines
664  * ----------------------------------------------------------------
665  */
666
667 /*
668  *              GetAttributeByName
669  *              GetAttributeByNum
670  *
671  *              These functions return the value of the requested attribute
672  *              out of the given tuple Datum.
673  *              C functions which take a tuple as an argument are expected
674  *              to use these.  Ex: overpaid(EMP) might call GetAttributeByNum().
675  *              Note: these are actually rather slow because they do a typcache
676  *              lookup on each call.
677  */
678 Datum
679 GetAttributeByNum(HeapTupleHeader tuple,
680                                   AttrNumber attrno,
681                                   bool *isNull)
682 {
683         Datum           result;
684         Oid                     tupType;
685         int32           tupTypmod;
686         TupleDesc       tupDesc;
687         HeapTupleData tmptup;
688
689         if (!AttributeNumberIsValid(attrno))
690                 elog(ERROR, "invalid attribute number %d", attrno);
691
692         if (isNull == NULL)
693                 elog(ERROR, "a NULL isNull pointer was passed");
694
695         if (tuple == NULL)
696         {
697                 /* Kinda bogus but compatible with old behavior... */
698                 *isNull = true;
699                 return (Datum) 0;
700         }
701
702         tupType = HeapTupleHeaderGetTypeId(tuple);
703         tupTypmod = HeapTupleHeaderGetTypMod(tuple);
704         tupDesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
705
706         /*
707          * heap_getattr needs a HeapTuple not a bare HeapTupleHeader.  We set all
708          * the fields in the struct just in case user tries to inspect system
709          * columns.
710          */
711         tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
712         ItemPointerSetInvalid(&(tmptup.t_self));
713         tmptup.t_tableOid = InvalidOid;
714         tmptup.t_data = tuple;
715
716         result = heap_getattr(&tmptup,
717                                                   attrno,
718                                                   tupDesc,
719                                                   isNull);
720
721         ReleaseTupleDesc(tupDesc);
722
723         return result;
724 }
725
726 Datum
727 GetAttributeByName(HeapTupleHeader tuple, const char *attname, bool *isNull)
728 {
729         AttrNumber      attrno;
730         Datum           result;
731         Oid                     tupType;
732         int32           tupTypmod;
733         TupleDesc       tupDesc;
734         HeapTupleData tmptup;
735         int                     i;
736
737         if (attname == NULL)
738                 elog(ERROR, "invalid attribute name");
739
740         if (isNull == NULL)
741                 elog(ERROR, "a NULL isNull pointer was passed");
742
743         if (tuple == NULL)
744         {
745                 /* Kinda bogus but compatible with old behavior... */
746                 *isNull = true;
747                 return (Datum) 0;
748         }
749
750         tupType = HeapTupleHeaderGetTypeId(tuple);
751         tupTypmod = HeapTupleHeaderGetTypMod(tuple);
752         tupDesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
753
754         attrno = InvalidAttrNumber;
755         for (i = 0; i < tupDesc->natts; i++)
756         {
757                 if (namestrcmp(&(tupDesc->attrs[i]->attname), attname) == 0)
758                 {
759                         attrno = tupDesc->attrs[i]->attnum;
760                         break;
761                 }
762         }
763
764         if (attrno == InvalidAttrNumber)
765                 elog(ERROR, "attribute \"%s\" does not exist", attname);
766
767         /*
768          * heap_getattr needs a HeapTuple not a bare HeapTupleHeader.  We set all
769          * the fields in the struct just in case user tries to inspect system
770          * columns.
771          */
772         tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
773         ItemPointerSetInvalid(&(tmptup.t_self));
774         tmptup.t_tableOid = InvalidOid;
775         tmptup.t_data = tuple;
776
777         result = heap_getattr(&tmptup,
778                                                   attrno,
779                                                   tupDesc,
780                                                   isNull);
781
782         ReleaseTupleDesc(tupDesc);
783
784         return result;
785 }
786
787 /*
788  * init_fcache - initialize a FuncExprState node during first use
789  */
790 void
791 init_fcache(Oid foid, FuncExprState *fcache, MemoryContext fcacheCxt)
792 {
793         AclResult       aclresult;
794
795         /* Check permission to call function */
796         aclresult = pg_proc_aclcheck(foid, GetUserId(), ACL_EXECUTE);
797         if (aclresult != ACLCHECK_OK)
798                 aclcheck_error(aclresult, ACL_KIND_PROC, get_func_name(foid));
799
800         /*
801          * Safety check on nargs.  Under normal circumstances this should never
802          * fail, as parser should check sooner.  But possibly it might fail if
803          * server has been compiled with FUNC_MAX_ARGS smaller than some functions
804          * declared in pg_proc?
805          */
806         if (list_length(fcache->args) > FUNC_MAX_ARGS)
807                 ereport(ERROR,
808                                 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
809                                  errmsg("cannot pass more than %d arguments to a function",
810                                                 FUNC_MAX_ARGS)));
811
812         /* Set up the primary fmgr lookup information */
813         fmgr_info_cxt(foid, &(fcache->func), fcacheCxt);
814
815         /* Initialize additional info */
816         fcache->setArgsValid = false;
817         fcache->shutdown_reg = false;
818         fcache->func.fn_expr = (Node *) fcache->xprstate.expr;
819 }
820
821 /*
822  * callback function in case a FuncExpr returning a set needs to be shut down
823  * before it has been run to completion
824  */
825 static void
826 ShutdownFuncExpr(Datum arg)
827 {
828         FuncExprState *fcache = (FuncExprState *) DatumGetPointer(arg);
829
830         /* Clear any active set-argument state */
831         fcache->setArgsValid = false;
832
833         /* execUtils will deregister the callback... */
834         fcache->shutdown_reg = false;
835 }
836
837 /*
838  * get_cached_rowtype: utility function to lookup a rowtype tupdesc
839  *
840  * type_id, typmod: identity of the rowtype
841  * cache_field: where to cache the TupleDesc pointer in expression state node
842  *              (field must be initialized to NULL)
843  * econtext: expression context we are executing in
844  *
845  * NOTE: because the shutdown callback will be called during plan rescan,
846  * must be prepared to re-do this during any node execution; cannot call
847  * just once during expression initialization
848  */
849 static TupleDesc
850 get_cached_rowtype(Oid type_id, int32 typmod,
851                                    TupleDesc *cache_field, ExprContext *econtext)
852 {
853         TupleDesc       tupDesc = *cache_field;
854
855         /* Do lookup if no cached value or if requested type changed */
856         if (tupDesc == NULL ||
857                 type_id != tupDesc->tdtypeid ||
858                 typmod != tupDesc->tdtypmod)
859         {
860                 tupDesc = lookup_rowtype_tupdesc(type_id, typmod);
861
862                 if (*cache_field)
863                 {
864                         /* Release old tupdesc; but callback is already registered */
865                         ReleaseTupleDesc(*cache_field);
866                 }
867                 else
868                 {
869                         /* Need to register shutdown callback to release tupdesc */
870                         RegisterExprContextCallback(econtext,
871                                                                                 ShutdownTupleDescRef,
872                                                                                 PointerGetDatum(cache_field));
873                 }
874                 *cache_field = tupDesc;
875         }
876         return tupDesc;
877 }
878
879 /*
880  * Callback function to release a tupdesc refcount at expression tree shutdown
881  */
882 static void
883 ShutdownTupleDescRef(Datum arg)
884 {
885         TupleDesc  *cache_field = (TupleDesc *) DatumGetPointer(arg);
886
887         if (*cache_field)
888                 ReleaseTupleDesc(*cache_field);
889         *cache_field = NULL;
890 }
891
892 /*
893  * Evaluate arguments for a function.
894  */
895 static ExprDoneCond
896 ExecEvalFuncArgs(FunctionCallInfo fcinfo,
897                                  List *argList,
898                                  ExprContext *econtext)
899 {
900         ExprDoneCond argIsDone;
901         int                     i;
902         ListCell   *arg;
903
904         argIsDone = ExprSingleResult;           /* default assumption */
905
906         i = 0;
907         foreach(arg, argList)
908         {
909                 ExprState  *argstate = (ExprState *) lfirst(arg);
910                 ExprDoneCond thisArgIsDone;
911
912                 fcinfo->arg[i] = ExecEvalExpr(argstate,
913                                                                           econtext,
914                                                                           &fcinfo->argnull[i],
915                                                                           &thisArgIsDone);
916
917                 if (thisArgIsDone != ExprSingleResult)
918                 {
919                         /*
920                          * We allow only one argument to have a set value; we'd need much
921                          * more complexity to keep track of multiple set arguments (cf.
922                          * ExecTargetList) and it doesn't seem worth it.
923                          */
924                         if (argIsDone != ExprSingleResult)
925                                 ereport(ERROR,
926                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
927                                                  errmsg("functions and operators can take at most one set argument")));
928                         argIsDone = thisArgIsDone;
929                 }
930                 i++;
931         }
932
933         fcinfo->nargs = i;
934
935         return argIsDone;
936 }
937
938 /*
939  *              ExecMakeFunctionResult
940  *
941  * Evaluate the arguments to a function and then the function itself.
942  */
943 Datum
944 ExecMakeFunctionResult(FuncExprState *fcache,
945                                            ExprContext *econtext,
946                                            bool *isNull,
947                                            ExprDoneCond *isDone)
948 {
949         List       *arguments = fcache->args;
950         Datum           result;
951         FunctionCallInfoData fcinfo;
952         ReturnSetInfo rsinfo;           /* for functions returning sets */
953         ExprDoneCond argDone;
954         bool            hasSetArg;
955         int                     i;
956
957         /* Guard against stack overflow due to overly complex expressions */
958         check_stack_depth();
959
960         /*
961          * arguments is a list of expressions to evaluate before passing to the
962          * function manager.  We skip the evaluation if it was already done in the
963          * previous call (ie, we are continuing the evaluation of a set-valued
964          * function).  Otherwise, collect the current argument values into fcinfo.
965          */
966         if (!fcache->setArgsValid)
967         {
968                 /* Need to prep callinfo structure */
969                 InitFunctionCallInfoData(fcinfo, &(fcache->func), 0, NULL, NULL);
970                 argDone = ExecEvalFuncArgs(&fcinfo, arguments, econtext);
971                 if (argDone == ExprEndResult)
972                 {
973                         /* input is an empty set, so return an empty set. */
974                         *isNull = true;
975                         if (isDone)
976                                 *isDone = ExprEndResult;
977                         else
978                                 ereport(ERROR,
979                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
980                                                  errmsg("set-valued function called in context that cannot accept a set")));
981                         return (Datum) 0;
982                 }
983                 hasSetArg = (argDone != ExprSingleResult);
984         }
985         else
986         {
987                 /* Copy callinfo from previous evaluation */
988                 memcpy(&fcinfo, &fcache->setArgs, sizeof(fcinfo));
989                 hasSetArg = fcache->setHasSetArg;
990                 /* Reset flag (we may set it again below) */
991                 fcache->setArgsValid = false;
992         }
993
994         /*
995          * If function returns set, prepare a resultinfo node for communication
996          */
997         if (fcache->func.fn_retset)
998         {
999                 fcinfo.resultinfo = (Node *) &rsinfo;
1000                 rsinfo.type = T_ReturnSetInfo;
1001                 rsinfo.econtext = econtext;
1002                 rsinfo.expectedDesc = NULL;
1003                 rsinfo.allowedModes = (int) SFRM_ValuePerCall;
1004                 rsinfo.returnMode = SFRM_ValuePerCall;
1005                 /* isDone is filled below */
1006                 rsinfo.setResult = NULL;
1007                 rsinfo.setDesc = NULL;
1008         }
1009
1010         /*
1011          * now return the value gotten by calling the function manager, passing
1012          * the function the evaluated parameter values.
1013          */
1014         if (fcache->func.fn_retset || hasSetArg)
1015         {
1016                 /*
1017                  * We need to return a set result.      Complain if caller not ready to
1018                  * accept one.
1019                  */
1020                 if (isDone == NULL)
1021                         ereport(ERROR,
1022                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1023                                          errmsg("set-valued function called in context that cannot accept a set")));
1024
1025                 /*
1026                  * This loop handles the situation where we have both a set argument
1027                  * and a set-valued function.  Once we have exhausted the function's
1028                  * value(s) for a particular argument value, we have to get the next
1029                  * argument value and start the function over again. We might have to
1030                  * do it more than once, if the function produces an empty result set
1031                  * for a particular input value.
1032                  */
1033                 for (;;)
1034                 {
1035                         /*
1036                          * If function is strict, and there are any NULL arguments, skip
1037                          * calling the function (at least for this set of args).
1038                          */
1039                         bool            callit = true;
1040
1041                         if (fcache->func.fn_strict)
1042                         {
1043                                 for (i = 0; i < fcinfo.nargs; i++)
1044                                 {
1045                                         if (fcinfo.argnull[i])
1046                                         {
1047                                                 callit = false;
1048                                                 break;
1049                                         }
1050                                 }
1051                         }
1052
1053                         if (callit)
1054                         {
1055                                 fcinfo.isnull = false;
1056                                 rsinfo.isDone = ExprSingleResult;
1057                                 result = FunctionCallInvoke(&fcinfo);
1058                                 *isNull = fcinfo.isnull;
1059                                 *isDone = rsinfo.isDone;
1060                         }
1061                         else
1062                         {
1063                                 result = (Datum) 0;
1064                                 *isNull = true;
1065                                 *isDone = ExprEndResult;
1066                         }
1067
1068                         if (*isDone != ExprEndResult)
1069                         {
1070                                 /*
1071                                  * Got a result from current argument.  If function itself
1072                                  * returns set, save the current argument values to re-use on
1073                                  * the next call.
1074                                  */
1075                                 if (fcache->func.fn_retset && *isDone == ExprMultipleResult)
1076                                 {
1077                                         memcpy(&fcache->setArgs, &fcinfo, sizeof(fcinfo));
1078                                         fcache->setHasSetArg = hasSetArg;
1079                                         fcache->setArgsValid = true;
1080                                         /* Register cleanup callback if we didn't already */
1081                                         if (!fcache->shutdown_reg)
1082                                         {
1083                                                 RegisterExprContextCallback(econtext,
1084                                                                                                         ShutdownFuncExpr,
1085                                                                                                         PointerGetDatum(fcache));
1086                                                 fcache->shutdown_reg = true;
1087                                         }
1088                                 }
1089
1090                                 /*
1091                                  * Make sure we say we are returning a set, even if the
1092                                  * function itself doesn't return sets.
1093                                  */
1094                                 if (hasSetArg)
1095                                         *isDone = ExprMultipleResult;
1096                                 break;
1097                         }
1098
1099                         /* Else, done with this argument */
1100                         if (!hasSetArg)
1101                                 break;                  /* input not a set, so done */
1102
1103                         /* Re-eval args to get the next element of the input set */
1104                         argDone = ExecEvalFuncArgs(&fcinfo, arguments, econtext);
1105
1106                         if (argDone != ExprMultipleResult)
1107                         {
1108                                 /* End of argument set, so we're done. */
1109                                 *isNull = true;
1110                                 *isDone = ExprEndResult;
1111                                 result = (Datum) 0;
1112                                 break;
1113                         }
1114
1115                         /*
1116                          * If we reach here, loop around to run the function on the new
1117                          * argument.
1118                          */
1119                 }
1120         }
1121         else
1122         {
1123                 /*
1124                  * Non-set case: much easier.
1125                  *
1126                  * We change the ExprState function pointer to use the simpler
1127                  * ExecMakeFunctionResultNoSets on subsequent calls.  This amounts to
1128                  * assuming that no argument can return a set if it didn't do so the
1129                  * first time.
1130                  */
1131                 fcache->xprstate.evalfunc = (ExprStateEvalFunc) ExecMakeFunctionResultNoSets;
1132
1133                 if (isDone)
1134                         *isDone = ExprSingleResult;
1135
1136                 /*
1137                  * If function is strict, and there are any NULL arguments, skip
1138                  * calling the function and return NULL.
1139                  */
1140                 if (fcache->func.fn_strict)
1141                 {
1142                         for (i = 0; i < fcinfo.nargs; i++)
1143                         {
1144                                 if (fcinfo.argnull[i])
1145                                 {
1146                                         *isNull = true;
1147                                         return (Datum) 0;
1148                                 }
1149                         }
1150                 }
1151                 fcinfo.isnull = false;
1152                 result = FunctionCallInvoke(&fcinfo);
1153                 *isNull = fcinfo.isnull;
1154         }
1155
1156         return result;
1157 }
1158
1159 /*
1160  *              ExecMakeFunctionResultNoSets
1161  *
1162  * Simplified version of ExecMakeFunctionResult that can only handle
1163  * non-set cases.  Hand-tuned for speed.
1164  */
1165 static Datum
1166 ExecMakeFunctionResultNoSets(FuncExprState *fcache,
1167                                                          ExprContext *econtext,
1168                                                          bool *isNull,
1169                                                          ExprDoneCond *isDone)
1170 {
1171         ListCell   *arg;
1172         Datum           result;
1173         FunctionCallInfoData fcinfo;
1174         int                     i;
1175
1176         /* Guard against stack overflow due to overly complex expressions */
1177         check_stack_depth();
1178
1179         if (isDone)
1180                 *isDone = ExprSingleResult;
1181
1182         /* inlined, simplified version of ExecEvalFuncArgs */
1183         i = 0;
1184         foreach(arg, fcache->args)
1185         {
1186                 ExprState  *argstate = (ExprState *) lfirst(arg);
1187
1188                 fcinfo.arg[i] = ExecEvalExpr(argstate,
1189                                                                          econtext,
1190                                                                          &fcinfo.argnull[i],
1191                                                                          NULL);
1192                 i++;
1193         }
1194
1195         InitFunctionCallInfoData(fcinfo, &(fcache->func), i, NULL, NULL);
1196
1197         /*
1198          * If function is strict, and there are any NULL arguments, skip calling
1199          * the function and return NULL.
1200          */
1201         if (fcache->func.fn_strict)
1202         {
1203                 while (--i >= 0)
1204                 {
1205                         if (fcinfo.argnull[i])
1206                         {
1207                                 *isNull = true;
1208                                 return (Datum) 0;
1209                         }
1210                 }
1211         }
1212         /* fcinfo.isnull = false; */    /* handled by InitFunctionCallInfoData */
1213         result = FunctionCallInvoke(&fcinfo);
1214         *isNull = fcinfo.isnull;
1215
1216         return result;
1217 }
1218
1219
1220 /*
1221  *              ExecMakeTableFunctionResult
1222  *
1223  * Evaluate a table function, producing a materialized result in a Tuplestore
1224  * object.      *returnDesc is set to the tupledesc actually returned by the
1225  * function, or NULL if it didn't provide one.
1226  */
1227 Tuplestorestate *
1228 ExecMakeTableFunctionResult(ExprState *funcexpr,
1229                                                         ExprContext *econtext,
1230                                                         TupleDesc expectedDesc,
1231                                                         TupleDesc *returnDesc)
1232 {
1233         Tuplestorestate *tupstore = NULL;
1234         TupleDesc       tupdesc = NULL;
1235         Oid                     funcrettype;
1236         bool            returnsTuple;
1237         bool            returnsSet = false;
1238         FunctionCallInfoData fcinfo;
1239         ReturnSetInfo rsinfo;
1240         HeapTupleData tmptup;
1241         MemoryContext callerContext;
1242         MemoryContext oldcontext;
1243         bool            direct_function_call;
1244         bool            first_time = true;
1245
1246         callerContext = CurrentMemoryContext;
1247
1248         funcrettype = exprType((Node *) funcexpr->expr);
1249
1250         returnsTuple = type_is_rowtype(funcrettype);
1251
1252         /*
1253          * Prepare a resultinfo node for communication.  We always do this even if
1254          * not expecting a set result, so that we can pass expectedDesc.  In the
1255          * generic-expression case, the expression doesn't actually get to see the
1256          * resultinfo, but set it up anyway because we use some of the fields as
1257          * our own state variables.
1258          */
1259         InitFunctionCallInfoData(fcinfo, NULL, 0, NULL, (Node *) &rsinfo);
1260         rsinfo.type = T_ReturnSetInfo;
1261         rsinfo.econtext = econtext;
1262         rsinfo.expectedDesc = expectedDesc;
1263         rsinfo.allowedModes = (int) (SFRM_ValuePerCall | SFRM_Materialize);
1264         rsinfo.returnMode = SFRM_ValuePerCall;
1265         /* isDone is filled below */
1266         rsinfo.setResult = NULL;
1267         rsinfo.setDesc = NULL;
1268
1269         /*
1270          * Normally the passed expression tree will be a FuncExprState, since the
1271          * grammar only allows a function call at the top level of a table
1272          * function reference.  However, if the function doesn't return set then
1273          * the planner might have replaced the function call via constant-folding
1274          * or inlining.  So if we see any other kind of expression node, execute
1275          * it via the general ExecEvalExpr() code; the only difference is that we
1276          * don't get a chance to pass a special ReturnSetInfo to any functions
1277          * buried in the expression.
1278          */
1279         if (funcexpr && IsA(funcexpr, FuncExprState) &&
1280                 IsA(funcexpr->expr, FuncExpr))
1281         {
1282                 FuncExprState *fcache = (FuncExprState *) funcexpr;
1283                 ExprDoneCond argDone;
1284
1285                 /*
1286                  * This path is similar to ExecMakeFunctionResult.
1287                  */
1288                 direct_function_call = true;
1289
1290                 /*
1291                  * Initialize function cache if first time through
1292                  */
1293                 if (fcache->func.fn_oid == InvalidOid)
1294                 {
1295                         FuncExpr   *func = (FuncExpr *) fcache->xprstate.expr;
1296
1297                         init_fcache(func->funcid, fcache, econtext->ecxt_per_query_memory);
1298                 }
1299                 returnsSet = fcache->func.fn_retset;
1300
1301                 /*
1302                  * Evaluate the function's argument list.
1303                  *
1304                  * Note: ideally, we'd do this in the per-tuple context, but then the
1305                  * argument values would disappear when we reset the context in the
1306                  * inner loop.  So do it in caller context.  Perhaps we should make a
1307                  * separate context just to hold the evaluated arguments?
1308                  */
1309                 fcinfo.flinfo = &(fcache->func);
1310                 argDone = ExecEvalFuncArgs(&fcinfo, fcache->args, econtext);
1311                 /* We don't allow sets in the arguments of the table function */
1312                 if (argDone != ExprSingleResult)
1313                         ereport(ERROR,
1314                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1315                                          errmsg("set-valued function called in context that cannot accept a set")));
1316
1317                 /*
1318                  * If function is strict, and there are any NULL arguments, skip
1319                  * calling the function and act like it returned NULL (or an empty
1320                  * set, in the returns-set case).
1321                  */
1322                 if (fcache->func.fn_strict)
1323                 {
1324                         int                     i;
1325
1326                         for (i = 0; i < fcinfo.nargs; i++)
1327                         {
1328                                 if (fcinfo.argnull[i])
1329                                         goto no_function_result;
1330                         }
1331                 }
1332         }
1333         else
1334         {
1335                 /* Treat funcexpr as a generic expression */
1336                 direct_function_call = false;
1337         }
1338
1339         /*
1340          * Switch to short-lived context for calling the function or expression.
1341          */
1342         MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
1343
1344         /*
1345          * Loop to handle the ValuePerCall protocol (which is also the same
1346          * behavior needed in the generic ExecEvalExpr path).
1347          */
1348         for (;;)
1349         {
1350                 Datum           result;
1351                 HeapTuple       tuple;
1352
1353                 CHECK_FOR_INTERRUPTS();
1354
1355                 /*
1356                  * reset per-tuple memory context before each call of the function or
1357                  * expression. This cleans up any local memory the function may leak
1358                  * when called.
1359                  */
1360                 ResetExprContext(econtext);
1361
1362                 /* Call the function or expression one time */
1363                 if (direct_function_call)
1364                 {
1365                         fcinfo.isnull = false;
1366                         rsinfo.isDone = ExprSingleResult;
1367                         result = FunctionCallInvoke(&fcinfo);
1368                 }
1369                 else
1370                 {
1371                         result = ExecEvalExpr(funcexpr, econtext,
1372                                                                   &fcinfo.isnull, &rsinfo.isDone);
1373                 }
1374
1375                 /* Which protocol does function want to use? */
1376                 if (rsinfo.returnMode == SFRM_ValuePerCall)
1377                 {
1378                         /*
1379                          * Check for end of result set.
1380                          */
1381                         if (rsinfo.isDone == ExprEndResult)
1382                                 break;
1383
1384                         /*
1385                          * Can't do anything very useful with NULL rowtype values. For a
1386                          * function returning set, we consider this a protocol violation
1387                          * (but another alternative would be to just ignore the result and
1388                          * "continue" to get another row).      For a function not returning
1389                          * set, we fall out of the loop; we'll cons up an all-nulls result
1390                          * row below.
1391                          */
1392                         if (returnsTuple && fcinfo.isnull)
1393                         {
1394                                 if (!returnsSet)
1395                                         break;
1396                                 ereport(ERROR,
1397                                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1398                                                  errmsg("function returning set of rows cannot return null value")));
1399                         }
1400
1401                         /*
1402                          * If first time through, build tupdesc and tuplestore for result
1403                          */
1404                         if (first_time)
1405                         {
1406                                 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1407                                 if (returnsTuple)
1408                                 {
1409                                         /*
1410                                          * Use the type info embedded in the rowtype Datum to look
1411                                          * up the needed tupdesc.  Make a copy for the query.
1412                                          */
1413                                         HeapTupleHeader td;
1414
1415                                         td = DatumGetHeapTupleHeader(result);
1416                                         tupdesc = lookup_rowtype_tupdesc_copy(HeapTupleHeaderGetTypeId(td),
1417                                                                                            HeapTupleHeaderGetTypMod(td));
1418                                 }
1419                                 else
1420                                 {
1421                                         /*
1422                                          * Scalar type, so make a single-column descriptor
1423                                          */
1424                                         tupdesc = CreateTemplateTupleDesc(1, false);
1425                                         TupleDescInitEntry(tupdesc,
1426                                                                            (AttrNumber) 1,
1427                                                                            "column",
1428                                                                            funcrettype,
1429                                                                            -1,
1430                                                                            0);
1431                                 }
1432                                 tupstore = tuplestore_begin_heap(true, false, work_mem);
1433                                 MemoryContextSwitchTo(oldcontext);
1434                                 rsinfo.setResult = tupstore;
1435                                 rsinfo.setDesc = tupdesc;
1436                         }
1437
1438                         /*
1439                          * Store current resultset item.
1440                          */
1441                         if (returnsTuple)
1442                         {
1443                                 HeapTupleHeader td;
1444
1445                                 td = DatumGetHeapTupleHeader(result);
1446
1447                                 /*
1448                                  * tuplestore_puttuple needs a HeapTuple not a bare
1449                                  * HeapTupleHeader, but it doesn't need all the fields.
1450                                  */
1451                                 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
1452                                 tmptup.t_data = td;
1453                                 tuple = &tmptup;
1454                         }
1455                         else
1456                         {
1457                                 tuple = heap_form_tuple(tupdesc, &result, &fcinfo.isnull);
1458                         }
1459
1460                         oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1461                         tuplestore_puttuple(tupstore, tuple);
1462                         MemoryContextSwitchTo(oldcontext);
1463
1464                         /*
1465                          * Are we done?
1466                          */
1467                         if (rsinfo.isDone != ExprMultipleResult)
1468                                 break;
1469                 }
1470                 else if (rsinfo.returnMode == SFRM_Materialize)
1471                 {
1472                         /* check we're on the same page as the function author */
1473                         if (!first_time || rsinfo.isDone != ExprSingleResult)
1474                                 ereport(ERROR,
1475                                                 (errcode(ERRCODE_E_R_I_E_SRF_PROTOCOL_VIOLATED),
1476                                                  errmsg("table-function protocol for materialize mode was not followed")));
1477                         /* Done evaluating the set result */
1478                         break;
1479                 }
1480                 else
1481                         ereport(ERROR,
1482                                         (errcode(ERRCODE_E_R_I_E_SRF_PROTOCOL_VIOLATED),
1483                                          errmsg("unrecognized table-function returnMode: %d",
1484                                                         (int) rsinfo.returnMode)));
1485
1486                 first_time = false;
1487         }
1488
1489 no_function_result:
1490
1491         /*
1492          * If we got nothing from the function (ie, an empty-set or NULL result),
1493          * we have to create the tuplestore to return, and if it's a
1494          * non-set-returning function then insert a single all-nulls row.
1495          */
1496         if (rsinfo.setResult == NULL)
1497         {
1498                 MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1499                 tupstore = tuplestore_begin_heap(true, false, work_mem);
1500                 rsinfo.setResult = tupstore;
1501                 if (!returnsSet)
1502                 {
1503                         int                     natts = expectedDesc->natts;
1504                         Datum      *nulldatums;
1505                         bool       *nullflags;
1506                         HeapTuple       tuple;
1507
1508                         MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
1509                         nulldatums = (Datum *) palloc0(natts * sizeof(Datum));
1510                         nullflags = (bool *) palloc(natts * sizeof(bool));
1511                         memset(nullflags, true, natts * sizeof(bool));
1512                         tuple = heap_form_tuple(expectedDesc, nulldatums, nullflags);
1513                         MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1514                         tuplestore_puttuple(tupstore, tuple);
1515                 }
1516         }
1517
1518         MemoryContextSwitchTo(callerContext);
1519
1520         /* The returned pointers are those in rsinfo */
1521         *returnDesc = rsinfo.setDesc;
1522         return rsinfo.setResult;
1523 }
1524
1525
1526 /* ----------------------------------------------------------------
1527  *              ExecEvalFunc
1528  *              ExecEvalOper
1529  *
1530  *              Evaluate the functional result of a list of arguments by calling the
1531  *              function manager.
1532  * ----------------------------------------------------------------
1533  */
1534
1535 /* ----------------------------------------------------------------
1536  *              ExecEvalFunc
1537  * ----------------------------------------------------------------
1538  */
1539 static Datum
1540 ExecEvalFunc(FuncExprState *fcache,
1541                          ExprContext *econtext,
1542                          bool *isNull,
1543                          ExprDoneCond *isDone)
1544 {
1545         /* This is called only the first time through */
1546         FuncExpr   *func = (FuncExpr *) fcache->xprstate.expr;
1547
1548         /* Initialize function lookup info */
1549         init_fcache(func->funcid, fcache, econtext->ecxt_per_query_memory);
1550
1551         /* Go directly to ExecMakeFunctionResult on subsequent uses */
1552         fcache->xprstate.evalfunc = (ExprStateEvalFunc) ExecMakeFunctionResult;
1553
1554         return ExecMakeFunctionResult(fcache, econtext, isNull, isDone);
1555 }
1556
1557 /* ----------------------------------------------------------------
1558  *              ExecEvalOper
1559  * ----------------------------------------------------------------
1560  */
1561 static Datum
1562 ExecEvalOper(FuncExprState *fcache,
1563                          ExprContext *econtext,
1564                          bool *isNull,
1565                          ExprDoneCond *isDone)
1566 {
1567         /* This is called only the first time through */
1568         OpExpr     *op = (OpExpr *) fcache->xprstate.expr;
1569
1570         /* Initialize function lookup info */
1571         init_fcache(op->opfuncid, fcache, econtext->ecxt_per_query_memory);
1572
1573         /* Go directly to ExecMakeFunctionResult on subsequent uses */
1574         fcache->xprstate.evalfunc = (ExprStateEvalFunc) ExecMakeFunctionResult;
1575
1576         return ExecMakeFunctionResult(fcache, econtext, isNull, isDone);
1577 }
1578
1579 /* ----------------------------------------------------------------
1580  *              ExecEvalDistinct
1581  *
1582  * IS DISTINCT FROM must evaluate arguments to determine whether
1583  * they are NULL; if either is NULL then the result is already
1584  * known. If neither is NULL, then proceed to evaluate the
1585  * function. Note that this is *always* derived from the equals
1586  * operator, but since we need special processing of the arguments
1587  * we can not simply reuse ExecEvalOper() or ExecEvalFunc().
1588  * ----------------------------------------------------------------
1589  */
1590 static Datum
1591 ExecEvalDistinct(FuncExprState *fcache,
1592                                  ExprContext *econtext,
1593                                  bool *isNull,
1594                                  ExprDoneCond *isDone)
1595 {
1596         Datum           result;
1597         FunctionCallInfoData fcinfo;
1598         ExprDoneCond argDone;
1599         List       *argList;
1600
1601         /* Set default values for result flags: non-null, not a set result */
1602         *isNull = false;
1603         if (isDone)
1604                 *isDone = ExprSingleResult;
1605
1606         /*
1607          * Initialize function cache if first time through
1608          */
1609         if (fcache->func.fn_oid == InvalidOid)
1610         {
1611                 DistinctExpr *op = (DistinctExpr *) fcache->xprstate.expr;
1612
1613                 init_fcache(op->opfuncid, fcache, econtext->ecxt_per_query_memory);
1614                 Assert(!fcache->func.fn_retset);
1615         }
1616
1617         /*
1618          * extract info from fcache
1619          */
1620         argList = fcache->args;
1621
1622         /* Need to prep callinfo structure */
1623         InitFunctionCallInfoData(fcinfo, &(fcache->func), 0, NULL, NULL);
1624         argDone = ExecEvalFuncArgs(&fcinfo, argList, econtext);
1625         if (argDone != ExprSingleResult)
1626                 ereport(ERROR,
1627                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1628                                  errmsg("IS DISTINCT FROM does not support set arguments")));
1629         Assert(fcinfo.nargs == 2);
1630
1631         if (fcinfo.argnull[0] && fcinfo.argnull[1])
1632         {
1633                 /* Both NULL? Then is not distinct... */
1634                 result = BoolGetDatum(FALSE);
1635         }
1636         else if (fcinfo.argnull[0] || fcinfo.argnull[1])
1637         {
1638                 /* Only one is NULL? Then is distinct... */
1639                 result = BoolGetDatum(TRUE);
1640         }
1641         else
1642         {
1643                 fcinfo.isnull = false;
1644                 result = FunctionCallInvoke(&fcinfo);
1645                 *isNull = fcinfo.isnull;
1646                 /* Must invert result of "=" */
1647                 result = BoolGetDatum(!DatumGetBool(result));
1648         }
1649
1650         return result;
1651 }
1652
1653 /*
1654  * ExecEvalScalarArrayOp
1655  *
1656  * Evaluate "scalar op ANY/ALL (array)".  The operator always yields boolean,
1657  * and we combine the results across all array elements using OR and AND
1658  * (for ANY and ALL respectively).      Of course we short-circuit as soon as
1659  * the result is known.
1660  */
1661 static Datum
1662 ExecEvalScalarArrayOp(ScalarArrayOpExprState *sstate,
1663                                           ExprContext *econtext,
1664                                           bool *isNull, ExprDoneCond *isDone)
1665 {
1666         ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) sstate->fxprstate.xprstate.expr;
1667         bool            useOr = opexpr->useOr;
1668         ArrayType  *arr;
1669         int                     nitems;
1670         Datum           result;
1671         bool            resultnull;
1672         FunctionCallInfoData fcinfo;
1673         ExprDoneCond argDone;
1674         int                     i;
1675         int16           typlen;
1676         bool            typbyval;
1677         char            typalign;
1678         char       *s;
1679         bits8      *bitmap;
1680         int                     bitmask;
1681
1682         /* Set default values for result flags: non-null, not a set result */
1683         *isNull = false;
1684         if (isDone)
1685                 *isDone = ExprSingleResult;
1686
1687         /*
1688          * Initialize function cache if first time through
1689          */
1690         if (sstate->fxprstate.func.fn_oid == InvalidOid)
1691         {
1692                 init_fcache(opexpr->opfuncid, &sstate->fxprstate,
1693                                         econtext->ecxt_per_query_memory);
1694                 Assert(!sstate->fxprstate.func.fn_retset);
1695         }
1696
1697         /* Need to prep callinfo structure */
1698         InitFunctionCallInfoData(fcinfo, &(sstate->fxprstate.func), 0, NULL, NULL);
1699         argDone = ExecEvalFuncArgs(&fcinfo, sstate->fxprstate.args, econtext);
1700         if (argDone != ExprSingleResult)
1701                 ereport(ERROR,
1702                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1703                            errmsg("op ANY/ALL (array) does not support set arguments")));
1704         Assert(fcinfo.nargs == 2);
1705
1706         /*
1707          * If the array is NULL then we return NULL --- it's not very meaningful
1708          * to do anything else, even if the operator isn't strict.
1709          */
1710         if (fcinfo.argnull[1])
1711         {
1712                 *isNull = true;
1713                 return (Datum) 0;
1714         }
1715         /* Else okay to fetch and detoast the array */
1716         arr = DatumGetArrayTypeP(fcinfo.arg[1]);
1717
1718         /*
1719          * If the array is empty, we return either FALSE or TRUE per the useOr
1720          * flag.  This is correct even if the scalar is NULL; since we would
1721          * evaluate the operator zero times, it matters not whether it would want
1722          * to return NULL.
1723          */
1724         nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr));
1725         if (nitems <= 0)
1726                 return BoolGetDatum(!useOr);
1727
1728         /*
1729          * If the scalar is NULL, and the function is strict, return NULL; no
1730          * point in iterating the loop.
1731          */
1732         if (fcinfo.argnull[0] && sstate->fxprstate.func.fn_strict)
1733         {
1734                 *isNull = true;
1735                 return (Datum) 0;
1736         }
1737
1738         /*
1739          * We arrange to look up info about the element type only once per series
1740          * of calls, assuming the element type doesn't change underneath us.
1741          */
1742         if (sstate->element_type != ARR_ELEMTYPE(arr))
1743         {
1744                 get_typlenbyvalalign(ARR_ELEMTYPE(arr),
1745                                                          &sstate->typlen,
1746                                                          &sstate->typbyval,
1747                                                          &sstate->typalign);
1748                 sstate->element_type = ARR_ELEMTYPE(arr);
1749         }
1750         typlen = sstate->typlen;
1751         typbyval = sstate->typbyval;
1752         typalign = sstate->typalign;
1753
1754         result = BoolGetDatum(!useOr);
1755         resultnull = false;
1756
1757         /* Loop over the array elements */
1758         s = (char *) ARR_DATA_PTR(arr);
1759         bitmap = ARR_NULLBITMAP(arr);
1760         bitmask = 1;
1761
1762         for (i = 0; i < nitems; i++)
1763         {
1764                 Datum           elt;
1765                 Datum           thisresult;
1766
1767                 /* Get array element, checking for NULL */
1768                 if (bitmap && (*bitmap & bitmask) == 0)
1769                 {
1770                         fcinfo.arg[1] = (Datum) 0;
1771                         fcinfo.argnull[1] = true;
1772                 }
1773                 else
1774                 {
1775                         elt = fetch_att(s, typbyval, typlen);
1776                         s = att_addlength(s, typlen, PointerGetDatum(s));
1777                         s = (char *) att_align(s, typalign);
1778                         fcinfo.arg[1] = elt;
1779                         fcinfo.argnull[1] = false;
1780                 }
1781
1782                 /* Call comparison function */
1783                 if (fcinfo.argnull[1] && sstate->fxprstate.func.fn_strict)
1784                 {
1785                         fcinfo.isnull = true;
1786                         thisresult = (Datum) 0;
1787                 }
1788                 else
1789                 {
1790                         fcinfo.isnull = false;
1791                         thisresult = FunctionCallInvoke(&fcinfo);
1792                 }
1793
1794                 /* Combine results per OR or AND semantics */
1795                 if (fcinfo.isnull)
1796                         resultnull = true;
1797                 else if (useOr)
1798                 {
1799                         if (DatumGetBool(thisresult))
1800                         {
1801                                 result = BoolGetDatum(true);
1802                                 resultnull = false;
1803                                 break;                  /* needn't look at any more elements */
1804                         }
1805                 }
1806                 else
1807                 {
1808                         if (!DatumGetBool(thisresult))
1809                         {
1810                                 result = BoolGetDatum(false);
1811                                 resultnull = false;
1812                                 break;                  /* needn't look at any more elements */
1813                         }
1814                 }
1815
1816                 /* advance bitmap pointer if any */
1817                 if (bitmap)
1818                 {
1819                         bitmask <<= 1;
1820                         if (bitmask == 0x100)
1821                         {
1822                                 bitmap++;
1823                                 bitmask = 1;
1824                         }
1825                 }
1826         }
1827
1828         *isNull = resultnull;
1829         return result;
1830 }
1831
1832 /* ----------------------------------------------------------------
1833  *              ExecEvalNot
1834  *              ExecEvalOr
1835  *              ExecEvalAnd
1836  *
1837  *              Evaluate boolean expressions, with appropriate short-circuiting.
1838  *
1839  *              The query planner reformulates clause expressions in the
1840  *              qualification to conjunctive normal form.  If we ever get
1841  *              an AND to evaluate, we can be sure that it's not a top-level
1842  *              clause in the qualification, but appears lower (as a function
1843  *              argument, for example), or in the target list.  Not that you
1844  *              need to know this, mind you...
1845  * ----------------------------------------------------------------
1846  */
1847 static Datum
1848 ExecEvalNot(BoolExprState *notclause, ExprContext *econtext,
1849                         bool *isNull, ExprDoneCond *isDone)
1850 {
1851         ExprState  *clause = linitial(notclause->args);
1852         Datum           expr_value;
1853
1854         if (isDone)
1855                 *isDone = ExprSingleResult;
1856
1857         expr_value = ExecEvalExpr(clause, econtext, isNull, NULL);
1858
1859         /*
1860          * if the expression evaluates to null, then we just cascade the null back
1861          * to whoever called us.
1862          */
1863         if (*isNull)
1864                 return expr_value;
1865
1866         /*
1867          * evaluation of 'not' is simple.. expr is false, then return 'true' and
1868          * vice versa.
1869          */
1870         return BoolGetDatum(!DatumGetBool(expr_value));
1871 }
1872
1873 /* ----------------------------------------------------------------
1874  *              ExecEvalOr
1875  * ----------------------------------------------------------------
1876  */
1877 static Datum
1878 ExecEvalOr(BoolExprState *orExpr, ExprContext *econtext,
1879                    bool *isNull, ExprDoneCond *isDone)
1880 {
1881         List       *clauses = orExpr->args;
1882         ListCell   *clause;
1883         bool            AnyNull;
1884
1885         if (isDone)
1886                 *isDone = ExprSingleResult;
1887
1888         AnyNull = false;
1889
1890         /*
1891          * If any of the clauses is TRUE, the OR result is TRUE regardless of the
1892          * states of the rest of the clauses, so we can stop evaluating and return
1893          * TRUE immediately.  If none are TRUE and one or more is NULL, we return
1894          * NULL; otherwise we return FALSE.  This makes sense when you interpret
1895          * NULL as "don't know": if we have a TRUE then the OR is TRUE even if we
1896          * aren't sure about some of the other inputs. If all the known inputs are
1897          * FALSE, but we have one or more "don't knows", then we have to report
1898          * that we "don't know" what the OR's result should be --- perhaps one of
1899          * the "don't knows" would have been TRUE if we'd known its value.  Only
1900          * when all the inputs are known to be FALSE can we state confidently that
1901          * the OR's result is FALSE.
1902          */
1903         foreach(clause, clauses)
1904         {
1905                 ExprState  *clausestate = (ExprState *) lfirst(clause);
1906                 Datum           clause_value;
1907
1908                 clause_value = ExecEvalExpr(clausestate, econtext, isNull, NULL);
1909
1910                 /*
1911                  * if we have a non-null true result, then return it.
1912                  */
1913                 if (*isNull)
1914                         AnyNull = true;         /* remember we got a null */
1915                 else if (DatumGetBool(clause_value))
1916                         return clause_value;
1917         }
1918
1919         /* AnyNull is true if at least one clause evaluated to NULL */
1920         *isNull = AnyNull;
1921         return BoolGetDatum(false);
1922 }
1923
1924 /* ----------------------------------------------------------------
1925  *              ExecEvalAnd
1926  * ----------------------------------------------------------------
1927  */
1928 static Datum
1929 ExecEvalAnd(BoolExprState *andExpr, ExprContext *econtext,
1930                         bool *isNull, ExprDoneCond *isDone)
1931 {
1932         List       *clauses = andExpr->args;
1933         ListCell   *clause;
1934         bool            AnyNull;
1935
1936         if (isDone)
1937                 *isDone = ExprSingleResult;
1938
1939         AnyNull = false;
1940
1941         /*
1942          * If any of the clauses is FALSE, the AND result is FALSE regardless of
1943          * the states of the rest of the clauses, so we can stop evaluating and
1944          * return FALSE immediately.  If none are FALSE and one or more is NULL,
1945          * we return NULL; otherwise we return TRUE.  This makes sense when you
1946          * interpret NULL as "don't know", using the same sort of reasoning as for
1947          * OR, above.
1948          */
1949
1950         foreach(clause, clauses)
1951         {
1952                 ExprState  *clausestate = (ExprState *) lfirst(clause);
1953                 Datum           clause_value;
1954
1955                 clause_value = ExecEvalExpr(clausestate, econtext, isNull, NULL);
1956
1957                 /*
1958                  * if we have a non-null false result, then return it.
1959                  */
1960                 if (*isNull)
1961                         AnyNull = true;         /* remember we got a null */
1962                 else if (!DatumGetBool(clause_value))
1963                         return clause_value;
1964         }
1965
1966         /* AnyNull is true if at least one clause evaluated to NULL */
1967         *isNull = AnyNull;
1968         return BoolGetDatum(!AnyNull);
1969 }
1970
1971 /* ----------------------------------------------------------------
1972  *              ExecEvalConvertRowtype
1973  *
1974  *              Evaluate a rowtype coercion operation.  This may require
1975  *              rearranging field positions.
1976  * ----------------------------------------------------------------
1977  */
1978 static Datum
1979 ExecEvalConvertRowtype(ConvertRowtypeExprState *cstate,
1980                                            ExprContext *econtext,
1981                                            bool *isNull, ExprDoneCond *isDone)
1982 {
1983         ConvertRowtypeExpr *convert = (ConvertRowtypeExpr *) cstate->xprstate.expr;
1984         HeapTuple       result;
1985         Datum           tupDatum;
1986         HeapTupleHeader tuple;
1987         HeapTupleData tmptup;
1988         AttrNumber *attrMap;
1989         Datum      *invalues;
1990         bool       *inisnull;
1991         Datum      *outvalues;
1992         bool       *outisnull;
1993         int                     i;
1994         int                     outnatts;
1995
1996         tupDatum = ExecEvalExpr(cstate->arg, econtext, isNull, isDone);
1997
1998         /* this test covers the isDone exception too: */
1999         if (*isNull)
2000                 return tupDatum;
2001
2002         tuple = DatumGetHeapTupleHeader(tupDatum);
2003
2004         /* Lookup tupdescs if first time through or after rescan */
2005         if (cstate->indesc == NULL)
2006                 get_cached_rowtype(exprType((Node *) convert->arg), -1,
2007                                                    &cstate->indesc, econtext);
2008         if (cstate->outdesc == NULL)
2009                 get_cached_rowtype(convert->resulttype, -1,
2010                                                    &cstate->outdesc, econtext);
2011
2012         Assert(HeapTupleHeaderGetTypeId(tuple) == cstate->indesc->tdtypeid);
2013         Assert(HeapTupleHeaderGetTypMod(tuple) == cstate->indesc->tdtypmod);
2014
2015         /* if first time through, initialize */
2016         if (cstate->attrMap == NULL)
2017         {
2018                 MemoryContext old_cxt;
2019                 int                     n;
2020
2021                 /* allocate state in long-lived memory context */
2022                 old_cxt = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
2023
2024                 /* prepare map from old to new attribute numbers */
2025                 n = cstate->outdesc->natts;
2026                 cstate->attrMap = (AttrNumber *) palloc0(n * sizeof(AttrNumber));
2027                 for (i = 0; i < n; i++)
2028                 {
2029                         Form_pg_attribute att = cstate->outdesc->attrs[i];
2030                         char       *attname;
2031                         Oid                     atttypid;
2032                         int32           atttypmod;
2033                         int                     j;
2034
2035                         if (att->attisdropped)
2036                                 continue;               /* attrMap[i] is already 0 */
2037                         attname = NameStr(att->attname);
2038                         atttypid = att->atttypid;
2039                         atttypmod = att->atttypmod;
2040                         for (j = 0; j < cstate->indesc->natts; j++)
2041                         {
2042                                 att = cstate->indesc->attrs[j];
2043                                 if (att->attisdropped)
2044                                         continue;
2045                                 if (strcmp(attname, NameStr(att->attname)) == 0)
2046                                 {
2047                                         /* Found it, check type */
2048                                         if (atttypid != att->atttypid || atttypmod != att->atttypmod)
2049                                                 elog(ERROR, "attribute \"%s\" of type %s does not match corresponding attribute of type %s",
2050                                                          attname,
2051                                                          format_type_be(cstate->indesc->tdtypeid),
2052                                                          format_type_be(cstate->outdesc->tdtypeid));
2053                                         cstate->attrMap[i] = (AttrNumber) (j + 1);
2054                                         break;
2055                                 }
2056                         }
2057                         if (cstate->attrMap[i] == 0)
2058                                 elog(ERROR, "attribute \"%s\" of type %s does not exist",
2059                                          attname,
2060                                          format_type_be(cstate->indesc->tdtypeid));
2061                 }
2062                 /* preallocate workspace for Datum arrays */
2063                 n = cstate->indesc->natts + 1;  /* +1 for NULL */
2064                 cstate->invalues = (Datum *) palloc(n * sizeof(Datum));
2065                 cstate->inisnull = (bool *) palloc(n * sizeof(bool));
2066                 n = cstate->outdesc->natts;
2067                 cstate->outvalues = (Datum *) palloc(n * sizeof(Datum));
2068                 cstate->outisnull = (bool *) palloc(n * sizeof(bool));
2069
2070                 MemoryContextSwitchTo(old_cxt);
2071         }
2072
2073         attrMap = cstate->attrMap;
2074         invalues = cstate->invalues;
2075         inisnull = cstate->inisnull;
2076         outvalues = cstate->outvalues;
2077         outisnull = cstate->outisnull;
2078         outnatts = cstate->outdesc->natts;
2079
2080         /*
2081          * heap_deform_tuple needs a HeapTuple not a bare HeapTupleHeader.
2082          */
2083         tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
2084         tmptup.t_data = tuple;
2085
2086         /*
2087          * Extract all the values of the old tuple, offsetting the arrays so that
2088          * invalues[0] is NULL and invalues[1] is the first source attribute; this
2089          * exactly matches the numbering convention in attrMap.
2090          */
2091         heap_deform_tuple(&tmptup, cstate->indesc, invalues + 1, inisnull + 1);
2092         invalues[0] = (Datum) 0;
2093         inisnull[0] = true;
2094
2095         /*
2096          * Transpose into proper fields of the new tuple.
2097          */
2098         for (i = 0; i < outnatts; i++)
2099         {
2100                 int                     j = attrMap[i];
2101
2102                 outvalues[i] = invalues[j];
2103                 outisnull[i] = inisnull[j];
2104         }
2105
2106         /*
2107          * Now form the new tuple.
2108          */
2109         result = heap_form_tuple(cstate->outdesc, outvalues, outisnull);
2110
2111         return HeapTupleGetDatum(result);
2112 }
2113
2114 /* ----------------------------------------------------------------
2115  *              ExecEvalCase
2116  *
2117  *              Evaluate a CASE clause. Will have boolean expressions
2118  *              inside the WHEN clauses, and will have expressions
2119  *              for results.
2120  *              - thomas 1998-11-09
2121  * ----------------------------------------------------------------
2122  */
2123 static Datum
2124 ExecEvalCase(CaseExprState *caseExpr, ExprContext *econtext,
2125                          bool *isNull, ExprDoneCond *isDone)
2126 {
2127         List       *clauses = caseExpr->args;
2128         ListCell   *clause;
2129         Datum           save_datum;
2130         bool            save_isNull;
2131
2132         if (isDone)
2133                 *isDone = ExprSingleResult;
2134
2135         /*
2136          * If there's a test expression, we have to evaluate it and save the value
2137          * where the CaseTestExpr placeholders can find it. We must save and
2138          * restore prior setting of econtext's caseValue fields, in case this node
2139          * is itself within a larger CASE.
2140          */
2141         save_datum = econtext->caseValue_datum;
2142         save_isNull = econtext->caseValue_isNull;
2143
2144         if (caseExpr->arg)
2145         {
2146                 econtext->caseValue_datum = ExecEvalExpr(caseExpr->arg,
2147                                                                                                  econtext,
2148                                                                                                  &econtext->caseValue_isNull,
2149                                                                                                  NULL);
2150         }
2151
2152         /*
2153          * we evaluate each of the WHEN clauses in turn, as soon as one is true we
2154          * return the corresponding result. If none are true then we return the
2155          * value of the default clause, or NULL if there is none.
2156          */
2157         foreach(clause, clauses)
2158         {
2159                 CaseWhenState *wclause = lfirst(clause);
2160                 Datum           clause_value;
2161
2162                 clause_value = ExecEvalExpr(wclause->expr,
2163                                                                         econtext,
2164                                                                         isNull,
2165                                                                         NULL);
2166
2167                 /*
2168                  * if we have a true test, then we return the result, since the case
2169                  * statement is satisfied.      A NULL result from the test is not
2170                  * considered true.
2171                  */
2172                 if (DatumGetBool(clause_value) && !*isNull)
2173                 {
2174                         econtext->caseValue_datum = save_datum;
2175                         econtext->caseValue_isNull = save_isNull;
2176                         return ExecEvalExpr(wclause->result,
2177                                                                 econtext,
2178                                                                 isNull,
2179                                                                 isDone);
2180                 }
2181         }
2182
2183         econtext->caseValue_datum = save_datum;
2184         econtext->caseValue_isNull = save_isNull;
2185
2186         if (caseExpr->defresult)
2187         {
2188                 return ExecEvalExpr(caseExpr->defresult,
2189                                                         econtext,
2190                                                         isNull,
2191                                                         isDone);
2192         }
2193
2194         *isNull = true;
2195         return (Datum) 0;
2196 }
2197
2198 /*
2199  * ExecEvalCaseTestExpr
2200  *
2201  * Return the value stored by CASE.
2202  */
2203 static Datum
2204 ExecEvalCaseTestExpr(ExprState *exprstate,
2205                                          ExprContext *econtext,
2206                                          bool *isNull, ExprDoneCond *isDone)
2207 {
2208         if (isDone)
2209                 *isDone = ExprSingleResult;
2210         *isNull = econtext->caseValue_isNull;
2211         return econtext->caseValue_datum;
2212 }
2213
2214 /* ----------------------------------------------------------------
2215  *              ExecEvalArray - ARRAY[] expressions
2216  * ----------------------------------------------------------------
2217  */
2218 static Datum
2219 ExecEvalArray(ArrayExprState *astate, ExprContext *econtext,
2220                           bool *isNull, ExprDoneCond *isDone)
2221 {
2222         ArrayExpr  *arrayExpr = (ArrayExpr *) astate->xprstate.expr;
2223         ArrayType  *result;
2224         ListCell   *element;
2225         Oid                     element_type = arrayExpr->element_typeid;
2226         int                     ndims = 0;
2227         int                     dims[MAXDIM];
2228         int                     lbs[MAXDIM];
2229
2230         /* Set default values for result flags: non-null, not a set result */
2231         *isNull = false;
2232         if (isDone)
2233                 *isDone = ExprSingleResult;
2234
2235         if (!arrayExpr->multidims)
2236         {
2237                 /* Elements are presumably of scalar type */
2238                 int                     nelems;
2239                 Datum      *dvalues;
2240                 bool       *dnulls;
2241                 int                     i = 0;
2242
2243                 ndims = 1;
2244                 nelems = list_length(astate->elements);
2245
2246                 /* Shouldn't happen here, but if length is 0, return empty array */
2247                 if (nelems == 0)
2248                         return PointerGetDatum(construct_empty_array(element_type));
2249
2250                 dvalues = (Datum *) palloc(nelems * sizeof(Datum));
2251                 dnulls = (bool *) palloc(nelems * sizeof(bool));
2252
2253                 /* loop through and build array of datums */
2254                 foreach(element, astate->elements)
2255                 {
2256                         ExprState  *e = (ExprState *) lfirst(element);
2257
2258                         dvalues[i] = ExecEvalExpr(e, econtext, &dnulls[i], NULL);
2259                         i++;
2260                 }
2261
2262                 /* setup for 1-D array of the given length */
2263                 dims[0] = nelems;
2264                 lbs[0] = 1;
2265
2266                 result = construct_md_array(dvalues, dnulls, ndims, dims, lbs,
2267                                                                         element_type,
2268                                                                         astate->elemlength,
2269                                                                         astate->elembyval,
2270                                                                         astate->elemalign);
2271         }
2272         else
2273         {
2274                 /* Must be nested array expressions */
2275                 int                     nbytes = 0;
2276                 int                     nitems = 0;
2277                 int                     outer_nelems = 0;
2278                 int                     elem_ndims = 0;
2279                 int                *elem_dims = NULL;
2280                 int                *elem_lbs = NULL;
2281                 bool            firstone = true;
2282                 bool            havenulls = false;
2283                 bool            haveempty = false;
2284                 char      **subdata;
2285                 bits8     **subbitmaps;
2286                 int                *subbytes;
2287                 int                *subnitems;
2288                 int                     i;
2289                 int32           dataoffset;
2290                 char       *dat;
2291                 int                     iitem;
2292
2293                 i = list_length(astate->elements);
2294                 subdata = (char **) palloc(i * sizeof(char *));
2295                 subbitmaps = (bits8 **) palloc(i * sizeof(bits8 *));
2296                 subbytes = (int *) palloc(i * sizeof(int));
2297                 subnitems = (int *) palloc(i * sizeof(int));
2298
2299                 /* loop through and get data area from each element */
2300                 foreach(element, astate->elements)
2301                 {
2302                         ExprState  *e = (ExprState *) lfirst(element);
2303                         bool            eisnull;
2304                         Datum           arraydatum;
2305                         ArrayType  *array;
2306                         int                     this_ndims;
2307
2308                         arraydatum = ExecEvalExpr(e, econtext, &eisnull, NULL);
2309                         /* temporarily ignore null subarrays */
2310                         if (eisnull)
2311                         {
2312                                 haveempty = true;
2313                                 continue;
2314                         }
2315
2316                         array = DatumGetArrayTypeP(arraydatum);
2317
2318                         /* run-time double-check on element type */
2319                         if (element_type != ARR_ELEMTYPE(array))
2320                                 ereport(ERROR,
2321                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
2322                                                  errmsg("cannot merge incompatible arrays"),
2323                                                  errdetail("Array with element type %s cannot be "
2324                                                  "included in ARRAY construct with element type %s.",
2325                                                                    format_type_be(ARR_ELEMTYPE(array)),
2326                                                                    format_type_be(element_type))));
2327
2328                         this_ndims = ARR_NDIM(array);
2329                         /* temporarily ignore zero-dimensional subarrays */
2330                         if (this_ndims <= 0)
2331                         {
2332                                 haveempty = true;
2333                                 continue;
2334                         }
2335
2336                         if (firstone)
2337                         {
2338                                 /* Get sub-array details from first member */
2339                                 elem_ndims = this_ndims;
2340                                 ndims = elem_ndims + 1;
2341                                 if (ndims <= 0 || ndims > MAXDIM)
2342                                         ereport(ERROR,
2343                                                         (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
2344                                                   errmsg("number of array dimensions (%d) exceeds " \
2345                                                                  "the maximum allowed (%d)", ndims, MAXDIM)));
2346
2347                                 elem_dims = (int *) palloc(elem_ndims * sizeof(int));
2348                                 memcpy(elem_dims, ARR_DIMS(array), elem_ndims * sizeof(int));
2349                                 elem_lbs = (int *) palloc(elem_ndims * sizeof(int));
2350                                 memcpy(elem_lbs, ARR_LBOUND(array), elem_ndims * sizeof(int));
2351
2352                                 firstone = false;
2353                         }
2354                         else
2355                         {
2356                                 /* Check other sub-arrays are compatible */
2357                                 if (elem_ndims != this_ndims ||
2358                                         memcmp(elem_dims, ARR_DIMS(array),
2359                                                    elem_ndims * sizeof(int)) != 0 ||
2360                                         memcmp(elem_lbs, ARR_LBOUND(array),
2361                                                    elem_ndims * sizeof(int)) != 0)
2362                                         ereport(ERROR,
2363                                                         (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2364                                                          errmsg("multidimensional arrays must have array "
2365                                                                         "expressions with matching dimensions")));
2366                         }
2367
2368                         subdata[outer_nelems] = ARR_DATA_PTR(array);
2369                         subbitmaps[outer_nelems] = ARR_NULLBITMAP(array);
2370                         subbytes[outer_nelems] = ARR_SIZE(array) - ARR_DATA_OFFSET(array);
2371                         nbytes += subbytes[outer_nelems];
2372                         subnitems[outer_nelems] = ArrayGetNItems(this_ndims,
2373                                                                                                          ARR_DIMS(array));
2374                         nitems += subnitems[outer_nelems];
2375                         havenulls |= ARR_HASNULL(array);
2376                         outer_nelems++;
2377                 }
2378
2379                 /*
2380                  * If all items were null or empty arrays, return an empty array;
2381                  * otherwise, if some were and some weren't, raise error.  (Note:
2382                  * we must special-case this somehow to avoid trying to generate
2383                  * a 1-D array formed from empty arrays.  It's not ideal...)
2384                  */
2385                 if (haveempty)
2386                 {
2387                         if (ndims == 0)         /* didn't find any nonempty array */
2388                                 return PointerGetDatum(construct_empty_array(element_type));
2389                         ereport(ERROR,
2390                                         (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2391                                          errmsg("multidimensional arrays must have array "
2392                                                         "expressions with matching dimensions")));
2393                 }
2394
2395                 /* setup for multi-D array */
2396                 dims[0] = outer_nelems;
2397                 lbs[0] = 1;
2398                 for (i = 1; i < ndims; i++)
2399                 {
2400                         dims[i] = elem_dims[i - 1];
2401                         lbs[i] = elem_lbs[i - 1];
2402                 }
2403
2404                 if (havenulls)
2405                 {
2406                         dataoffset = ARR_OVERHEAD_WITHNULLS(ndims, nitems);
2407                         nbytes += dataoffset;
2408                 }
2409                 else
2410                 {
2411                         dataoffset = 0;         /* marker for no null bitmap */
2412                         nbytes += ARR_OVERHEAD_NONULLS(ndims);
2413                 }
2414
2415                 result = (ArrayType *) palloc(nbytes);
2416                 result->size = nbytes;
2417                 result->ndim = ndims;
2418                 result->dataoffset = dataoffset;
2419                 result->elemtype = element_type;
2420                 memcpy(ARR_DIMS(result), dims, ndims * sizeof(int));
2421                 memcpy(ARR_LBOUND(result), lbs, ndims * sizeof(int));
2422
2423                 dat = ARR_DATA_PTR(result);
2424                 iitem = 0;
2425                 for (i = 0; i < outer_nelems; i++)
2426                 {
2427                         memcpy(dat, subdata[i], subbytes[i]);
2428                         dat += subbytes[i];
2429                         if (havenulls)
2430                                 array_bitmap_copy(ARR_NULLBITMAP(result), iitem,
2431                                                                   subbitmaps[i], 0,
2432                                                                   subnitems[i]);
2433                         iitem += subnitems[i];
2434                 }
2435         }
2436
2437         return PointerGetDatum(result);
2438 }
2439
2440 /* ----------------------------------------------------------------
2441  *              ExecEvalRow - ROW() expressions
2442  * ----------------------------------------------------------------
2443  */
2444 static Datum
2445 ExecEvalRow(RowExprState *rstate,
2446                         ExprContext *econtext,
2447                         bool *isNull, ExprDoneCond *isDone)
2448 {
2449         HeapTuple       tuple;
2450         Datum      *values;
2451         bool       *isnull;
2452         int                     natts;
2453         ListCell   *arg;
2454         int                     i;
2455
2456         /* Set default values for result flags: non-null, not a set result */
2457         *isNull = false;
2458         if (isDone)
2459                 *isDone = ExprSingleResult;
2460
2461         /* Allocate workspace */
2462         natts = rstate->tupdesc->natts;
2463         values = (Datum *) palloc0(natts * sizeof(Datum));
2464         isnull = (bool *) palloc(natts * sizeof(bool));
2465
2466         /* preset to nulls in case rowtype has some later-added columns */
2467         memset(isnull, true, natts * sizeof(bool));
2468
2469         /* Evaluate field values */
2470         i = 0;
2471         foreach(arg, rstate->args)
2472         {
2473                 ExprState  *e = (ExprState *) lfirst(arg);
2474
2475                 values[i] = ExecEvalExpr(e, econtext, &isnull[i], NULL);
2476                 i++;
2477         }
2478
2479         tuple = heap_form_tuple(rstate->tupdesc, values, isnull);
2480
2481         pfree(values);
2482         pfree(isnull);
2483
2484         return HeapTupleGetDatum(tuple);
2485 }
2486
2487 /* ----------------------------------------------------------------
2488  *              ExecEvalRowCompare - ROW() comparison-op ROW()
2489  * ----------------------------------------------------------------
2490  */
2491 static Datum
2492 ExecEvalRowCompare(RowCompareExprState *rstate,
2493                                    ExprContext *econtext,
2494                                    bool *isNull, ExprDoneCond *isDone)
2495 {
2496         bool            result;
2497         RowCompareType rctype = ((RowCompareExpr *) rstate->xprstate.expr)->rctype;
2498         int32           cmpresult = 0;
2499         ListCell   *l;
2500         ListCell   *r;
2501         int                     i;
2502
2503         if (isDone)
2504                 *isDone = ExprSingleResult;
2505         *isNull = true;                         /* until we get a result */
2506
2507         i = 0;
2508         forboth(l, rstate->largs, r, rstate->rargs)
2509         {
2510                 ExprState  *le = (ExprState *) lfirst(l);
2511                 ExprState  *re = (ExprState *) lfirst(r);
2512                 FunctionCallInfoData locfcinfo;
2513
2514                 InitFunctionCallInfoData(locfcinfo, &(rstate->funcs[i]), 2,
2515                                                                  NULL, NULL);
2516                 locfcinfo.arg[0] = ExecEvalExpr(le, econtext,
2517                                                                                 &locfcinfo.argnull[0], NULL);
2518                 locfcinfo.arg[1] = ExecEvalExpr(re, econtext,
2519                                                                                 &locfcinfo.argnull[1], NULL);
2520                 if (rstate->funcs[i].fn_strict &&
2521                         (locfcinfo.argnull[0] || locfcinfo.argnull[1]))
2522                         return (Datum) 0;       /* force NULL result */
2523                 locfcinfo.isnull = false;
2524                 cmpresult = DatumGetInt32(FunctionCallInvoke(&locfcinfo));
2525                 if (locfcinfo.isnull)
2526                         return (Datum) 0;       /* force NULL result */
2527                 if (cmpresult != 0)
2528                         break;                          /* no need to compare remaining columns */
2529                 i++;
2530         }
2531
2532         switch (rctype)
2533         {
2534                         /* EQ and NE cases aren't allowed here */
2535                 case ROWCOMPARE_LT:
2536                         result = (cmpresult < 0);
2537                         break;
2538                 case ROWCOMPARE_LE:
2539                         result = (cmpresult <= 0);
2540                         break;
2541                 case ROWCOMPARE_GE:
2542                         result = (cmpresult >= 0);
2543                         break;
2544                 case ROWCOMPARE_GT:
2545                         result = (cmpresult > 0);
2546                         break;
2547                 default:
2548                         elog(ERROR, "unrecognized RowCompareType: %d", (int) rctype);
2549                         result = 0;                     /* keep compiler quiet */
2550                         break;
2551         }
2552
2553         *isNull = false;
2554         return BoolGetDatum(result);
2555 }
2556
2557 /* ----------------------------------------------------------------
2558  *              ExecEvalCoalesce
2559  * ----------------------------------------------------------------
2560  */
2561 static Datum
2562 ExecEvalCoalesce(CoalesceExprState *coalesceExpr, ExprContext *econtext,
2563                                  bool *isNull, ExprDoneCond *isDone)
2564 {
2565         ListCell   *arg;
2566
2567         if (isDone)
2568                 *isDone = ExprSingleResult;
2569
2570         /* Simply loop through until something NOT NULL is found */
2571         foreach(arg, coalesceExpr->args)
2572         {
2573                 ExprState  *e = (ExprState *) lfirst(arg);
2574                 Datum           value;
2575
2576                 value = ExecEvalExpr(e, econtext, isNull, NULL);
2577                 if (!*isNull)
2578                         return value;
2579         }
2580
2581         /* Else return NULL */
2582         *isNull = true;
2583         return (Datum) 0;
2584 }
2585
2586 /* ----------------------------------------------------------------
2587  *              ExecEvalMinMax
2588  * ----------------------------------------------------------------
2589  */
2590 static Datum
2591 ExecEvalMinMax(MinMaxExprState *minmaxExpr, ExprContext *econtext,
2592                            bool *isNull, ExprDoneCond *isDone)
2593 {
2594         Datum           result = (Datum) 0;
2595         MinMaxOp        op = ((MinMaxExpr *) minmaxExpr->xprstate.expr)->op;
2596         FunctionCallInfoData locfcinfo;
2597         ListCell   *arg;
2598
2599         if (isDone)
2600                 *isDone = ExprSingleResult;
2601         *isNull = true;                         /* until we get a result */
2602
2603         InitFunctionCallInfoData(locfcinfo, &minmaxExpr->cfunc, 2, NULL, NULL);
2604         locfcinfo.argnull[0] = false;
2605         locfcinfo.argnull[1] = false;
2606
2607         foreach(arg, minmaxExpr->args)
2608         {
2609                 ExprState  *e = (ExprState *) lfirst(arg);
2610                 Datum           value;
2611                 bool            valueIsNull;
2612                 int32           cmpresult;
2613
2614                 value = ExecEvalExpr(e, econtext, &valueIsNull, NULL);
2615                 if (valueIsNull)
2616                         continue;                       /* ignore NULL inputs */
2617
2618                 if (*isNull)
2619                 {
2620                         /* first nonnull input, adopt value */
2621                         result = value;
2622                         *isNull = false;
2623                 }
2624                 else
2625                 {
2626                         /* apply comparison function */
2627                         locfcinfo.arg[0] = result;
2628                         locfcinfo.arg[1] = value;
2629                         locfcinfo.isnull = false;
2630                         cmpresult = DatumGetInt32(FunctionCallInvoke(&locfcinfo));
2631                         if (locfcinfo.isnull)           /* probably should not happen */
2632                                 continue;
2633                         if (cmpresult > 0 && op == IS_LEAST)
2634                                 result = value;
2635                         else if (cmpresult < 0 && op == IS_GREATEST)
2636                                 result = value;
2637                 }
2638         }
2639
2640         return result;
2641 }
2642
2643 /* ----------------------------------------------------------------
2644  *              ExecEvalNullIf
2645  *
2646  * Note that this is *always* derived from the equals operator,
2647  * but since we need special processing of the arguments
2648  * we can not simply reuse ExecEvalOper() or ExecEvalFunc().
2649  * ----------------------------------------------------------------
2650  */
2651 static Datum
2652 ExecEvalNullIf(FuncExprState *nullIfExpr,
2653                            ExprContext *econtext,
2654                            bool *isNull, ExprDoneCond *isDone)
2655 {
2656         Datum           result;
2657         FunctionCallInfoData fcinfo;
2658         ExprDoneCond argDone;
2659         List       *argList;
2660
2661         if (isDone)
2662                 *isDone = ExprSingleResult;
2663
2664         /*
2665          * Initialize function cache if first time through
2666          */
2667         if (nullIfExpr->func.fn_oid == InvalidOid)
2668         {
2669                 NullIfExpr *op = (NullIfExpr *) nullIfExpr->xprstate.expr;
2670
2671                 init_fcache(op->opfuncid, nullIfExpr, econtext->ecxt_per_query_memory);
2672                 Assert(!nullIfExpr->func.fn_retset);
2673         }
2674
2675         /*
2676          * extract info from nullIfExpr
2677          */
2678         argList = nullIfExpr->args;
2679
2680         /* Need to prep callinfo structure */
2681         InitFunctionCallInfoData(fcinfo, &(nullIfExpr->func), 0, NULL, NULL);
2682         argDone = ExecEvalFuncArgs(&fcinfo, argList, econtext);
2683         if (argDone != ExprSingleResult)
2684                 ereport(ERROR,
2685                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
2686                                  errmsg("NULLIF does not support set arguments")));
2687         Assert(fcinfo.nargs == 2);
2688
2689         /* if either argument is NULL they can't be equal */
2690         if (!fcinfo.argnull[0] && !fcinfo.argnull[1])
2691         {
2692                 fcinfo.isnull = false;
2693                 result = FunctionCallInvoke(&fcinfo);
2694                 /* if the arguments are equal return null */
2695                 if (!fcinfo.isnull && DatumGetBool(result))
2696                 {
2697                         *isNull = true;
2698                         return (Datum) 0;
2699                 }
2700         }
2701
2702         /* else return first argument */
2703         *isNull = fcinfo.argnull[0];
2704         return fcinfo.arg[0];
2705 }
2706
2707 /* ----------------------------------------------------------------
2708  *              ExecEvalNullTest
2709  *
2710  *              Evaluate a NullTest node.
2711  * ----------------------------------------------------------------
2712  */
2713 static Datum
2714 ExecEvalNullTest(NullTestState *nstate,
2715                                  ExprContext *econtext,
2716                                  bool *isNull,
2717                                  ExprDoneCond *isDone)
2718 {
2719         NullTest   *ntest = (NullTest *) nstate->xprstate.expr;
2720         Datum           result;
2721
2722         result = ExecEvalExpr(nstate->arg, econtext, isNull, isDone);
2723
2724         if (isDone && *isDone == ExprEndResult)
2725                 return result;                  /* nothing to check */
2726
2727         if (nstate->argisrow && !(*isNull))
2728         {
2729                 HeapTupleHeader tuple;
2730                 Oid                     tupType;
2731                 int32           tupTypmod;
2732                 TupleDesc       tupDesc;
2733                 HeapTupleData tmptup;
2734                 int                     att;
2735
2736                 tuple = DatumGetHeapTupleHeader(result);
2737
2738                 tupType = HeapTupleHeaderGetTypeId(tuple);
2739                 tupTypmod = HeapTupleHeaderGetTypMod(tuple);
2740
2741                 /* Lookup tupdesc if first time through or if type changes */
2742                 tupDesc = get_cached_rowtype(tupType, tupTypmod,
2743                                                                          &nstate->argdesc, econtext);
2744
2745                 /*
2746                  * heap_attisnull needs a HeapTuple not a bare HeapTupleHeader.
2747                  */
2748                 tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
2749                 tmptup.t_data = tuple;
2750
2751                 for (att = 1; att <= tupDesc->natts; att++)
2752                 {
2753                         /* ignore dropped columns */
2754                         if (tupDesc->attrs[att - 1]->attisdropped)
2755                                 continue;
2756                         if (heap_attisnull(&tmptup, att))
2757                         {
2758                                 /* null field disproves IS NOT NULL */
2759                                 if (ntest->nulltesttype == IS_NOT_NULL)
2760                                         return BoolGetDatum(false);
2761                         }
2762                         else
2763                         {
2764                                 /* non-null field disproves IS NULL */
2765                                 if (ntest->nulltesttype == IS_NULL)
2766                                         return BoolGetDatum(false);
2767                         }
2768                 }
2769
2770                 return BoolGetDatum(true);
2771         }
2772         else
2773         {
2774                 /* Simple scalar-argument case, or a null rowtype datum */
2775                 switch (ntest->nulltesttype)
2776                 {
2777                         case IS_NULL:
2778                                 if (*isNull)
2779                                 {
2780                                         *isNull = false;
2781                                         return BoolGetDatum(true);
2782                                 }
2783                                 else
2784                                         return BoolGetDatum(false);
2785                         case IS_NOT_NULL:
2786                                 if (*isNull)
2787                                 {
2788                                         *isNull = false;
2789                                         return BoolGetDatum(false);
2790                                 }
2791                                 else
2792                                         return BoolGetDatum(true);
2793                         default:
2794                                 elog(ERROR, "unrecognized nulltesttype: %d",
2795                                          (int) ntest->nulltesttype);
2796                                 return (Datum) 0;               /* keep compiler quiet */
2797                 }
2798         }
2799 }
2800
2801 /* ----------------------------------------------------------------
2802  *              ExecEvalBooleanTest
2803  *
2804  *              Evaluate a BooleanTest node.
2805  * ----------------------------------------------------------------
2806  */
2807 static Datum
2808 ExecEvalBooleanTest(GenericExprState *bstate,
2809                                         ExprContext *econtext,
2810                                         bool *isNull,
2811                                         ExprDoneCond *isDone)
2812 {
2813         BooleanTest *btest = (BooleanTest *) bstate->xprstate.expr;
2814         Datum           result;
2815
2816         result = ExecEvalExpr(bstate->arg, econtext, isNull, isDone);
2817
2818         if (isDone && *isDone == ExprEndResult)
2819                 return result;                  /* nothing to check */
2820
2821         switch (btest->booltesttype)
2822         {
2823                 case IS_TRUE:
2824                         if (*isNull)
2825                         {
2826                                 *isNull = false;
2827                                 return BoolGetDatum(false);
2828                         }
2829                         else if (DatumGetBool(result))
2830                                 return BoolGetDatum(true);
2831                         else
2832                                 return BoolGetDatum(false);
2833                 case IS_NOT_TRUE:
2834                         if (*isNull)
2835                         {
2836                                 *isNull = false;
2837                                 return BoolGetDatum(true);
2838                         }
2839                         else if (DatumGetBool(result))
2840                                 return BoolGetDatum(false);
2841                         else
2842                                 return BoolGetDatum(true);
2843                 case IS_FALSE:
2844                         if (*isNull)
2845                         {
2846                                 *isNull = false;
2847                                 return BoolGetDatum(false);
2848                         }
2849                         else if (DatumGetBool(result))
2850                                 return BoolGetDatum(false);
2851                         else
2852                                 return BoolGetDatum(true);
2853                 case IS_NOT_FALSE:
2854                         if (*isNull)
2855                         {
2856                                 *isNull = false;
2857                                 return BoolGetDatum(true);
2858                         }
2859                         else if (DatumGetBool(result))
2860                                 return BoolGetDatum(true);
2861                         else
2862                                 return BoolGetDatum(false);
2863                 case IS_UNKNOWN:
2864                         if (*isNull)
2865                         {
2866                                 *isNull = false;
2867                                 return BoolGetDatum(true);
2868                         }
2869                         else
2870                                 return BoolGetDatum(false);
2871                 case IS_NOT_UNKNOWN:
2872                         if (*isNull)
2873                         {
2874                                 *isNull = false;
2875                                 return BoolGetDatum(false);
2876                         }
2877                         else
2878                                 return BoolGetDatum(true);
2879                 default:
2880                         elog(ERROR, "unrecognized booltesttype: %d",
2881                                  (int) btest->booltesttype);
2882                         return (Datum) 0;       /* keep compiler quiet */
2883         }
2884 }
2885
2886 /*
2887  * ExecEvalCoerceToDomain
2888  *
2889  * Test the provided data against the domain constraint(s).  If the data
2890  * passes the constraint specifications, pass it through (return the
2891  * datum) otherwise throw an error.
2892  */
2893 static Datum
2894 ExecEvalCoerceToDomain(CoerceToDomainState *cstate, ExprContext *econtext,
2895                                            bool *isNull, ExprDoneCond *isDone)
2896 {
2897         CoerceToDomain *ctest = (CoerceToDomain *) cstate->xprstate.expr;
2898         Datum           result;
2899         ListCell   *l;
2900
2901         result = ExecEvalExpr(cstate->arg, econtext, isNull, isDone);
2902
2903         if (isDone && *isDone == ExprEndResult)
2904                 return result;                  /* nothing to check */
2905
2906         foreach(l, cstate->constraints)
2907         {
2908                 DomainConstraintState *con = (DomainConstraintState *) lfirst(l);
2909
2910                 switch (con->constrainttype)
2911                 {
2912                         case DOM_CONSTRAINT_NOTNULL:
2913                                 if (*isNull)
2914                                         ereport(ERROR,
2915                                                         (errcode(ERRCODE_NOT_NULL_VIOLATION),
2916                                                          errmsg("domain %s does not allow null values",
2917                                                                         format_type_be(ctest->resulttype))));
2918                                 break;
2919                         case DOM_CONSTRAINT_CHECK:
2920                                 {
2921                                         Datum           conResult;
2922                                         bool            conIsNull;
2923                                         Datum           save_datum;
2924                                         bool            save_isNull;
2925
2926                                         /*
2927                                          * Set up value to be returned by CoerceToDomainValue
2928                                          * nodes. We must save and restore prior setting of
2929                                          * econtext's domainValue fields, in case this node is
2930                                          * itself within a check expression for another domain.
2931                                          */
2932                                         save_datum = econtext->domainValue_datum;
2933                                         save_isNull = econtext->domainValue_isNull;
2934
2935                                         econtext->domainValue_datum = result;
2936                                         econtext->domainValue_isNull = *isNull;
2937
2938                                         conResult = ExecEvalExpr(con->check_expr,
2939                                                                                          econtext, &conIsNull, NULL);
2940
2941                                         if (!conIsNull &&
2942                                                 !DatumGetBool(conResult))
2943                                                 ereport(ERROR,
2944                                                                 (errcode(ERRCODE_CHECK_VIOLATION),
2945                                                                  errmsg("value for domain %s violates check constraint \"%s\"",
2946                                                                                 format_type_be(ctest->resulttype),
2947                                                                                 con->name)));
2948                                         econtext->domainValue_datum = save_datum;
2949                                         econtext->domainValue_isNull = save_isNull;
2950
2951                                         break;
2952                                 }
2953                         default:
2954                                 elog(ERROR, "unrecognized constraint type: %d",
2955                                          (int) con->constrainttype);
2956                                 break;
2957                 }
2958         }
2959
2960         /* If all has gone well (constraints did not fail) return the datum */
2961         return result;
2962 }
2963
2964 /*
2965  * ExecEvalCoerceToDomainValue
2966  *
2967  * Return the value stored by CoerceToDomain.
2968  */
2969 static Datum
2970 ExecEvalCoerceToDomainValue(ExprState *exprstate,
2971                                                         ExprContext *econtext,
2972                                                         bool *isNull, ExprDoneCond *isDone)
2973 {
2974         if (isDone)
2975                 *isDone = ExprSingleResult;
2976         *isNull = econtext->domainValue_isNull;
2977         return econtext->domainValue_datum;
2978 }
2979
2980 /* ----------------------------------------------------------------
2981  *              ExecEvalFieldSelect
2982  *
2983  *              Evaluate a FieldSelect node.
2984  * ----------------------------------------------------------------
2985  */
2986 static Datum
2987 ExecEvalFieldSelect(FieldSelectState *fstate,
2988                                         ExprContext *econtext,
2989                                         bool *isNull,
2990                                         ExprDoneCond *isDone)
2991 {
2992         FieldSelect *fselect = (FieldSelect *) fstate->xprstate.expr;
2993         Datum           result;
2994         Datum           tupDatum;
2995         HeapTupleHeader tuple;
2996         Oid                     tupType;
2997         int32           tupTypmod;
2998         TupleDesc       tupDesc;
2999         HeapTupleData tmptup;
3000
3001         tupDatum = ExecEvalExpr(fstate->arg, econtext, isNull, isDone);
3002
3003         /* this test covers the isDone exception too: */
3004         if (*isNull)
3005                 return tupDatum;
3006
3007         tuple = DatumGetHeapTupleHeader(tupDatum);
3008
3009         tupType = HeapTupleHeaderGetTypeId(tuple);
3010         tupTypmod = HeapTupleHeaderGetTypMod(tuple);
3011
3012         /* Lookup tupdesc if first time through or if type changes */
3013         tupDesc = get_cached_rowtype(tupType, tupTypmod,
3014                                                                  &fstate->argdesc, econtext);
3015
3016         /*
3017          * heap_getattr needs a HeapTuple not a bare HeapTupleHeader.  We set all
3018          * the fields in the struct just in case user tries to inspect system
3019          * columns.
3020          */
3021         tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
3022         ItemPointerSetInvalid(&(tmptup.t_self));
3023         tmptup.t_tableOid = InvalidOid;
3024         tmptup.t_data = tuple;
3025
3026         result = heap_getattr(&tmptup,
3027                                                   fselect->fieldnum,
3028                                                   tupDesc,
3029                                                   isNull);
3030         return result;
3031 }
3032
3033 /* ----------------------------------------------------------------
3034  *              ExecEvalFieldStore
3035  *
3036  *              Evaluate a FieldStore node.
3037  * ----------------------------------------------------------------
3038  */
3039 static Datum
3040 ExecEvalFieldStore(FieldStoreState *fstate,
3041                                    ExprContext *econtext,
3042                                    bool *isNull,
3043                                    ExprDoneCond *isDone)
3044 {
3045         FieldStore *fstore = (FieldStore *) fstate->xprstate.expr;
3046         HeapTuple       tuple;
3047         Datum           tupDatum;
3048         TupleDesc       tupDesc;
3049         Datum      *values;
3050         bool       *isnull;
3051         Datum           save_datum;
3052         bool            save_isNull;
3053         ListCell   *l1,
3054                            *l2;
3055
3056         tupDatum = ExecEvalExpr(fstate->arg, econtext, isNull, isDone);
3057
3058         if (isDone && *isDone == ExprEndResult)
3059                 return tupDatum;
3060
3061         /* Lookup tupdesc if first time through or after rescan */
3062         tupDesc = get_cached_rowtype(fstore->resulttype, -1,
3063                                                                  &fstate->argdesc, econtext);
3064
3065         /* Allocate workspace */
3066         values = (Datum *) palloc(tupDesc->natts * sizeof(Datum));
3067         isnull = (bool *) palloc(tupDesc->natts * sizeof(bool));
3068
3069         if (!*isNull)
3070         {
3071                 /*
3072                  * heap_deform_tuple needs a HeapTuple not a bare HeapTupleHeader. We
3073                  * set all the fields in the struct just in case.
3074                  */
3075                 HeapTupleHeader tuphdr;
3076                 HeapTupleData tmptup;
3077
3078                 tuphdr = DatumGetHeapTupleHeader(tupDatum);
3079                 tmptup.t_len = HeapTupleHeaderGetDatumLength(tuphdr);
3080                 ItemPointerSetInvalid(&(tmptup.t_self));
3081                 tmptup.t_tableOid = InvalidOid;
3082                 tmptup.t_data = tuphdr;
3083
3084                 heap_deform_tuple(&tmptup, tupDesc, values, isnull);
3085         }
3086         else
3087         {
3088                 /* Convert null input tuple into an all-nulls row */
3089                 memset(isnull, true, tupDesc->natts * sizeof(bool));
3090         }
3091
3092         /* Result is never null */
3093         *isNull = false;
3094
3095         save_datum = econtext->caseValue_datum;
3096         save_isNull = econtext->caseValue_isNull;
3097
3098         forboth(l1, fstate->newvals, l2, fstore->fieldnums)
3099         {
3100                 ExprState  *newval = (ExprState *) lfirst(l1);
3101                 AttrNumber      fieldnum = lfirst_int(l2);
3102
3103                 Assert(fieldnum > 0 && fieldnum <= tupDesc->natts);
3104
3105                 /*
3106                  * Use the CaseTestExpr mechanism to pass down the old value of the
3107                  * field being replaced; this is useful in case we have a nested field
3108                  * update situation.  It's safe to reuse the CASE mechanism because
3109                  * there cannot be a CASE between here and where the value would be
3110                  * needed.
3111                  */
3112                 econtext->caseValue_datum = values[fieldnum - 1];
3113                 econtext->caseValue_isNull = isnull[fieldnum - 1];
3114
3115                 values[fieldnum - 1] = ExecEvalExpr(newval,
3116                                                                                         econtext,
3117                                                                                         &isnull[fieldnum - 1],
3118                                                                                         NULL);
3119         }
3120
3121         econtext->caseValue_datum = save_datum;
3122         econtext->caseValue_isNull = save_isNull;
3123
3124         tuple = heap_form_tuple(tupDesc, values, isnull);
3125
3126         pfree(values);
3127         pfree(isnull);
3128
3129         return HeapTupleGetDatum(tuple);
3130 }
3131
3132 /* ----------------------------------------------------------------
3133  *              ExecEvalRelabelType
3134  *
3135  *              Evaluate a RelabelType node.
3136  * ----------------------------------------------------------------
3137  */
3138 static Datum
3139 ExecEvalRelabelType(GenericExprState *exprstate,
3140                                         ExprContext *econtext,
3141                                         bool *isNull, ExprDoneCond *isDone)
3142 {
3143         return ExecEvalExpr(exprstate->arg, econtext, isNull, isDone);
3144 }
3145
3146
3147 /*
3148  * ExecEvalExprSwitchContext
3149  *
3150  * Same as ExecEvalExpr, but get into the right allocation context explicitly.
3151  */
3152 Datum
3153 ExecEvalExprSwitchContext(ExprState *expression,
3154                                                   ExprContext *econtext,
3155                                                   bool *isNull,
3156                                                   ExprDoneCond *isDone)
3157 {
3158         Datum           retDatum;
3159         MemoryContext oldContext;
3160
3161         oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
3162         retDatum = ExecEvalExpr(expression, econtext, isNull, isDone);
3163         MemoryContextSwitchTo(oldContext);
3164         return retDatum;
3165 }
3166
3167
3168 /*
3169  * ExecInitExpr: prepare an expression tree for execution
3170  *
3171  * This function builds and returns an ExprState tree paralleling the given
3172  * Expr node tree.      The ExprState tree can then be handed to ExecEvalExpr
3173  * for execution.  Because the Expr tree itself is read-only as far as
3174  * ExecInitExpr and ExecEvalExpr are concerned, several different executions
3175  * of the same plan tree can occur concurrently.
3176  *
3177  * This must be called in a memory context that will last as long as repeated
3178  * executions of the expression are needed.  Typically the context will be
3179  * the same as the per-query context of the associated ExprContext.
3180  *
3181  * Any Aggref and SubPlan nodes found in the tree are added to the lists
3182  * of such nodes held by the parent PlanState.  Otherwise, we do very little
3183  * initialization here other than building the state-node tree.  Any nontrivial
3184  * work associated with initializing runtime info for a node should happen
3185  * during the first actual evaluation of that node.  (This policy lets us
3186  * avoid work if the node is never actually evaluated.)
3187  *
3188  * Note: there is no ExecEndExpr function; we assume that any resource
3189  * cleanup needed will be handled by just releasing the memory context
3190  * in which the state tree is built.  Functions that require additional
3191  * cleanup work can register a shutdown callback in the ExprContext.
3192  *
3193  *      'node' is the root of the expression tree to examine
3194  *      'parent' is the PlanState node that owns the expression.
3195  *
3196  * 'parent' may be NULL if we are preparing an expression that is not
3197  * associated with a plan tree.  (If so, it can't have aggs or subplans.)
3198  * This case should usually come through ExecPrepareExpr, not directly here.
3199  */
3200 ExprState *
3201 ExecInitExpr(Expr *node, PlanState *parent)
3202 {
3203         ExprState  *state;
3204
3205         if (node == NULL)
3206                 return NULL;
3207
3208         /* Guard against stack overflow due to overly complex expressions */
3209         check_stack_depth();
3210
3211         switch (nodeTag(node))
3212         {
3213                 case T_Var:
3214                         {
3215                                 Var                *var = (Var *) node;
3216
3217                                 state = (ExprState *) makeNode(ExprState);
3218                                 if (var->varattno != InvalidAttrNumber)
3219                                         state->evalfunc = ExecEvalVar;
3220                                 else
3221                                         state->evalfunc = ExecEvalWholeRowVar;
3222                         }
3223                         break;
3224                 case T_Const:
3225                         state = (ExprState *) makeNode(ExprState);
3226                         state->evalfunc = ExecEvalConst;
3227                         break;
3228                 case T_Param:
3229                         state = (ExprState *) makeNode(ExprState);
3230                         state->evalfunc = ExecEvalParam;
3231                         break;
3232                 case T_CoerceToDomainValue:
3233                         state = (ExprState *) makeNode(ExprState);
3234                         state->evalfunc = ExecEvalCoerceToDomainValue;
3235                         break;
3236                 case T_CaseTestExpr:
3237                         state = (ExprState *) makeNode(ExprState);
3238                         state->evalfunc = ExecEvalCaseTestExpr;
3239                         break;
3240                 case T_Aggref:
3241                         {
3242                                 Aggref     *aggref = (Aggref *) node;
3243                                 AggrefExprState *astate = makeNode(AggrefExprState);
3244
3245                                 astate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalAggref;
3246                                 if (parent && IsA(parent, AggState))
3247                                 {
3248                                         AggState   *aggstate = (AggState *) parent;
3249                                         int                     naggs;
3250
3251                                         aggstate->aggs = lcons(astate, aggstate->aggs);
3252                                         naggs = ++aggstate->numaggs;
3253
3254                                         astate->args = (List *) ExecInitExpr((Expr *) aggref->args,
3255                                                                                                                  parent);
3256
3257                                         /*
3258                                          * Complain if the aggregate's arguments contain any
3259                                          * aggregates; nested agg functions are semantically
3260                                          * nonsensical.  (This should have been caught earlier,
3261                                          * but we defend against it here anyway.)
3262                                          */
3263                                         if (naggs != aggstate->numaggs)
3264                                                 ereport(ERROR,
3265                                                                 (errcode(ERRCODE_GROUPING_ERROR),
3266                                                                  errmsg("aggregate function calls may not be nested")));
3267                                 }
3268                                 else
3269                                 {
3270                                         /* planner messed up */
3271                                         elog(ERROR, "aggref found in non-Agg plan node");
3272                                 }
3273                                 state = (ExprState *) astate;
3274                         }
3275                         break;
3276                 case T_ArrayRef:
3277                         {
3278                                 ArrayRef   *aref = (ArrayRef *) node;
3279                                 ArrayRefExprState *astate = makeNode(ArrayRefExprState);
3280
3281                                 astate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalArrayRef;
3282                                 astate->refupperindexpr = (List *)
3283                                         ExecInitExpr((Expr *) aref->refupperindexpr, parent);
3284                                 astate->reflowerindexpr = (List *)
3285                                         ExecInitExpr((Expr *) aref->reflowerindexpr, parent);
3286                                 astate->refexpr = ExecInitExpr(aref->refexpr, parent);
3287                                 astate->refassgnexpr = ExecInitExpr(aref->refassgnexpr,
3288                                                                                                         parent);
3289                                 /* do one-time catalog lookups for type info */
3290                                 astate->refattrlength = get_typlen(aref->refarraytype);
3291                                 get_typlenbyvalalign(aref->refelemtype,
3292                                                                          &astate->refelemlength,
3293                                                                          &astate->refelembyval,
3294                                                                          &astate->refelemalign);
3295                                 state = (ExprState *) astate;
3296                         }
3297                         break;
3298                 case T_FuncExpr:
3299                         {
3300                                 FuncExpr   *funcexpr = (FuncExpr *) node;
3301                                 FuncExprState *fstate = makeNode(FuncExprState);
3302
3303                                 fstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalFunc;
3304                                 fstate->args = (List *)
3305                                         ExecInitExpr((Expr *) funcexpr->args, parent);
3306                                 fstate->func.fn_oid = InvalidOid;               /* not initialized */
3307                                 state = (ExprState *) fstate;
3308                         }
3309                         break;
3310                 case T_OpExpr:
3311                         {
3312                                 OpExpr     *opexpr = (OpExpr *) node;
3313                                 FuncExprState *fstate = makeNode(FuncExprState);
3314
3315                                 fstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalOper;
3316                                 fstate->args = (List *)
3317                                         ExecInitExpr((Expr *) opexpr->args, parent);
3318                                 fstate->func.fn_oid = InvalidOid;               /* not initialized */
3319                                 state = (ExprState *) fstate;
3320                         }
3321                         break;
3322                 case T_DistinctExpr:
3323                         {
3324                                 DistinctExpr *distinctexpr = (DistinctExpr *) node;
3325                                 FuncExprState *fstate = makeNode(FuncExprState);
3326
3327                                 fstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalDistinct;
3328                                 fstate->args = (List *)
3329                                         ExecInitExpr((Expr *) distinctexpr->args, parent);
3330                                 fstate->func.fn_oid = InvalidOid;               /* not initialized */
3331                                 state = (ExprState *) fstate;
3332                         }
3333                         break;
3334                 case T_ScalarArrayOpExpr:
3335                         {
3336                                 ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) node;
3337                                 ScalarArrayOpExprState *sstate = makeNode(ScalarArrayOpExprState);
3338
3339                                 sstate->fxprstate.xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalScalarArrayOp;
3340                                 sstate->fxprstate.args = (List *)
3341                                         ExecInitExpr((Expr *) opexpr->args, parent);
3342                                 sstate->fxprstate.func.fn_oid = InvalidOid;             /* not initialized */
3343                                 sstate->element_type = InvalidOid;              /* ditto */
3344                                 state = (ExprState *) sstate;
3345                         }
3346                         break;
3347                 case T_BoolExpr:
3348                         {
3349                                 BoolExpr   *boolexpr = (BoolExpr *) node;
3350                                 BoolExprState *bstate = makeNode(BoolExprState);
3351
3352                                 switch (boolexpr->boolop)
3353                                 {
3354                                         case AND_EXPR:
3355                                                 bstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalAnd;
3356                                                 break;
3357                                         case OR_EXPR:
3358                                                 bstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalOr;
3359                                                 break;
3360                                         case NOT_EXPR:
3361                                                 bstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalNot;
3362                                                 break;
3363                                         default:
3364                                                 elog(ERROR, "unrecognized boolop: %d",
3365                                                          (int) boolexpr->boolop);
3366                                                 break;
3367                                 }
3368                                 bstate->args = (List *)
3369                                         ExecInitExpr((Expr *) boolexpr->args, parent);
3370                                 state = (ExprState *) bstate;
3371                         }
3372                         break;
3373                 case T_SubPlan:
3374                         {
3375                                 /* Keep this in sync with ExecInitExprInitPlan, below */
3376                                 SubPlan    *subplan = (SubPlan *) node;
3377                                 SubPlanState *sstate = makeNode(SubPlanState);
3378
3379                                 sstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecSubPlan;
3380
3381                                 if (!parent)
3382                                         elog(ERROR, "SubPlan found with no parent plan");
3383
3384                                 /*
3385                                  * Here we just add the SubPlanState nodes to parent->subPlan.
3386                                  * The subplans will be initialized later.
3387                                  */
3388                                 parent->subPlan = lcons(sstate, parent->subPlan);
3389                                 sstate->sub_estate = NULL;
3390                                 sstate->planstate = NULL;
3391
3392                                 sstate->testexpr =
3393                                         ExecInitExpr((Expr *) subplan->testexpr, parent);
3394                                 sstate->args = (List *)
3395                                         ExecInitExpr((Expr *) subplan->args, parent);
3396
3397                                 state = (ExprState *) sstate;
3398                         }
3399                         break;
3400                 case T_FieldSelect:
3401                         {
3402                                 FieldSelect *fselect = (FieldSelect *) node;
3403                                 FieldSelectState *fstate = makeNode(FieldSelectState);
3404
3405                                 fstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalFieldSelect;
3406                                 fstate->arg = ExecInitExpr(fselect->arg, parent);
3407                                 fstate->argdesc = NULL;
3408                                 state = (ExprState *) fstate;
3409                         }
3410                         break;
3411                 case T_FieldStore:
3412                         {
3413                                 FieldStore *fstore = (FieldStore *) node;
3414                                 FieldStoreState *fstate = makeNode(FieldStoreState);
3415
3416                                 fstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalFieldStore;
3417                                 fstate->arg = ExecInitExpr(fstore->arg, parent);
3418                                 fstate->newvals = (List *) ExecInitExpr((Expr *) fstore->newvals, parent);
3419                                 fstate->argdesc = NULL;
3420                                 state = (ExprState *) fstate;
3421                         }
3422                         break;
3423                 case T_RelabelType:
3424                         {
3425                                 RelabelType *relabel = (RelabelType *) node;
3426                                 GenericExprState *gstate = makeNode(GenericExprState);
3427
3428                                 gstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalRelabelType;
3429                                 gstate->arg = ExecInitExpr(relabel->arg, parent);
3430                                 state = (ExprState *) gstate;
3431                         }
3432                         break;
3433                 case T_ConvertRowtypeExpr:
3434                         {
3435                                 ConvertRowtypeExpr *convert = (ConvertRowtypeExpr *) node;
3436                                 ConvertRowtypeExprState *cstate = makeNode(ConvertRowtypeExprState);
3437
3438                                 cstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalConvertRowtype;
3439                                 cstate->arg = ExecInitExpr(convert->arg, parent);
3440                                 state = (ExprState *) cstate;
3441                         }
3442                         break;
3443                 case T_CaseExpr:
3444                         {
3445                                 CaseExpr   *caseexpr = (CaseExpr *) node;
3446                                 CaseExprState *cstate = makeNode(CaseExprState);
3447                                 List       *outlist = NIL;
3448                                 ListCell   *l;
3449
3450                                 cstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalCase;
3451                                 cstate->arg = ExecInitExpr(caseexpr->arg, parent);
3452                                 foreach(l, caseexpr->args)
3453                                 {
3454                                         CaseWhen   *when = (CaseWhen *) lfirst(l);
3455                                         CaseWhenState *wstate = makeNode(CaseWhenState);
3456
3457                                         Assert(IsA(when, CaseWhen));
3458                                         wstate->xprstate.evalfunc = NULL;       /* not used */
3459                                         wstate->xprstate.expr = (Expr *) when;
3460                                         wstate->expr = ExecInitExpr(when->expr, parent);
3461                                         wstate->result = ExecInitExpr(when->result, parent);
3462                                         outlist = lappend(outlist, wstate);
3463                                 }
3464                                 cstate->args = outlist;
3465                                 cstate->defresult = ExecInitExpr(caseexpr->defresult, parent);
3466                                 state = (ExprState *) cstate;
3467                         }
3468                         break;
3469                 case T_ArrayExpr:
3470                         {
3471                                 ArrayExpr  *arrayexpr = (ArrayExpr *) node;
3472                                 ArrayExprState *astate = makeNode(ArrayExprState);
3473                                 List       *outlist = NIL;
3474                                 ListCell   *l;
3475
3476                                 astate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalArray;
3477                                 foreach(l, arrayexpr->elements)
3478                                 {
3479                                         Expr       *e = (Expr *) lfirst(l);
3480                                         ExprState  *estate;
3481
3482                                         estate = ExecInitExpr(e, parent);
3483                                         outlist = lappend(outlist, estate);
3484                                 }
3485                                 astate->elements = outlist;
3486                                 /* do one-time catalog lookup for type info */
3487                                 get_typlenbyvalalign(arrayexpr->element_typeid,
3488                                                                          &astate->elemlength,
3489                                                                          &astate->elembyval,
3490                                                                          &astate->elemalign);
3491                                 state = (ExprState *) astate;
3492                         }
3493                         break;
3494                 case T_RowExpr:
3495                         {
3496                                 RowExpr    *rowexpr = (RowExpr *) node;
3497                                 RowExprState *rstate = makeNode(RowExprState);
3498                                 Form_pg_attribute *attrs;
3499                                 List       *outlist = NIL;
3500                                 ListCell   *l;
3501                                 int                     i;
3502
3503                                 rstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalRow;
3504                                 /* Build tupdesc to describe result tuples */
3505                                 if (rowexpr->row_typeid == RECORDOID)
3506                                 {
3507                                         /* generic record, use runtime type assignment */
3508                                         rstate->tupdesc = ExecTypeFromExprList(rowexpr->args);
3509                                         BlessTupleDesc(rstate->tupdesc);
3510                                         /* we won't need to redo this at runtime */
3511                                 }
3512                                 else
3513                                 {
3514                                         /* it's been cast to a named type, use that */
3515                                         rstate->tupdesc = lookup_rowtype_tupdesc_copy(rowexpr->row_typeid, -1);
3516                                 }
3517                                 /* Set up evaluation, skipping any deleted columns */
3518                                 Assert(list_length(rowexpr->args) <= rstate->tupdesc->natts);
3519                                 attrs = rstate->tupdesc->attrs;
3520                                 i = 0;
3521                                 foreach(l, rowexpr->args)
3522                                 {
3523                                         Expr       *e = (Expr *) lfirst(l);
3524                                         ExprState  *estate;
3525
3526                                         if (!attrs[i]->attisdropped)
3527                                         {
3528                                                 /*
3529                                                  * Guard against ALTER COLUMN TYPE on rowtype since
3530                                                  * the RowExpr was created.  XXX should we check
3531                                                  * typmod too?  Not sure we can be sure it'll be the
3532                                                  * same.
3533                                                  */
3534                                                 if (exprType((Node *) e) != attrs[i]->atttypid)
3535                                                         ereport(ERROR,
3536                                                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
3537                                                                          errmsg("ROW() column has type %s instead of type %s",
3538                                                                                 format_type_be(exprType((Node *) e)),
3539                                                                            format_type_be(attrs[i]->atttypid))));
3540                                         }
3541                                         else
3542                                         {
3543                                                 /*
3544                                                  * Ignore original expression and insert a NULL. We
3545                                                  * don't really care what type of NULL it is, so
3546                                                  * always make an int4 NULL.
3547                                                  */
3548                                                 e = (Expr *) makeNullConst(INT4OID);
3549                                         }
3550                                         estate = ExecInitExpr(e, parent);
3551                                         outlist = lappend(outlist, estate);
3552                                         i++;
3553                                 }
3554                                 rstate->args = outlist;
3555                                 state = (ExprState *) rstate;
3556                         }
3557                         break;
3558                 case T_RowCompareExpr:
3559                         {
3560                                 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
3561                                 RowCompareExprState *rstate = makeNode(RowCompareExprState);
3562                                 int                     nopers = list_length(rcexpr->opnos);
3563                                 List       *outlist;
3564                                 ListCell   *l;
3565                                 ListCell   *l2;
3566                                 int                     i;
3567
3568                                 rstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalRowCompare;
3569                                 Assert(list_length(rcexpr->largs) == nopers);
3570                                 outlist = NIL;
3571                                 foreach(l, rcexpr->largs)
3572                                 {
3573                                         Expr       *e = (Expr *) lfirst(l);
3574                                         ExprState  *estate;
3575
3576                                         estate = ExecInitExpr(e, parent);
3577                                         outlist = lappend(outlist, estate);
3578                                 }
3579                                 rstate->largs = outlist;
3580                                 Assert(list_length(rcexpr->rargs) == nopers);
3581                                 outlist = NIL;
3582                                 foreach(l, rcexpr->rargs)
3583                                 {
3584                                         Expr       *e = (Expr *) lfirst(l);
3585                                         ExprState  *estate;
3586
3587                                         estate = ExecInitExpr(e, parent);
3588                                         outlist = lappend(outlist, estate);
3589                                 }
3590                                 rstate->rargs = outlist;
3591                                 Assert(list_length(rcexpr->opclasses) == nopers);
3592                                 rstate->funcs = (FmgrInfo *) palloc(nopers * sizeof(FmgrInfo));
3593                                 i = 0;
3594                                 forboth(l, rcexpr->opnos, l2, rcexpr->opclasses)
3595                                 {
3596                                         Oid                     opno = lfirst_oid(l);
3597                                         Oid                     opclass = lfirst_oid(l2);
3598                                         int                     strategy;
3599                                         Oid                     subtype;
3600                                         bool            recheck;
3601                                         Oid                     proc;
3602
3603                                         get_op_opclass_properties(opno, opclass,
3604                                                                                           &strategy, &subtype, &recheck);
3605                                         proc = get_opclass_proc(opclass, subtype, BTORDER_PROC);
3606
3607                                         /*
3608                                          * If we enforced permissions checks on index support
3609                                          * functions, we'd need to make a check here.  But the
3610                                          * index support machinery doesn't do that, and neither
3611                                          * does this code.
3612                                          */
3613                                         fmgr_info(proc, &(rstate->funcs[i]));
3614                                         i++;
3615                                 }
3616                                 state = (ExprState *) rstate;
3617                         }
3618                         break;
3619                 case T_CoalesceExpr:
3620                         {
3621                                 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
3622                                 CoalesceExprState *cstate = makeNode(CoalesceExprState);
3623                                 List       *outlist = NIL;
3624                                 ListCell   *l;
3625
3626                                 cstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalCoalesce;
3627                                 foreach(l, coalesceexpr->args)
3628                                 {
3629                                         Expr       *e = (Expr *) lfirst(l);
3630                                         ExprState  *estate;
3631
3632                                         estate = ExecInitExpr(e, parent);
3633                                         outlist = lappend(outlist, estate);
3634                                 }
3635                                 cstate->args = outlist;
3636                                 state = (ExprState *) cstate;
3637                         }
3638                         break;
3639                 case T_MinMaxExpr:
3640                         {
3641                                 MinMaxExpr *minmaxexpr = (MinMaxExpr *) node;
3642                                 MinMaxExprState *mstate = makeNode(MinMaxExprState);
3643                                 List       *outlist = NIL;
3644                                 ListCell   *l;
3645                                 TypeCacheEntry *typentry;
3646
3647                                 mstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalMinMax;
3648                                 foreach(l, minmaxexpr->args)
3649                                 {
3650                                         Expr       *e = (Expr *) lfirst(l);
3651                                         ExprState  *estate;
3652
3653                                         estate = ExecInitExpr(e, parent);
3654                                         outlist = lappend(outlist, estate);
3655                                 }
3656                                 mstate->args = outlist;
3657                                 /* Look up the btree comparison function for the datatype */
3658                                 typentry = lookup_type_cache(minmaxexpr->minmaxtype,
3659                                                                                          TYPECACHE_CMP_PROC);
3660                                 if (!OidIsValid(typentry->cmp_proc))
3661                                         ereport(ERROR,
3662                                                         (errcode(ERRCODE_UNDEFINED_FUNCTION),
3663                                                          errmsg("could not identify a comparison function for type %s",
3664                                                                         format_type_be(minmaxexpr->minmaxtype))));
3665
3666                                 /*
3667                                  * If we enforced permissions checks on index support
3668                                  * functions, we'd need to make a check here.  But the index
3669                                  * support machinery doesn't do that, and neither does this
3670                                  * code.
3671                                  */
3672                                 fmgr_info(typentry->cmp_proc, &(mstate->cfunc));
3673                                 state = (ExprState *) mstate;
3674                         }
3675                         break;
3676                 case T_NullIfExpr:
3677                         {
3678                                 NullIfExpr *nullifexpr = (NullIfExpr *) node;
3679                                 FuncExprState *fstate = makeNode(FuncExprState);
3680
3681                                 fstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalNullIf;
3682                                 fstate->args = (List *)
3683                                         ExecInitExpr((Expr *) nullifexpr->args, parent);
3684                                 fstate->func.fn_oid = InvalidOid;               /* not initialized */
3685                                 state = (ExprState *) fstate;
3686                         }
3687                         break;
3688                 case T_NullTest:
3689                         {
3690                                 NullTest   *ntest = (NullTest *) node;
3691                                 NullTestState *nstate = makeNode(NullTestState);
3692
3693                                 nstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalNullTest;
3694                                 nstate->arg = ExecInitExpr(ntest->arg, parent);
3695                                 nstate->argisrow = type_is_rowtype(exprType((Node *) ntest->arg));
3696                                 nstate->argdesc = NULL;
3697                                 state = (ExprState *) nstate;
3698                         }
3699                         break;
3700                 case T_BooleanTest:
3701                         {
3702                                 BooleanTest *btest = (BooleanTest *) node;
3703                                 GenericExprState *gstate = makeNode(GenericExprState);
3704
3705                                 gstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalBooleanTest;
3706                                 gstate->arg = ExecInitExpr(btest->arg, parent);
3707                                 state = (ExprState *) gstate;
3708                         }
3709                         break;
3710                 case T_CoerceToDomain:
3711                         {
3712                                 CoerceToDomain *ctest = (CoerceToDomain *) node;
3713                                 CoerceToDomainState *cstate = makeNode(CoerceToDomainState);
3714
3715                                 cstate->xprstate.evalfunc = (ExprStateEvalFunc) ExecEvalCoerceToDomain;
3716                                 cstate->arg = ExecInitExpr(ctest->arg, parent);
3717                                 cstate->constraints = GetDomainConstraints(ctest->resulttype);
3718                                 state = (ExprState *) cstate;
3719                         }
3720                         break;
3721                 case T_TargetEntry:
3722                         {
3723                                 TargetEntry *tle = (TargetEntry *) node;
3724                                 GenericExprState *gstate = makeNode(GenericExprState);
3725
3726                                 gstate->xprstate.evalfunc = NULL;               /* not used */
3727                                 gstate->arg = ExecInitExpr(tle->expr, parent);
3728                                 state = (ExprState *) gstate;
3729                         }
3730                         break;
3731                 case T_List:
3732                         {
3733                                 List       *outlist = NIL;
3734                                 ListCell   *l;
3735
3736                                 foreach(l, (List *) node)
3737                                 {
3738                                         outlist = lappend(outlist,
3739                                                                           ExecInitExpr((Expr *) lfirst(l),
3740                                                                                                    parent));
3741                                 }
3742                                 /* Don't fall through to the "common" code below */
3743                                 return (ExprState *) outlist;
3744                         }
3745                 default:
3746                         elog(ERROR, "unrecognized node type: %d",
3747                                  (int) nodeTag(node));
3748                         state = NULL;           /* keep compiler quiet */
3749                         break;
3750         }
3751
3752         /* Common code for all state-node types */
3753         state->expr = node;
3754
3755         return state;
3756 }
3757
3758 /*
3759  * ExecInitExprInitPlan --- initialize a subplan expr that's being handled
3760  * as an InitPlan.      This is identical to ExecInitExpr's handling of a regular
3761  * subplan expr, except we do NOT want to add the node to the parent's
3762  * subplan list.
3763  */
3764 SubPlanState *
3765 ExecInitExprInitPlan(SubPlan *node, PlanState *parent)
3766 {
3767         SubPlanState *sstate = makeNode(SubPlanState);
3768
3769         if (!parent)
3770                 elog(ERROR, "SubPlan found with no parent plan");
3771
3772         /* The subplan's state will be initialized later */
3773         sstate->sub_estate = NULL;
3774         sstate->planstate = NULL;
3775
3776         sstate->testexpr = ExecInitExpr((Expr *) node->testexpr, parent);
3777         sstate->args = (List *) ExecInitExpr((Expr *) node->args, parent);
3778
3779         sstate->xprstate.expr = (Expr *) node;
3780
3781         return sstate;
3782 }
3783
3784 /*
3785  * ExecPrepareExpr --- initialize for expression execution outside a normal
3786  * Plan tree context.
3787  *
3788  * This differs from ExecInitExpr in that we don't assume the caller is
3789  * already running in the EState's per-query context.  Also, we apply
3790  * fix_opfuncids() to the passed expression tree to be sure it is ready
3791  * to run.      (In ordinary Plan trees the planner will have fixed opfuncids,
3792  * but callers outside the executor will not have done this.)
3793  */
3794 ExprState *
3795 ExecPrepareExpr(Expr *node, EState *estate)
3796 {
3797         ExprState  *result;
3798         MemoryContext oldcontext;
3799
3800         fix_opfuncids((Node *) node);
3801
3802         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
3803
3804         result = ExecInitExpr(node, NULL);
3805
3806         MemoryContextSwitchTo(oldcontext);
3807
3808         return result;
3809 }
3810
3811
3812 /* ----------------------------------------------------------------
3813  *                                       ExecQual / ExecTargetList / ExecProject
3814  * ----------------------------------------------------------------
3815  */
3816
3817 /* ----------------------------------------------------------------
3818  *              ExecQual
3819  *
3820  *              Evaluates a conjunctive boolean expression (qual list) and
3821  *              returns true iff none of the subexpressions are false.
3822  *              (We also return true if the list is empty.)
3823  *
3824  *      If some of the subexpressions yield NULL but none yield FALSE,
3825  *      then the result of the conjunction is NULL (ie, unknown)
3826  *      according to three-valued boolean logic.  In this case,
3827  *      we return the value specified by the "resultForNull" parameter.
3828  *
3829  *      Callers evaluating WHERE clauses should pass resultForNull=FALSE,
3830  *      since SQL specifies that tuples with null WHERE results do not
3831  *      get selected.  On the other hand, callers evaluating constraint
3832  *      conditions should pass resultForNull=TRUE, since SQL also specifies
3833  *      that NULL constraint conditions are not failures.
3834  *
3835  *      NOTE: it would not be correct to use this routine to evaluate an
3836  *      AND subclause of a boolean expression; for that purpose, a NULL
3837  *      result must be returned as NULL so that it can be properly treated
3838  *      in the next higher operator (cf. ExecEvalAnd and ExecEvalOr).
3839  *      This routine is only used in contexts where a complete expression
3840  *      is being evaluated and we know that NULL can be treated the same
3841  *      as one boolean result or the other.
3842  *
3843  * ----------------------------------------------------------------
3844  */
3845 bool
3846 ExecQual(List *qual, ExprContext *econtext, bool resultForNull)
3847 {
3848         bool            result;
3849         MemoryContext oldContext;
3850         ListCell   *l;
3851
3852         /*
3853          * debugging stuff
3854          */
3855         EV_printf("ExecQual: qual is ");
3856         EV_nodeDisplay(qual);
3857         EV_printf("\n");
3858
3859         IncrProcessed();
3860
3861         /*
3862          * Run in short-lived per-tuple context while computing expressions.
3863          */
3864         oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
3865
3866         /*
3867          * Evaluate the qual conditions one at a time.  If we find a FALSE result,
3868          * we can stop evaluating and return FALSE --- the AND result must be
3869          * FALSE.  Also, if we find a NULL result when resultForNull is FALSE, we
3870          * can stop and return FALSE --- the AND result must be FALSE or NULL in
3871          * that case, and the caller doesn't care which.
3872          *
3873          * If we get to the end of the list, we can return TRUE.  This will happen
3874          * when the AND result is indeed TRUE, or when the AND result is NULL (one
3875          * or more NULL subresult, with all the rest TRUE) and the caller has
3876          * specified resultForNull = TRUE.
3877          */
3878         result = true;
3879
3880         foreach(l, qual)
3881         {
3882                 ExprState  *clause = (ExprState *) lfirst(l);
3883                 Datum           expr_value;
3884                 bool            isNull;
3885
3886                 expr_value = ExecEvalExpr(clause, econtext, &isNull, NULL);
3887
3888                 if (isNull)
3889                 {
3890                         if (resultForNull == false)
3891                         {
3892                                 result = false; /* treat NULL as FALSE */
3893                                 break;
3894                         }
3895                 }
3896                 else
3897                 {
3898                         if (!DatumGetBool(expr_value))
3899                         {
3900                                 result = false; /* definitely FALSE */
3901                                 break;
3902                         }
3903                 }
3904         }
3905
3906         MemoryContextSwitchTo(oldContext);
3907
3908         return result;
3909 }
3910
3911 /*
3912  * Number of items in a tlist (including any resjunk items!)
3913  */
3914 int
3915 ExecTargetListLength(List *targetlist)
3916 {
3917         /* This used to be more complex, but fjoins are dead */
3918         return list_length(targetlist);
3919 }
3920
3921 /*
3922  * Number of items in a tlist, not including any resjunk items
3923  */
3924 int
3925 ExecCleanTargetListLength(List *targetlist)
3926 {
3927         int                     len = 0;
3928         ListCell   *tl;
3929
3930         foreach(tl, targetlist)
3931         {
3932                 TargetEntry *curTle = (TargetEntry *) lfirst(tl);
3933
3934                 Assert(IsA(curTle, TargetEntry));
3935                 if (!curTle->resjunk)
3936                         len++;
3937         }
3938         return len;
3939 }
3940
3941 /*
3942  * ExecTargetList
3943  *              Evaluates a targetlist with respect to the given
3944  *              expression context.  Returns TRUE if we were able to create
3945  *              a result, FALSE if we have exhausted a set-valued expression.
3946  *
3947  * Results are stored into the passed values and isnull arrays.
3948  * The caller must provide an itemIsDone array that persists across calls.
3949  *
3950  * As with ExecEvalExpr, the caller should pass isDone = NULL if not
3951  * prepared to deal with sets of result tuples.  Otherwise, a return
3952  * of *isDone = ExprMultipleResult signifies a set element, and a return
3953  * of *isDone = ExprEndResult signifies end of the set of tuple.
3954  */
3955 static bool
3956 ExecTargetList(List *targetlist,
3957                            ExprContext *econtext,
3958                            Datum *values,
3959                            bool *isnull,
3960                            ExprDoneCond *itemIsDone,
3961                            ExprDoneCond *isDone)
3962 {
3963         MemoryContext oldContext;
3964         ListCell   *tl;
3965         bool            haveDoneSets;
3966
3967         /*
3968          * Run in short-lived per-tuple context while computing expressions.
3969          */
3970         oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
3971
3972         /*
3973          * evaluate all the expressions in the target list
3974          */
3975         if (isDone)
3976                 *isDone = ExprSingleResult;             /* until proven otherwise */
3977
3978         haveDoneSets = false;           /* any exhausted set exprs in tlist? */
3979
3980         foreach(tl, targetlist)
3981         {
3982                 GenericExprState *gstate = (GenericExprState *) lfirst(tl);
3983                 TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr;
3984                 AttrNumber      resind = tle->resno - 1;
3985
3986                 values[resind] = ExecEvalExpr(gstate->arg,
3987                                                                           econtext,
3988                                                                           &isnull[resind],
3989                                                                           &itemIsDone[resind]);
3990
3991                 if (itemIsDone[resind] != ExprSingleResult)
3992                 {
3993                         /* We have a set-valued expression in the tlist */
3994                         if (isDone == NULL)
3995                                 ereport(ERROR,
3996                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3997                                                  errmsg("set-valued function called in context that cannot accept a set")));
3998                         if (itemIsDone[resind] == ExprMultipleResult)
3999                         {
4000                                 /* we have undone sets in the tlist, set flag */
4001                                 *isDone = ExprMultipleResult;
4002                         }
4003                         else
4004                         {
4005                                 /* we have done sets in the tlist, set flag for that */
4006                                 haveDoneSets = true;
4007                         }
4008                 }
4009         }
4010
4011         if (haveDoneSets)
4012         {
4013                 /*
4014                  * note: can't get here unless we verified isDone != NULL
4015                  */
4016                 if (*isDone == ExprSingleResult)
4017                 {
4018                         /*
4019                          * all sets are done, so report that tlist expansion is complete.
4020                          */
4021                         *isDone = ExprEndResult;
4022                         MemoryContextSwitchTo(oldContext);
4023                         return false;
4024                 }
4025                 else
4026                 {
4027                         /*
4028                          * We have some done and some undone sets.      Restart the done ones
4029                          * so that we can deliver a tuple (if possible).
4030                          */
4031                         foreach(tl, targetlist)
4032                         {
4033                                 GenericExprState *gstate = (GenericExprState *) lfirst(tl);
4034                                 TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr;
4035                                 AttrNumber      resind = tle->resno - 1;
4036
4037                                 if (itemIsDone[resind] == ExprEndResult)
4038                                 {
4039                                         values[resind] = ExecEvalExpr(gstate->arg,
4040                                                                                                   econtext,
4041                                                                                                   &isnull[resind],
4042                                                                                                   &itemIsDone[resind]);
4043
4044                                         if (itemIsDone[resind] == ExprEndResult)
4045                                         {
4046                                                 /*
4047                                                  * Oh dear, this item is returning an empty set. Guess
4048                                                  * we can't make a tuple after all.
4049                                                  */
4050                                                 *isDone = ExprEndResult;
4051                                                 break;
4052                                         }
4053                                 }
4054                         }
4055
4056                         /*
4057                          * If we cannot make a tuple because some sets are empty, we still
4058                          * have to cycle the nonempty sets to completion, else resources
4059                          * will not be released from subplans etc.
4060                          *
4061                          * XXX is that still necessary?
4062                          */
4063                         if (*isDone == ExprEndResult)
4064                         {
4065                                 foreach(tl, targetlist)
4066                                 {
4067                                         GenericExprState *gstate = (GenericExprState *) lfirst(tl);
4068                                         TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr;
4069                                         AttrNumber      resind = tle->resno - 1;
4070
4071                                         while (itemIsDone[resind] == ExprMultipleResult)
4072                                         {
4073                                                 values[resind] = ExecEvalExpr(gstate->arg,
4074                                                                                                           econtext,
4075                                                                                                           &isnull[resind],
4076                                                                                                           &itemIsDone[resind]);
4077                                         }
4078                                 }
4079
4080                                 MemoryContextSwitchTo(oldContext);
4081                                 return false;
4082                         }
4083                 }
4084         }
4085
4086         /* Report success */
4087         MemoryContextSwitchTo(oldContext);
4088
4089         return true;
4090 }
4091
4092 /*
4093  * ExecVariableList
4094  *              Evaluates a simple-Variable-list projection.
4095  *
4096  * Results are stored into the passed values and isnull arrays.
4097  */
4098 static void
4099 ExecVariableList(ProjectionInfo *projInfo,
4100                                  Datum *values,
4101                                  bool *isnull)
4102 {
4103         ExprContext *econtext = projInfo->pi_exprContext;
4104         int                *varSlotOffsets = projInfo->pi_varSlotOffsets;
4105         int                *varNumbers = projInfo->pi_varNumbers;
4106         int                     i;
4107
4108         /*
4109          * Force extraction of all input values that we need.
4110          */
4111         if (projInfo->pi_lastInnerVar > 0)
4112                 slot_getsomeattrs(econtext->ecxt_innertuple,
4113                                                   projInfo->pi_lastInnerVar);
4114         if (projInfo->pi_lastOuterVar > 0)
4115                 slot_getsomeattrs(econtext->ecxt_outertuple,
4116                                                   projInfo->pi_lastOuterVar);
4117         if (projInfo->pi_lastScanVar > 0)
4118                 slot_getsomeattrs(econtext->ecxt_scantuple,
4119                                                   projInfo->pi_lastScanVar);
4120
4121         /*
4122          * Assign to result by direct extraction of fields from source slots ... a
4123          * mite ugly, but fast ...
4124          */
4125         for (i = list_length(projInfo->pi_targetlist) - 1; i >= 0; i--)
4126         {
4127                 char       *slotptr = ((char *) econtext) + varSlotOffsets[i];
4128                 TupleTableSlot *varSlot = *((TupleTableSlot **) slotptr);
4129                 int                     varNumber = varNumbers[i] - 1;
4130
4131                 values[i] = varSlot->tts_values[varNumber];
4132                 isnull[i] = varSlot->tts_isnull[varNumber];
4133         }
4134 }
4135
4136 /*
4137  * ExecProject
4138  *
4139  *              projects a tuple based on projection info and stores
4140  *              it in the previously specified tuple table slot.
4141  *
4142  *              Note: the result is always a virtual tuple; therefore it
4143  *              may reference the contents of the exprContext's scan tuples
4144  *              and/or temporary results constructed in the exprContext.
4145  *              If the caller wishes the result to be valid longer than that
4146  *              data will be valid, he must call ExecMaterializeSlot on the
4147  *              result slot.
4148  */
4149 TupleTableSlot *
4150 ExecProject(ProjectionInfo *projInfo, ExprDoneCond *isDone)
4151 {
4152         TupleTableSlot *slot;
4153
4154         /*
4155          * sanity checks
4156          */
4157         Assert(projInfo != NULL);
4158
4159         /*
4160          * get the projection info we want
4161          */
4162         slot = projInfo->pi_slot;
4163
4164         /*
4165          * Clear any former contents of the result slot.  This makes it safe for
4166          * us to use the slot's Datum/isnull arrays as workspace. (Also, we can
4167          * return the slot as-is if we decide no rows can be projected.)
4168          */
4169         ExecClearTuple(slot);
4170
4171         /*
4172          * form a new result tuple (if possible); if successful, mark the result
4173          * slot as containing a valid virtual tuple
4174          */
4175         if (projInfo->pi_isVarList)
4176         {
4177                 /* simple Var list: this always succeeds with one result row */
4178                 if (isDone)
4179                         *isDone = ExprSingleResult;
4180                 ExecVariableList(projInfo,
4181                                                  slot->tts_values,
4182                                                  slot->tts_isnull);
4183                 ExecStoreVirtualTuple(slot);
4184         }
4185         else
4186         {
4187                 if (ExecTargetList(projInfo->pi_targetlist,
4188                                                    projInfo->pi_exprContext,
4189                                                    slot->tts_values,
4190                                                    slot->tts_isnull,
4191                                                    projInfo->pi_itemIsDone,
4192                                                    isDone))
4193                         ExecStoreVirtualTuple(slot);
4194         }
4195
4196         return slot;
4197 }