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