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