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