]> granicus.if.org Git - postgresql/blob - src/backend/executor/execQual.c
a1c1fdd8ad350e8851b79ec5b4c655513a5b729d
[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-2002, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $Header: /cvsroot/pgsql/src/backend/executor/execQual.c,v 1.126 2003/03/09 02:19:13 tgl Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15 /*
16  *       INTERFACE ROUTINES
17  *              ExecEvalExpr    - evaluate an expression and 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  *              ExecEvalExpr() and ExecEvalVar() are hotspots.  making these faster
24  *              will speed up the entire system.  Unfortunately they are currently
25  *              implemented recursively.  Eliminating the recursion is bound to
26  *              improve the speed of the executor.
27  *
28  *              ExecProject() is used to make tuple projections.  Rather then
29  *              trying to speed it up, the execution plan should be pre-processed
30  *              to facilitate attribute sharing between nodes wherever possible,
31  *              instead of doing needless copying.      -cim 5/31/91
32  *
33  */
34
35 #include "postgres.h"
36
37 #include "access/heapam.h"
38 #include "catalog/pg_type.h"
39 #include "commands/typecmds.h"
40 #include "executor/execdebug.h"
41 #include "executor/functions.h"
42 #include "executor/nodeSubplan.h"
43 #include "miscadmin.h"
44 #include "optimizer/planmain.h"
45 #include "parser/parse_expr.h"
46 #include "utils/acl.h"
47 #include "utils/array.h"
48 #include "utils/builtins.h"
49 #include "utils/lsyscache.h"
50
51
52 /* static function decls */
53 static Datum ExecEvalAggref(AggrefExprState *aggref,
54                                                         ExprContext *econtext,
55                                                         bool *isNull);
56 static Datum ExecEvalArrayRef(ArrayRefExprState *astate,
57                                                           ExprContext *econtext,
58                                                           bool *isNull, ExprDoneCond *isDone);
59 static Datum ExecEvalVar(Var *variable, ExprContext *econtext, bool *isNull);
60 static Datum ExecEvalParam(Param *expression, ExprContext *econtext,
61                                                    bool *isNull);
62 static Datum ExecEvalFunc(FuncExprState *fcache, ExprContext *econtext,
63                          bool *isNull, ExprDoneCond *isDone);
64 static Datum ExecEvalOper(FuncExprState *fcache, ExprContext *econtext,
65                          bool *isNull, ExprDoneCond *isDone);
66 static Datum ExecEvalDistinct(FuncExprState *fcache, ExprContext *econtext,
67                                  bool *isNull);
68 static ExprDoneCond ExecEvalFuncArgs(FunctionCallInfo fcinfo,
69                                  List *argList, ExprContext *econtext);
70 static Datum ExecEvalNot(BoolExprState *notclause, ExprContext *econtext,
71                                                  bool *isNull);
72 static Datum ExecEvalOr(BoolExprState *orExpr, ExprContext *econtext,
73                                                 bool *isNull);
74 static Datum ExecEvalAnd(BoolExprState *andExpr, ExprContext *econtext,
75                                                  bool *isNull);
76 static Datum ExecEvalCase(CaseExprState *caseExpr, ExprContext *econtext,
77                          bool *isNull, ExprDoneCond *isDone);
78 static Datum ExecEvalCoalesce(CoalesceExprState *coalesceExpr,
79                                                           ExprContext *econtext,
80                                                           bool *isNull);
81 static Datum ExecEvalNullIf(FuncExprState *nullIfExpr, ExprContext *econtext,
82                                                         bool *isNull);
83 static Datum ExecEvalNullTest(GenericExprState *nstate,
84                                                           ExprContext *econtext,
85                                                           bool *isNull, ExprDoneCond *isDone);
86 static Datum ExecEvalBooleanTest(GenericExprState *bstate,
87                                                                  ExprContext *econtext,
88                                                                  bool *isNull, ExprDoneCond *isDone);
89 static Datum ExecEvalCoerceToDomain(CoerceToDomainState *cstate,
90                                            ExprContext *econtext,
91                                            bool *isNull, ExprDoneCond *isDone);
92 static Datum ExecEvalCoerceToDomainValue(CoerceToDomainValue *conVal,
93                                            ExprContext *econtext, bool *isNull);
94 static Datum ExecEvalFieldSelect(GenericExprState *fstate,
95                                                                  ExprContext *econtext,
96                                                                  bool *isNull, ExprDoneCond *isDone);
97
98
99 /*----------
100  *        ExecEvalArrayRef
101  *
102  *         This function takes an ArrayRef and returns the extracted Datum
103  *         if it's a simple reference, or the modified array value if it's
104  *         an array assignment (i.e., array element or slice insertion).
105  *
106  * NOTE: if we get a NULL result from a subexpression, we return NULL when
107  * it's an array reference, or the unmodified source array when it's an
108  * array assignment.  This may seem peculiar, but if we return NULL (as was
109  * done in versions up through 7.0) then an assignment like
110  *                      UPDATE table SET arrayfield[4] = NULL
111  * will result in setting the whole array to NULL, which is certainly not
112  * very desirable.      By returning the source array we make the assignment
113  * into a no-op, instead.  (Eventually we need to redesign arrays so that
114  * individual elements can be NULL, but for now, let's try to protect users
115  * from shooting themselves in the foot.)
116  *
117  * NOTE: we deliberately refrain from applying DatumGetArrayTypeP() here,
118  * even though that might seem natural, because this code needs to support
119  * both varlena arrays and fixed-length array types.  DatumGetArrayTypeP()
120  * only works for the varlena kind.  The routines we call in arrayfuncs.c
121  * have to know the difference (that's what they need refattrlength for).
122  *----------
123  */
124 static Datum
125 ExecEvalArrayRef(ArrayRefExprState *astate,
126                                  ExprContext *econtext,
127                                  bool *isNull,
128                                  ExprDoneCond *isDone)
129 {
130         ArrayRef   *arrayRef = (ArrayRef *) astate->xprstate.expr;
131         ArrayType  *array_source;
132         ArrayType  *resultArray;
133         bool            isAssignment = (arrayRef->refassgnexpr != NULL);
134         List       *elt;
135         int                     i = 0,
136                                 j = 0;
137         IntArray        upper,
138                                 lower;
139         int                *lIndex;
140
141         if (arrayRef->refexpr != NULL)
142         {
143                 array_source = (ArrayType *)
144                         DatumGetPointer(ExecEvalExpr(astate->refexpr,
145                                                                                  econtext,
146                                                                                  isNull,
147                                                                                  isDone));
148
149                 /*
150                  * If refexpr yields NULL, result is always NULL, for now anyway.
151                  * (This means you cannot assign to an element or slice of an
152                  * array that's NULL; it'll just stay NULL.)
153                  */
154                 if (*isNull)
155                         return (Datum) NULL;
156         }
157         else
158         {
159                 /*
160                  * Empty refexpr indicates we are doing an INSERT into an array
161                  * column. For now, we just take the refassgnexpr (which the
162                  * parser will have ensured is an array value) and return it
163                  * as-is, ignoring any subscripts that may have been supplied in
164                  * the INSERT column list. This is a kluge, but it's not real
165                  * clear what the semantics ought to be...
166                  */
167                 array_source = NULL;
168         }
169
170         foreach(elt, astate->refupperindexpr)
171         {
172                 if (i >= MAXDIM)
173                         elog(ERROR, "ExecEvalArrayRef: can only handle %d dimensions",
174                                  MAXDIM);
175
176                 upper.indx[i++] = DatumGetInt32(ExecEvalExpr((ExprState *) lfirst(elt),
177                                                                                                          econtext,
178                                                                                                          isNull,
179                                                                                                          NULL));
180                 /* If any index expr yields NULL, result is NULL or source array */
181                 if (*isNull)
182                 {
183                         if (!isAssignment || array_source == NULL)
184                                 return (Datum) NULL;
185                         *isNull = false;
186                         return PointerGetDatum(array_source);
187                 }
188         }
189
190         if (astate->reflowerindexpr != NIL)
191         {
192                 foreach(elt, astate->reflowerindexpr)
193                 {
194                         if (j >= MAXDIM)
195                                 elog(ERROR, "ExecEvalArrayRef: can only handle %d dimensions",
196                                          MAXDIM);
197
198                         lower.indx[j++] = DatumGetInt32(ExecEvalExpr((ExprState *) lfirst(elt),
199                                                                                                                  econtext,
200                                                                                                                  isNull,
201                                                                                                                  NULL));
202
203                         /*
204                          * If any index expr yields NULL, result is NULL or source
205                          * array
206                          */
207                         if (*isNull)
208                         {
209                                 if (!isAssignment || array_source == NULL)
210                                         return (Datum) NULL;
211                                 *isNull = false;
212                                 return PointerGetDatum(array_source);
213                         }
214                 }
215                 if (i != j)
216                         elog(ERROR,
217                                  "ExecEvalArrayRef: upper and lower indices mismatch");
218                 lIndex = lower.indx;
219         }
220         else
221                 lIndex = NULL;
222
223         if (isAssignment)
224         {
225                 Datum           sourceData = ExecEvalExpr(astate->refassgnexpr,
226                                                                                           econtext,
227                                                                                           isNull,
228                                                                                           NULL);
229
230                 /*
231                  * For now, can't cope with inserting NULL into an array, so make
232                  * it a no-op per discussion above...
233                  */
234                 if (*isNull)
235                 {
236                         if (array_source == NULL)
237                                 return (Datum) NULL;
238                         *isNull = false;
239                         return PointerGetDatum(array_source);
240                 }
241
242                 if (array_source == NULL)
243                         return sourceData;      /* XXX do something else? */
244
245                 if (lIndex == NULL)
246                         resultArray = array_set(array_source, i,
247                                                                         upper.indx,
248                                                                         sourceData,
249                                                                         arrayRef->refattrlength,
250                                                                         arrayRef->refelemlength,
251                                                                         arrayRef->refelembyval,
252                                                                         arrayRef->refelemalign,
253                                                                         isNull);
254                 else
255                         resultArray = array_set_slice(array_source, i,
256                                                                                   upper.indx, lower.indx,
257                                                            (ArrayType *) DatumGetPointer(sourceData),
258                                                                                   arrayRef->refattrlength,
259                                                                                   arrayRef->refelemlength,
260                                                                                   arrayRef->refelembyval,
261                                                                                   arrayRef->refelemalign,
262                                                                                   isNull);
263                 return PointerGetDatum(resultArray);
264         }
265
266         if (lIndex == NULL)
267                 return array_ref(array_source, i, upper.indx,
268                                                  arrayRef->refattrlength,
269                                                  arrayRef->refelemlength,
270                                                  arrayRef->refelembyval,
271                                                  arrayRef->refelemalign,
272                                                  isNull);
273         else
274         {
275                 resultArray = array_get_slice(array_source, i,
276                                                                           upper.indx, lower.indx,
277                                                                           arrayRef->refattrlength,
278                                                                           arrayRef->refelemlength,
279                                                                           arrayRef->refelembyval,
280                                                                           arrayRef->refelemalign,
281                                                                           isNull);
282                 return PointerGetDatum(resultArray);
283         }
284 }
285
286
287 /* ----------------------------------------------------------------
288  *              ExecEvalAggref
289  *
290  *              Returns a Datum whose value is the value of the precomputed
291  *              aggregate found in the given expression context.
292  * ----------------------------------------------------------------
293  */
294 static Datum
295 ExecEvalAggref(AggrefExprState *aggref, ExprContext *econtext, bool *isNull)
296 {
297         if (econtext->ecxt_aggvalues == NULL)           /* safety check */
298                 elog(ERROR, "ExecEvalAggref: no aggregates in this expression context");
299
300         *isNull = econtext->ecxt_aggnulls[aggref->aggno];
301         return econtext->ecxt_aggvalues[aggref->aggno];
302 }
303
304 /* ----------------------------------------------------------------
305  *              ExecEvalVar
306  *
307  *              Returns a Datum whose value is the value of a range
308  *              variable with respect to given expression context.
309  *
310  *
311  *              As an entry condition, we expect that the datatype the
312  *              plan expects to get (as told by our "variable" argument) is in
313  *              fact the datatype of the attribute the plan says to fetch (as
314  *              seen in the current context, identified by our "econtext"
315  *              argument).
316  *
317  *              If we fetch a Type A attribute and Caller treats it as if it
318  *              were Type B, there will be undefined results (e.g. crash).
319  *              One way these might mismatch now is that we're accessing a
320  *              catalog class and the type information in the pg_attribute
321  *              class does not match the hardcoded pg_attribute information
322  *              (in pg_attribute.h) for the class in question.
323  *
324  *              We have an Assert to make sure this entry condition is met.
325  *
326  * ---------------------------------------------------------------- */
327 static Datum
328 ExecEvalVar(Var *variable, ExprContext *econtext, bool *isNull)
329 {
330         Datum           result;
331         TupleTableSlot *slot;
332         AttrNumber      attnum;
333         HeapTuple       heapTuple;
334         TupleDesc       tuple_type;
335
336         /*
337          * get the slot we want
338          */
339         switch (variable->varno)
340         {
341                 case INNER:                             /* get the tuple from the inner node */
342                         slot = econtext->ecxt_innertuple;
343                         break;
344
345                 case OUTER:                             /* get the tuple from the outer node */
346                         slot = econtext->ecxt_outertuple;
347                         break;
348
349                 default:                                /* get the tuple from the relation being
350                                                                  * scanned */
351                         slot = econtext->ecxt_scantuple;
352                         break;
353         }
354
355         /*
356          * extract tuple information from the slot
357          */
358         heapTuple = slot->val;
359         tuple_type = slot->ttc_tupleDescriptor;
360
361         attnum = variable->varattno;
362
363         /* (See prolog for explanation of this Assert) */
364         Assert(attnum <= 0 ||
365                    (attnum - 1 <= tuple_type->natts - 1 &&
366                         tuple_type->attrs[attnum - 1] != NULL &&
367                   variable->vartype == tuple_type->attrs[attnum - 1]->atttypid));
368
369         /*
370          * If the attribute number is invalid, then we are supposed to return
371          * the entire tuple; we give back a whole slot so that callers know
372          * what the tuple looks like.
373          *
374          * XXX this is a horrid crock: since the pointer to the slot might live
375          * longer than the current evaluation context, we are forced to copy
376          * the tuple and slot into a long-lived context --- we use
377          * TransactionCommandContext which should be safe enough.  This
378          * represents a serious memory leak if many such tuples are processed
379          * in one command, however.  We ought to redesign the representation
380          * of whole-tuple datums so that this is not necessary.
381          *
382          * We assume it's OK to point to the existing tupleDescriptor, rather
383          * than copy that too.
384          */
385         if (attnum == InvalidAttrNumber)
386         {
387                 MemoryContext oldContext;
388                 TupleTableSlot *tempSlot;
389                 HeapTuple       tup;
390
391                 oldContext = MemoryContextSwitchTo(TransactionCommandContext);
392                 tempSlot = MakeTupleTableSlot();
393                 tup = heap_copytuple(heapTuple);
394                 ExecStoreTuple(tup, tempSlot, InvalidBuffer, true);
395                 ExecSetSlotDescriptor(tempSlot, tuple_type, false);
396                 MemoryContextSwitchTo(oldContext);
397                 return PointerGetDatum(tempSlot);
398         }
399
400         result = heap_getattr(heapTuple,        /* tuple containing attribute */
401                                                   attnum,               /* attribute number of desired
402                                                                                  * attribute */
403                                                   tuple_type,   /* tuple descriptor of tuple */
404                                                   isNull);              /* return: is attribute null? */
405
406         return result;
407 }
408
409 /* ----------------------------------------------------------------
410  *              ExecEvalParam
411  *
412  *              Returns the value of a parameter.  A param node contains
413  *              something like ($.name) and the expression context contains
414  *              the current parameter bindings (name = "sam") (age = 34)...
415  *              so our job is to find and return the appropriate datum ("sam").
416  *
417  *              Q: if we have a parameter ($.foo) without a binding, i.e.
418  *                 there is no (foo = xxx) in the parameter list info,
419  *                 is this a fatal error or should this be a "not available"
420  *                 (in which case we could return NULL)?        -cim 10/13/89
421  * ----------------------------------------------------------------
422  */
423 static Datum
424 ExecEvalParam(Param *expression, ExprContext *econtext, bool *isNull)
425 {
426         int                     thisParamKind = expression->paramkind;
427         AttrNumber      thisParamId = expression->paramid;
428
429         if (thisParamKind == PARAM_EXEC)
430         {
431                 /*
432                  * PARAM_EXEC params (internal executor parameters) are stored in
433                  * the ecxt_param_exec_vals array, and can be accessed by array index.
434                  */
435                 ParamExecData *prm;
436
437                 prm = &(econtext->ecxt_param_exec_vals[thisParamId]);
438                 if (prm->execPlan != NULL)
439                 {
440                         /* Parameter not evaluated yet, so go do it */
441                         ExecSetParamPlan(prm->execPlan, econtext);
442                         /* ExecSetParamPlan should have processed this param... */
443                         Assert(prm->execPlan == NULL);
444                 }
445                 *isNull = prm->isnull;
446                 return prm->value;
447         }
448         else
449         {
450                 /*
451                  * All other parameter types must be sought in ecxt_param_list_info.
452                  * NOTE: The last entry in the param array is always an
453                  * entry with kind == PARAM_INVALID.
454                  */
455                 ParamListInfo paramList = econtext->ecxt_param_list_info;
456                 char       *thisParamName = expression->paramname;
457                 bool            matchFound = false;
458
459                 if (paramList != NULL)
460                 {
461                         while (paramList->kind != PARAM_INVALID && !matchFound)
462                         {
463                                 if (thisParamKind == paramList->kind)
464                                 {
465                                         switch (thisParamKind)
466                                         {
467                                                 case PARAM_NAMED:
468                                                         if (strcmp(paramList->name, thisParamName) == 0)
469                                                                 matchFound = true;
470                                                         break;
471                                                 case PARAM_NUM:
472                                                         if (paramList->id == thisParamId)
473                                                                 matchFound = true;
474                                                         break;
475                                                 default:
476                                                         elog(ERROR, "ExecEvalParam: invalid paramkind %d",
477                                                                  thisParamKind);
478                                         }
479                                 }
480                                 if (!matchFound)
481                                         paramList++;
482                         } /* while */
483                 } /* if */
484
485                 if (!matchFound)
486                 {
487                         if (thisParamKind == PARAM_NAMED)
488                                 elog(ERROR, "ExecEvalParam: Unknown value for parameter %s",
489                                          thisParamName);
490                         else
491                                 elog(ERROR, "ExecEvalParam: Unknown value for parameter %d",
492                                          thisParamId);
493                 }
494
495                 *isNull = paramList->isnull;
496                 return paramList->value;
497         }
498 }
499
500
501 /* ----------------------------------------------------------------
502  *              ExecEvalOper / ExecEvalFunc support routines
503  * ----------------------------------------------------------------
504  */
505
506 /*
507  *              GetAttributeByName
508  *              GetAttributeByNum
509  *
510  *              These are functions which return the value of the
511  *              named attribute out of the tuple from the arg slot.  User defined
512  *              C functions which take a tuple as an argument are expected
513  *              to use this.  Ex: overpaid(EMP) might call GetAttributeByNum().
514  */
515 Datum
516 GetAttributeByNum(TupleTableSlot *slot,
517                                   AttrNumber attrno,
518                                   bool *isNull)
519 {
520         Datum           retval;
521
522         if (!AttributeNumberIsValid(attrno))
523                 elog(ERROR, "GetAttributeByNum: Invalid attribute number");
524
525         if (!AttrNumberIsForUserDefinedAttr(attrno))
526                 elog(ERROR, "GetAttributeByNum: cannot access system attributes here");
527
528         if (isNull == (bool *) NULL)
529                 elog(ERROR, "GetAttributeByNum: a NULL isNull flag was passed");
530
531         if (TupIsNull(slot))
532         {
533                 *isNull = true;
534                 return (Datum) 0;
535         }
536
537         retval = heap_getattr(slot->val,
538                                                   attrno,
539                                                   slot->ttc_tupleDescriptor,
540                                                   isNull);
541         if (*isNull)
542                 return (Datum) 0;
543
544         return retval;
545 }
546
547 Datum
548 GetAttributeByName(TupleTableSlot *slot, char *attname, bool *isNull)
549 {
550         AttrNumber      attrno;
551         TupleDesc       tupdesc;
552         Datum           retval;
553         int                     natts;
554         int                     i;
555
556         if (attname == NULL)
557                 elog(ERROR, "GetAttributeByName: Invalid attribute name");
558
559         if (isNull == (bool *) NULL)
560                 elog(ERROR, "GetAttributeByName: a NULL isNull flag was passed");
561
562         if (TupIsNull(slot))
563         {
564                 *isNull = true;
565                 return (Datum) 0;
566         }
567
568         tupdesc = slot->ttc_tupleDescriptor;
569         natts = slot->val->t_data->t_natts;
570
571         attrno = InvalidAttrNumber;
572         for (i = 0; i < tupdesc->natts; i++)
573         {
574                 if (namestrcmp(&(tupdesc->attrs[i]->attname), attname) == 0)
575                 {
576                         attrno = tupdesc->attrs[i]->attnum;
577                         break;
578                 }
579         }
580
581         if (attrno == InvalidAttrNumber)
582                 elog(ERROR, "GetAttributeByName: attribute %s not found", attname);
583
584         retval = heap_getattr(slot->val,
585                                                   attrno,
586                                                   tupdesc,
587                                                   isNull);
588         if (*isNull)
589                 return (Datum) 0;
590
591         return retval;
592 }
593
594 /*
595  * init_fcache - initialize a FuncExprState node during first use
596  */
597 void
598 init_fcache(Oid foid, FuncExprState *fcache, MemoryContext fcacheCxt)
599 {
600         AclResult       aclresult;
601
602         /* Check permission to call function */
603         aclresult = pg_proc_aclcheck(foid, GetUserId(), ACL_EXECUTE);
604         if (aclresult != ACLCHECK_OK)
605                 aclcheck_error(aclresult, get_func_name(foid));
606
607         /* Safety check (should never fail, as parser should check sooner) */
608         if (length(fcache->args) > FUNC_MAX_ARGS)
609                 elog(ERROR, "init_fcache: too many arguments");
610
611         /* Set up the primary fmgr lookup information */
612         fmgr_info_cxt(foid, &(fcache->func), fcacheCxt);
613
614         /* Initialize additional info */
615         fcache->setArgsValid = false;
616 }
617
618 /*
619  * Evaluate arguments for a function.
620  */
621 static ExprDoneCond
622 ExecEvalFuncArgs(FunctionCallInfo fcinfo,
623                                  List *argList,
624                                  ExprContext *econtext)
625 {
626         ExprDoneCond argIsDone;
627         int                     i;
628         List       *arg;
629
630         argIsDone = ExprSingleResult;           /* default assumption */
631
632         i = 0;
633         foreach(arg, argList)
634         {
635                 ExprDoneCond thisArgIsDone;
636
637                 fcinfo->arg[i] = ExecEvalExpr((ExprState *) lfirst(arg),
638                                                                           econtext,
639                                                                           &fcinfo->argnull[i],
640                                                                           &thisArgIsDone);
641
642                 if (thisArgIsDone != ExprSingleResult)
643                 {
644                         /*
645                          * We allow only one argument to have a set value; we'd need
646                          * much more complexity to keep track of multiple set
647                          * arguments (cf. ExecTargetList) and it doesn't seem worth
648                          * it.
649                          */
650                         if (argIsDone != ExprSingleResult)
651                                 elog(ERROR, "Functions and operators can take only one set argument");
652                         argIsDone = thisArgIsDone;
653                 }
654                 i++;
655         }
656
657         fcinfo->nargs = i;
658
659         return argIsDone;
660 }
661
662 /*
663  *              ExecMakeFunctionResult
664  *
665  * Evaluate the arguments to a function and then the function itself.
666  */
667 Datum
668 ExecMakeFunctionResult(FuncExprState *fcache,
669                                            ExprContext *econtext,
670                                            bool *isNull,
671                                            ExprDoneCond *isDone)
672 {
673         List       *arguments = fcache->args;
674         Datum           result;
675         FunctionCallInfoData fcinfo;
676         ReturnSetInfo rsinfo;           /* for functions returning sets */
677         ExprDoneCond argDone;
678         bool            hasSetArg;
679         int                     i;
680
681         /*
682          * arguments is a list of expressions to evaluate before passing to
683          * the function manager.  We skip the evaluation if it was already
684          * done in the previous call (ie, we are continuing the evaluation of
685          * a set-valued function).      Otherwise, collect the current argument
686          * values into fcinfo.
687          */
688         if (!fcache->setArgsValid)
689         {
690                 /* Need to prep callinfo structure */
691                 MemSet(&fcinfo, 0, sizeof(fcinfo));
692                 fcinfo.flinfo = &(fcache->func);
693                 argDone = ExecEvalFuncArgs(&fcinfo, arguments, econtext);
694                 if (argDone == ExprEndResult)
695                 {
696                         /* input is an empty set, so return an empty set. */
697                         *isNull = true;
698                         if (isDone)
699                                 *isDone = ExprEndResult;
700                         else
701                                 elog(ERROR, "Set-valued function called in context that cannot accept a set");
702                         return (Datum) 0;
703                 }
704                 hasSetArg = (argDone != ExprSingleResult);
705         }
706         else
707         {
708                 /* Copy callinfo from previous evaluation */
709                 memcpy(&fcinfo, &fcache->setArgs, sizeof(fcinfo));
710                 hasSetArg = fcache->setHasSetArg;
711                 /* Reset flag (we may set it again below) */
712                 fcache->setArgsValid = false;
713         }
714
715         /*
716          * If function returns set, prepare a resultinfo node for
717          * communication
718          */
719         if (fcache->func.fn_retset)
720         {
721                 fcinfo.resultinfo = (Node *) &rsinfo;
722                 rsinfo.type = T_ReturnSetInfo;
723                 rsinfo.econtext = econtext;
724                 rsinfo.expectedDesc = NULL;
725                 rsinfo.allowedModes = (int) SFRM_ValuePerCall;
726                 rsinfo.returnMode = SFRM_ValuePerCall;
727                 /* isDone is filled below */
728                 rsinfo.setResult = NULL;
729                 rsinfo.setDesc = NULL;
730         }
731
732         /*
733          * now return the value gotten by calling the function manager,
734          * passing the function the evaluated parameter values.
735          */
736         if (fcache->func.fn_retset || hasSetArg)
737         {
738                 /*
739                  * We need to return a set result.      Complain if caller not ready
740                  * to accept one.
741                  */
742                 if (isDone == NULL)
743                         elog(ERROR, "Set-valued function called in context that cannot accept a set");
744
745                 /*
746                  * This loop handles the situation where we have both a set
747                  * argument and a set-valued function.  Once we have exhausted the
748                  * function's value(s) for a particular argument value, we have to
749                  * get the next argument value and start the function over again.
750                  * We might have to do it more than once, if the function produces
751                  * an empty result set for a particular input value.
752                  */
753                 for (;;)
754                 {
755                         /*
756                          * If function is strict, and there are any NULL arguments,
757                          * skip calling the function (at least for this set of args).
758                          */
759                         bool            callit = true;
760
761                         if (fcache->func.fn_strict)
762                         {
763                                 for (i = 0; i < fcinfo.nargs; i++)
764                                 {
765                                         if (fcinfo.argnull[i])
766                                         {
767                                                 callit = false;
768                                                 break;
769                                         }
770                                 }
771                         }
772
773                         if (callit)
774                         {
775                                 fcinfo.isnull = false;
776                                 rsinfo.isDone = ExprSingleResult;
777                                 result = FunctionCallInvoke(&fcinfo);
778                                 *isNull = fcinfo.isnull;
779                                 *isDone = rsinfo.isDone;
780                         }
781                         else
782                         {
783                                 result = (Datum) 0;
784                                 *isNull = true;
785                                 *isDone = ExprEndResult;
786                         }
787
788                         if (*isDone != ExprEndResult)
789                         {
790                                 /*
791                                  * Got a result from current argument.  If function itself
792                                  * returns set, save the current argument values to re-use
793                                  * on the next call.
794                                  */
795                                 if (fcache->func.fn_retset)
796                                 {
797                                         memcpy(&fcache->setArgs, &fcinfo, sizeof(fcinfo));
798                                         fcache->setHasSetArg = hasSetArg;
799                                         fcache->setArgsValid = true;
800                                 }
801
802                                 /*
803                                  * Make sure we say we are returning a set, even if the
804                                  * function itself doesn't return sets.
805                                  */
806                                 *isDone = ExprMultipleResult;
807                                 break;
808                         }
809
810                         /* Else, done with this argument */
811                         if (!hasSetArg)
812                                 break;                  /* input not a set, so done */
813
814                         /* Re-eval args to get the next element of the input set */
815                         argDone = ExecEvalFuncArgs(&fcinfo, arguments, econtext);
816
817                         if (argDone != ExprMultipleResult)
818                         {
819                                 /* End of argument set, so we're done. */
820                                 *isNull = true;
821                                 *isDone = ExprEndResult;
822                                 result = (Datum) 0;
823                                 break;
824                         }
825
826                         /*
827                          * If we reach here, loop around to run the function on the
828                          * new argument.
829                          */
830                 }
831         }
832         else
833         {
834                 /*
835                  * Non-set case: much easier.
836                  *
837                  * If function is strict, and there are any NULL arguments, skip
838                  * calling the function and return NULL.
839                  */
840                 if (fcache->func.fn_strict)
841                 {
842                         for (i = 0; i < fcinfo.nargs; i++)
843                         {
844                                 if (fcinfo.argnull[i])
845                                 {
846                                         *isNull = true;
847                                         return (Datum) 0;
848                                 }
849                         }
850                 }
851                 fcinfo.isnull = false;
852                 result = FunctionCallInvoke(&fcinfo);
853                 *isNull = fcinfo.isnull;
854         }
855
856         return result;
857 }
858
859
860 /*
861  *              ExecMakeTableFunctionResult
862  *
863  * Evaluate a table function, producing a materialized result in a Tuplestore
864  * object.      (If function returns an empty set, we just return NULL instead.)
865  */
866 Tuplestorestate *
867 ExecMakeTableFunctionResult(ExprState *funcexpr,
868                                                         ExprContext *econtext,
869                                                         TupleDesc expectedDesc,
870                                                         TupleDesc *returnDesc)
871 {
872         Tuplestorestate *tupstore = NULL;
873         TupleDesc       tupdesc = NULL;
874         Oid                     funcrettype;
875         FunctionCallInfoData fcinfo;
876         ReturnSetInfo rsinfo;
877         MemoryContext callerContext;
878         MemoryContext oldcontext;
879         TupleTableSlot *slot;
880         bool            direct_function_call;
881         bool            first_time = true;
882         bool            returnsTuple = false;
883
884         /*
885          * Normally the passed expression tree will be a FuncExprState, since the
886          * grammar only allows a function call at the top level of a table
887          * function reference.  However, if the function doesn't return set then
888          * the planner might have replaced the function call via constant-folding
889          * or inlining.  So if we see any other kind of expression node, execute
890          * it via the general ExecEvalExpr() code; the only difference is that
891          * we don't get a chance to pass a special ReturnSetInfo to any functions
892          * buried in the expression.
893          */
894         if (funcexpr && IsA(funcexpr, FuncExprState) &&
895                 IsA(funcexpr->expr, FuncExpr))
896         {
897                 FuncExprState *fcache = (FuncExprState *) funcexpr;
898                 ExprDoneCond argDone;
899
900                 /*
901                  * This path is similar to ExecMakeFunctionResult.
902                  */
903                 direct_function_call = true;
904
905                 /*
906                  * Initialize function cache if first time through
907                  */
908                 if (fcache->func.fn_oid == InvalidOid)
909                 {
910                         FuncExpr *func = (FuncExpr *) fcache->xprstate.expr;
911
912                         init_fcache(func->funcid, fcache, econtext->ecxt_per_query_memory);
913                 }
914
915                 /*
916                  * Evaluate the function's argument list.
917                  *
918                  * Note: ideally, we'd do this in the per-tuple context, but then the
919                  * argument values would disappear when we reset the context in the
920                  * inner loop.  So do it in caller context.  Perhaps we should make a
921                  * separate context just to hold the evaluated arguments?
922                  */
923                 MemSet(&fcinfo, 0, sizeof(fcinfo));
924                 fcinfo.flinfo = &(fcache->func);
925                 argDone = ExecEvalFuncArgs(&fcinfo, fcache->args, econtext);
926                 /* We don't allow sets in the arguments of the table function */
927                 if (argDone != ExprSingleResult)
928                         elog(ERROR, "Set-valued function called in context that cannot accept a set");
929
930                 /*
931                  * If function is strict, and there are any NULL arguments, skip
932                  * calling the function and return NULL (actually an empty set).
933                  */
934                 if (fcache->func.fn_strict)
935                 {
936                         int                     i;
937
938                         for (i = 0; i < fcinfo.nargs; i++)
939                         {
940                                 if (fcinfo.argnull[i])
941                                 {
942                                         *returnDesc = NULL;
943                                         return NULL;
944                                 }
945                         }
946                 }
947         }
948         else
949         {
950                 /* Treat funcexpr as a generic expression */
951                 direct_function_call = false;
952         }
953
954         funcrettype = exprType((Node *) funcexpr->expr);
955
956         /*
957          * Prepare a resultinfo node for communication.  We always do this
958          * even if not expecting a set result, so that we can pass
959          * expectedDesc.  In the generic-expression case, the expression
960          * doesn't actually get to see the resultinfo, but set it up anyway
961          * because we use some of the fields as our own state variables.
962          */
963         fcinfo.resultinfo = (Node *) &rsinfo;
964         rsinfo.type = T_ReturnSetInfo;
965         rsinfo.econtext = econtext;
966         rsinfo.expectedDesc = expectedDesc;
967         rsinfo.allowedModes = (int) (SFRM_ValuePerCall | SFRM_Materialize);
968         rsinfo.returnMode = SFRM_ValuePerCall;
969         /* isDone is filled below */
970         rsinfo.setResult = NULL;
971         rsinfo.setDesc = NULL;
972
973         /*
974          * Switch to short-lived context for calling the function or expression.
975          */
976         callerContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
977
978         /*
979          * Loop to handle the ValuePerCall protocol (which is also the same
980          * behavior needed in the generic ExecEvalExpr path).
981          */
982         for (;;)
983         {
984                 Datum           result;
985                 HeapTuple       tuple;
986
987                 /*
988                  * reset per-tuple memory context before each call of the
989                  * function or expression. This cleans up any local memory the
990                  * function may leak when called.
991                  */
992                 ResetExprContext(econtext);
993
994                 /* Call the function or expression one time */
995                 if (direct_function_call)
996                 {
997                         fcinfo.isnull = false;
998                         rsinfo.isDone = ExprSingleResult;
999                         result = FunctionCallInvoke(&fcinfo);
1000                 }
1001                 else
1002                 {
1003                         result = ExecEvalExpr(funcexpr, econtext,
1004                                                                   &fcinfo.isnull, &rsinfo.isDone);
1005                 }
1006
1007                 /* Which protocol does function want to use? */
1008                 if (rsinfo.returnMode == SFRM_ValuePerCall)
1009                 {
1010                         /*
1011                          * Check for end of result set.
1012                          *
1013                          * Note: if function returns an empty set, we don't build a
1014                          * tupdesc or tuplestore (since we can't get a tupdesc in the
1015                          * function-returning-tuple case)
1016                          */
1017                         if (rsinfo.isDone == ExprEndResult)
1018                                 break;
1019
1020                         /*
1021                          * If first time through, build tupdesc and tuplestore for
1022                          * result
1023                          */
1024                         if (first_time)
1025                         {
1026                                 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1027                                 if (funcrettype == RECORDOID ||
1028                                         get_typtype(funcrettype) == 'c')
1029                                 {
1030                                         /*
1031                                          * Composite type, so function should have returned a
1032                                          * TupleTableSlot; use its descriptor
1033                                          */
1034                                         slot = (TupleTableSlot *) DatumGetPointer(result);
1035                                         if (fcinfo.isnull ||
1036                                                 !slot ||
1037                                                 !IsA(slot, TupleTableSlot) ||
1038                                                 !slot->ttc_tupleDescriptor)
1039                                                 elog(ERROR, "ExecMakeTableFunctionResult: Invalid result from function returning tuple");
1040                                         tupdesc = CreateTupleDescCopy(slot->ttc_tupleDescriptor);
1041                                         returnsTuple = true;
1042                                 }
1043                                 else
1044                                 {
1045                                         /*
1046                                          * Scalar type, so make a single-column descriptor
1047                                          */
1048                                         tupdesc = CreateTemplateTupleDesc(1, false);
1049                                         TupleDescInitEntry(tupdesc,
1050                                                                            (AttrNumber) 1,
1051                                                                            "column",
1052                                                                            funcrettype,
1053                                                                            -1,
1054                                                                            0,
1055                                                                            false);
1056                                 }
1057                                 tupstore = tuplestore_begin_heap(true,  /* randomAccess */
1058                                                                                                  SortMem);
1059                                 MemoryContextSwitchTo(oldcontext);
1060                                 rsinfo.setResult = tupstore;
1061                                 rsinfo.setDesc = tupdesc;
1062                         }
1063
1064                         /*
1065                          * Store current resultset item.
1066                          */
1067                         if (returnsTuple)
1068                         {
1069                                 slot = (TupleTableSlot *) DatumGetPointer(result);
1070                                 if (fcinfo.isnull ||
1071                                         !slot ||
1072                                         !IsA(slot, TupleTableSlot) ||
1073                                         TupIsNull(slot))
1074                                         elog(ERROR, "ExecMakeTableFunctionResult: Invalid result from function returning tuple");
1075                                 tuple = slot->val;
1076                         }
1077                         else
1078                         {
1079                                 char            nullflag;
1080
1081                                 nullflag = fcinfo.isnull ? 'n' : ' ';
1082                                 tuple = heap_formtuple(tupdesc, &result, &nullflag);
1083                         }
1084
1085                         oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1086                         tuplestore_puttuple(tupstore, tuple);
1087                         MemoryContextSwitchTo(oldcontext);
1088
1089                         /*
1090                          * Are we done?
1091                          */
1092                         if (rsinfo.isDone != ExprMultipleResult)
1093                                 break;
1094                 }
1095                 else if (rsinfo.returnMode == SFRM_Materialize)
1096                 {
1097                         /* check we're on the same page as the function author */
1098                         if (!first_time || rsinfo.isDone != ExprSingleResult)
1099                                 elog(ERROR, "ExecMakeTableFunctionResult: Materialize-mode protocol not followed");
1100                         /* Done evaluating the set result */
1101                         break;
1102                 }
1103                 else
1104                         elog(ERROR, "ExecMakeTableFunctionResult: unknown returnMode %d",
1105                                  (int) rsinfo.returnMode);
1106
1107                 first_time = false;
1108         }
1109
1110         MemoryContextSwitchTo(callerContext);
1111
1112         /* The returned pointers are those in rsinfo */
1113         *returnDesc = rsinfo.setDesc;
1114         return rsinfo.setResult;
1115 }
1116
1117
1118 /* ----------------------------------------------------------------
1119  *              ExecEvalFunc
1120  *              ExecEvalOper
1121  *              ExecEvalDistinct
1122  *
1123  *              Evaluate the functional result of a list of arguments by calling the
1124  *              function manager.
1125  * ----------------------------------------------------------------
1126  */
1127
1128 /* ----------------------------------------------------------------
1129  *              ExecEvalFunc
1130  * ----------------------------------------------------------------
1131  */
1132 static Datum
1133 ExecEvalFunc(FuncExprState *fcache,
1134                          ExprContext *econtext,
1135                          bool *isNull,
1136                          ExprDoneCond *isDone)
1137 {
1138         /*
1139          * Initialize function cache if first time through
1140          */
1141         if (fcache->func.fn_oid == InvalidOid)
1142         {
1143                 FuncExpr *func = (FuncExpr *) fcache->xprstate.expr;
1144
1145                 init_fcache(func->funcid, fcache, econtext->ecxt_per_query_memory);
1146         }
1147
1148         return ExecMakeFunctionResult(fcache, econtext, isNull, isDone);
1149 }
1150
1151 /* ----------------------------------------------------------------
1152  *              ExecEvalOper
1153  * ----------------------------------------------------------------
1154  */
1155 static Datum
1156 ExecEvalOper(FuncExprState *fcache,
1157                          ExprContext *econtext,
1158                          bool *isNull,
1159                          ExprDoneCond *isDone)
1160 {
1161         /*
1162          * Initialize function cache if first time through
1163          */
1164         if (fcache->func.fn_oid == InvalidOid)
1165         {
1166                 OpExpr *op = (OpExpr *) fcache->xprstate.expr;
1167
1168                 init_fcache(op->opfuncid, fcache, econtext->ecxt_per_query_memory);
1169         }
1170
1171         return ExecMakeFunctionResult(fcache, econtext, isNull, isDone);
1172 }
1173
1174 /* ----------------------------------------------------------------
1175  *              ExecEvalDistinct
1176  *
1177  * IS DISTINCT FROM must evaluate arguments to determine whether
1178  * they are NULL; if either is NULL then the result is already
1179  * known. If neither is NULL, then proceed to evaluate the
1180  * function. Note that this is *always* derived from the equals
1181  * operator, but since we need special processing of the arguments
1182  * we can not simply reuse ExecEvalOper() or ExecEvalFunc().
1183  * ----------------------------------------------------------------
1184  */
1185 static Datum
1186 ExecEvalDistinct(FuncExprState *fcache,
1187                                  ExprContext *econtext,
1188                                  bool *isNull)
1189 {
1190         Datum           result;
1191         FunctionCallInfoData fcinfo;
1192         ExprDoneCond argDone;
1193         List       *argList;
1194
1195         /*
1196          * Initialize function cache if first time through
1197          */
1198         if (fcache->func.fn_oid == InvalidOid)
1199         {
1200                 DistinctExpr *op = (DistinctExpr *) fcache->xprstate.expr;
1201
1202                 init_fcache(op->opfuncid, fcache, econtext->ecxt_per_query_memory);
1203                 Assert(!fcache->func.fn_retset);
1204         }
1205
1206         /*
1207          * extract info from fcache
1208          */
1209         argList = fcache->args;
1210
1211         /* Need to prep callinfo structure */
1212         MemSet(&fcinfo, 0, sizeof(fcinfo));
1213         fcinfo.flinfo = &(fcache->func);
1214         argDone = ExecEvalFuncArgs(&fcinfo, argList, econtext);
1215         if (argDone != ExprSingleResult)
1216                 elog(ERROR, "IS DISTINCT FROM does not support set arguments");
1217         Assert(fcinfo.nargs == 2);
1218
1219         if (fcinfo.argnull[0] && fcinfo.argnull[1])
1220         {
1221                 /* Both NULL? Then is not distinct... */
1222                 result = BoolGetDatum(FALSE);
1223         }
1224         else if (fcinfo.argnull[0] || fcinfo.argnull[1])
1225         {
1226                 /* Only one is NULL? Then is distinct... */
1227                 result = BoolGetDatum(TRUE);
1228         }
1229         else
1230         {
1231                 fcinfo.isnull = false;
1232                 result = FunctionCallInvoke(&fcinfo);
1233                 *isNull = fcinfo.isnull;
1234                 /* Must invert result of "=" */
1235                 result = BoolGetDatum(!DatumGetBool(result));
1236         }
1237
1238         return result;
1239 }
1240
1241 /* ----------------------------------------------------------------
1242  *              ExecEvalNot
1243  *              ExecEvalOr
1244  *              ExecEvalAnd
1245  *
1246  *              Evaluate boolean expressions, with appropriate short-circuiting.
1247  *
1248  *              The query planner reformulates clause expressions in the
1249  *              qualification to conjunctive normal form.  If we ever get
1250  *              an AND to evaluate, we can be sure that it's not a top-level
1251  *              clause in the qualification, but appears lower (as a function
1252  *              argument, for example), or in the target list.  Not that you
1253  *              need to know this, mind you...
1254  * ----------------------------------------------------------------
1255  */
1256 static Datum
1257 ExecEvalNot(BoolExprState *notclause, ExprContext *econtext, bool *isNull)
1258 {
1259         ExprState  *clause;
1260         Datum           expr_value;
1261
1262         clause = lfirst(notclause->args);
1263
1264         expr_value = ExecEvalExpr(clause, econtext, isNull, NULL);
1265
1266         /*
1267          * if the expression evaluates to null, then we just cascade the null
1268          * back to whoever called us.
1269          */
1270         if (*isNull)
1271                 return expr_value;
1272
1273         /*
1274          * evaluation of 'not' is simple.. expr is false, then return 'true'
1275          * and vice versa.
1276          */
1277         return BoolGetDatum(!DatumGetBool(expr_value));
1278 }
1279
1280 /* ----------------------------------------------------------------
1281  *              ExecEvalOr
1282  * ----------------------------------------------------------------
1283  */
1284 static Datum
1285 ExecEvalOr(BoolExprState *orExpr, ExprContext *econtext, bool *isNull)
1286 {
1287         List       *clauses;
1288         List       *clause;
1289         bool            AnyNull;
1290         Datum           clause_value;
1291
1292         clauses = orExpr->args;
1293         AnyNull = false;
1294
1295         /*
1296          * If any of the clauses is TRUE, the OR result is TRUE regardless of
1297          * the states of the rest of the clauses, so we can stop evaluating
1298          * and return TRUE immediately.  If none are TRUE and one or more is
1299          * NULL, we return NULL; otherwise we return FALSE.  This makes sense
1300          * when you interpret NULL as "don't know": if we have a TRUE then the
1301          * OR is TRUE even if we aren't sure about some of the other inputs.
1302          * If all the known inputs are FALSE, but we have one or more "don't
1303          * knows", then we have to report that we "don't know" what the OR's
1304          * result should be --- perhaps one of the "don't knows" would have
1305          * been TRUE if we'd known its value.  Only when all the inputs are
1306          * known to be FALSE can we state confidently that the OR's result is
1307          * FALSE.
1308          */
1309         foreach(clause, clauses)
1310         {
1311                 clause_value = ExecEvalExpr((ExprState *) lfirst(clause),
1312                                                                         econtext, isNull, NULL);
1313
1314                 /*
1315                  * if we have a non-null true result, then return it.
1316                  */
1317                 if (*isNull)
1318                         AnyNull = true;         /* remember we got a null */
1319                 else if (DatumGetBool(clause_value))
1320                         return clause_value;
1321         }
1322
1323         /* AnyNull is true if at least one clause evaluated to NULL */
1324         *isNull = AnyNull;
1325         return BoolGetDatum(false);
1326 }
1327
1328 /* ----------------------------------------------------------------
1329  *              ExecEvalAnd
1330  * ----------------------------------------------------------------
1331  */
1332 static Datum
1333 ExecEvalAnd(BoolExprState *andExpr, ExprContext *econtext, bool *isNull)
1334 {
1335         List       *clauses;
1336         List       *clause;
1337         bool            AnyNull;
1338         Datum           clause_value;
1339
1340         clauses = andExpr->args;
1341         AnyNull = false;
1342
1343         /*
1344          * If any of the clauses is FALSE, the AND result is FALSE regardless
1345          * of the states of the rest of the clauses, so we can stop evaluating
1346          * and return FALSE immediately.  If none are FALSE and one or more is
1347          * NULL, we return NULL; otherwise we return TRUE.      This makes sense
1348          * when you interpret NULL as "don't know", using the same sort of
1349          * reasoning as for OR, above.
1350          */
1351         foreach(clause, clauses)
1352         {
1353                 clause_value = ExecEvalExpr((ExprState *) lfirst(clause),
1354                                                                         econtext, isNull, NULL);
1355
1356                 /*
1357                  * if we have a non-null false result, then return it.
1358                  */
1359                 if (*isNull)
1360                         AnyNull = true;         /* remember we got a null */
1361                 else if (!DatumGetBool(clause_value))
1362                         return clause_value;
1363         }
1364
1365         /* AnyNull is true if at least one clause evaluated to NULL */
1366         *isNull = AnyNull;
1367         return BoolGetDatum(!AnyNull);
1368 }
1369
1370
1371 /* ----------------------------------------------------------------
1372  *              ExecEvalCase
1373  *
1374  *              Evaluate a CASE clause. Will have boolean expressions
1375  *              inside the WHEN clauses, and will have expressions
1376  *              for results.
1377  *              - thomas 1998-11-09
1378  * ----------------------------------------------------------------
1379  */
1380 static Datum
1381 ExecEvalCase(CaseExprState *caseExpr, ExprContext *econtext,
1382                          bool *isNull, ExprDoneCond *isDone)
1383 {
1384         List       *clauses;
1385         List       *clause;
1386         Datum           clause_value;
1387
1388         clauses = caseExpr->args;
1389
1390         /*
1391          * we evaluate each of the WHEN clauses in turn, as soon as one is
1392          * true we return the corresponding result. If none are true then we
1393          * return the value of the default clause, or NULL if there is none.
1394          */
1395         foreach(clause, clauses)
1396         {
1397                 CaseWhenState *wclause = lfirst(clause);
1398
1399                 clause_value = ExecEvalExpr(wclause->expr,
1400                                                                         econtext,
1401                                                                         isNull,
1402                                                                         NULL);
1403
1404                 /*
1405                  * if we have a true test, then we return the result, since the
1406                  * case statement is satisfied.  A NULL result from the test is
1407                  * not considered true.
1408                  */
1409                 if (DatumGetBool(clause_value) && !*isNull)
1410                 {
1411                         return ExecEvalExpr(wclause->result,
1412                                                                 econtext,
1413                                                                 isNull,
1414                                                                 isDone);
1415                 }
1416         }
1417
1418         if (caseExpr->defresult)
1419         {
1420                 return ExecEvalExpr(caseExpr->defresult,
1421                                                         econtext,
1422                                                         isNull,
1423                                                         isDone);
1424         }
1425
1426         *isNull = true;
1427         return (Datum) 0;
1428 }
1429
1430 /* ----------------------------------------------------------------
1431  *              ExecEvalCoalesce
1432  * ----------------------------------------------------------------
1433  */
1434 static Datum
1435 ExecEvalCoalesce(CoalesceExprState *coalesceExpr, ExprContext *econtext,
1436                                  bool *isNull)
1437 {
1438         List *arg;
1439
1440         /* Simply loop through until something NOT NULL is found */
1441         foreach(arg, coalesceExpr->args)
1442         {
1443                 ExprState *e = (ExprState *) lfirst(arg);
1444                 Datum value;
1445
1446                 value = ExecEvalExpr(e, econtext, isNull, NULL);
1447                 if (!*isNull)
1448                         return value;
1449         }
1450
1451         /* Else return NULL */
1452         *isNull = true;
1453         return (Datum) 0;
1454 }
1455         
1456 /* ----------------------------------------------------------------
1457  *              ExecEvalNullIf
1458  *
1459  * Note that this is *always* derived from the equals operator,
1460  * but since we need special processing of the arguments
1461  * we can not simply reuse ExecEvalOper() or ExecEvalFunc().
1462  * ----------------------------------------------------------------
1463  */
1464 static Datum
1465 ExecEvalNullIf(FuncExprState *fcache, ExprContext *econtext,
1466                            bool *isNull)
1467 {
1468         Datum           result;
1469         FunctionCallInfoData fcinfo;
1470         ExprDoneCond argDone;
1471         List       *argList;
1472
1473         /*
1474          * Initialize function cache if first time through
1475          */
1476         if (fcache->func.fn_oid == InvalidOid)
1477         {
1478                 NullIfExpr *op = (NullIfExpr *) fcache->xprstate.expr;
1479
1480                 init_fcache(op->opfuncid, fcache, econtext->ecxt_per_query_memory);
1481                 Assert(!fcache->func.fn_retset);
1482         }
1483
1484         /*
1485          * extract info from fcache
1486          */
1487         argList = fcache->args;
1488
1489         /* Need to prep callinfo structure */
1490         MemSet(&fcinfo, 0, sizeof(fcinfo));
1491         fcinfo.flinfo = &(fcache->func);
1492         argDone = ExecEvalFuncArgs(&fcinfo, argList, econtext);
1493         if (argDone != ExprSingleResult)
1494                 elog(ERROR, "NULLIF does not support set arguments");
1495         Assert(fcinfo.nargs == 2);
1496
1497         /* if either argument is NULL they can't be equal */
1498         if (!fcinfo.argnull[0] && !fcinfo.argnull[1])
1499         {
1500                 fcinfo.isnull = false;
1501                 result = FunctionCallInvoke(&fcinfo);
1502                 /* if the arguments are equal return null */
1503                 if (!fcinfo.isnull && DatumGetBool(result))
1504                 {
1505                         *isNull = true;
1506                         return (Datum) 0;
1507                 }
1508         }
1509
1510         /* else return first argument */
1511         *isNull = fcinfo.argnull[0];
1512         return fcinfo.arg[0];
1513 }
1514
1515 /* ----------------------------------------------------------------
1516  *              ExecEvalNullTest
1517  *
1518  *              Evaluate a NullTest node.
1519  * ----------------------------------------------------------------
1520  */
1521 static Datum
1522 ExecEvalNullTest(GenericExprState *nstate,
1523                                  ExprContext *econtext,
1524                                  bool *isNull,
1525                                  ExprDoneCond *isDone)
1526 {
1527         NullTest   *ntest = (NullTest *) nstate->xprstate.expr;
1528         Datum           result;
1529
1530         result = ExecEvalExpr(nstate->arg, econtext, isNull, isDone);
1531
1532         if (isDone && *isDone == ExprEndResult)
1533                 return result;                  /* nothing to check */
1534
1535         switch (ntest->nulltesttype)
1536         {
1537                 case IS_NULL:
1538                         if (*isNull)
1539                         {
1540                                 *isNull = false;
1541                                 return BoolGetDatum(true);
1542                         }
1543                         else
1544                                 return BoolGetDatum(false);
1545                 case IS_NOT_NULL:
1546                         if (*isNull)
1547                         {
1548                                 *isNull = false;
1549                                 return BoolGetDatum(false);
1550                         }
1551                         else
1552                                 return BoolGetDatum(true);
1553                 default:
1554                         elog(ERROR, "ExecEvalNullTest: unexpected nulltesttype %d",
1555                                  (int) ntest->nulltesttype);
1556                         return (Datum) 0;       /* keep compiler quiet */
1557         }
1558 }
1559
1560 /* ----------------------------------------------------------------
1561  *              ExecEvalBooleanTest
1562  *
1563  *              Evaluate a BooleanTest node.
1564  * ----------------------------------------------------------------
1565  */
1566 static Datum
1567 ExecEvalBooleanTest(GenericExprState *bstate,
1568                                         ExprContext *econtext,
1569                                         bool *isNull,
1570                                         ExprDoneCond *isDone)
1571 {
1572         BooleanTest *btest = (BooleanTest *) bstate->xprstate.expr;
1573         Datum           result;
1574
1575         result = ExecEvalExpr(bstate->arg, econtext, isNull, isDone);
1576
1577         if (isDone && *isDone == ExprEndResult)
1578                 return result;                  /* nothing to check */
1579
1580         switch (btest->booltesttype)
1581         {
1582                 case IS_TRUE:
1583                         if (*isNull)
1584                         {
1585                                 *isNull = false;
1586                                 return BoolGetDatum(false);
1587                         }
1588                         else if (DatumGetBool(result))
1589                                 return BoolGetDatum(true);
1590                         else
1591                                 return BoolGetDatum(false);
1592                 case IS_NOT_TRUE:
1593                         if (*isNull)
1594                         {
1595                                 *isNull = false;
1596                                 return BoolGetDatum(true);
1597                         }
1598                         else if (DatumGetBool(result))
1599                                 return BoolGetDatum(false);
1600                         else
1601                                 return BoolGetDatum(true);
1602                 case IS_FALSE:
1603                         if (*isNull)
1604                         {
1605                                 *isNull = false;
1606                                 return BoolGetDatum(false);
1607                         }
1608                         else if (DatumGetBool(result))
1609                                 return BoolGetDatum(false);
1610                         else
1611                                 return BoolGetDatum(true);
1612                 case IS_NOT_FALSE:
1613                         if (*isNull)
1614                         {
1615                                 *isNull = false;
1616                                 return BoolGetDatum(true);
1617                         }
1618                         else if (DatumGetBool(result))
1619                                 return BoolGetDatum(true);
1620                         else
1621                                 return BoolGetDatum(false);
1622                 case IS_UNKNOWN:
1623                         if (*isNull)
1624                         {
1625                                 *isNull = false;
1626                                 return BoolGetDatum(true);
1627                         }
1628                         else
1629                                 return BoolGetDatum(false);
1630                 case IS_NOT_UNKNOWN:
1631                         if (*isNull)
1632                         {
1633                                 *isNull = false;
1634                                 return BoolGetDatum(false);
1635                         }
1636                         else
1637                                 return BoolGetDatum(true);
1638                 default:
1639                         elog(ERROR, "ExecEvalBooleanTest: unexpected booltesttype %d",
1640                                  (int) btest->booltesttype);
1641                         return (Datum) 0;       /* keep compiler quiet */
1642         }
1643 }
1644
1645 /*
1646  * ExecEvalCoerceToDomain
1647  *
1648  * Test the provided data against the domain constraint(s).  If the data
1649  * passes the constraint specifications, pass it through (return the
1650  * datum) otherwise throw an error.
1651  */
1652 static Datum
1653 ExecEvalCoerceToDomain(CoerceToDomainState *cstate, ExprContext *econtext,
1654                                            bool *isNull, ExprDoneCond *isDone)
1655 {
1656         CoerceToDomain *ctest = (CoerceToDomain *) cstate->xprstate.expr;
1657         Datum           result;
1658         List       *l;
1659
1660         result = ExecEvalExpr(cstate->arg, econtext, isNull, isDone);
1661
1662         if (isDone && *isDone == ExprEndResult)
1663                 return result;                  /* nothing to check */
1664
1665         foreach(l, cstate->constraints)
1666         {
1667                 DomainConstraintState *con = (DomainConstraintState *) lfirst(l);
1668
1669                 switch (con->constrainttype)
1670                 {
1671                         case DOM_CONSTRAINT_NOTNULL:
1672                                 if (*isNull)
1673                                         elog(ERROR, "Domain %s does not allow NULL values",
1674                                                  format_type_be(ctest->resulttype));
1675                                 break;
1676                         case DOM_CONSTRAINT_CHECK:
1677                         {
1678                                 Datum   conResult;
1679                                 bool    conIsNull;
1680                                 Datum   save_datum;
1681                                 bool    save_isNull;
1682
1683                                 /*
1684                                  * Set up value to be returned by CoerceToDomainValue nodes.
1685                                  * We must save and restore prior setting of econtext's
1686                                  * domainValue fields, in case this node is itself within
1687                                  * a check expression for another domain.
1688                                  */
1689                                 save_datum = econtext->domainValue_datum;
1690                                 save_isNull = econtext->domainValue_isNull;
1691
1692                                 econtext->domainValue_datum = result;
1693                                 econtext->domainValue_isNull = *isNull;
1694
1695                                 conResult = ExecEvalExpr(con->check_expr,
1696                                                                                  econtext, &conIsNull, NULL);
1697
1698                                 if (!conIsNull &&
1699                                         !DatumGetBool(conResult))
1700                                         elog(ERROR, "ExecEvalCoerceToDomain: Domain %s constraint %s failed",
1701                                                  format_type_be(ctest->resulttype), con->name);
1702
1703                                 econtext->domainValue_datum = save_datum;
1704                                 econtext->domainValue_isNull = save_isNull;
1705
1706                                 break;
1707                         }
1708                         default:
1709                                 elog(ERROR, "ExecEvalCoerceToDomain: Constraint type unknown");
1710                                 break;
1711                 }
1712         }
1713
1714         /* If all has gone well (constraints did not fail) return the datum */
1715         return result;
1716 }
1717
1718 /*
1719  * ExecEvalCoerceToDomainValue
1720  *
1721  * Return the value stored by CoerceToDomain.
1722  */
1723 static Datum
1724 ExecEvalCoerceToDomainValue(CoerceToDomainValue *conVal,
1725                                                         ExprContext *econtext, bool *isNull)
1726 {
1727         *isNull = econtext->domainValue_isNull;
1728         return econtext->domainValue_datum;
1729 }
1730
1731 /* ----------------------------------------------------------------
1732  *              ExecEvalFieldSelect
1733  *
1734  *              Evaluate a FieldSelect node.
1735  * ----------------------------------------------------------------
1736  */
1737 static Datum
1738 ExecEvalFieldSelect(GenericExprState *fstate,
1739                                         ExprContext *econtext,
1740                                         bool *isNull,
1741                                         ExprDoneCond *isDone)
1742 {
1743         FieldSelect *fselect = (FieldSelect *) fstate->xprstate.expr;
1744         Datum           result;
1745         TupleTableSlot *resSlot;
1746
1747         result = ExecEvalExpr(fstate->arg, econtext, isNull, isDone);
1748
1749         /* this test covers the isDone exception too: */
1750         if (*isNull)
1751                 return result;
1752
1753         resSlot = (TupleTableSlot *) DatumGetPointer(result);
1754         Assert(resSlot != NULL && IsA(resSlot, TupleTableSlot));
1755         result = heap_getattr(resSlot->val,
1756                                                   fselect->fieldnum,
1757                                                   resSlot->ttc_tupleDescriptor,
1758                                                   isNull);
1759         return result;
1760 }
1761
1762 /* ----------------------------------------------------------------
1763  *              ExecEvalExpr
1764  *
1765  *              Recursively evaluate a targetlist or qualification expression.
1766  *
1767  * Inputs:
1768  *              expression: the expression state tree to evaluate
1769  *              econtext: evaluation context information
1770  *
1771  * Outputs:
1772  *              return value: Datum value of result
1773  *              *isNull: set to TRUE if result is NULL (actual return value is
1774  *                               meaningless if so); set to FALSE if non-null result
1775  *              *isDone: set to indicator of set-result status
1776  *
1777  * A caller that can only accept a singleton (non-set) result should pass
1778  * NULL for isDone; if the expression computes a set result then an elog()
1779  * error will be reported.      If the caller does pass an isDone pointer then
1780  * *isDone is set to one of these three states:
1781  *              ExprSingleResult                singleton result (not a set)
1782  *              ExprMultipleResult              return value is one element of a set
1783  *              ExprEndResult                   there are no more elements in the set
1784  * When ExprMultipleResult is returned, the caller should invoke
1785  * ExecEvalExpr() repeatedly until ExprEndResult is returned.  ExprEndResult
1786  * is returned after the last real set element.  For convenience isNull will
1787  * always be set TRUE when ExprEndResult is returned, but this should not be
1788  * taken as indicating a NULL element of the set.  Note that these return
1789  * conventions allow us to distinguish among a singleton NULL, a NULL element
1790  * of a set, and an empty set.
1791  *
1792  * The caller should already have switched into the temporary memory
1793  * context econtext->ecxt_per_tuple_memory.  The convenience entry point
1794  * ExecEvalExprSwitchContext() is provided for callers who don't prefer to
1795  * do the switch in an outer loop.      We do not do the switch here because
1796  * it'd be a waste of cycles during recursive entries to ExecEvalExpr().
1797  *
1798  * This routine is an inner loop routine and must be as fast as possible.
1799  * ----------------------------------------------------------------
1800  */
1801 Datum
1802 ExecEvalExpr(ExprState *expression,
1803                          ExprContext *econtext,
1804                          bool *isNull,
1805                          ExprDoneCond *isDone)
1806 {
1807         Datum           retDatum;
1808         Expr       *expr;
1809
1810         /* Set default values for result flags: non-null, not a set result */
1811         *isNull = false;
1812         if (isDone)
1813                 *isDone = ExprSingleResult;
1814
1815         /* Is this still necessary?  Doubtful... */
1816         if (expression == NULL)
1817         {
1818                 *isNull = true;
1819                 return (Datum) 0;
1820         }
1821
1822         /*
1823          * here we dispatch the work to the appropriate type of function given
1824          * the type of our expression.
1825          */
1826         expr = expression->expr;
1827         switch (nodeTag(expr))
1828         {
1829                 case T_Var:
1830                         retDatum = ExecEvalVar((Var *) expr, econtext, isNull);
1831                         break;
1832                 case T_Const:
1833                         {
1834                                 Const      *con = (Const *) expr;
1835
1836                                 retDatum = con->constvalue;
1837                                 *isNull = con->constisnull;
1838                                 break;
1839                         }
1840                 case T_Param:
1841                         retDatum = ExecEvalParam((Param *) expr, econtext, isNull);
1842                         break;
1843                 case T_Aggref:
1844                         retDatum = ExecEvalAggref((AggrefExprState *) expression,
1845                                                                           econtext,
1846                                                                           isNull);
1847                         break;
1848                 case T_ArrayRef:
1849                         retDatum = ExecEvalArrayRef((ArrayRefExprState *) expression,
1850                                                                                 econtext,
1851                                                                                 isNull,
1852                                                                                 isDone);
1853                         break;
1854                 case T_FuncExpr:
1855                         retDatum = ExecEvalFunc((FuncExprState *) expression, econtext,
1856                                                                         isNull, isDone);
1857                         break;
1858                 case T_OpExpr:
1859                         retDatum = ExecEvalOper((FuncExprState *) expression, econtext,
1860                                                                         isNull, isDone);
1861                         break;
1862                 case T_DistinctExpr:
1863                         retDatum = ExecEvalDistinct((FuncExprState *) expression, econtext,
1864                                                                                 isNull);
1865                         break;
1866                 case T_BoolExpr:
1867                         {
1868                                 BoolExprState *state = (BoolExprState *) expression;
1869
1870                                 switch (((BoolExpr *) expr)->boolop)
1871                                 {
1872                                         case AND_EXPR:
1873                                                 retDatum = ExecEvalAnd(state, econtext, isNull);
1874                                                 break;
1875                                         case OR_EXPR:
1876                                                 retDatum = ExecEvalOr(state, econtext, isNull);
1877                                                 break;
1878                                         case NOT_EXPR:
1879                                                 retDatum = ExecEvalNot(state, econtext, isNull);
1880                                                 break;
1881                                         default:
1882                                                 elog(ERROR, "ExecEvalExpr: unknown boolop %d",
1883                                                          ((BoolExpr *) expr)->boolop);
1884                                                 retDatum = 0;   /* keep compiler quiet */
1885                                                 break;
1886                                 }
1887                                 break;
1888                         }
1889                 case T_SubPlan:
1890                         retDatum = ExecSubPlan((SubPlanState *) expression,
1891                                                                    econtext,
1892                                                                    isNull);
1893                         break;
1894                 case T_FieldSelect:
1895                         retDatum = ExecEvalFieldSelect((GenericExprState *) expression,
1896                                                                                    econtext,
1897                                                                                    isNull,
1898                                                                                    isDone);
1899                         break;
1900                 case T_RelabelType:
1901                         retDatum = ExecEvalExpr(((GenericExprState *) expression)->arg,
1902                                                                         econtext,
1903                                                                         isNull,
1904                                                                         isDone);
1905                         break;
1906                 case T_CaseExpr:
1907                         retDatum = ExecEvalCase((CaseExprState *) expression,
1908                                                                         econtext,
1909                                                                         isNull,
1910                                                                         isDone);
1911                         break;
1912                 case T_CoalesceExpr:
1913                         retDatum = ExecEvalCoalesce((CoalesceExprState *) expression,
1914                                                                                 econtext,
1915                                                                                 isNull);
1916                         break;
1917                 case T_NullIfExpr:
1918                         retDatum = ExecEvalNullIf((FuncExprState *) expression,
1919                                                                           econtext,
1920                                                                           isNull);
1921                         break;
1922                 case T_NullTest:
1923                         retDatum = ExecEvalNullTest((GenericExprState *) expression,
1924                                                                                 econtext,
1925                                                                                 isNull,
1926                                                                                 isDone);
1927                         break;
1928                 case T_BooleanTest:
1929                         retDatum = ExecEvalBooleanTest((GenericExprState *) expression,
1930                                                                                    econtext,
1931                                                                                    isNull,
1932                                                                                    isDone);
1933                         break;
1934                 case T_CoerceToDomain:
1935                         retDatum = ExecEvalCoerceToDomain((CoerceToDomainState *) expression,
1936                                                                                           econtext,
1937                                                                                           isNull,
1938                                                                                           isDone);
1939                         break;
1940                 case T_CoerceToDomainValue:
1941                         retDatum = ExecEvalCoerceToDomainValue((CoerceToDomainValue *) expr,
1942                                                                                                    econtext,
1943                                                                                                    isNull);
1944                         break;
1945                 default:
1946                         elog(ERROR, "ExecEvalExpr: unknown expression type %d",
1947                                  nodeTag(expression));
1948                         retDatum = 0;           /* keep compiler quiet */
1949                         break;
1950         }
1951
1952         return retDatum;
1953 }       /* ExecEvalExpr() */
1954
1955
1956 /*
1957  * Same as above, but get into the right allocation context explicitly.
1958  */
1959 Datum
1960 ExecEvalExprSwitchContext(ExprState *expression,
1961                                                   ExprContext *econtext,
1962                                                   bool *isNull,
1963                                                   ExprDoneCond *isDone)
1964 {
1965         Datum           retDatum;
1966         MemoryContext oldContext;
1967
1968         oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
1969         retDatum = ExecEvalExpr(expression, econtext, isNull, isDone);
1970         MemoryContextSwitchTo(oldContext);
1971         return retDatum;
1972 }
1973
1974
1975 /*
1976  * ExecInitExpr: prepare an expression tree for execution
1977  *
1978  * This function builds and returns an ExprState tree paralleling the given
1979  * Expr node tree.  The ExprState tree can then be handed to ExecEvalExpr
1980  * for execution.  Because the Expr tree itself is read-only as far as
1981  * ExecInitExpr and ExecEvalExpr are concerned, several different executions
1982  * of the same plan tree can occur concurrently.
1983  *
1984  * This must be called in a memory context that will last as long as repeated
1985  * executions of the expression are needed.  Typically the context will be
1986  * the same as the per-query context of the associated ExprContext.
1987  *
1988  * Any Aggref and SubPlan nodes found in the tree are added to the lists
1989  * of such nodes held by the parent PlanState.  Otherwise, we do very little
1990  * initialization here other than building the state-node tree.  Any nontrivial
1991  * work associated with initializing runtime info for a node should happen
1992  * during the first actual evaluation of that node.  (This policy lets us
1993  * avoid work if the node is never actually evaluated.)
1994  *
1995  * Note: there is no ExecEndExpr function; we assume that any resource
1996  * cleanup needed will be handled by just releasing the memory context
1997  * in which the state tree is built.  Functions that require additional
1998  * cleanup work can register a shutdown callback in the ExprContext.
1999  *
2000  *      'node' is the root of the expression tree to examine
2001  *      'parent' is the PlanState node that owns the expression.
2002  *
2003  * 'parent' may be NULL if we are preparing an expression that is not
2004  * associated with a plan tree.  (If so, it can't have aggs or subplans.)
2005  * This case should usually come through ExecPrepareExpr, not directly here.
2006  */
2007 ExprState *
2008 ExecInitExpr(Expr *node, PlanState *parent)
2009 {
2010         ExprState  *state;
2011
2012         if (node == NULL)
2013                 return NULL;
2014         switch (nodeTag(node))
2015         {
2016                 case T_Var:
2017                 case T_Const:
2018                 case T_Param:
2019                 case T_CoerceToDomainValue:
2020                         /* No special setup needed for these node types */
2021                         state = (ExprState *) makeNode(ExprState);
2022                         break;
2023                 case T_Aggref:
2024                         {
2025                                 Aggref   *aggref = (Aggref *) node;
2026                                 AggrefExprState *astate = makeNode(AggrefExprState);
2027
2028                                 if (parent && IsA(parent, AggState))
2029                                 {
2030                                         AggState   *aggstate = (AggState *) parent;
2031                                         int                     naggs;
2032
2033                                         aggstate->aggs = lcons(astate, aggstate->aggs);
2034                                         naggs = ++aggstate->numaggs;
2035
2036                                         astate->target = ExecInitExpr(aggref->target, parent);
2037
2038                                         /*
2039                                          * Complain if the aggregate's argument contains any
2040                                          * aggregates; nested agg functions are semantically
2041                                          * nonsensical.  (This probably was caught earlier,
2042                                          * but we defend against it here anyway.)
2043                                          */
2044                                         if (naggs != aggstate->numaggs)
2045                                                 elog(ERROR, "Aggregate function calls may not be nested");
2046                                 }
2047                                 else
2048                                         elog(ERROR, "ExecInitExpr: Aggref not expected here");
2049                                 state = (ExprState *) astate;
2050                         }
2051                         break;
2052                 case T_ArrayRef:
2053                         {
2054                                 ArrayRef   *aref = (ArrayRef *) node;
2055                                 ArrayRefExprState *astate = makeNode(ArrayRefExprState);
2056
2057                                 astate->refupperindexpr = (List *)
2058                                         ExecInitExpr((Expr *) aref->refupperindexpr, parent);
2059                                 astate->reflowerindexpr = (List *)
2060                                         ExecInitExpr((Expr *) aref->reflowerindexpr, parent);
2061                                 astate->refexpr = ExecInitExpr(aref->refexpr, parent);
2062                                 astate->refassgnexpr = ExecInitExpr(aref->refassgnexpr,
2063                                                                                                         parent);
2064                                 state = (ExprState *) astate;
2065                         }
2066                         break;
2067                 case T_FuncExpr:
2068                         {
2069                                 FuncExpr   *funcexpr = (FuncExpr *) node;
2070                                 FuncExprState *fstate = makeNode(FuncExprState);
2071
2072                                 fstate->args = (List *)
2073                                         ExecInitExpr((Expr *) funcexpr->args, parent);
2074                                 fstate->func.fn_oid = InvalidOid; /* not initialized */
2075                                 state = (ExprState *) fstate;
2076                         }
2077                         break;
2078                 case T_OpExpr:
2079                         {
2080                                 OpExpr   *opexpr = (OpExpr *) node;
2081                                 FuncExprState *fstate = makeNode(FuncExprState);
2082
2083                                 fstate->args = (List *)
2084                                         ExecInitExpr((Expr *) opexpr->args, parent);
2085                                 fstate->func.fn_oid = InvalidOid; /* not initialized */
2086                                 state = (ExprState *) fstate;
2087                         }
2088                         break;
2089                 case T_DistinctExpr:
2090                         {
2091                                 DistinctExpr   *distinctexpr = (DistinctExpr *) node;
2092                                 FuncExprState *fstate = makeNode(FuncExprState);
2093
2094                                 fstate->args = (List *)
2095                                         ExecInitExpr((Expr *) distinctexpr->args, parent);
2096                                 fstate->func.fn_oid = InvalidOid; /* not initialized */
2097                                 state = (ExprState *) fstate;
2098                         }
2099                         break;
2100                 case T_BoolExpr:
2101                         {
2102                                 BoolExpr   *boolexpr = (BoolExpr *) node;
2103                                 BoolExprState *bstate = makeNode(BoolExprState);
2104
2105                                 bstate->args = (List *)
2106                                         ExecInitExpr((Expr *) boolexpr->args, parent);
2107                                 state = (ExprState *) bstate;
2108                         }
2109                         break;
2110                 case T_SubPlan:
2111                         {
2112                                 /* Keep this in sync with ExecInitExprInitPlan, below */
2113                                 SubPlan *subplan = (SubPlan *) node;
2114                                 SubPlanState *sstate = makeNode(SubPlanState);
2115
2116                                 if (!parent)
2117                                         elog(ERROR, "ExecInitExpr: SubPlan not expected here");
2118
2119                                 /*
2120                                  * Here we just add the SubPlanState nodes to
2121                                  * parent->subPlan.  The subplans will be initialized later.
2122                                  */
2123                                 parent->subPlan = lcons(sstate, parent->subPlan);
2124                                 sstate->sub_estate = NULL;
2125                                 sstate->planstate = NULL;
2126
2127                                 sstate->exprs = (List *)
2128                                         ExecInitExpr((Expr *) subplan->exprs, parent);
2129                                 sstate->args = (List *)
2130                                         ExecInitExpr((Expr *) subplan->args, parent);
2131
2132                                 state = (ExprState *) sstate;
2133                         }
2134                         break;
2135                 case T_FieldSelect:
2136                         {
2137                                 FieldSelect   *fselect = (FieldSelect *) node;
2138                                 GenericExprState *gstate = makeNode(GenericExprState);
2139
2140                                 gstate->arg = ExecInitExpr(fselect->arg, parent);
2141                                 state = (ExprState *) gstate;
2142                         }
2143                         break;
2144                 case T_RelabelType:
2145                         {
2146                                 RelabelType   *relabel = (RelabelType *) node;
2147                                 GenericExprState *gstate = makeNode(GenericExprState);
2148
2149                                 gstate->arg = ExecInitExpr(relabel->arg, parent);
2150                                 state = (ExprState *) gstate;
2151                         }
2152                         break;
2153                 case T_CaseExpr:
2154                         {
2155                                 CaseExpr   *caseexpr = (CaseExpr *) node;
2156                                 CaseExprState *cstate = makeNode(CaseExprState);
2157                                 List       *outlist = NIL;
2158                                 List       *inlist;
2159
2160                                 foreach(inlist, caseexpr->args)
2161                                 {
2162                                         CaseWhen   *when = (CaseWhen *) lfirst(inlist);
2163                                         CaseWhenState *wstate = makeNode(CaseWhenState);
2164
2165                                         Assert(IsA(when, CaseWhen));
2166                                         wstate->xprstate.expr = (Expr *) when;
2167                                         wstate->expr = ExecInitExpr(when->expr, parent);
2168                                         wstate->result = ExecInitExpr(when->result, parent);
2169                                         outlist = lappend(outlist, wstate);
2170                                 }
2171                                 cstate->args = outlist;
2172                                 /* caseexpr->arg should be null by now */
2173                                 Assert(caseexpr->arg == NULL);
2174                                 cstate->defresult = ExecInitExpr(caseexpr->defresult, parent);
2175                                 state = (ExprState *) cstate;
2176                         }
2177                         break;
2178                 case T_CoalesceExpr:
2179                         {
2180                                 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
2181                                 CoalesceExprState *cstate = makeNode(CoalesceExprState);
2182                                 List       *outlist = NIL;
2183                                 List       *inlist;
2184
2185                                 foreach(inlist, coalesceexpr->args)
2186                                 {
2187                                         Expr *e = (Expr *) lfirst(inlist);
2188                                         ExprState *estate;
2189
2190                                         estate = ExecInitExpr(e, parent);
2191                                         outlist = lappend(outlist, estate);
2192                                 }
2193                                 cstate->args = outlist;
2194                                 state = (ExprState *) cstate;
2195                         }
2196                         break;
2197                 case T_NullIfExpr:
2198                         {
2199                                 NullIfExpr *nullifexpr = (NullIfExpr *) node;
2200                                 FuncExprState *fstate = makeNode(FuncExprState);
2201
2202                                 fstate->args = (List *)
2203                                         ExecInitExpr((Expr *) nullifexpr->args, parent);
2204                                 fstate->func.fn_oid = InvalidOid; /* not initialized */
2205                                 state = (ExprState *) fstate;
2206                         }
2207                         break;
2208                 case T_NullTest:
2209                         {
2210                                 NullTest   *ntest = (NullTest *) node;
2211                                 GenericExprState *gstate = makeNode(GenericExprState);
2212
2213                                 gstate->arg = ExecInitExpr(ntest->arg, parent);
2214                                 state = (ExprState *) gstate;
2215                         }
2216                         break;
2217                 case T_BooleanTest:
2218                         {
2219                                 BooleanTest   *btest = (BooleanTest *) node;
2220                                 GenericExprState *gstate = makeNode(GenericExprState);
2221
2222                                 gstate->arg = ExecInitExpr(btest->arg, parent);
2223                                 state = (ExprState *) gstate;
2224                         }
2225                         break;
2226                 case T_CoerceToDomain:
2227                         {
2228                                 CoerceToDomain   *ctest = (CoerceToDomain *) node;
2229                                 CoerceToDomainState *cstate = makeNode(CoerceToDomainState);
2230
2231                                 cstate->arg = ExecInitExpr(ctest->arg, parent);
2232                                 cstate->constraints = GetDomainConstraints(ctest->resulttype);
2233                                 state = (ExprState *) cstate;
2234                         }
2235                         break;
2236                 case T_TargetEntry:
2237                         {
2238                                 TargetEntry   *tle = (TargetEntry *) node;
2239                                 GenericExprState *gstate = makeNode(GenericExprState);
2240
2241                                 gstate->arg = ExecInitExpr(tle->expr, parent);
2242                                 state = (ExprState *) gstate;
2243                         }
2244                         break;
2245                 case T_List:
2246                         {
2247                                 List       *outlist = NIL;
2248                                 List       *inlist;
2249
2250                                 foreach(inlist, (List *) node)
2251                                 {
2252                                         outlist = lappend(outlist,
2253                                                                           ExecInitExpr((Expr *) lfirst(inlist),
2254                                                                                                    parent));
2255                                 }
2256                                 /* Don't fall through to the "common" code below */
2257                                 return (ExprState *) outlist;
2258                         }
2259                 default:
2260                         elog(ERROR, "ExecInitExpr: unknown expression type %d",
2261                                  nodeTag(node));
2262                         state = NULL;           /* keep compiler quiet */
2263                         break;
2264         }
2265
2266         /* Common code for all state-node types */
2267         state->expr = node;
2268
2269         return state;
2270 }
2271
2272 /*
2273  * ExecInitExprInitPlan --- initialize a subplan expr that's being handled
2274  * as an InitPlan.  This is identical to ExecInitExpr's handling of a regular
2275  * subplan expr, except we do NOT want to add the node to the parent's
2276  * subplan list.
2277  */
2278 SubPlanState *
2279 ExecInitExprInitPlan(SubPlan *node, PlanState *parent)
2280 {
2281         SubPlanState *sstate = makeNode(SubPlanState);
2282
2283         if (!parent)
2284                 elog(ERROR, "ExecInitExpr: SubPlan not expected here");
2285
2286         /* The subplan's state will be initialized later */
2287         sstate->sub_estate = NULL;
2288         sstate->planstate = NULL;
2289
2290         sstate->exprs = (List *) ExecInitExpr((Expr *) node->exprs, parent);
2291         sstate->args = (List *) ExecInitExpr((Expr *) node->args, parent);
2292
2293         sstate->xprstate.expr = (Expr *) node;
2294
2295         return sstate;
2296 }
2297
2298 /*
2299  * ExecPrepareExpr --- initialize for expression execution outside a normal
2300  * Plan tree context.
2301  *
2302  * This differs from ExecInitExpr in that we don't assume the caller is
2303  * already running in the EState's per-query context.  Also, we apply
2304  * fix_opfuncids() to the passed expression tree to be sure it is ready
2305  * to run.  (In ordinary Plan trees the planner will have fixed opfuncids,
2306  * but callers outside the executor will not have done this.)
2307  */
2308 ExprState *
2309 ExecPrepareExpr(Expr *node, EState *estate)
2310 {
2311         ExprState  *result;
2312         MemoryContext oldcontext;
2313
2314         fix_opfuncids((Node *) node);
2315
2316         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2317
2318         result = ExecInitExpr(node, NULL);
2319
2320         MemoryContextSwitchTo(oldcontext);
2321
2322         return result;
2323 }
2324
2325
2326 /* ----------------------------------------------------------------
2327  *                                       ExecQual / ExecTargetList / ExecProject
2328  * ----------------------------------------------------------------
2329  */
2330
2331 /* ----------------------------------------------------------------
2332  *              ExecQual
2333  *
2334  *              Evaluates a conjunctive boolean expression (qual list) and
2335  *              returns true iff none of the subexpressions are false.
2336  *              (We also return true if the list is empty.)
2337  *
2338  *      If some of the subexpressions yield NULL but none yield FALSE,
2339  *      then the result of the conjunction is NULL (ie, unknown)
2340  *      according to three-valued boolean logic.  In this case,
2341  *      we return the value specified by the "resultForNull" parameter.
2342  *
2343  *      Callers evaluating WHERE clauses should pass resultForNull=FALSE,
2344  *      since SQL specifies that tuples with null WHERE results do not
2345  *      get selected.  On the other hand, callers evaluating constraint
2346  *      conditions should pass resultForNull=TRUE, since SQL also specifies
2347  *      that NULL constraint conditions are not failures.
2348  *
2349  *      NOTE: it would not be correct to use this routine to evaluate an
2350  *      AND subclause of a boolean expression; for that purpose, a NULL
2351  *      result must be returned as NULL so that it can be properly treated
2352  *      in the next higher operator (cf. ExecEvalAnd and ExecEvalOr).
2353  *      This routine is only used in contexts where a complete expression
2354  *      is being evaluated and we know that NULL can be treated the same
2355  *      as one boolean result or the other.
2356  *
2357  * ----------------------------------------------------------------
2358  */
2359 bool
2360 ExecQual(List *qual, ExprContext *econtext, bool resultForNull)
2361 {
2362         bool            result;
2363         MemoryContext oldContext;
2364         List       *qlist;
2365
2366         /*
2367          * debugging stuff
2368          */
2369         EV_printf("ExecQual: qual is ");
2370         EV_nodeDisplay(qual);
2371         EV_printf("\n");
2372
2373         IncrProcessed();
2374
2375         /*
2376          * Run in short-lived per-tuple context while computing expressions.
2377          */
2378         oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
2379
2380         /*
2381          * Evaluate the qual conditions one at a time.  If we find a FALSE
2382          * result, we can stop evaluating and return FALSE --- the AND result
2383          * must be FALSE.  Also, if we find a NULL result when resultForNull
2384          * is FALSE, we can stop and return FALSE --- the AND result must be
2385          * FALSE or NULL in that case, and the caller doesn't care which.
2386          *
2387          * If we get to the end of the list, we can return TRUE.  This will
2388          * happen when the AND result is indeed TRUE, or when the AND result
2389          * is NULL (one or more NULL subresult, with all the rest TRUE) and
2390          * the caller has specified resultForNull = TRUE.
2391          */
2392         result = true;
2393
2394         foreach(qlist, qual)
2395         {
2396                 ExprState  *clause = (ExprState *) lfirst(qlist);
2397                 Datum           expr_value;
2398                 bool            isNull;
2399
2400                 expr_value = ExecEvalExpr(clause, econtext, &isNull, NULL);
2401
2402                 if (isNull)
2403                 {
2404                         if (resultForNull == false)
2405                         {
2406                                 result = false; /* treat NULL as FALSE */
2407                                 break;
2408                         }
2409                 }
2410                 else
2411                 {
2412                         if (!DatumGetBool(expr_value))
2413                         {
2414                                 result = false; /* definitely FALSE */
2415                                 break;
2416                         }
2417                 }
2418         }
2419
2420         MemoryContextSwitchTo(oldContext);
2421
2422         return result;
2423 }
2424
2425 /*
2426  * Number of items in a tlist (including any resjunk items!)
2427  */
2428 int
2429 ExecTargetListLength(List *targetlist)
2430 {
2431         /* This used to be more complex, but fjoins are dead */
2432         return length(targetlist);
2433 }
2434
2435 /*
2436  * Number of items in a tlist, not including any resjunk items
2437  */
2438 int
2439 ExecCleanTargetListLength(List *targetlist)
2440 {
2441         int                     len = 0;
2442         List       *tl;
2443
2444         foreach(tl, targetlist)
2445         {
2446                 TargetEntry *curTle = (TargetEntry *) lfirst(tl);
2447
2448                 Assert(IsA(curTle, TargetEntry));
2449                 if (!curTle->resdom->resjunk)
2450                         len++;
2451         }
2452         return len;
2453 }
2454
2455 /* ----------------------------------------------------------------
2456  *              ExecTargetList
2457  *
2458  *              Evaluates a targetlist with respect to the given
2459  *              expression context and returns a tuple.
2460  *
2461  * The caller must pass workspace for the values and nulls arrays
2462  * as well as the itemIsDone array.  This convention saves palloc'ing
2463  * workspace on each call, and some callers may find it useful to examine
2464  * the values array directly.
2465  *
2466  * As with ExecEvalExpr, the caller should pass isDone = NULL if not
2467  * prepared to deal with sets of result tuples.  Otherwise, a return
2468  * of *isDone = ExprMultipleResult signifies a set element, and a return
2469  * of *isDone = ExprEndResult signifies end of the set of tuple.
2470  * ----------------------------------------------------------------
2471  */
2472 static HeapTuple
2473 ExecTargetList(List *targetlist,
2474                            TupleDesc targettype,
2475                            ExprContext *econtext,
2476                            Datum *values,
2477                            char *nulls,
2478                            ExprDoneCond *itemIsDone,
2479                            ExprDoneCond *isDone)
2480 {
2481         MemoryContext oldContext;
2482         List       *tl;
2483         bool            isNull;
2484         bool            haveDoneSets;
2485         static struct tupleDesc NullTupleDesc;          /* we assume this inits to
2486                                                                                                  * zeroes */
2487
2488         /*
2489          * debugging stuff
2490          */
2491         EV_printf("ExecTargetList: tl is ");
2492         EV_nodeDisplay(targetlist);
2493         EV_printf("\n");
2494
2495         /*
2496          * Run in short-lived per-tuple context while computing expressions.
2497          */
2498         oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
2499
2500         /*
2501          * There used to be some klugy and demonstrably broken code here that
2502          * special-cased the situation where targetlist == NIL.  Now we just
2503          * fall through and return an empty-but-valid tuple.  We do, however,
2504          * have to cope with the possibility that targettype is NULL ---
2505          * heap_formtuple won't like that, so pass a dummy descriptor with
2506          * natts = 0 to deal with it.
2507          */
2508         if (targettype == NULL)
2509                 targettype = &NullTupleDesc;
2510
2511         /*
2512          * evaluate all the expressions in the target list
2513          */
2514         if (isDone)
2515                 *isDone = ExprSingleResult;             /* until proven otherwise */
2516
2517         haveDoneSets = false;           /* any exhausted set exprs in tlist? */
2518
2519         foreach(tl, targetlist)
2520         {
2521                 GenericExprState *gstate = (GenericExprState *) lfirst(tl);
2522                 TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr;
2523                 AttrNumber      resind = tle->resdom->resno - 1;
2524
2525                 values[resind] = ExecEvalExpr(gstate->arg,
2526                                                                           econtext,
2527                                                                           &isNull,
2528                                                                           &itemIsDone[resind]);
2529                 nulls[resind] = isNull ? 'n' : ' ';
2530
2531                 if (itemIsDone[resind] != ExprSingleResult)
2532                 {
2533                         /* We have a set-valued expression in the tlist */
2534                         if (isDone == NULL)
2535                                 elog(ERROR, "Set-valued function called in context that cannot accept a set");
2536                         if (itemIsDone[resind] == ExprMultipleResult)
2537                         {
2538                                 /* we have undone sets in the tlist, set flag */
2539                                 *isDone = ExprMultipleResult;
2540                         }
2541                         else
2542                         {
2543                                 /* we have done sets in the tlist, set flag for that */
2544                                 haveDoneSets = true;
2545                         }
2546                 }
2547         }
2548
2549         if (haveDoneSets)
2550         {
2551                 /*
2552                  * note: can't get here unless we verified isDone != NULL
2553                  */
2554                 if (*isDone == ExprSingleResult)
2555                 {
2556                         /*
2557                          * all sets are done, so report that tlist expansion is
2558                          * complete.
2559                          */
2560                         *isDone = ExprEndResult;
2561                         MemoryContextSwitchTo(oldContext);
2562                         return NULL;
2563                 }
2564                 else
2565                 {
2566                         /*
2567                          * We have some done and some undone sets.      Restart the done
2568                          * ones so that we can deliver a tuple (if possible).
2569                          */
2570                         foreach(tl, targetlist)
2571                         {
2572                                 GenericExprState *gstate = (GenericExprState *) lfirst(tl);
2573                                 TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr;
2574                                 AttrNumber      resind = tle->resdom->resno - 1;
2575
2576                                 if (itemIsDone[resind] == ExprEndResult)
2577                                 {
2578                                         values[resind] = ExecEvalExpr(gstate->arg,
2579                                                                                                   econtext,
2580                                                                                                   &isNull,
2581                                                                                                   &itemIsDone[resind]);
2582                                         nulls[resind] = isNull ? 'n' : ' ';
2583
2584                                         if (itemIsDone[resind] == ExprEndResult)
2585                                         {
2586                                                 /*
2587                                                  * Oh dear, this item is returning an empty
2588                                                  * set. Guess we can't make a tuple after all.
2589                                                  */
2590                                                 *isDone = ExprEndResult;
2591                                                 break;
2592                                         }
2593                                 }
2594                         }
2595
2596                         /*
2597                          * If we cannot make a tuple because some sets are empty, we
2598                          * still have to cycle the nonempty sets to completion, else
2599                          * resources will not be released from subplans etc.
2600                          *
2601                          * XXX is that still necessary?
2602                          */
2603                         if (*isDone == ExprEndResult)
2604                         {
2605                                 foreach(tl, targetlist)
2606                                 {
2607                                         GenericExprState *gstate = (GenericExprState *) lfirst(tl);
2608                                         TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr;
2609                                         AttrNumber      resind = tle->resdom->resno - 1;
2610
2611                                         while (itemIsDone[resind] == ExprMultipleResult)
2612                                         {
2613                                                 (void) ExecEvalExpr(gstate->arg,
2614                                                                                         econtext,
2615                                                                                         &isNull,
2616                                                                                         &itemIsDone[resind]);
2617                                         }
2618                                 }
2619
2620                                 MemoryContextSwitchTo(oldContext);
2621                                 return NULL;
2622                         }
2623                 }
2624         }
2625
2626         /*
2627          * form the new result tuple (in the caller's memory context!)
2628          */
2629         MemoryContextSwitchTo(oldContext);
2630
2631         return heap_formtuple(targettype, values, nulls);
2632 }
2633
2634 /* ----------------------------------------------------------------
2635  *              ExecProject
2636  *
2637  *              projects a tuple based on projection info and stores
2638  *              it in the specified tuple table slot.
2639  *
2640  *              Note: someday soon the executor can be extended to eliminate
2641  *                        redundant projections by storing pointers to datums
2642  *                        in the tuple table and then passing these around when
2643  *                        possible.  this should make things much quicker.
2644  *                        -cim 6/3/91
2645  * ----------------------------------------------------------------
2646  */
2647 TupleTableSlot *
2648 ExecProject(ProjectionInfo *projInfo, ExprDoneCond *isDone)
2649 {
2650         TupleTableSlot *slot;
2651         TupleDesc       tupType;
2652         HeapTuple       newTuple;
2653
2654         /*
2655          * sanity checks
2656          */
2657         if (projInfo == NULL)
2658                 return (TupleTableSlot *) NULL;
2659
2660         /*
2661          * get the projection info we want
2662          */
2663         slot = projInfo->pi_slot;
2664         tupType = slot->ttc_tupleDescriptor;
2665
2666         /*
2667          * form a new result tuple (if possible --- result can be NULL)
2668          */
2669         newTuple = ExecTargetList(projInfo->pi_targetlist,
2670                                                           tupType,
2671                                                           projInfo->pi_exprContext,
2672                                                           projInfo->pi_tupValues,
2673                                                           projInfo->pi_tupNulls,
2674                                                           projInfo->pi_itemIsDone,
2675                                                           isDone);
2676
2677         /*
2678          * store the tuple in the projection slot and return the slot.
2679          */
2680         return ExecStoreTuple(newTuple,         /* tuple to store */
2681                                                   slot, /* slot to store in */
2682                                                   InvalidBuffer,                /* tuple has no buffer */
2683                                                   true);
2684 }