execQual.c 84.7 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * execQual.c
4
 *	  Routines to evaluate qualification and targetlist expressions
5
 *
Bruce Momjian's avatar
Bruce Momjian committed
6
 * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
Bruce Momjian's avatar
Add:  
Bruce Momjian committed
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.148 2003/10/11 18:04:25 momjian Exp $
12 13 14 15
 *
 *-------------------------------------------------------------------------
 */
/*
16 17
 *	 INTERFACE ROUTINES
 *		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 23 24
 *	 NOTES
 *		ExecEvalExpr() and ExecEvalVar() are hotspots.	making these faster
 *		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 30 31
 *		trying to speed it up, the execution plan should be pre-processed
 *		to facilitate attribute sharing between nodes wherever possible,
 *		instead of doing needless copying.	-cim 5/31/91
32 33
 *
 */
34

35
#include "postgres.h"
36

Bruce Momjian's avatar
Bruce Momjian committed
37
#include "access/heapam.h"
38
#include "catalog/pg_type.h"
39
#include "commands/typecmds.h"
40
#include "executor/execdebug.h"
41
#include "executor/functions.h"
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
42
#include "executor/nodeSubplan.h"
43
#include "miscadmin.h"
44
#include "optimizer/planmain.h"
45
#include "parser/parse_expr.h"
46
#include "utils/acl.h"
47
#include "utils/array.h"
48
#include "utils/builtins.h"
49
#include "utils/lsyscache.h"
Bruce Momjian's avatar
Bruce Momjian committed
50

51

52
/* static function decls */
53
static Datum ExecEvalAggref(AggrefExprState *aggref,
Bruce Momjian's avatar
Bruce Momjian committed
54 55
			   ExprContext *econtext,
			   bool *isNull);
56
static Datum ExecEvalArrayRef(ArrayRefExprState *astate,
Bruce Momjian's avatar
Bruce Momjian committed
57 58
				 ExprContext *econtext,
				 bool *isNull, ExprDoneCond *isDone);
59
static Datum ExecEvalVar(Var *variable, ExprContext *econtext, bool *isNull);
60
static Datum ExecEvalParam(Param *expression, ExprContext *econtext,
Bruce Momjian's avatar
Bruce Momjian committed
61
			  bool *isNull);
62
static Datum ExecEvalFunc(FuncExprState *fcache, ExprContext *econtext,
63
			 bool *isNull, ExprDoneCond *isDone);
64
static Datum ExecEvalOper(FuncExprState *fcache, ExprContext *econtext,
65
			 bool *isNull, ExprDoneCond *isDone);
66
static Datum ExecEvalDistinct(FuncExprState *fcache, ExprContext *econtext,
67
				 bool *isNull);
68
static Datum ExecEvalScalarArrayOp(ScalarArrayOpExprState *sstate,
Bruce Momjian's avatar
Bruce Momjian committed
69
					  ExprContext *econtext, bool *isNull);
70 71
static ExprDoneCond ExecEvalFuncArgs(FunctionCallInfo fcinfo,
				 List *argList, ExprContext *econtext);
72
static Datum ExecEvalNot(BoolExprState *notclause, ExprContext *econtext,
Bruce Momjian's avatar
Bruce Momjian committed
73
			bool *isNull);
74
static Datum ExecEvalOr(BoolExprState *orExpr, ExprContext *econtext,
Bruce Momjian's avatar
Bruce Momjian committed
75
		   bool *isNull);
76
static Datum ExecEvalAnd(BoolExprState *andExpr, ExprContext *econtext,
Bruce Momjian's avatar
Bruce Momjian committed
77
			bool *isNull);
78
static Datum ExecEvalCase(CaseExprState *caseExpr, ExprContext *econtext,
79
			 bool *isNull, ExprDoneCond *isDone);
80
static Datum ExecEvalArray(ArrayExprState *astate,
Bruce Momjian's avatar
Bruce Momjian committed
81 82
			  ExprContext *econtext,
			  bool *isNull);
83
static Datum ExecEvalCoalesce(CoalesceExprState *coalesceExpr,
Bruce Momjian's avatar
Bruce Momjian committed
84 85
				 ExprContext *econtext,
				 bool *isNull);
86
static Datum ExecEvalNullIf(FuncExprState *nullIfExpr, ExprContext *econtext,
Bruce Momjian's avatar
Bruce Momjian committed
87
			   bool *isNull);
88
static Datum ExecEvalNullTest(GenericExprState *nstate,
Bruce Momjian's avatar
Bruce Momjian committed
89 90
				 ExprContext *econtext,
				 bool *isNull, ExprDoneCond *isDone);
91
static Datum ExecEvalBooleanTest(GenericExprState *bstate,
Bruce Momjian's avatar
Bruce Momjian committed
92 93
					ExprContext *econtext,
					bool *isNull, ExprDoneCond *isDone);
94
static Datum ExecEvalCoerceToDomain(CoerceToDomainState *cstate,
Bruce Momjian's avatar
Bruce Momjian committed
95 96
					   ExprContext *econtext,
					   bool *isNull, ExprDoneCond *isDone);
97
static Datum ExecEvalCoerceToDomainValue(CoerceToDomainValue *conVal,
Bruce Momjian's avatar
Bruce Momjian committed
98
							ExprContext *econtext, bool *isNull);
99
static Datum ExecEvalFieldSelect(GenericExprState *fstate,
Bruce Momjian's avatar
Bruce Momjian committed
100 101
					ExprContext *econtext,
					bool *isNull, ExprDoneCond *isDone);
102

103

104
/*----------
105
 *	  ExecEvalArrayRef
106
 *
107 108
 *	   This function takes an ArrayRef and returns the extracted Datum
 *	   if it's a simple reference, or the modified array value if it's
109 110 111 112 113 114 115 116
 *	   an array assignment (i.e., array element or slice insertion).
 *
 * NOTE: if we get a NULL result from a subexpression, we return NULL when
 * it's an array reference, or the unmodified source array when it's an
 * array assignment.  This may seem peculiar, but if we return NULL (as was
 * done in versions up through 7.0) then an assignment like
 *			UPDATE table SET arrayfield[4] = NULL
 * will result in setting the whole array to NULL, which is certainly not
117
 * very desirable.	By returning the source array we make the assignment
118 119 120
 * into a no-op, instead.  (Eventually we need to redesign arrays so that
 * individual elements can be NULL, but for now, let's try to protect users
 * from shooting themselves in the foot.)
121 122 123 124 125 126
 *
 * NOTE: we deliberately refrain from applying DatumGetArrayTypeP() here,
 * even though that might seem natural, because this code needs to support
 * both varlena arrays and fixed-length array types.  DatumGetArrayTypeP()
 * only works for the varlena kind.  The routines we call in arrayfuncs.c
 * have to know the difference (that's what they need refattrlength for).
127
 *----------
Bruce Momjian's avatar
Bruce Momjian committed
128
 */
129
static Datum
130
ExecEvalArrayRef(ArrayRefExprState *astate,
131 132
				 ExprContext *econtext,
				 bool *isNull,
133
				 ExprDoneCond *isDone)
134
{
135
	ArrayRef   *arrayRef = (ArrayRef *) astate->xprstate.expr;
136 137
	ArrayType  *array_source;
	ArrayType  *resultArray;
138
	bool		isAssignment = (arrayRef->refassgnexpr != NULL);
139
	List	   *elt;
140 141
	int			i = 0,
				j = 0;
142 143 144
	IntArray	upper,
				lower;
	int		   *lIndex;
145

146 147
	if (arrayRef->refexpr != NULL)
	{
148
		array_source = (ArrayType *)
149
			DatumGetPointer(ExecEvalExpr(astate->refexpr,
150 151 152
										 econtext,
										 isNull,
										 isDone));
153

154 155
		/*
		 * If refexpr yields NULL, result is always NULL, for now anyway.
156 157
		 * (This means you cannot assign to an element or slice of an
		 * array that's NULL; it'll just stay NULL.)
158
		 */
159 160 161 162 163
		if (*isNull)
			return (Datum) NULL;
	}
	else
	{
164
		/*
165
		 * Empty refexpr indicates we are doing an INSERT into an array
166 167 168 169 170
		 * column. For now, we just take the refassgnexpr (which the
		 * parser will have ensured is an array value) and return it
		 * as-is, ignoring any subscripts that may have been supplied in
		 * the INSERT column list. This is a kluge, but it's not real
		 * clear what the semantics ought to be...
171
		 */
172
		array_source = NULL;
173
	}
174

175
	foreach(elt, astate->refupperindexpr)
176
	{
177
		if (i >= MAXDIM)
178 179
			ereport(ERROR,
					(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
180 181
					 errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
							i, MAXDIM)));
182

183
		upper.indx[i++] = DatumGetInt32(ExecEvalExpr((ExprState *) lfirst(elt),
184 185
													 econtext,
													 isNull,
186
													 NULL));
187
		/* If any index expr yields NULL, result is NULL or source array */
188
		if (*isNull)
189
		{
190
			if (!isAssignment || array_source == NULL)
191 192 193 194
				return (Datum) NULL;
			*isNull = false;
			return PointerGetDatum(array_source);
		}
195 196
	}

197
	if (astate->reflowerindexpr != NIL)
198
	{
199
		foreach(elt, astate->reflowerindexpr)
200
		{
201
			if (j >= MAXDIM)
202 203
				ereport(ERROR,
						(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
204 205
						 errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
								i, MAXDIM)));
206

207
			lower.indx[j++] = DatumGetInt32(ExecEvalExpr((ExprState *) lfirst(elt),
208 209
														 econtext,
														 isNull,
210
														 NULL));
211 212 213 214 215

			/*
			 * If any index expr yields NULL, result is NULL or source
			 * array
			 */
216
			if (*isNull)
217
			{
218
				if (!isAssignment || array_source == NULL)
219 220 221 222
					return (Datum) NULL;
				*isNull = false;
				return PointerGetDatum(array_source);
			}
223
		}
224
		/* this can't happen unless parser messed up */
225
		if (i != j)
226
			elog(ERROR, "upper and lower index lists are not same length");
227
		lIndex = lower.indx;
228
	}
229 230
	else
		lIndex = NULL;
231

232
	if (isAssignment)
233
	{
234
		Datum		sourceData = ExecEvalExpr(astate->refassgnexpr,
235 236
											  econtext,
											  isNull,
237
											  NULL);
238

239
		/*
240 241
		 * For now, can't cope with inserting NULL into an array, so make
		 * it a no-op per discussion above...
242
		 */
243
		if (*isNull)
244 245 246 247 248 249
		{
			if (array_source == NULL)
				return (Datum) NULL;
			*isNull = false;
			return PointerGetDatum(array_source);
		}
250

251
		if (array_source == NULL)
252
			return sourceData;	/* XXX do something else? */
253

254
		if (lIndex == NULL)
255 256 257
			resultArray = array_set(array_source, i,
									upper.indx,
									sourceData,
258 259 260 261
									astate->refattrlength,
									astate->refelemlength,
									astate->refelembyval,
									astate->refelemalign,
262 263 264 265
									isNull);
		else
			resultArray = array_set_slice(array_source, i,
										  upper.indx, lower.indx,
266
							   (ArrayType *) DatumGetPointer(sourceData),
267 268 269 270
										  astate->refattrlength,
										  astate->refelemlength,
										  astate->refelembyval,
										  astate->refelemalign,
271 272
										  isNull);
		return PointerGetDatum(resultArray);
273
	}
274

275
	if (lIndex == NULL)
276
		return array_ref(array_source, i, upper.indx,
277 278 279 280
						 astate->refattrlength,
						 astate->refelemlength,
						 astate->refelembyval,
						 astate->refelemalign,
281
						 isNull);
282 283 284
	else
	{
		resultArray = array_get_slice(array_source, i,
285
									  upper.indx, lower.indx,
286 287 288 289
									  astate->refattrlength,
									  astate->refelemlength,
									  astate->refelembyval,
									  astate->refelemalign,
290 291 292
									  isNull);
		return PointerGetDatum(resultArray);
	}
293 294 295 296
}


/* ----------------------------------------------------------------
Bruce Momjian's avatar
Bruce Momjian committed
297
 *		ExecEvalAggref
298 299 300
 *
 *		Returns a Datum whose value is the value of the precomputed
 *		aggregate found in the given expression context.
301 302
 * ----------------------------------------------------------------
 */
303
static Datum
304
ExecEvalAggref(AggrefExprState *aggref, ExprContext *econtext, bool *isNull)
305
{
306
	if (econtext->ecxt_aggvalues == NULL)		/* safety check */
307
		elog(ERROR, "no aggregates in this expression context");
308

309 310
	*isNull = econtext->ecxt_aggnulls[aggref->aggno];
	return econtext->ecxt_aggvalues[aggref->aggno];
311 312 313
}

/* ----------------------------------------------------------------
314 315 316 317
 *		ExecEvalVar
 *
 *		Returns a Datum whose value is the value of a range
 *		variable with respect to given expression context.
318
 * ---------------------------------------------------------------- */
319
static Datum
320
ExecEvalVar(Var *variable, ExprContext *econtext, bool *isNull)
321
{
322
	Datum		result;
323
	TupleTableSlot *slot;
324 325 326
	AttrNumber	attnum;
	HeapTuple	heapTuple;
	TupleDesc	tuple_type;
327

Bruce Momjian's avatar
Bruce Momjian committed
328
	/*
Bruce Momjian's avatar
Bruce Momjian committed
329
	 * get the slot we want
330 331 332
	 */
	switch (variable->varno)
	{
333 334 335
		case INNER:				/* get the tuple from the inner node */
			slot = econtext->ecxt_innertuple;
			break;
336

337 338 339
		case OUTER:				/* get the tuple from the outer node */
			slot = econtext->ecxt_outertuple;
			break;
340

341
		default:				/* get the tuple from the relation being
342
								 * scanned */
343 344
			slot = econtext->ecxt_scantuple;
			break;
345 346
	}

Bruce Momjian's avatar
Bruce Momjian committed
347
	/*
Bruce Momjian's avatar
Bruce Momjian committed
348
	 * extract tuple information from the slot
349 350 351 352 353 354
	 */
	heapTuple = slot->val;
	tuple_type = slot->ttc_tupleDescriptor;

	attnum = variable->varattno;

355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
	/*
	 * Some checks that are only applied for user attribute numbers
	 * (bogus system attnums will be caught inside heap_getattr).
	 */
	if (attnum > 0)
	{
		/*
		 * This assert checks that the attnum is valid.
		 */
		Assert(attnum <= tuple_type->natts &&
			   tuple_type->attrs[attnum - 1] != NULL);

		/*
		 * If the attribute's column has been dropped, we force a NULL result.
		 * This case should not happen in normal use, but it could happen if
		 * we are executing a plan cached before the column was dropped.
		 */
		if (tuple_type->attrs[attnum - 1]->attisdropped)
		{
			*isNull = true;
			return (Datum) 0;
		}

		/*
		 * This assert checks that the datatype the plan expects to get (as
		 * told by our "variable" argument) is in fact the datatype of the
		 * attribute being fetched (as seen in the current context, identified
		 * by our "econtext" argument).  Otherwise crashes are likely.
		 *
		 * Note that we can't check dropped columns, since their atttypid
		 * has been zeroed.
		 */
		Assert(variable->vartype == tuple_type->attrs[attnum - 1]->atttypid);
	}
389 390 391

	/*
	 * If the attribute number is invalid, then we are supposed to return
392 393 394
	 * the entire tuple; we give back a whole slot so that callers know
	 * what the tuple looks like.
	 *
395 396
	 * XXX this is a horrid crock: since the pointer to the slot might live
	 * longer than the current evaluation context, we are forced to copy
Bruce Momjian's avatar
Bruce Momjian committed
397 398
	 * the tuple and slot into a long-lived context --- we use the
	 * econtext's per-query memory which should be safe enough.  This
399 400 401 402 403 404
	 * represents a serious memory leak if many such tuples are processed
	 * in one command, however.  We ought to redesign the representation
	 * of whole-tuple datums so that this is not necessary.
	 *
	 * We assume it's OK to point to the existing tupleDescriptor, rather
	 * than copy that too.
405
	 */
406
	if (attnum == InvalidAttrNumber)
407
	{
408 409
		MemoryContext oldContext;
		TupleTableSlot *tempSlot;
410
		HeapTuple	tup;
411

412
		oldContext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
413
		tempSlot = MakeTupleTableSlot();
414
		tup = heap_copytuple(heapTuple);
415
		ExecStoreTuple(tup, tempSlot, InvalidBuffer, true);
416 417
		ExecSetSlotDescriptor(tempSlot, tuple_type, false);
		MemoryContextSwitchTo(oldContext);
418
		return PointerGetDatum(tempSlot);
419
	}
420

421 422 423 424 425
	result = heap_getattr(heapTuple,	/* tuple containing attribute */
						  attnum,		/* attribute number of desired
										 * attribute */
						  tuple_type,	/* tuple descriptor of tuple */
						  isNull);		/* return: is attribute null? */
426 427

	return result;
428 429 430
}

/* ----------------------------------------------------------------
431
 *		ExecEvalParam
432
 *
433 434 435
 *		Returns the value of a parameter.  A param node contains
 *		something like ($.name) and the expression context contains
 *		the current parameter bindings (name = "sam") (age = 34)...
436
 *		so our job is to find and return the appropriate datum ("sam").
437
 *
438 439 440
 *		Q: if we have a parameter ($.foo) without a binding, i.e.
 *		   there is no (foo = xxx) in the parameter list info,
 *		   is this a fatal error or should this be a "not available"
441
 *		   (in which case we could return NULL)?	-cim 10/13/89
442 443
 * ----------------------------------------------------------------
 */
444
static Datum
445
ExecEvalParam(Param *expression, ExprContext *econtext, bool *isNull)
446
{
447 448
	int			thisParamKind = expression->paramkind;
	AttrNumber	thisParamId = expression->paramid;
449

450
	if (thisParamKind == PARAM_EXEC)
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
451
	{
452 453
		/*
		 * PARAM_EXEC params (internal executor parameters) are stored in
Bruce Momjian's avatar
Bruce Momjian committed
454 455
		 * the ecxt_param_exec_vals array, and can be accessed by array
		 * index.
456
		 */
457
		ParamExecData *prm;
458

459
		prm = &(econtext->ecxt_param_exec_vals[thisParamId]);
460
		if (prm->execPlan != NULL)
461
		{
462
			/* Parameter not evaluated yet, so go do it */
463 464 465 466
			ExecSetParamPlan(prm->execPlan, econtext);
			/* ExecSetParamPlan should have processed this param... */
			Assert(prm->execPlan == NULL);
		}
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
467
		*isNull = prm->isnull;
468
		return prm->value;
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
469
	}
470
	else
471 472
	{
		/*
Bruce Momjian's avatar
Bruce Momjian committed
473 474 475
		 * All other parameter types must be sought in
		 * ecxt_param_list_info. NOTE: The last entry in the param array
		 * is always an entry with kind == PARAM_INVALID.
476
		 */
477 478 479 480 481
		ParamListInfo paramList = econtext->ecxt_param_list_info;
		char	   *thisParamName = expression->paramname;
		bool		matchFound = false;

		if (paramList != NULL)
482
		{
483
			while (paramList->kind != PARAM_INVALID && !matchFound)
484
			{
485 486 487
				if (thisParamKind == paramList->kind)
				{
					switch (thisParamKind)
488
					{
489 490 491 492 493 494 495 496 497
						case PARAM_NAMED:
							if (strcmp(paramList->name, thisParamName) == 0)
								matchFound = true;
							break;
						case PARAM_NUM:
							if (paramList->id == thisParamId)
								matchFound = true;
							break;
						default:
498
							elog(ERROR, "unrecognized paramkind: %d",
499
								 thisParamKind);
500
					}
501 502 503
				}
				if (!matchFound)
					paramList++;
Bruce Momjian's avatar
Bruce Momjian committed
504 505
			}					/* while */
		}						/* if */
506

507 508 509
		if (!matchFound)
		{
			if (thisParamKind == PARAM_NAMED)
510 511 512 513
				ereport(ERROR,
						(errcode(ERRCODE_UNDEFINED_OBJECT),
						 errmsg("no value found for parameter \"%s\"",
								thisParamName)));
514
			else
515 516 517 518
				ereport(ERROR,
						(errcode(ERRCODE_UNDEFINED_OBJECT),
						 errmsg("no value found for parameter %d",
								thisParamId)));
519
		}
520

521 522 523
		*isNull = paramList->isnull;
		return paramList->value;
	}
524 525 526 527
}


/* ----------------------------------------------------------------
528
 *		ExecEvalOper / ExecEvalFunc support routines
529 530 531
 * ----------------------------------------------------------------
 */

Bruce Momjian's avatar
Bruce Momjian committed
532
/*
533 534
 *		GetAttributeByName
 *		GetAttributeByNum
535
 *
536 537 538 539
 *		These are functions which return the value of the
 *		named attribute out of the tuple from the arg slot.  User defined
 *		C functions which take a tuple as an argument are expected
 *		to use this.  Ex: overpaid(EMP) might call GetAttributeByNum().
540
 */
541
Datum
542
GetAttributeByNum(TupleTableSlot *slot,
543
				  AttrNumber attrno,
544
				  bool *isNull)
545
{
546
	Datum		retval;
547 548

	if (!AttributeNumberIsValid(attrno))
549
		elog(ERROR, "invalid attribute number %d", attrno);
550 551

	if (isNull == (bool *) NULL)
552
		elog(ERROR, "a NULL isNull pointer was passed");
553 554

	if (TupIsNull(slot))
555
	{
556
		*isNull = true;
557
		return (Datum) 0;
558
	}
559

560 561 562 563
	retval = heap_getattr(slot->val,
						  attrno,
						  slot->ttc_tupleDescriptor,
						  isNull);
564
	if (*isNull)
565 566 567
		return (Datum) 0;

	return retval;
568
}
569

570
Datum
571
GetAttributeByName(TupleTableSlot *slot, char *attname, bool *isNull)
572
{
573 574 575 576 577
	AttrNumber	attrno;
	TupleDesc	tupdesc;
	Datum		retval;
	int			natts;
	int			i;
578 579

	if (attname == NULL)
580
		elog(ERROR, "invalid attribute name");
581 582

	if (isNull == (bool *) NULL)
583
		elog(ERROR, "a NULL isNull pointer was passed");
584 585

	if (TupIsNull(slot))
586
	{
587
		*isNull = true;
588
		return (Datum) 0;
589
	}
590 591

	tupdesc = slot->ttc_tupleDescriptor;
592
	natts = slot->val->t_data->t_natts;
593 594 595 596 597 598 599 600 601

	attrno = InvalidAttrNumber;
	for (i = 0; i < tupdesc->natts; i++)
	{
		if (namestrcmp(&(tupdesc->attrs[i]->attname), attname) == 0)
		{
			attrno = tupdesc->attrs[i]->attnum;
			break;
		}
602
	}
603 604

	if (attrno == InvalidAttrNumber)
605
		elog(ERROR, "attribute \"%s\" does not exist", attname);
606

607 608 609 610
	retval = heap_getattr(slot->val,
						  attrno,
						  tupdesc,
						  isNull);
611
	if (*isNull)
612 613 614
		return (Datum) 0;

	return retval;
615 616
}

617 618 619 620
/*
 * init_fcache - initialize a FuncExprState node during first use
 */
void
621
init_fcache(Oid foid, FuncExprState *fcache, MemoryContext fcacheCxt)
622 623 624 625 626 627
{
	AclResult	aclresult;

	/* Check permission to call function */
	aclresult = pg_proc_aclcheck(foid, GetUserId(), ACL_EXECUTE);
	if (aclresult != ACLCHECK_OK)
628
		aclcheck_error(aclresult, ACL_KIND_PROC, get_func_name(foid));
629 630 631

	/* Safety check (should never fail, as parser should check sooner) */
	if (length(fcache->args) > FUNC_MAX_ARGS)
632
		elog(ERROR, "too many arguments");
633 634 635 636 637 638

	/* Set up the primary fmgr lookup information */
	fmgr_info_cxt(foid, &(fcache->func), fcacheCxt);

	/* Initialize additional info */
	fcache->setArgsValid = false;
639
	fcache->func.fn_expr = (Node *) fcache->xprstate.expr;
640 641
}

642 643 644 645
/*
 * Evaluate arguments for a function.
 */
static ExprDoneCond
646
ExecEvalFuncArgs(FunctionCallInfo fcinfo,
647
				 List *argList,
648
				 ExprContext *econtext)
649
{
650
	ExprDoneCond argIsDone;
651 652
	int			i;
	List	   *arg;
653

654
	argIsDone = ExprSingleResult;		/* default assumption */
655

656 657 658
	i = 0;
	foreach(arg, argList)
	{
659
		ExprDoneCond thisArgIsDone;
Bruce Momjian's avatar
Bruce Momjian committed
660

661
		fcinfo->arg[i] = ExecEvalExpr((ExprState *) lfirst(arg),
662 663 664
									  econtext,
									  &fcinfo->argnull[i],
									  &thisArgIsDone);
665

666
		if (thisArgIsDone != ExprSingleResult)
667
		{
668 669
			/*
			 * We allow only one argument to have a set value; we'd need
670 671 672
			 * much more complexity to keep track of multiple set
			 * arguments (cf. ExecTargetList) and it doesn't seem worth
			 * it.
673 674
			 */
			if (argIsDone != ExprSingleResult)
675 676 677
				ereport(ERROR,
						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
						 errmsg("functions and operators can take at most one set argument")));
678
			argIsDone = thisArgIsDone;
679 680 681
		}
		i++;
	}
682

683 684
	fcinfo->nargs = i;

685
	return argIsDone;
686 687
}

Bruce Momjian's avatar
Bruce Momjian committed
688
/*
689
 *		ExecMakeFunctionResult
690 691
 *
 * Evaluate the arguments to a function and then the function itself.
692
 */
693
Datum
694
ExecMakeFunctionResult(FuncExprState *fcache,
695 696
					   ExprContext *econtext,
					   bool *isNull,
697
					   ExprDoneCond *isDone)
698
{
699
	List	   *arguments = fcache->args;
700
	Datum		result;
701 702
	FunctionCallInfoData fcinfo;
	ReturnSetInfo rsinfo;		/* for functions returning sets */
703
	ExprDoneCond argDone;
704
	bool		hasSetArg;
705
	int			i;
706

Bruce Momjian's avatar
Bruce Momjian committed
707
	/*
Bruce Momjian's avatar
Bruce Momjian committed
708
	 * arguments is a list of expressions to evaluate before passing to
709
	 * the function manager.  We skip the evaluation if it was already
710 711
	 * done in the previous call (ie, we are continuing the evaluation of
	 * a set-valued function).	Otherwise, collect the current argument
712
	 * values into fcinfo.
713
	 */
714
	if (!fcache->setArgsValid)
715
	{
716 717 718 719
		/* Need to prep callinfo structure */
		MemSet(&fcinfo, 0, sizeof(fcinfo));
		fcinfo.flinfo = &(fcache->func);
		argDone = ExecEvalFuncArgs(&fcinfo, arguments, econtext);
720
		if (argDone == ExprEndResult)
721
		{
722
			/* input is an empty set, so return an empty set. */
723
			*isNull = true;
724 725 726
			if (isDone)
				*isDone = ExprEndResult;
			else
727
				ereport(ERROR,
728
						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
729
						 errmsg("set-valued function called in context that cannot accept a set")));
730
			return (Datum) 0;
731
		}
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
		hasSetArg = (argDone != ExprSingleResult);
	}
	else
	{
		/* Copy callinfo from previous evaluation */
		memcpy(&fcinfo, &fcache->setArgs, sizeof(fcinfo));
		hasSetArg = fcache->setHasSetArg;
		/* Reset flag (we may set it again below) */
		fcache->setArgsValid = false;
	}

	/*
	 * If function returns set, prepare a resultinfo node for
	 * communication
	 */
	if (fcache->func.fn_retset)
	{
749
		fcinfo.resultinfo = (Node *) &rsinfo;
750
		rsinfo.type = T_ReturnSetInfo;
751
		rsinfo.econtext = econtext;
752
		rsinfo.expectedDesc = NULL;
753 754 755 756 757
		rsinfo.allowedModes = (int) SFRM_ValuePerCall;
		rsinfo.returnMode = SFRM_ValuePerCall;
		/* isDone is filled below */
		rsinfo.setResult = NULL;
		rsinfo.setDesc = NULL;
758
	}
759

Bruce Momjian's avatar
Bruce Momjian committed
760
	/*
Bruce Momjian's avatar
Bruce Momjian committed
761 762
	 * now return the value gotten by calling the function manager,
	 * passing the function the evaluated parameter values.
763
	 */
764
	if (fcache->func.fn_retset || hasSetArg)
765
	{
766
		/*
767
		 * We need to return a set result.	Complain if caller not ready
768 769 770
		 * to accept one.
		 */
		if (isDone == NULL)
771
			ereport(ERROR,
772
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
773
					 errmsg("set-valued function called in context that cannot accept a set")));
774 775

		/*
776 777 778 779 780 781
		 * This loop handles the situation where we have both a set
		 * argument and a set-valued function.	Once we have exhausted the
		 * function's value(s) for a particular argument value, we have to
		 * get the next argument value and start the function over again.
		 * We might have to do it more than once, if the function produces
		 * an empty result set for a particular input value.
782
		 */
783
		for (;;)
784
		{
785 786 787 788
			/*
			 * If function is strict, and there are any NULL arguments,
			 * skip calling the function (at least for this set of args).
			 */
789
			bool		callit = true;
790

791
			if (fcache->func.fn_strict)
792
			{
793
				for (i = 0; i < fcinfo.nargs; i++)
794
				{
795
					if (fcinfo.argnull[i])
796 797 798 799 800 801 802 803 804
					{
						callit = false;
						break;
					}
				}
			}

			if (callit)
			{
805 806 807 808 809
				fcinfo.isnull = false;
				rsinfo.isDone = ExprSingleResult;
				result = FunctionCallInvoke(&fcinfo);
				*isNull = fcinfo.isnull;
				*isDone = rsinfo.isDone;
810 811 812 813 814
			}
			else
			{
				result = (Datum) 0;
				*isNull = true;
815 816 817 818 819 820
				*isDone = ExprEndResult;
			}

			if (*isDone != ExprEndResult)
			{
				/*
821
				 * Got a result from current argument.	If function itself
822 823
				 * returns set, save the current argument values to re-use
				 * on the next call.
824 825
				 */
				if (fcache->func.fn_retset)
826 827 828 829 830
				{
					memcpy(&fcache->setArgs, &fcinfo, sizeof(fcinfo));
					fcache->setHasSetArg = hasSetArg;
					fcache->setArgsValid = true;
				}
831

832 833 834 835 836 837
				/*
				 * Make sure we say we are returning a set, even if the
				 * function itself doesn't return sets.
				 */
				*isDone = ExprMultipleResult;
				break;
838
			}
839

840
			/* Else, done with this argument */
841
			if (!hasSetArg)
842
				break;			/* input not a set, so done */
843

844
			/* Re-eval args to get the next element of the input set */
845
			argDone = ExecEvalFuncArgs(&fcinfo, arguments, econtext);
846

847
			if (argDone != ExprMultipleResult)
848
			{
849
				/* End of argument set, so we're done. */
850
				*isNull = true;
851
				*isDone = ExprEndResult;
852
				result = (Datum) 0;
853
				break;
854
			}
855

856 857
			/*
			 * If we reach here, loop around to run the function on the
858 859
			 * new argument.
			 */
860
		}
861
	}
862
	else
863
	{
864
		/*
865 866
		 * Non-set case: much easier.
		 *
867 868
		 * If function is strict, and there are any NULL arguments, skip
		 * calling the function and return NULL.
869
		 */
870
		if (fcache->func.fn_strict)
871
		{
872
			for (i = 0; i < fcinfo.nargs; i++)
873
			{
874
				if (fcinfo.argnull[i])
875 876 877 878 879 880
				{
					*isNull = true;
					return (Datum) 0;
				}
			}
		}
881 882 883
		fcinfo.isnull = false;
		result = FunctionCallInvoke(&fcinfo);
		*isNull = fcinfo.isnull;
884
	}
885 886

	return result;
887 888 889
}


890 891 892 893
/*
 *		ExecMakeTableFunctionResult
 *
 * Evaluate a table function, producing a materialized result in a Tuplestore
Bruce Momjian's avatar
Bruce Momjian committed
894
 * object.	(If function returns an empty set, we just return NULL instead.)
895 896
 */
Tuplestorestate *
897
ExecMakeTableFunctionResult(ExprState *funcexpr,
898
							ExprContext *econtext,
899
							TupleDesc expectedDesc,
900 901 902 903
							TupleDesc *returnDesc)
{
	Tuplestorestate *tupstore = NULL;
	TupleDesc	tupdesc = NULL;
904
	Oid			funcrettype;
905
	FunctionCallInfoData fcinfo;
906
	ReturnSetInfo rsinfo;
907 908 909
	MemoryContext callerContext;
	MemoryContext oldcontext;
	TupleTableSlot *slot;
910
	bool		direct_function_call;
911 912 913 914
	bool		first_time = true;
	bool		returnsTuple = false;

	/*
Bruce Momjian's avatar
Bruce Momjian committed
915 916 917 918 919 920 921 922
	 * Normally the passed expression tree will be a FuncExprState, since
	 * the grammar only allows a function call at the top level of a table
	 * function reference.	However, if the function doesn't return set
	 * then the planner might have replaced the function call via
	 * constant-folding or inlining.  So if we see any other kind of
	 * expression node, execute it via the general ExecEvalExpr() code;
	 * the only difference is that we don't get a chance to pass a special
	 * ReturnSetInfo to any functions buried in the expression.
923
	 */
924 925
	if (funcexpr && IsA(funcexpr, FuncExprState) &&
		IsA(funcexpr->expr, FuncExpr))
926
	{
927
		FuncExprState *fcache = (FuncExprState *) funcexpr;
928
		ExprDoneCond argDone;
929

930 931 932 933
		/*
		 * This path is similar to ExecMakeFunctionResult.
		 */
		direct_function_call = true;
934

935
		/*
936
		 * Initialize function cache if first time through
937
		 */
938
		if (fcache->func.fn_oid == InvalidOid)
939
		{
Bruce Momjian's avatar
Bruce Momjian committed
940
			FuncExpr   *func = (FuncExpr *) fcache->xprstate.expr;
941 942

			init_fcache(func->funcid, fcache, econtext->ecxt_per_query_memory);
943 944 945 946 947 948
		}

		/*
		 * Evaluate the function's argument list.
		 *
		 * Note: ideally, we'd do this in the per-tuple context, but then the
Bruce Momjian's avatar
Bruce Momjian committed
949 950 951
		 * argument values would disappear when we reset the context in
		 * the inner loop.	So do it in caller context.  Perhaps we should
		 * make a separate context just to hold the evaluated arguments?
952 953 954
		 */
		MemSet(&fcinfo, 0, sizeof(fcinfo));
		fcinfo.flinfo = &(fcache->func);
955
		argDone = ExecEvalFuncArgs(&fcinfo, fcache->args, econtext);
956 957
		/* We don't allow sets in the arguments of the table function */
		if (argDone != ExprSingleResult)
958
			ereport(ERROR,
959
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
960
					 errmsg("set-valued function called in context that cannot accept a set")));
961 962 963 964 965 966 967 968 969 970

		/*
		 * If function is strict, and there are any NULL arguments, skip
		 * calling the function and return NULL (actually an empty set).
		 */
		if (fcache->func.fn_strict)
		{
			int			i;

			for (i = 0; i < fcinfo.nargs; i++)
971
			{
972 973 974 975 976
				if (fcinfo.argnull[i])
				{
					*returnDesc = NULL;
					return NULL;
				}
977 978 979
			}
		}
	}
980 981 982 983 984
	else
	{
		/* Treat funcexpr as a generic expression */
		direct_function_call = false;
	}
985

986 987
	funcrettype = exprType((Node *) funcexpr->expr);

988
	/*
Bruce Momjian's avatar
Bruce Momjian committed
989 990
	 * Prepare a resultinfo node for communication.  We always do this
	 * even if not expecting a set result, so that we can pass
991 992 993
	 * expectedDesc.  In the generic-expression case, the expression
	 * doesn't actually get to see the resultinfo, but set it up anyway
	 * because we use some of the fields as our own state variables.
994
	 */
995
	fcinfo.resultinfo = (Node *) &rsinfo;
996 997 998 999
	rsinfo.type = T_ReturnSetInfo;
	rsinfo.econtext = econtext;
	rsinfo.expectedDesc = expectedDesc;
	rsinfo.allowedModes = (int) (SFRM_ValuePerCall | SFRM_Materialize);
1000 1001 1002 1003 1004 1005
	rsinfo.returnMode = SFRM_ValuePerCall;
	/* isDone is filled below */
	rsinfo.setResult = NULL;
	rsinfo.setDesc = NULL;

	/*
Bruce Momjian's avatar
Bruce Momjian committed
1006 1007
	 * Switch to short-lived context for calling the function or
	 * expression.
1008 1009 1010 1011
	 */
	callerContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);

	/*
1012 1013
	 * Loop to handle the ValuePerCall protocol (which is also the same
	 * behavior needed in the generic ExecEvalExpr path).
1014 1015 1016 1017 1018 1019 1020
	 */
	for (;;)
	{
		Datum		result;
		HeapTuple	tuple;

		/*
Bruce Momjian's avatar
Bruce Momjian committed
1021 1022 1023
		 * reset per-tuple memory context before each call of the function
		 * or expression. This cleans up any local memory the function may
		 * leak when called.
1024 1025 1026
		 */
		ResetExprContext(econtext);

1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
		/* Call the function or expression one time */
		if (direct_function_call)
		{
			fcinfo.isnull = false;
			rsinfo.isDone = ExprSingleResult;
			result = FunctionCallInvoke(&fcinfo);
		}
		else
		{
			result = ExecEvalExpr(funcexpr, econtext,
								  &fcinfo.isnull, &rsinfo.isDone);
		}
1039 1040 1041 1042 1043 1044 1045

		/* Which protocol does function want to use? */
		if (rsinfo.returnMode == SFRM_ValuePerCall)
		{
			/*
			 * Check for end of result set.
			 *
Bruce Momjian's avatar
Bruce Momjian committed
1046
			 * Note: if function returns an empty set, we don't build a
1047 1048 1049 1050 1051
			 * tupdesc or tuplestore (since we can't get a tupdesc in the
			 * function-returning-tuple case)
			 */
			if (rsinfo.isDone == ExprEndResult)
				break;
Bruce Momjian's avatar
Bruce Momjian committed
1052

1053
			/*
Bruce Momjian's avatar
Bruce Momjian committed
1054 1055
			 * If first time through, build tupdesc and tuplestore for
			 * result
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
			 */
			if (first_time)
			{
				oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
				if (funcrettype == RECORDOID ||
					get_typtype(funcrettype) == 'c')
				{
					/*
					 * Composite type, so function should have returned a
					 * TupleTableSlot; use its descriptor
					 */
					slot = (TupleTableSlot *) DatumGetPointer(result);
1068 1069 1070
					if (fcinfo.isnull || !slot)
						ereport(ERROR,
								(errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1071
								 errmsg("function returning row cannot return null value")));
1072
					if (!IsA(slot, TupleTableSlot) ||
1073
						!slot->ttc_tupleDescriptor)
1074 1075
						ereport(ERROR,
								(errcode(ERRCODE_DATATYPE_MISMATCH),
1076
								 errmsg("function returning row did not return a valid tuple slot")));
1077 1078 1079 1080 1081 1082 1083 1084
					tupdesc = CreateTupleDescCopy(slot->ttc_tupleDescriptor);
					returnsTuple = true;
				}
				else
				{
					/*
					 * Scalar type, so make a single-column descriptor
					 */
1085
					tupdesc = CreateTemplateTupleDesc(1, false);
1086 1087 1088 1089 1090 1091 1092 1093
					TupleDescInitEntry(tupdesc,
									   (AttrNumber) 1,
									   "column",
									   funcrettype,
									   -1,
									   0,
									   false);
				}
1094
				tupstore = tuplestore_begin_heap(true, false, SortMem);
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
				MemoryContextSwitchTo(oldcontext);
				rsinfo.setResult = tupstore;
				rsinfo.setDesc = tupdesc;
			}

			/*
			 * Store current resultset item.
			 */
			if (returnsTuple)
			{
				slot = (TupleTableSlot *) DatumGetPointer(result);
1106 1107 1108
				if (fcinfo.isnull ||
					!slot ||
					!IsA(slot, TupleTableSlot) ||
1109
					TupIsNull(slot))
1110 1111
					ereport(ERROR,
							(errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1112
							 errmsg("function returning row cannot return null value")));
1113 1114 1115 1116
				tuple = slot->val;
			}
			else
			{
Bruce Momjian's avatar
Bruce Momjian committed
1117
				char		nullflag;
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136

				nullflag = fcinfo.isnull ? 'n' : ' ';
				tuple = heap_formtuple(tupdesc, &result, &nullflag);
			}

			oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
			tuplestore_puttuple(tupstore, tuple);
			MemoryContextSwitchTo(oldcontext);

			/*
			 * Are we done?
			 */
			if (rsinfo.isDone != ExprMultipleResult)
				break;
		}
		else if (rsinfo.returnMode == SFRM_Materialize)
		{
			/* check we're on the same page as the function author */
			if (!first_time || rsinfo.isDone != ExprSingleResult)
1137 1138 1139
				ereport(ERROR,
						(errcode(ERRCODE_E_R_I_E_SRF_PROTOCOL_VIOLATED),
						 errmsg("table-function protocol for materialize mode was not followed")));
1140 1141 1142 1143
			/* Done evaluating the set result */
			break;
		}
		else
1144 1145 1146 1147
			ereport(ERROR,
					(errcode(ERRCODE_E_R_I_E_SRF_PROTOCOL_VIOLATED),
					 errmsg("unrecognized table-function returnMode: %d",
							(int) rsinfo.returnMode)));
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159

		first_time = false;
	}

	MemoryContextSwitchTo(callerContext);

	/* The returned pointers are those in rsinfo */
	*returnDesc = rsinfo.setDesc;
	return rsinfo.setResult;
}


1160
/* ----------------------------------------------------------------
1161
 *		ExecEvalFunc
1162
 *		ExecEvalOper
1163 1164
 *
 *		Evaluate the functional result of a list of arguments by calling the
1165
 *		function manager.
1166 1167 1168 1169
 * ----------------------------------------------------------------
 */

/* ----------------------------------------------------------------
1170
 *		ExecEvalFunc
1171 1172
 * ----------------------------------------------------------------
 */
1173
static Datum
1174
ExecEvalFunc(FuncExprState *fcache,
1175 1176 1177
			 ExprContext *econtext,
			 bool *isNull,
			 ExprDoneCond *isDone)
1178
{
Bruce Momjian's avatar
Bruce Momjian committed
1179
	/*
1180
	 * Initialize function cache if first time through
1181
	 */
1182
	if (fcache->func.fn_oid == InvalidOid)
1183
	{
Bruce Momjian's avatar
Bruce Momjian committed
1184
		FuncExpr   *func = (FuncExpr *) fcache->xprstate.expr;
1185 1186

		init_fcache(func->funcid, fcache, econtext->ecxt_per_query_memory);
1187 1188
	}

1189
	return ExecMakeFunctionResult(fcache, econtext, isNull, isDone);
1190 1191
}

1192
/* ----------------------------------------------------------------
1193
 *		ExecEvalOper
1194 1195 1196
 * ----------------------------------------------------------------
 */
static Datum
1197
ExecEvalOper(FuncExprState *fcache,
1198 1199 1200 1201 1202
			 ExprContext *econtext,
			 bool *isNull,
			 ExprDoneCond *isDone)
{
	/*
1203
	 * Initialize function cache if first time through
1204
	 */
1205
	if (fcache->func.fn_oid == InvalidOid)
1206
	{
Bruce Momjian's avatar
Bruce Momjian committed
1207
		OpExpr	   *op = (OpExpr *) fcache->xprstate.expr;
1208 1209

		init_fcache(op->opfuncid, fcache, econtext->ecxt_per_query_memory);
1210 1211
	}

1212
	return ExecMakeFunctionResult(fcache, econtext, isNull, isDone);
1213 1214
}

1215 1216 1217 1218 1219 1220 1221
/* ----------------------------------------------------------------
 *		ExecEvalDistinct
 *
 * IS DISTINCT FROM must evaluate arguments to determine whether
 * they are NULL; if either is NULL then the result is already
 * known. If neither is NULL, then proceed to evaluate the
 * function. Note that this is *always* derived from the equals
1222
 * operator, but since we need special processing of the arguments
1223 1224 1225 1226
 * we can not simply reuse ExecEvalOper() or ExecEvalFunc().
 * ----------------------------------------------------------------
 */
static Datum
1227
ExecEvalDistinct(FuncExprState *fcache,
1228
				 ExprContext *econtext,
1229
				 bool *isNull)
1230
{
1231
	Datum		result;
1232 1233 1234 1235 1236
	FunctionCallInfoData fcinfo;
	ExprDoneCond argDone;
	List	   *argList;

	/*
1237
	 * Initialize function cache if first time through
1238
	 */
1239 1240 1241 1242 1243 1244 1245
	if (fcache->func.fn_oid == InvalidOid)
	{
		DistinctExpr *op = (DistinctExpr *) fcache->xprstate.expr;

		init_fcache(op->opfuncid, fcache, econtext->ecxt_per_query_memory);
		Assert(!fcache->func.fn_retset);
	}
1246 1247

	/*
1248
	 * extract info from fcache
1249
	 */
1250
	argList = fcache->args;
1251 1252 1253 1254 1255

	/* Need to prep callinfo structure */
	MemSet(&fcinfo, 0, sizeof(fcinfo));
	fcinfo.flinfo = &(fcache->func);
	argDone = ExecEvalFuncArgs(&fcinfo, argList, econtext);
1256
	if (argDone != ExprSingleResult)
1257 1258
		ereport(ERROR,
				(errcode(ERRCODE_DATATYPE_MISMATCH),
Bruce Momjian's avatar
Bruce Momjian committed
1259
			 errmsg("IS DISTINCT FROM does not support set arguments")));
1260
	Assert(fcinfo.nargs == 2);
1261 1262 1263 1264

	if (fcinfo.argnull[0] && fcinfo.argnull[1])
	{
		/* Both NULL? Then is not distinct... */
1265
		result = BoolGetDatum(FALSE);
1266 1267 1268
	}
	else if (fcinfo.argnull[0] || fcinfo.argnull[1])
	{
1269 1270
		/* Only one is NULL? Then is distinct... */
		result = BoolGetDatum(TRUE);
1271 1272 1273 1274 1275 1276
	}
	else
	{
		fcinfo.isnull = false;
		result = FunctionCallInvoke(&fcinfo);
		*isNull = fcinfo.isnull;
1277 1278
		/* Must invert result of "=" */
		result = BoolGetDatum(!DatumGetBool(result));
1279 1280
	}

1281
	return result;
1282 1283
}

1284 1285 1286 1287 1288
/*
 * ExecEvalScalarArrayOp
 *
 * Evaluate "scalar op ANY/ALL (array)".  The operator always yields boolean,
 * and we combine the results across all array elements using OR and AND
Bruce Momjian's avatar
Bruce Momjian committed
1289
 * (for ANY and ALL respectively).	Of course we short-circuit as soon as
1290 1291 1292
 * the result is known.
 */
static Datum
1293
ExecEvalScalarArrayOp(ScalarArrayOpExprState *sstate,
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
					  ExprContext *econtext, bool *isNull)
{
	ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) sstate->fxprstate.xprstate.expr;
	bool		useOr = opexpr->useOr;
	ArrayType  *arr;
	int			nitems;
	Datum		result;
	bool		resultnull;
	FunctionCallInfoData fcinfo;
	ExprDoneCond argDone;
	int			i;
	int16		typlen;
	bool		typbyval;
	char		typalign;
	char	   *s;

	/*
	 * Initialize function cache if first time through
	 */
	if (sstate->fxprstate.func.fn_oid == InvalidOid)
	{
		init_fcache(opexpr->opfuncid, &sstate->fxprstate,
					econtext->ecxt_per_query_memory);
		Assert(!sstate->fxprstate.func.fn_retset);
	}

	/* Need to prep callinfo structure */
	MemSet(&fcinfo, 0, sizeof(fcinfo));
	fcinfo.flinfo = &(sstate->fxprstate.func);
	argDone = ExecEvalFuncArgs(&fcinfo, sstate->fxprstate.args, econtext);
	if (argDone != ExprSingleResult)
1325 1326
		ereport(ERROR,
				(errcode(ERRCODE_DATATYPE_MISMATCH),
Bruce Momjian's avatar
Bruce Momjian committed
1327
		   errmsg("op ANY/ALL (array) does not support set arguments")));
1328 1329 1330
	Assert(fcinfo.nargs == 2);

	/*
Bruce Momjian's avatar
Bruce Momjian committed
1331 1332
	 * If the array is NULL then we return NULL --- it's not very
	 * meaningful to do anything else, even if the operator isn't strict.
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350
	 */
	if (fcinfo.argnull[1])
	{
		*isNull = true;
		return (Datum) 0;
	}
	/* Else okay to fetch and detoast the array */
	arr = DatumGetArrayTypeP(fcinfo.arg[1]);

	/*
	 * If the array is empty, we return either FALSE or TRUE per the useOr
	 * flag.  This is correct even if the scalar is NULL; since we would
	 * evaluate the operator zero times, it matters not whether it would
	 * want to return NULL.
	 */
	nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr));
	if (nitems <= 0)
		return BoolGetDatum(!useOr);
Bruce Momjian's avatar
Bruce Momjian committed
1351

1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
	/*
	 * If the scalar is NULL, and the function is strict, return NULL.
	 * This is just to avoid having to test for strictness inside the
	 * loop.  (XXX but if arrays could have null elements, we'd need a
	 * test anyway.)
	 */
	if (fcinfo.argnull[0] && sstate->fxprstate.func.fn_strict)
	{
		*isNull = true;
		return (Datum) 0;
	}

	/*
Bruce Momjian's avatar
Bruce Momjian committed
1365 1366
	 * We arrange to look up info about the element type only once per
	 * series of calls, assuming the element type doesn't change
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387
	 * underneath us.
	 */
	if (sstate->element_type != ARR_ELEMTYPE(arr))
	{
		get_typlenbyvalalign(ARR_ELEMTYPE(arr),
							 &sstate->typlen,
							 &sstate->typbyval,
							 &sstate->typalign);
		sstate->element_type = ARR_ELEMTYPE(arr);
	}
	typlen = sstate->typlen;
	typbyval = sstate->typbyval;
	typalign = sstate->typalign;

	result = BoolGetDatum(!useOr);
	resultnull = false;

	/* Loop over the array elements */
	s = (char *) ARR_DATA_PTR(arr);
	for (i = 0; i < nitems; i++)
	{
Bruce Momjian's avatar
Bruce Momjian committed
1388 1389
		Datum		elt;
		Datum		thisresult;
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411

		/* Get array element */
		elt = fetch_att(s, typbyval, typlen);

		s = att_addlength(s, typlen, PointerGetDatum(s));
		s = (char *) att_align(s, typalign);

		/* Call comparison function */
		fcinfo.arg[1] = elt;
		fcinfo.argnull[1] = false;
		fcinfo.isnull = false;
		thisresult = FunctionCallInvoke(&fcinfo);

		/* Combine results per OR or AND semantics */
		if (fcinfo.isnull)
			resultnull = true;
		else if (useOr)
		{
			if (DatumGetBool(thisresult))
			{
				result = BoolGetDatum(true);
				resultnull = false;
Bruce Momjian's avatar
Bruce Momjian committed
1412
				break;			/* needn't look at any more elements */
1413 1414 1415 1416 1417 1418 1419 1420
			}
		}
		else
		{
			if (!DatumGetBool(thisresult))
			{
				result = BoolGetDatum(false);
				resultnull = false;
Bruce Momjian's avatar
Bruce Momjian committed
1421
				break;			/* needn't look at any more elements */
1422 1423 1424 1425 1426 1427 1428 1429
			}
		}
	}

	*isNull = resultnull;
	return result;
}

1430
/* ----------------------------------------------------------------
1431 1432 1433
 *		ExecEvalNot
 *		ExecEvalOr
 *		ExecEvalAnd
1434
 *
1435
 *		Evaluate boolean expressions, with appropriate short-circuiting.
1436 1437 1438 1439 1440 1441 1442
 *
 *		The query planner reformulates clause expressions in the
 *		qualification to conjunctive normal form.  If we ever get
 *		an AND to evaluate, we can be sure that it's not a top-level
 *		clause in the qualification, but appears lower (as a function
 *		argument, for example), or in the target list.	Not that you
 *		need to know this, mind you...
1443 1444
 * ----------------------------------------------------------------
 */
1445
static Datum
1446
ExecEvalNot(BoolExprState *notclause, ExprContext *econtext, bool *isNull)
1447
{
1448
	ExprState  *clause;
1449
	Datum		expr_value;
1450 1451

	clause = lfirst(notclause->args);
1452

1453
	expr_value = ExecEvalExpr(clause, econtext, isNull, NULL);
1454

Bruce Momjian's avatar
Bruce Momjian committed
1455
	/*
Bruce Momjian's avatar
Bruce Momjian committed
1456 1457
	 * if the expression evaluates to null, then we just cascade the null
	 * back to whoever called us.
1458 1459
	 */
	if (*isNull)
1460 1461
		return expr_value;

Bruce Momjian's avatar
Bruce Momjian committed
1462
	/*
Bruce Momjian's avatar
Bruce Momjian committed
1463 1464
	 * evaluation of 'not' is simple.. expr is false, then return 'true'
	 * and vice versa.
1465
	 */
1466
	return BoolGetDatum(!DatumGetBool(expr_value));
1467 1468 1469
}

/* ----------------------------------------------------------------
1470
 *		ExecEvalOr
1471 1472
 * ----------------------------------------------------------------
 */
1473
static Datum
1474
ExecEvalOr(BoolExprState *orExpr, ExprContext *econtext, bool *isNull)
1475
{
1476 1477
	List	   *clauses;
	List	   *clause;
1478 1479
	bool		AnyNull;
	Datum		clause_value;
1480 1481

	clauses = orExpr->args;
1482
	AnyNull = false;
1483

Bruce Momjian's avatar
Bruce Momjian committed
1484
	/*
1485 1486
	 * If any of the clauses is TRUE, the OR result is TRUE regardless of
	 * the states of the rest of the clauses, so we can stop evaluating
1487 1488 1489 1490 1491 1492
	 * and return TRUE immediately.  If none are TRUE and one or more is
	 * NULL, we return NULL; otherwise we return FALSE.  This makes sense
	 * when you interpret NULL as "don't know": if we have a TRUE then the
	 * OR is TRUE even if we aren't sure about some of the other inputs.
	 * If all the known inputs are FALSE, but we have one or more "don't
	 * knows", then we have to report that we "don't know" what the OR's
1493 1494 1495 1496
	 * result should be --- perhaps one of the "don't knows" would have
	 * been TRUE if we'd known its value.  Only when all the inputs are
	 * known to be FALSE can we state confidently that the OR's result is
	 * FALSE.
1497
	 */
1498 1499
	foreach(clause, clauses)
	{
1500
		clause_value = ExecEvalExpr((ExprState *) lfirst(clause),
1501
									econtext, isNull, NULL);
1502

Bruce Momjian's avatar
Bruce Momjian committed
1503
		/*
1504
		 * if we have a non-null true result, then return it.
1505 1506
		 */
		if (*isNull)
1507
			AnyNull = true;		/* remember we got a null */
1508
		else if (DatumGetBool(clause_value))
1509
			return clause_value;
1510 1511
	}

1512 1513
	/* AnyNull is true if at least one clause evaluated to NULL */
	*isNull = AnyNull;
1514
	return BoolGetDatum(false);
1515 1516 1517 1518 1519 1520
}

/* ----------------------------------------------------------------
 *		ExecEvalAnd
 * ----------------------------------------------------------------
 */
1521
static Datum
1522
ExecEvalAnd(BoolExprState *andExpr, ExprContext *econtext, bool *isNull)
1523
{
1524 1525
	List	   *clauses;
	List	   *clause;
1526 1527
	bool		AnyNull;
	Datum		clause_value;
1528 1529

	clauses = andExpr->args;
1530
	AnyNull = false;
1531

Bruce Momjian's avatar
Bruce Momjian committed
1532
	/*
1533 1534 1535
	 * If any of the clauses is FALSE, the AND result is FALSE regardless
	 * of the states of the rest of the clauses, so we can stop evaluating
	 * and return FALSE immediately.  If none are FALSE and one or more is
1536
	 * NULL, we return NULL; otherwise we return TRUE.	This makes sense
1537 1538
	 * when you interpret NULL as "don't know", using the same sort of
	 * reasoning as for OR, above.
1539
	 */
1540 1541
	foreach(clause, clauses)
	{
1542
		clause_value = ExecEvalExpr((ExprState *) lfirst(clause),
1543
									econtext, isNull, NULL);
1544

Bruce Momjian's avatar
Bruce Momjian committed
1545
		/*
1546
		 * if we have a non-null false result, then return it.
1547 1548
		 */
		if (*isNull)
1549
			AnyNull = true;		/* remember we got a null */
1550
		else if (!DatumGetBool(clause_value))
1551
			return clause_value;
1552 1553
	}

1554 1555
	/* AnyNull is true if at least one clause evaluated to NULL */
	*isNull = AnyNull;
1556
	return BoolGetDatum(!AnyNull);
1557 1558
}

1559

1560 1561 1562 1563
/* ----------------------------------------------------------------
 *		ExecEvalCase
 *
 *		Evaluate a CASE clause. Will have boolean expressions
1564
 *		inside the WHEN clauses, and will have expressions
1565 1566 1567 1568 1569
 *		for results.
 *		- thomas 1998-11-09
 * ----------------------------------------------------------------
 */
static Datum
1570
ExecEvalCase(CaseExprState *caseExpr, ExprContext *econtext,
1571
			 bool *isNull, ExprDoneCond *isDone)
1572 1573 1574
{
	List	   *clauses;
	List	   *clause;
1575
	Datum		clause_value;
1576 1577 1578

	clauses = caseExpr->args;

Bruce Momjian's avatar
Bruce Momjian committed
1579
	/*
Bruce Momjian's avatar
Bruce Momjian committed
1580 1581
	 * we evaluate each of the WHEN clauses in turn, as soon as one is
	 * true we return the corresponding result. If none are true then we
1582
	 * return the value of the default clause, or NULL if there is none.
1583 1584 1585
	 */
	foreach(clause, clauses)
	{
1586
		CaseWhenState *wclause = lfirst(clause);
1587

1588
		clause_value = ExecEvalExpr(wclause->expr,
1589 1590
									econtext,
									isNull,
1591
									NULL);
1592

Bruce Momjian's avatar
Bruce Momjian committed
1593
		/*
Bruce Momjian's avatar
Bruce Momjian committed
1594
		 * if we have a true test, then we return the result, since the
1595 1596
		 * case statement is satisfied.  A NULL result from the test is
		 * not considered true.
1597
		 */
1598
		if (DatumGetBool(clause_value) && !*isNull)
1599
		{
1600
			return ExecEvalExpr(wclause->result,
1601 1602
								econtext,
								isNull,
1603
								isDone);
1604 1605 1606 1607 1608
		}
	}

	if (caseExpr->defresult)
	{
1609
		return ExecEvalExpr(caseExpr->defresult,
1610 1611
							econtext,
							isNull,
1612
							isDone);
1613 1614
	}

1615 1616
	*isNull = true;
	return (Datum) 0;
1617 1618
}

1619 1620
/* ----------------------------------------------------------------
 *		ExecEvalArray - ARRAY[] expressions
1621 1622 1623 1624
 *
 * NOTE: currently, if any input value is NULL then we return a NULL array,
 * so the ARRAY[] construct can be considered strict.  Eventually this will
 * change; when it does, be sure to fix contain_nonstrict_functions().
1625 1626 1627
 * ----------------------------------------------------------------
 */
static Datum
1628
ExecEvalArray(ArrayExprState *astate, ExprContext *econtext,
1629 1630
			  bool *isNull)
{
Bruce Momjian's avatar
Bruce Momjian committed
1631
	ArrayExpr  *arrayExpr = (ArrayExpr *) astate->xprstate.expr;
1632
	ArrayType  *result;
Bruce Momjian's avatar
Bruce Momjian committed
1633 1634
	List	   *element;
	Oid			element_type = arrayExpr->element_typeid;
1635
	int			ndims = 0;
Bruce Momjian's avatar
Bruce Momjian committed
1636 1637
	int			dims[MAXDIM];
	int			lbs[MAXDIM];
1638

1639
	if (!arrayExpr->multidims)
1640
	{
1641
		/* Elements are presumably of scalar type */
Bruce Momjian's avatar
Bruce Momjian committed
1642 1643 1644
		int			nelems;
		Datum	   *dvalues;
		int			i = 0;
1645

1646
		ndims = 1;
1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665
		nelems = length(astate->elements);

		/* Shouldn't happen here, but if length is 0, return NULL */
		if (nelems == 0)
		{
			*isNull = true;
			return (Datum) 0;
		}

		dvalues = (Datum *) palloc(nelems * sizeof(Datum));

		/* loop through and build array of datums */
		foreach(element, astate->elements)
		{
			ExprState  *e = (ExprState *) lfirst(element);
			bool		eisnull;

			dvalues[i++] = ExecEvalExpr(e, econtext, &eisnull, NULL);
			if (eisnull)
1666 1667 1668 1669
			{
				*isNull = true;
				return (Datum) 0;
			}
1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683
		}

		/* setup for 1-D array of the given length */
		dims[0] = nelems;
		lbs[0] = 1;

		result = construct_md_array(dvalues, ndims, dims, lbs,
									element_type,
									astate->elemlength,
									astate->elembyval,
									astate->elemalign);
	}
	else
	{
1684
		/* Must be nested array expressions */
1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697
		char	   *dat = NULL;
		Size		ndatabytes = 0;
		int			nbytes;
		int			outer_nelems = length(astate->elements);
		int			elem_ndims = 0;
		int		   *elem_dims = NULL;
		int		   *elem_lbs = NULL;
		bool		firstone = true;
		int			i;

		/* loop through and get data area from each element */
		foreach(element, astate->elements)
		{
Bruce Momjian's avatar
Bruce Momjian committed
1698
			ExprState  *e = (ExprState *) lfirst(element);
1699 1700 1701 1702 1703 1704 1705
			bool		eisnull;
			Datum		arraydatum;
			ArrayType  *array;
			int			elem_ndatabytes;

			arraydatum = ExecEvalExpr(e, econtext, &eisnull, NULL);
			if (eisnull)
1706 1707 1708 1709
			{
				*isNull = true;
				return (Datum) 0;
			}
1710 1711 1712

			array = DatumGetArrayTypeP(arraydatum);

1713 1714 1715 1716 1717 1718 1719 1720 1721 1722
			/* run-time double-check on element type */
			if (element_type != ARR_ELEMTYPE(array))
				ereport(ERROR,
						(errcode(ERRCODE_DATATYPE_MISMATCH),
						 errmsg("cannot merge incompatible arrays"),
						 errdetail("Array with element type %s cannot be "
								   "included in ARRAY construct with element type %s.",
								   format_type_be(ARR_ELEMTYPE(array)),
								   format_type_be(element_type))));

1723 1724 1725 1726
			if (firstone)
			{
				/* Get sub-array details from first member */
				elem_ndims = ARR_NDIM(array);
1727 1728 1729 1730
				ndims = elem_ndims + 1;
				if (ndims <= 0 || ndims > MAXDIM)
					ereport(ERROR,
							(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1731 1732
							 errmsg("number of array dimensions (%d) exceeds " \
									"the maximum allowed (%d)", ndims, MAXDIM)));
1733

1734 1735 1736 1737
				elem_dims = (int *) palloc(elem_ndims * sizeof(int));
				memcpy(elem_dims, ARR_DIMS(array), elem_ndims * sizeof(int));
				elem_lbs = (int *) palloc(elem_ndims * sizeof(int));
				memcpy(elem_lbs, ARR_LBOUND(array), elem_ndims * sizeof(int));
1738

1739 1740 1741 1742 1743
				firstone = false;
			}
			else
			{
				/* Check other sub-arrays are compatible */
1744 1745 1746 1747
				if (elem_ndims != ARR_NDIM(array) ||
					memcmp(elem_dims, ARR_DIMS(array),
						   elem_ndims * sizeof(int)) != 0 ||
					memcmp(elem_lbs, ARR_LBOUND(array),
1748
						   elem_ndims * sizeof(int)) != 0)
1749 1750
					ereport(ERROR,
							(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
Bruce Momjian's avatar
Bruce Momjian committed
1751 1752
						errmsg("multidimensional arrays must have array "
							   "expressions with matching dimensions")));
1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794
			}

			elem_ndatabytes = ARR_SIZE(array) - ARR_OVERHEAD(elem_ndims);
			ndatabytes += elem_ndatabytes;
			if (dat == NULL)
				dat = (char *) palloc(ndatabytes);
			else
				dat = (char *) repalloc(dat, ndatabytes);

			memcpy(dat + (ndatabytes - elem_ndatabytes),
				   ARR_DATA_PTR(array),
				   elem_ndatabytes);
		}

		/* setup for multi-D array */
		dims[0] = outer_nelems;
		lbs[0] = 1;
		for (i = 1; i < ndims; i++)
		{
			dims[i] = elem_dims[i - 1];
			lbs[i] = elem_lbs[i - 1];
		}

		nbytes = ndatabytes + ARR_OVERHEAD(ndims);
		result = (ArrayType *) palloc(nbytes);

		result->size = nbytes;
		result->ndim = ndims;
		result->flags = 0;
		result->elemtype = element_type;
		memcpy(ARR_DIMS(result), dims, ndims * sizeof(int));
		memcpy(ARR_LBOUND(result), lbs, ndims * sizeof(int));
		if (ndatabytes > 0)
			memcpy(ARR_DATA_PTR(result), dat, ndatabytes);

		if (dat != NULL)
			pfree(dat);
	}

	return PointerGetDatum(result);
}

1795 1796 1797 1798 1799
/* ----------------------------------------------------------------
 *		ExecEvalCoalesce
 * ----------------------------------------------------------------
 */
static Datum
1800
ExecEvalCoalesce(CoalesceExprState *coalesceExpr, ExprContext *econtext,
1801 1802
				 bool *isNull)
{
Bruce Momjian's avatar
Bruce Momjian committed
1803
	List	   *arg;
1804 1805 1806 1807

	/* Simply loop through until something NOT NULL is found */
	foreach(arg, coalesceExpr->args)
	{
Bruce Momjian's avatar
Bruce Momjian committed
1808 1809
		ExprState  *e = (ExprState *) lfirst(arg);
		Datum		value;
1810 1811 1812 1813 1814 1815 1816 1817 1818 1819

		value = ExecEvalExpr(e, econtext, isNull, NULL);
		if (!*isNull)
			return value;
	}

	/* Else return NULL */
	*isNull = true;
	return (Datum) 0;
}
Bruce Momjian's avatar
Bruce Momjian committed
1820

1821 1822 1823 1824 1825 1826 1827 1828 1829
/* ----------------------------------------------------------------
 *		ExecEvalNullIf
 *
 * Note that this is *always* derived from the equals operator,
 * but since we need special processing of the arguments
 * we can not simply reuse ExecEvalOper() or ExecEvalFunc().
 * ----------------------------------------------------------------
 */
static Datum
1830
ExecEvalNullIf(FuncExprState *fcache, ExprContext *econtext,
1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858
			   bool *isNull)
{
	Datum		result;
	FunctionCallInfoData fcinfo;
	ExprDoneCond argDone;
	List	   *argList;

	/*
	 * Initialize function cache if first time through
	 */
	if (fcache->func.fn_oid == InvalidOid)
	{
		NullIfExpr *op = (NullIfExpr *) fcache->xprstate.expr;

		init_fcache(op->opfuncid, fcache, econtext->ecxt_per_query_memory);
		Assert(!fcache->func.fn_retset);
	}

	/*
	 * extract info from fcache
	 */
	argList = fcache->args;

	/* Need to prep callinfo structure */
	MemSet(&fcinfo, 0, sizeof(fcinfo));
	fcinfo.flinfo = &(fcache->func);
	argDone = ExecEvalFuncArgs(&fcinfo, argList, econtext);
	if (argDone != ExprSingleResult)
1859 1860 1861
		ereport(ERROR,
				(errcode(ERRCODE_DATATYPE_MISMATCH),
				 errmsg("NULLIF does not support set arguments")));
1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881
	Assert(fcinfo.nargs == 2);

	/* if either argument is NULL they can't be equal */
	if (!fcinfo.argnull[0] && !fcinfo.argnull[1])
	{
		fcinfo.isnull = false;
		result = FunctionCallInvoke(&fcinfo);
		/* if the arguments are equal return null */
		if (!fcinfo.isnull && DatumGetBool(result))
		{
			*isNull = true;
			return (Datum) 0;
		}
	}

	/* else return first argument */
	*isNull = fcinfo.argnull[0];
	return fcinfo.arg[0];
}

1882 1883 1884 1885 1886 1887 1888
/* ----------------------------------------------------------------
 *		ExecEvalNullTest
 *
 *		Evaluate a NullTest node.
 * ----------------------------------------------------------------
 */
static Datum
1889
ExecEvalNullTest(GenericExprState *nstate,
1890 1891 1892 1893
				 ExprContext *econtext,
				 bool *isNull,
				 ExprDoneCond *isDone)
{
1894
	NullTest   *ntest = (NullTest *) nstate->xprstate.expr;
1895 1896
	Datum		result;

1897 1898 1899 1900 1901
	result = ExecEvalExpr(nstate->arg, econtext, isNull, isDone);

	if (isDone && *isDone == ExprEndResult)
		return result;			/* nothing to check */

1902
	switch (ntest->nulltesttype)
1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920
	{
		case IS_NULL:
			if (*isNull)
			{
				*isNull = false;
				return BoolGetDatum(true);
			}
			else
				return BoolGetDatum(false);
		case IS_NOT_NULL:
			if (*isNull)
			{
				*isNull = false;
				return BoolGetDatum(false);
			}
			else
				return BoolGetDatum(true);
		default:
1921
			elog(ERROR, "unrecognized nulltesttype: %d",
1922 1923 1924
				 (int) ntest->nulltesttype);
			return (Datum) 0;	/* keep compiler quiet */
	}
1925 1926 1927 1928 1929 1930 1931 1932 1933
}

/* ----------------------------------------------------------------
 *		ExecEvalBooleanTest
 *
 *		Evaluate a BooleanTest node.
 * ----------------------------------------------------------------
 */
static Datum
1934
ExecEvalBooleanTest(GenericExprState *bstate,
1935 1936 1937 1938
					ExprContext *econtext,
					bool *isNull,
					ExprDoneCond *isDone)
{
1939
	BooleanTest *btest = (BooleanTest *) bstate->xprstate.expr;
1940 1941
	Datum		result;

1942 1943 1944 1945 1946
	result = ExecEvalExpr(bstate->arg, econtext, isNull, isDone);

	if (isDone && *isDone == ExprEndResult)
		return result;			/* nothing to check */

1947
	switch (btest->booltesttype)
1948 1949 1950 1951 1952 1953 1954 1955 1956
	{
		case IS_TRUE:
			if (*isNull)
			{
				*isNull = false;
				return BoolGetDatum(false);
			}
			else if (DatumGetBool(result))
				return BoolGetDatum(true);
1957
			else
1958 1959 1960 1961 1962 1963 1964 1965 1966
				return BoolGetDatum(false);
		case IS_NOT_TRUE:
			if (*isNull)
			{
				*isNull = false;
				return BoolGetDatum(true);
			}
			else if (DatumGetBool(result))
				return BoolGetDatum(false);
1967
			else
1968 1969 1970 1971 1972 1973 1974 1975 1976
				return BoolGetDatum(true);
		case IS_FALSE:
			if (*isNull)
			{
				*isNull = false;
				return BoolGetDatum(false);
			}
			else if (DatumGetBool(result))
				return BoolGetDatum(false);
1977
			else
1978 1979 1980 1981 1982 1983 1984 1985 1986
				return BoolGetDatum(true);
		case IS_NOT_FALSE:
			if (*isNull)
			{
				*isNull = false;
				return BoolGetDatum(true);
			}
			else if (DatumGetBool(result))
				return BoolGetDatum(true);
1987
			else
1988 1989 1990 1991 1992 1993 1994
				return BoolGetDatum(false);
		case IS_UNKNOWN:
			if (*isNull)
			{
				*isNull = false;
				return BoolGetDatum(true);
			}
1995
			else
1996 1997 1998 1999 2000 2001 2002
				return BoolGetDatum(false);
		case IS_NOT_UNKNOWN:
			if (*isNull)
			{
				*isNull = false;
				return BoolGetDatum(false);
			}
2003
			else
2004 2005
				return BoolGetDatum(true);
		default:
2006
			elog(ERROR, "unrecognized booltesttype: %d",
2007 2008 2009
				 (int) btest->booltesttype);
			return (Datum) 0;	/* keep compiler quiet */
	}
2010 2011
}

2012
/*
2013
 * ExecEvalCoerceToDomain
2014
 *
2015 2016
 * Test the provided data against the domain constraint(s).  If the data
 * passes the constraint specifications, pass it through (return the
2017 2018 2019
 * datum) otherwise throw an error.
 */
static Datum
2020
ExecEvalCoerceToDomain(CoerceToDomainState *cstate, ExprContext *econtext,
2021 2022
					   bool *isNull, ExprDoneCond *isDone)
{
2023
	CoerceToDomain *ctest = (CoerceToDomain *) cstate->xprstate.expr;
2024
	Datum		result;
2025
	List	   *l;
2026

2027
	result = ExecEvalExpr(cstate->arg, econtext, isNull, isDone);
2028

2029 2030 2031
	if (isDone && *isDone == ExprEndResult)
		return result;			/* nothing to check */

2032
	foreach(l, cstate->constraints)
2033
	{
2034 2035 2036 2037 2038 2039
		DomainConstraintState *con = (DomainConstraintState *) lfirst(l);

		switch (con->constrainttype)
		{
			case DOM_CONSTRAINT_NOTNULL:
				if (*isNull)
2040 2041
					ereport(ERROR,
							(errcode(ERRCODE_NOT_NULL_VIOLATION),
2042
						   errmsg("domain %s does not allow null values",
Bruce Momjian's avatar
Bruce Momjian committed
2043
								  format_type_be(ctest->resulttype))));
2044 2045
				break;
			case DOM_CONSTRAINT_CHECK:
Bruce Momjian's avatar
Bruce Momjian committed
2046 2047 2048 2049 2050
				{
					Datum		conResult;
					bool		conIsNull;
					Datum		save_datum;
					bool		save_isNull;
2051

Bruce Momjian's avatar
Bruce Momjian committed
2052 2053 2054 2055 2056 2057 2058 2059 2060
					/*
					 * Set up value to be returned by CoerceToDomainValue
					 * nodes. We must save and restore prior setting of
					 * econtext's domainValue fields, in case this node is
					 * itself within a check expression for another
					 * domain.
					 */
					save_datum = econtext->domainValue_datum;
					save_isNull = econtext->domainValue_isNull;
2061

Bruce Momjian's avatar
Bruce Momjian committed
2062 2063
					econtext->domainValue_datum = result;
					econtext->domainValue_isNull = *isNull;
2064

Bruce Momjian's avatar
Bruce Momjian committed
2065 2066
					conResult = ExecEvalExpr(con->check_expr,
											 econtext, &conIsNull, NULL);
2067

Bruce Momjian's avatar
Bruce Momjian committed
2068 2069 2070 2071
					if (!conIsNull &&
						!DatumGetBool(conResult))
						ereport(ERROR,
								(errcode(ERRCODE_CHECK_VIOLATION),
2072
								 errmsg("value for domain %s violates check constraint \"%s\"",
Bruce Momjian's avatar
Bruce Momjian committed
2073 2074 2075 2076 2077 2078 2079
										format_type_be(ctest->resulttype),
										con->name)));
					econtext->domainValue_datum = save_datum;
					econtext->domainValue_isNull = save_isNull;

					break;
				}
2080
			default:
2081 2082
				elog(ERROR, "unrecognized constraint type: %d",
					 (int) con->constrainttype);
2083 2084
				break;
		}
2085 2086
	}

2087
	/* If all has gone well (constraints did not fail) return the datum */
2088 2089 2090
	return result;
}

2091
/*
2092
 * ExecEvalCoerceToDomainValue
2093
 *
2094
 * Return the value stored by CoerceToDomain.
2095 2096
 */
static Datum
2097
ExecEvalCoerceToDomainValue(CoerceToDomainValue *conVal,
2098
							ExprContext *econtext, bool *isNull)
2099 2100 2101 2102 2103
{
	*isNull = econtext->domainValue_isNull;
	return econtext->domainValue_datum;
}

2104 2105 2106 2107 2108 2109 2110
/* ----------------------------------------------------------------
 *		ExecEvalFieldSelect
 *
 *		Evaluate a FieldSelect node.
 * ----------------------------------------------------------------
 */
static Datum
2111
ExecEvalFieldSelect(GenericExprState *fstate,
2112 2113
					ExprContext *econtext,
					bool *isNull,
2114
					ExprDoneCond *isDone)
2115
{
2116
	FieldSelect *fselect = (FieldSelect *) fstate->xprstate.expr;
2117
	Datum		result;
2118 2119
	TupleTableSlot *resSlot;

2120 2121 2122
	result = ExecEvalExpr(fstate->arg, econtext, isNull, isDone);

	/* this test covers the isDone exception too: */
2123 2124
	if (*isNull)
		return result;
2125

2126 2127 2128 2129 2130 2131 2132 2133 2134
	resSlot = (TupleTableSlot *) DatumGetPointer(result);
	Assert(resSlot != NULL && IsA(resSlot, TupleTableSlot));
	result = heap_getattr(resSlot->val,
						  fselect->fieldnum,
						  resSlot->ttc_tupleDescriptor,
						  isNull);
	return result;
}

2135 2136 2137 2138
/* ----------------------------------------------------------------
 *		ExecEvalExpr
 *
 *		Recursively evaluate a targetlist or qualification expression.
2139
 *
2140
 * Inputs:
2141
 *		expression: the expression state tree to evaluate
2142 2143 2144 2145 2146 2147 2148 2149 2150
 *		econtext: evaluation context information
 *
 * Outputs:
 *		return value: Datum value of result
 *		*isNull: set to TRUE if result is NULL (actual return value is
 *				 meaningless if so); set to FALSE if non-null result
 *		*isDone: set to indicator of set-result status
 *
 * A caller that can only accept a singleton (non-set) result should pass
2151 2152 2153
 * NULL for isDone; if the expression computes a set result then an error
 * will be reported via ereport.  If the caller does pass an isDone pointer
 * then *isDone is set to one of these three states:
2154 2155 2156 2157 2158 2159 2160 2161 2162 2163
 *		ExprSingleResult		singleton result (not a set)
 *		ExprMultipleResult		return value is one element of a set
 *		ExprEndResult			there are no more elements in the set
 * When ExprMultipleResult is returned, the caller should invoke
 * ExecEvalExpr() repeatedly until ExprEndResult is returned.  ExprEndResult
 * is returned after the last real set element.  For convenience isNull will
 * always be set TRUE when ExprEndResult is returned, but this should not be
 * taken as indicating a NULL element of the set.  Note that these return
 * conventions allow us to distinguish among a singleton NULL, a NULL element
 * of a set, and an empty set.
2164
 *
2165 2166 2167
 * The caller should already have switched into the temporary memory
 * context econtext->ecxt_per_tuple_memory.  The convenience entry point
 * ExecEvalExprSwitchContext() is provided for callers who don't prefer to
2168
 * do the switch in an outer loop.	We do not do the switch here because
2169 2170 2171
 * it'd be a waste of cycles during recursive entries to ExecEvalExpr().
 *
 * This routine is an inner loop routine and must be as fast as possible.
2172 2173 2174
 * ----------------------------------------------------------------
 */
Datum
2175
ExecEvalExpr(ExprState *expression,
2176 2177
			 ExprContext *econtext,
			 bool *isNull,
2178
			 ExprDoneCond *isDone)
2179
{
2180
	Datum		retDatum;
2181
	Expr	   *expr;
2182

2183
	/* Set default values for result flags: non-null, not a set result */
2184
	*isNull = false;
2185 2186
	if (isDone)
		*isDone = ExprSingleResult;
2187

2188
	/* Is this still necessary?  Doubtful... */
2189 2190 2191
	if (expression == NULL)
	{
		*isNull = true;
2192
		return (Datum) 0;
2193 2194
	}

2195 2196 2197 2198
	/*
	 * here we dispatch the work to the appropriate type of function given
	 * the type of our expression.
	 */
2199 2200
	expr = expression->expr;
	switch (nodeTag(expr))
2201
	{
2202
		case T_Var:
2203
			retDatum = ExecEvalVar((Var *) expr, econtext, isNull);
2204 2205 2206
			break;
		case T_Const:
			{
2207
				Const	   *con = (Const *) expr;
2208

2209
				retDatum = con->constvalue;
2210
				*isNull = con->constisnull;
2211 2212 2213
				break;
			}
		case T_Param:
2214
			retDatum = ExecEvalParam((Param *) expr, econtext, isNull);
2215
			break;
Bruce Momjian's avatar
Bruce Momjian committed
2216
		case T_Aggref:
2217 2218 2219
			retDatum = ExecEvalAggref((AggrefExprState *) expression,
									  econtext,
									  isNull);
2220 2221
			break;
		case T_ArrayRef:
2222
			retDatum = ExecEvalArrayRef((ArrayRefExprState *) expression,
2223 2224 2225
										econtext,
										isNull,
										isDone);
2226
			break;
2227
		case T_FuncExpr:
2228
			retDatum = ExecEvalFunc((FuncExprState *) expression, econtext,
2229 2230 2231
									isNull, isDone);
			break;
		case T_OpExpr:
2232
			retDatum = ExecEvalOper((FuncExprState *) expression, econtext,
2233 2234 2235
									isNull, isDone);
			break;
		case T_DistinctExpr:
2236
			retDatum = ExecEvalDistinct((FuncExprState *) expression, econtext,
2237
										isNull);
2238
			break;
2239 2240 2241 2242
		case T_ScalarArrayOpExpr:
			retDatum = ExecEvalScalarArrayOp((ScalarArrayOpExprState *) expression,
											 econtext, isNull);
			break;
2243
		case T_BoolExpr:
2244
			{
2245
				BoolExprState *state = (BoolExprState *) expression;
2246

2247
				switch (((BoolExpr *) expr)->boolop)
2248
				{
2249
					case AND_EXPR:
2250
						retDatum = ExecEvalAnd(state, econtext, isNull);
2251 2252
						break;
					case OR_EXPR:
2253
						retDatum = ExecEvalOr(state, econtext, isNull);
2254 2255
						break;
					case NOT_EXPR:
2256
						retDatum = ExecEvalNot(state, econtext, isNull);
2257 2258
						break;
					default:
2259 2260
						elog(ERROR, "unrecognized boolop: %d",
							 (int) ((BoolExpr *) expr)->boolop);
2261
						retDatum = 0;	/* keep compiler quiet */
2262 2263
						break;
				}
2264 2265
				break;
			}
2266 2267
		case T_SubPlan:
			retDatum = ExecSubPlan((SubPlanState *) expression,
2268 2269 2270
								   econtext,
								   isNull);
			break;
2271
		case T_FieldSelect:
2272
			retDatum = ExecEvalFieldSelect((GenericExprState *) expression,
2273 2274 2275 2276
										   econtext,
										   isNull,
										   isDone);
			break;
2277
		case T_RelabelType:
2278
			retDatum = ExecEvalExpr(((GenericExprState *) expression)->arg,
2279 2280 2281 2282
									econtext,
									isNull,
									isDone);
			break;
2283
		case T_CaseExpr:
2284
			retDatum = ExecEvalCase((CaseExprState *) expression,
2285 2286 2287
									econtext,
									isNull,
									isDone);
2288
			break;
2289 2290 2291 2292 2293
		case T_ArrayExpr:
			retDatum = ExecEvalArray((ArrayExprState *) expression,
									 econtext,
									 isNull);
			break;
2294 2295 2296 2297 2298 2299 2300 2301 2302 2303
		case T_CoalesceExpr:
			retDatum = ExecEvalCoalesce((CoalesceExprState *) expression,
										econtext,
										isNull);
			break;
		case T_NullIfExpr:
			retDatum = ExecEvalNullIf((FuncExprState *) expression,
									  econtext,
									  isNull);
			break;
2304
		case T_NullTest:
2305
			retDatum = ExecEvalNullTest((GenericExprState *) expression,
2306 2307 2308
										econtext,
										isNull,
										isDone);
2309 2310
			break;
		case T_BooleanTest:
2311
			retDatum = ExecEvalBooleanTest((GenericExprState *) expression,
2312 2313 2314
										   econtext,
										   isNull,
										   isDone);
2315
			break;
2316 2317
		case T_CoerceToDomain:
			retDatum = ExecEvalCoerceToDomain((CoerceToDomainState *) expression,
2318 2319 2320 2321
											  econtext,
											  isNull,
											  isDone);
			break;
2322 2323
		case T_CoerceToDomainValue:
			retDatum = ExecEvalCoerceToDomainValue((CoerceToDomainValue *) expr,
2324 2325
												   econtext,
												   isNull);
2326
			break;
2327
		default:
2328 2329
			elog(ERROR, "unrecognized node type: %d",
				 (int) nodeTag(expression));
2330
			retDatum = 0;		/* keep compiler quiet */
2331
			break;
2332
	}
2333 2334

	return retDatum;
Bruce Momjian's avatar
Bruce Momjian committed
2335
}	/* ExecEvalExpr() */
2336

2337

2338 2339 2340 2341
/*
 * Same as above, but get into the right allocation context explicitly.
 */
Datum
2342
ExecEvalExprSwitchContext(ExprState *expression,
2343 2344
						  ExprContext *econtext,
						  bool *isNull,
2345
						  ExprDoneCond *isDone)
2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356
{
	Datum		retDatum;
	MemoryContext oldContext;

	oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
	retDatum = ExecEvalExpr(expression, econtext, isNull, isDone);
	MemoryContextSwitchTo(oldContext);
	return retDatum;
}


2357 2358 2359
/*
 * ExecInitExpr: prepare an expression tree for execution
 *
2360
 * This function builds and returns an ExprState tree paralleling the given
Bruce Momjian's avatar
Bruce Momjian committed
2361
 * Expr node tree.	The ExprState tree can then be handed to ExecEvalExpr
2362 2363 2364 2365 2366 2367 2368 2369
 * for execution.  Because the Expr tree itself is read-only as far as
 * ExecInitExpr and ExecEvalExpr are concerned, several different executions
 * of the same plan tree can occur concurrently.
 *
 * This must be called in a memory context that will last as long as repeated
 * executions of the expression are needed.  Typically the context will be
 * the same as the per-query context of the associated ExprContext.
 *
2370
 * Any Aggref and SubPlan nodes found in the tree are added to the lists
Bruce Momjian's avatar
Bruce Momjian committed
2371
 * of such nodes held by the parent PlanState.	Otherwise, we do very little
2372 2373 2374 2375 2376 2377 2378 2379 2380 2381
 * initialization here other than building the state-node tree.  Any nontrivial
 * work associated with initializing runtime info for a node should happen
 * during the first actual evaluation of that node.  (This policy lets us
 * avoid work if the node is never actually evaluated.)
 *
 * Note: there is no ExecEndExpr function; we assume that any resource
 * cleanup needed will be handled by just releasing the memory context
 * in which the state tree is built.  Functions that require additional
 * cleanup work can register a shutdown callback in the ExprContext.
 *
2382
 *	'node' is the root of the expression tree to examine
2383 2384 2385 2386 2387
 *	'parent' is the PlanState node that owns the expression.
 *
 * 'parent' may be NULL if we are preparing an expression that is not
 * associated with a plan tree.  (If so, it can't have aggs or subplans.)
 * This case should usually come through ExecPrepareExpr, not directly here.
2388
 */
2389
ExprState *
2390
ExecInitExpr(Expr *node, PlanState *parent)
2391
{
2392
	ExprState  *state;
2393 2394 2395 2396 2397 2398 2399 2400

	if (node == NULL)
		return NULL;
	switch (nodeTag(node))
	{
		case T_Var:
		case T_Const:
		case T_Param:
2401
		case T_CoerceToDomainValue:
2402 2403
			/* No special setup needed for these node types */
			state = (ExprState *) makeNode(ExprState);
2404 2405 2406
			break;
		case T_Aggref:
			{
Bruce Momjian's avatar
Bruce Momjian committed
2407
				Aggref	   *aggref = (Aggref *) node;
2408
				AggrefExprState *astate = makeNode(AggrefExprState);
2409

2410 2411 2412 2413
				if (parent && IsA(parent, AggState))
				{
					AggState   *aggstate = (AggState *) parent;
					int			naggs;
2414

2415 2416
					aggstate->aggs = lcons(astate, aggstate->aggs);
					naggs = ++aggstate->numaggs;
2417

2418 2419 2420 2421 2422
					astate->target = ExecInitExpr(aggref->target, parent);

					/*
					 * Complain if the aggregate's argument contains any
					 * aggregates; nested agg functions are semantically
Bruce Momjian's avatar
Bruce Momjian committed
2423 2424
					 * nonsensical.  (This should have been caught
					 * earlier, but we defend against it here anyway.)
2425 2426
					 */
					if (naggs != aggstate->numaggs)
2427 2428 2429
						ereport(ERROR,
								(errcode(ERRCODE_GROUPING_ERROR),
								 errmsg("aggregate function calls may not be nested")));
2430 2431
				}
				else
2432 2433 2434 2435
				{
					/* planner messed up */
					elog(ERROR, "aggref found in non-Agg plan node");
				}
2436
				state = (ExprState *) astate;
2437 2438 2439 2440 2441
			}
			break;
		case T_ArrayRef:
			{
				ArrayRef   *aref = (ArrayRef *) node;
2442 2443 2444 2445 2446 2447 2448 2449 2450
				ArrayRefExprState *astate = makeNode(ArrayRefExprState);

				astate->refupperindexpr = (List *)
					ExecInitExpr((Expr *) aref->refupperindexpr, parent);
				astate->reflowerindexpr = (List *)
					ExecInitExpr((Expr *) aref->reflowerindexpr, parent);
				astate->refexpr = ExecInitExpr(aref->refexpr, parent);
				astate->refassgnexpr = ExecInitExpr(aref->refassgnexpr,
													parent);
2451 2452 2453 2454 2455 2456
				/* do one-time catalog lookups for type info */
				astate->refattrlength = get_typlen(aref->refarraytype);
				get_typlenbyvalalign(aref->refelemtype,
									 &astate->refelemlength,
									 &astate->refelembyval,
									 &astate->refelemalign);
2457
				state = (ExprState *) astate;
2458 2459
			}
			break;
2460
		case T_FuncExpr:
2461
			{
2462
				FuncExpr   *funcexpr = (FuncExpr *) node;
2463
				FuncExprState *fstate = makeNode(FuncExprState);
2464

2465 2466
				fstate->args = (List *)
					ExecInitExpr((Expr *) funcexpr->args, parent);
Bruce Momjian's avatar
Bruce Momjian committed
2467
				fstate->func.fn_oid = InvalidOid;		/* not initialized */
2468
				state = (ExprState *) fstate;
2469 2470 2471 2472
			}
			break;
		case T_OpExpr:
			{
Bruce Momjian's avatar
Bruce Momjian committed
2473
				OpExpr	   *opexpr = (OpExpr *) node;
2474
				FuncExprState *fstate = makeNode(FuncExprState);
2475

2476 2477
				fstate->args = (List *)
					ExecInitExpr((Expr *) opexpr->args, parent);
Bruce Momjian's avatar
Bruce Momjian committed
2478
				fstate->func.fn_oid = InvalidOid;		/* not initialized */
2479
				state = (ExprState *) fstate;
2480 2481 2482 2483
			}
			break;
		case T_DistinctExpr:
			{
Bruce Momjian's avatar
Bruce Momjian committed
2484
				DistinctExpr *distinctexpr = (DistinctExpr *) node;
2485
				FuncExprState *fstate = makeNode(FuncExprState);
2486

2487 2488
				fstate->args = (List *)
					ExecInitExpr((Expr *) distinctexpr->args, parent);
Bruce Momjian's avatar
Bruce Momjian committed
2489
				fstate->func.fn_oid = InvalidOid;		/* not initialized */
2490
				state = (ExprState *) fstate;
2491 2492
			}
			break;
2493 2494
		case T_ScalarArrayOpExpr:
			{
Bruce Momjian's avatar
Bruce Momjian committed
2495
				ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) node;
2496 2497 2498 2499
				ScalarArrayOpExprState *sstate = makeNode(ScalarArrayOpExprState);

				sstate->fxprstate.args = (List *)
					ExecInitExpr((Expr *) opexpr->args, parent);
Bruce Momjian's avatar
Bruce Momjian committed
2500 2501
				sstate->fxprstate.func.fn_oid = InvalidOid;		/* not initialized */
				sstate->element_type = InvalidOid;		/* ditto */
2502 2503 2504
				state = (ExprState *) sstate;
			}
			break;
2505 2506 2507
		case T_BoolExpr:
			{
				BoolExpr   *boolexpr = (BoolExpr *) node;
2508
				BoolExprState *bstate = makeNode(BoolExprState);
2509

2510 2511 2512
				bstate->args = (List *)
					ExecInitExpr((Expr *) boolexpr->args, parent);
				state = (ExprState *) bstate;
2513 2514
			}
			break;
2515
		case T_SubPlan:
2516
			{
2517
				/* Keep this in sync with ExecInitExprInitPlan, below */
Bruce Momjian's avatar
Bruce Momjian committed
2518
				SubPlan    *subplan = (SubPlan *) node;
2519
				SubPlanState *sstate = makeNode(SubPlanState);
2520 2521

				if (!parent)
2522
					elog(ERROR, "SubPlan found with no parent plan");
2523 2524

				/*
2525
				 * Here we just add the SubPlanState nodes to
Bruce Momjian's avatar
Bruce Momjian committed
2526 2527
				 * parent->subPlan.  The subplans will be initialized
				 * later.
2528
				 */
2529
				parent->subPlan = lcons(sstate, parent->subPlan);
2530
				sstate->sub_estate = NULL;
2531 2532
				sstate->planstate = NULL;

2533 2534
				sstate->exprs = (List *)
					ExecInitExpr((Expr *) subplan->exprs, parent);
2535 2536
				sstate->args = (List *)
					ExecInitExpr((Expr *) subplan->args, parent);
2537

2538
				state = (ExprState *) sstate;
2539 2540 2541
			}
			break;
		case T_FieldSelect:
2542
			{
Bruce Momjian's avatar
Bruce Momjian committed
2543
				FieldSelect *fselect = (FieldSelect *) node;
2544 2545 2546 2547 2548
				GenericExprState *gstate = makeNode(GenericExprState);

				gstate->arg = ExecInitExpr(fselect->arg, parent);
				state = (ExprState *) gstate;
			}
2549 2550
			break;
		case T_RelabelType:
2551
			{
Bruce Momjian's avatar
Bruce Momjian committed
2552
				RelabelType *relabel = (RelabelType *) node;
2553 2554 2555 2556 2557
				GenericExprState *gstate = makeNode(GenericExprState);

				gstate->arg = ExecInitExpr(relabel->arg, parent);
				state = (ExprState *) gstate;
			}
2558 2559 2560 2561
			break;
		case T_CaseExpr:
			{
				CaseExpr   *caseexpr = (CaseExpr *) node;
2562
				CaseExprState *cstate = makeNode(CaseExprState);
2563
				FastList	outlist;
2564
				List	   *inlist;
2565

2566
				FastListInit(&outlist);
2567
				foreach(inlist, caseexpr->args)
2568
				{
2569 2570
					CaseWhen   *when = (CaseWhen *) lfirst(inlist);
					CaseWhenState *wstate = makeNode(CaseWhenState);
2571 2572

					Assert(IsA(when, CaseWhen));
2573 2574 2575
					wstate->xprstate.expr = (Expr *) when;
					wstate->expr = ExecInitExpr(when->expr, parent);
					wstate->result = ExecInitExpr(when->result, parent);
2576
					FastAppend(&outlist, wstate);
2577
				}
2578
				cstate->args = FastListValue(&outlist);
2579 2580 2581 2582
				/* caseexpr->arg should be null by now */
				Assert(caseexpr->arg == NULL);
				cstate->defresult = ExecInitExpr(caseexpr->defresult, parent);
				state = (ExprState *) cstate;
2583 2584
			}
			break;
2585 2586
		case T_ArrayExpr:
			{
Bruce Momjian's avatar
Bruce Momjian committed
2587
				ArrayExpr  *arrayexpr = (ArrayExpr *) node;
2588
				ArrayExprState *astate = makeNode(ArrayExprState);
Bruce Momjian's avatar
Bruce Momjian committed
2589 2590
				FastList	outlist;
				List	   *inlist;
2591

2592
				FastListInit(&outlist);
2593 2594 2595 2596 2597 2598
				foreach(inlist, arrayexpr->elements)
				{
					Expr	   *e = (Expr *) lfirst(inlist);
					ExprState  *estate;

					estate = ExecInitExpr(e, parent);
2599
					FastAppend(&outlist, estate);
2600
				}
2601
				astate->elements = FastListValue(&outlist);
2602 2603 2604 2605 2606 2607 2608 2609
				/* do one-time catalog lookup for type info */
				get_typlenbyvalalign(arrayexpr->element_typeid,
									 &astate->elemlength,
									 &astate->elembyval,
									 &astate->elemalign);
				state = (ExprState *) astate;
			}
			break;
2610 2611 2612 2613
		case T_CoalesceExpr:
			{
				CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
				CoalesceExprState *cstate = makeNode(CoalesceExprState);
2614
				FastList	outlist;
2615 2616
				List	   *inlist;

2617
				FastListInit(&outlist);
2618 2619
				foreach(inlist, coalesceexpr->args)
				{
Bruce Momjian's avatar
Bruce Momjian committed
2620 2621
					Expr	   *e = (Expr *) lfirst(inlist);
					ExprState  *estate;
2622 2623

					estate = ExecInitExpr(e, parent);
2624
					FastAppend(&outlist, estate);
2625
				}
2626
				cstate->args = FastListValue(&outlist);
2627 2628 2629 2630 2631 2632 2633 2634 2635 2636
				state = (ExprState *) cstate;
			}
			break;
		case T_NullIfExpr:
			{
				NullIfExpr *nullifexpr = (NullIfExpr *) node;
				FuncExprState *fstate = makeNode(FuncExprState);

				fstate->args = (List *)
					ExecInitExpr((Expr *) nullifexpr->args, parent);
Bruce Momjian's avatar
Bruce Momjian committed
2637
				fstate->func.fn_oid = InvalidOid;		/* not initialized */
2638 2639 2640
				state = (ExprState *) fstate;
			}
			break;
2641
		case T_NullTest:
2642 2643 2644 2645 2646 2647 2648
			{
				NullTest   *ntest = (NullTest *) node;
				GenericExprState *gstate = makeNode(GenericExprState);

				gstate->arg = ExecInitExpr(ntest->arg, parent);
				state = (ExprState *) gstate;
			}
2649 2650
			break;
		case T_BooleanTest:
2651
			{
Bruce Momjian's avatar
Bruce Momjian committed
2652
				BooleanTest *btest = (BooleanTest *) node;
2653 2654 2655 2656 2657
				GenericExprState *gstate = makeNode(GenericExprState);

				gstate->arg = ExecInitExpr(btest->arg, parent);
				state = (ExprState *) gstate;
			}
2658
			break;
2659
		case T_CoerceToDomain:
2660
			{
Bruce Momjian's avatar
Bruce Momjian committed
2661
				CoerceToDomain *ctest = (CoerceToDomain *) node;
2662
				CoerceToDomainState *cstate = makeNode(CoerceToDomainState);
2663 2664

				cstate->arg = ExecInitExpr(ctest->arg, parent);
2665
				cstate->constraints = GetDomainConstraints(ctest->resulttype);
2666 2667
				state = (ExprState *) cstate;
			}
2668
			break;
2669
		case T_TargetEntry:
2670
			{
Bruce Momjian's avatar
Bruce Momjian committed
2671
				TargetEntry *tle = (TargetEntry *) node;
2672 2673 2674 2675 2676
				GenericExprState *gstate = makeNode(GenericExprState);

				gstate->arg = ExecInitExpr(tle->expr, parent);
				state = (ExprState *) gstate;
			}
2677
			break;
2678 2679
		case T_List:
			{
2680
				FastList	outlist;
2681 2682
				List	   *inlist;

2683
				FastListInit(&outlist);
2684 2685
				foreach(inlist, (List *) node)
				{
2686 2687 2688
					FastAppend(&outlist,
							   ExecInitExpr((Expr *) lfirst(inlist),
											parent));
2689 2690
				}
				/* Don't fall through to the "common" code below */
2691
				return (ExprState *) FastListValue(&outlist);
2692 2693
			}
		default:
2694 2695
			elog(ERROR, "unrecognized node type: %d",
				 (int) nodeTag(node));
2696
			state = NULL;		/* keep compiler quiet */
2697 2698 2699
			break;
	}

2700 2701 2702 2703 2704 2705 2706 2707
	/* Common code for all state-node types */
	state->expr = node;

	return state;
}

/*
 * ExecInitExprInitPlan --- initialize a subplan expr that's being handled
Bruce Momjian's avatar
Bruce Momjian committed
2708
 * as an InitPlan.	This is identical to ExecInitExpr's handling of a regular
2709 2710 2711
 * subplan expr, except we do NOT want to add the node to the parent's
 * subplan list.
 */
2712
SubPlanState *
2713
ExecInitExprInitPlan(SubPlan *node, PlanState *parent)
2714
{
2715
	SubPlanState *sstate = makeNode(SubPlanState);
2716 2717

	if (!parent)
2718
		elog(ERROR, "SubPlan found with no parent plan");
2719 2720

	/* The subplan's state will be initialized later */
2721
	sstate->sub_estate = NULL;
2722 2723
	sstate->planstate = NULL;

2724
	sstate->exprs = (List *) ExecInitExpr((Expr *) node->exprs, parent);
2725 2726 2727 2728 2729
	sstate->args = (List *) ExecInitExpr((Expr *) node->args, parent);

	sstate->xprstate.expr = (Expr *) node;

	return sstate;
2730 2731
}

2732 2733 2734 2735 2736 2737 2738
/*
 * ExecPrepareExpr --- initialize for expression execution outside a normal
 * Plan tree context.
 *
 * This differs from ExecInitExpr in that we don't assume the caller is
 * already running in the EState's per-query context.  Also, we apply
 * fix_opfuncids() to the passed expression tree to be sure it is ready
Bruce Momjian's avatar
Bruce Momjian committed
2739
 * to run.	(In ordinary Plan trees the planner will have fixed opfuncids,
2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758
 * but callers outside the executor will not have done this.)
 */
ExprState *
ExecPrepareExpr(Expr *node, EState *estate)
{
	ExprState  *result;
	MemoryContext oldcontext;

	fix_opfuncids((Node *) node);

	oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);

	result = ExecInitExpr(node, NULL);

	MemoryContextSwitchTo(oldcontext);

	return result;
}

2759

2760
/* ----------------------------------------------------------------
2761
 *					 ExecQual / ExecTargetList / ExecProject
2762 2763 2764 2765
 * ----------------------------------------------------------------
 */

/* ----------------------------------------------------------------
2766 2767
 *		ExecQual
 *
2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790
 *		Evaluates a conjunctive boolean expression (qual list) and
 *		returns true iff none of the subexpressions are false.
 *		(We also return true if the list is empty.)
 *
 *	If some of the subexpressions yield NULL but none yield FALSE,
 *	then the result of the conjunction is NULL (ie, unknown)
 *	according to three-valued boolean logic.  In this case,
 *	we return the value specified by the "resultForNull" parameter.
 *
 *	Callers evaluating WHERE clauses should pass resultForNull=FALSE,
 *	since SQL specifies that tuples with null WHERE results do not
 *	get selected.  On the other hand, callers evaluating constraint
 *	conditions should pass resultForNull=TRUE, since SQL also specifies
 *	that NULL constraint conditions are not failures.
 *
 *	NOTE: it would not be correct to use this routine to evaluate an
 *	AND subclause of a boolean expression; for that purpose, a NULL
 *	result must be returned as NULL so that it can be properly treated
 *	in the next higher operator (cf. ExecEvalAnd and ExecEvalOr).
 *	This routine is only used in contexts where a complete expression
 *	is being evaluated and we know that NULL can be treated the same
 *	as one boolean result or the other.
 *
2791 2792 2793
 * ----------------------------------------------------------------
 */
bool
2794
ExecQual(List *qual, ExprContext *econtext, bool resultForNull)
2795
{
2796 2797
	bool		result;
	MemoryContext oldContext;
2798
	List	   *qlist;
2799

Bruce Momjian's avatar
Bruce Momjian committed
2800
	/*
Bruce Momjian's avatar
Bruce Momjian committed
2801
	 * debugging stuff
2802 2803 2804 2805 2806 2807 2808
	 */
	EV_printf("ExecQual: qual is ");
	EV_nodeDisplay(qual);
	EV_printf("\n");

	IncrProcessed();

2809 2810 2811 2812 2813
	/*
	 * Run in short-lived per-tuple context while computing expressions.
	 */
	oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);

Bruce Momjian's avatar
Bruce Momjian committed
2814
	/*
2815
	 * Evaluate the qual conditions one at a time.	If we find a FALSE
2816 2817 2818 2819
	 * result, we can stop evaluating and return FALSE --- the AND result
	 * must be FALSE.  Also, if we find a NULL result when resultForNull
	 * is FALSE, we can stop and return FALSE --- the AND result must be
	 * FALSE or NULL in that case, and the caller doesn't care which.
2820
	 *
2821 2822 2823 2824
	 * If we get to the end of the list, we can return TRUE.  This will
	 * happen when the AND result is indeed TRUE, or when the AND result
	 * is NULL (one or more NULL subresult, with all the rest TRUE) and
	 * the caller has specified resultForNull = TRUE.
2825
	 */
2826
	result = true;
2827

2828
	foreach(qlist, qual)
2829
	{
2830
		ExprState  *clause = (ExprState *) lfirst(qlist);
2831 2832 2833
		Datum		expr_value;
		bool		isNull;

2834
		expr_value = ExecEvalExpr(clause, econtext, &isNull, NULL);
2835

2836
		if (isNull)
2837 2838
		{
			if (resultForNull == false)
2839
			{
2840
				result = false; /* treat NULL as FALSE */
2841 2842
				break;
			}
2843 2844 2845
		}
		else
		{
2846
			if (!DatumGetBool(expr_value))
2847
			{
2848
				result = false; /* definitely FALSE */
2849 2850
				break;
			}
2851
		}
2852 2853
	}

2854 2855 2856
	MemoryContextSwitchTo(oldContext);

	return result;
2857 2858
}

2859 2860 2861
/*
 * Number of items in a tlist (including any resjunk items!)
 */
2862
int
2863
ExecTargetListLength(List *targetlist)
2864
{
2865 2866
	/* This used to be more complex, but fjoins are dead */
	return length(targetlist);
2867 2868
}

2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879
/*
 * Number of items in a tlist, not including any resjunk items
 */
int
ExecCleanTargetListLength(List *targetlist)
{
	int			len = 0;
	List	   *tl;

	foreach(tl, targetlist)
	{
2880
		TargetEntry *curTle = (TargetEntry *) lfirst(tl);
2881

2882
		Assert(IsA(curTle, TargetEntry));
2883 2884
		if (!curTle->resdom->resjunk)
			len++;
2885 2886 2887 2888
	}
	return len;
}

2889
/* ----------------------------------------------------------------
2890 2891
 *		ExecTargetList
 *
2892 2893 2894 2895 2896 2897 2898
 *		Evaluates a targetlist with respect to the given
 *		expression context and returns a tuple.
 *
 * The caller must pass workspace for the values and nulls arrays
 * as well as the itemIsDone array.  This convention saves palloc'ing
 * workspace on each call, and some callers may find it useful to examine
 * the values array directly.
2899 2900 2901 2902 2903
 *
 * As with ExecEvalExpr, the caller should pass isDone = NULL if not
 * prepared to deal with sets of result tuples.  Otherwise, a return
 * of *isDone = ExprMultipleResult signifies a set element, and a return
 * of *isDone = ExprEndResult signifies end of the set of tuple.
2904 2905
 * ----------------------------------------------------------------
 */
2906
static HeapTuple
2907
ExecTargetList(List *targetlist,
2908
			   TupleDesc targettype,
2909
			   ExprContext *econtext,
2910 2911 2912
			   Datum *values,
			   char *nulls,
			   ExprDoneCond *itemIsDone,
2913
			   ExprDoneCond *isDone)
2914
{
2915
	MemoryContext oldContext;
2916 2917
	List	   *tl;
	bool		isNull;
2918
	bool		haveDoneSets;
2919 2920
	static struct tupleDesc NullTupleDesc;		/* we assume this inits to
												 * zeroes */
2921

Bruce Momjian's avatar
Bruce Momjian committed
2922
	/*
Bruce Momjian's avatar
Bruce Momjian committed
2923
	 * debugging stuff
2924
	 */
2925 2926 2927 2928
	EV_printf("ExecTargetList: tl is ");
	EV_nodeDisplay(targetlist);
	EV_printf("\n");

2929 2930 2931 2932 2933
	/*
	 * Run in short-lived per-tuple context while computing expressions.
	 */
	oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);

Bruce Momjian's avatar
Bruce Momjian committed
2934
	/*
2935 2936 2937 2938 2939 2940
	 * There used to be some klugy and demonstrably broken code here that
	 * special-cased the situation where targetlist == NIL.  Now we just
	 * fall through and return an empty-but-valid tuple.  We do, however,
	 * have to cope with the possibility that targettype is NULL ---
	 * heap_formtuple won't like that, so pass a dummy descriptor with
	 * natts = 0 to deal with it.
2941
	 */
2942 2943
	if (targettype == NULL)
		targettype = &NullTupleDesc;
2944

Bruce Momjian's avatar
Bruce Momjian committed
2945
	/*
Bruce Momjian's avatar
Bruce Momjian committed
2946
	 * evaluate all the expressions in the target list
2947
	 */
2948
	if (isDone)
2949
		*isDone = ExprSingleResult;		/* until proven otherwise */
2950 2951

	haveDoneSets = false;		/* any exhausted set exprs in tlist? */
2952

2953 2954
	foreach(tl, targetlist)
	{
2955 2956 2957
		GenericExprState *gstate = (GenericExprState *) lfirst(tl);
		TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr;
		AttrNumber	resind = tle->resdom->resno - 1;
2958

2959
		values[resind] = ExecEvalExpr(gstate->arg,
2960 2961 2962 2963
									  econtext,
									  &isNull,
									  &itemIsDone[resind]);
		nulls[resind] = isNull ? 'n' : ' ';
2964

2965
		if (itemIsDone[resind] != ExprSingleResult)
2966
		{
2967 2968
			/* We have a set-valued expression in the tlist */
			if (isDone == NULL)
2969
				ereport(ERROR,
2970
						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2971
						 errmsg("set-valued function called in context that cannot accept a set")));
2972
			if (itemIsDone[resind] == ExprMultipleResult)
2973
			{
2974 2975
				/* we have undone sets in the tlist, set flag */
				*isDone = ExprMultipleResult;
2976
			}
2977
			else
2978
			{
2979 2980
				/* we have done sets in the tlist, set flag for that */
				haveDoneSets = true;
2981
			}
2982 2983
		}
	}
2984

2985
	if (haveDoneSets)
2986
	{
2987 2988 2989 2990
		/*
		 * note: can't get here unless we verified isDone != NULL
		 */
		if (*isDone == ExprSingleResult)
2991
		{
2992
			/*
2993 2994
			 * all sets are done, so report that tlist expansion is
			 * complete.
2995
			 */
2996 2997
			*isDone = ExprEndResult;
			MemoryContextSwitchTo(oldContext);
2998
			return NULL;
2999 3000 3001
		}
		else
		{
3002
			/*
3003
			 * We have some done and some undone sets.	Restart the done
3004
			 * ones so that we can deliver a tuple (if possible).
3005 3006 3007
			 */
			foreach(tl, targetlist)
			{
3008 3009 3010
				GenericExprState *gstate = (GenericExprState *) lfirst(tl);
				TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr;
				AttrNumber	resind = tle->resdom->resno - 1;
3011

3012
				if (itemIsDone[resind] == ExprEndResult)
3013
				{
3014 3015 3016 3017 3018
					values[resind] = ExecEvalExpr(gstate->arg,
												  econtext,
												  &isNull,
												  &itemIsDone[resind]);
					nulls[resind] = isNull ? 'n' : ' ';
3019

3020
					if (itemIsDone[resind] == ExprEndResult)
3021
					{
3022
						/*
Bruce Momjian's avatar
Bruce Momjian committed
3023 3024
						 * Oh dear, this item is returning an empty set.
						 * Guess we can't make a tuple after all.
3025 3026 3027
						 */
						*isDone = ExprEndResult;
						break;
3028 3029 3030
					}
				}
			}
3031

3032
			/*
3033 3034 3035
			 * If we cannot make a tuple because some sets are empty, we
			 * still have to cycle the nonempty sets to completion, else
			 * resources will not be released from subplans etc.
3036 3037
			 *
			 * XXX is that still necessary?
3038 3039 3040 3041 3042
			 */
			if (*isDone == ExprEndResult)
			{
				foreach(tl, targetlist)
				{
3043 3044 3045
					GenericExprState *gstate = (GenericExprState *) lfirst(tl);
					TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr;
					AttrNumber	resind = tle->resdom->resno - 1;
3046

3047
					while (itemIsDone[resind] == ExprMultipleResult)
3048
					{
3049 3050 3051 3052
						(void) ExecEvalExpr(gstate->arg,
											econtext,
											&isNull,
											&itemIsDone[resind]);
3053 3054
					}
				}
3055 3056

				MemoryContextSwitchTo(oldContext);
3057
				return NULL;
3058 3059 3060 3061
			}
		}
	}

Bruce Momjian's avatar
Bruce Momjian committed
3062
	/*
3063
	 * form the new result tuple (in the caller's memory context!)
3064
	 */
3065 3066
	MemoryContextSwitchTo(oldContext);

3067
	return heap_formtuple(targettype, values, nulls);
3068 3069 3070
}

/* ----------------------------------------------------------------
3071 3072
 *		ExecProject
 *
3073
 *		projects a tuple based on projection info and stores
3074
 *		it in the specified tuple table slot.
3075
 *
3076 3077 3078 3079 3080
 *		Note: someday soon the executor can be extended to eliminate
 *			  redundant projections by storing pointers to datums
 *			  in the tuple table and then passing these around when
 *			  possible.  this should make things much quicker.
 *			  -cim 6/3/91
3081 3082 3083
 * ----------------------------------------------------------------
 */
TupleTableSlot *
3084
ExecProject(ProjectionInfo *projInfo, ExprDoneCond *isDone)
3085
{
3086
	TupleTableSlot *slot;
3087 3088
	TupleDesc	tupType;
	HeapTuple	newTuple;
3089

Bruce Momjian's avatar
Bruce Momjian committed
3090
	/*
Bruce Momjian's avatar
Bruce Momjian committed
3091
	 * sanity checks
3092 3093 3094
	 */
	if (projInfo == NULL)
		return (TupleTableSlot *) NULL;
3095

Bruce Momjian's avatar
Bruce Momjian committed
3096
	/*
Bruce Momjian's avatar
Bruce Momjian committed
3097
	 * get the projection info we want
3098 3099 3100 3101
	 */
	slot = projInfo->pi_slot;
	tupType = slot->ttc_tupleDescriptor;

Bruce Momjian's avatar
Bruce Momjian committed
3102
	/*
3103
	 * form a new result tuple (if possible --- result can be NULL)
3104
	 */
3105
	newTuple = ExecTargetList(projInfo->pi_targetlist,
3106
							  tupType,
3107 3108 3109 3110
							  projInfo->pi_exprContext,
							  projInfo->pi_tupValues,
							  projInfo->pi_tupNulls,
							  projInfo->pi_itemIsDone,
3111 3112
							  isDone);

Bruce Momjian's avatar
Bruce Momjian committed
3113
	/*
Bruce Momjian's avatar
Bruce Momjian committed
3114
	 * store the tuple in the projection slot and return the slot.
3115
	 */
3116 3117 3118
	return ExecStoreTuple(newTuple,		/* tuple to store */
						  slot, /* slot to store in */
						  InvalidBuffer,		/* tuple has no buffer */
3119
						  true);
3120
}