execQual.c 41.4 KB
Newer Older
1 2 3
/*-------------------------------------------------------------------------
 *
 * execQual.c--
4
 *	  Routines to evaluate qualification and targetlist expressions
5 6 7 8 9
 *
 * Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
B
Bruce Momjian 已提交
10
 *	  $Header: /cvsroot/pgsql/src/backend/executor/execQual.c,v 1.15 1997/09/08 20:55:37 momjian Exp $
11 12 13 14
 *
 *-------------------------------------------------------------------------
 */
/*
15 16 17 18
 *	 INTERFACE ROUTINES
 *		ExecEvalExpr	- evaluate an expression and return a datum
 *		ExecQual		- return true/false if qualification is satisified
 *		ExecTargetList	- form a new tuple by projecting the given tuple
19
 *
20 21 22 23 24
 *	 NOTES
 *		ExecEvalExpr() and ExecEvalVar() are hotspots.	making these faster
 *		will speed up the entire system.  Unfortunately they are currently
 *		implemented recursively..  Eliminating the recursion is bound to
 *		improve the speed of the executor.
25
 *
26 27 28 29
 *		ExecTargetList() is used to make tuple projections.  Rather then
 *		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
30 31
 *
 */
32 33
#include <string.h>

34
#include "postgres.h"
35
#include "fmgr.h"
36

37 38 39 40 41 42 43
#include "nodes/primnodes.h"
#include "nodes/relation.h"

#include "optimizer/clauses.h"

#include "nodes/memnodes.h"
#include "catalog/pg_language.h"
44
#include "catalog/pg_proc.h"
45
#include "executor/executor.h"
46
#include "executor/execdebug.h"
47 48 49 50 51 52 53 54 55
#include "executor/execFlatten.h"
#include "executor/functions.h"
#include "access/heapam.h"
#include "utils/memutils.h"
#include "utils/builtins.h"
#include "utils/palloc.h"
#include "utils/fcache.h"
#include "utils/fcache2.h"
#include "utils/array.h"
56
#include "utils/mcxt.h"
57 58

/* ----------------
59
 *		externs and constants
60 61 62 63 64 65 66 67
 * ----------------
 */

/*
 * XXX Used so we can get rid of use of Const nodes in the executor.
 * Currently only used by ExecHashGetBucket and set only by ExecMakeVarConst
 * and by ExecEvalArrayRef.
 */
68 69
bool		execConstByVal;
int			execConstLen;
70 71

/* static functions decls */
B
Bruce Momjian 已提交
72
static Datum ExecEvalAggreg(Aggreg *agg, ExprContext * econtext, bool * isNull);
73
static Datum
B
Bruce Momjian 已提交
74
ExecEvalArrayRef(ArrayRef *arrayRef, ExprContext * econtext,
75
				 bool * isNull, bool * isDone);
76
static Datum ExecEvalAnd(Expr * andExpr, ExprContext * econtext, bool * isNull);
77 78 79 80 81 82
static Datum
ExecEvalFunc(Expr * funcClause, ExprContext * econtext,
			 bool * isNull, bool * isDone);
static void
ExecEvalFuncArgs(FunctionCachePtr fcache, ExprContext * econtext,
				 List * argList, Datum argV[], bool * argIsDone);
83
static Datum ExecEvalNot(Expr * notclause, ExprContext * econtext, bool * isNull);
84 85 86
static Datum
ExecEvalOper(Expr * opClause, ExprContext * econtext,
			 bool * isNull);
87 88
static Datum ExecEvalOr(Expr * orExpr, ExprContext * econtext, bool * isNull);
static Datum ExecEvalVar(Var * variable, ExprContext * econtext, bool * isNull);
89 90 91
static Datum
ExecMakeFunctionResult(Node * node, List * arguments,
				   ExprContext * econtext, bool * isNull, bool * isDone);
92
static bool ExecQualClause(Node * clause, ExprContext * econtext);
93 94

/* --------------------------------
95
 *	  ExecEvalArrayRef
96
 *
97 98 99
 *	   This function takes an ArrayRef and returns a Const Node if it
 *	   is an array reference or returns the changed Array Node if it is
 *		   an array assignment.
100 101 102
 *
 * --------------------------------
 */
103
static Datum
B
Bruce Momjian 已提交
104
ExecEvalArrayRef(ArrayRef *arrayRef,
105 106 107
				 ExprContext * econtext,
				 bool * isNull,
				 bool * isDone)
108
{
109 110 111 112 113 114 115 116 117 118 119 120
	bool		dummy;
	int			i = 0,
				j = 0;
	ArrayType  *array_scanner;
	List	   *upperIndexpr,
			   *lowerIndexpr;
	Node	   *assgnexpr;
	List	   *elt;
	IntArray	upper,
				lower;
	int		   *lIndex;
	char	   *dataPtr;
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158

	*isNull = false;
	array_scanner = (ArrayType *) ExecEvalExpr(arrayRef->refexpr,
											   econtext,
											   isNull,
											   isDone);
	if (*isNull)
		return (Datum) NULL;

	upperIndexpr = arrayRef->refupperindexpr;

	foreach(elt, upperIndexpr)
	{
		upper.indx[i++] = (int32) ExecEvalExpr((Node *) lfirst(elt),
											   econtext,
											   isNull,
											   &dummy);
		if (*isNull)
			return (Datum) NULL;
	}

	lowerIndexpr = arrayRef->reflowerindexpr;
	lIndex = NULL;
	if (lowerIndexpr != NIL)
	{
		foreach(elt, lowerIndexpr)
		{
			lower.indx[j++] = (int32) ExecEvalExpr((Node *) lfirst(elt),
												   econtext,
												   isNull,
												   &dummy);
			if (*isNull)
				return (Datum) NULL;
		}
		if (i != j)
			elog(WARN,
				 "ExecEvalArrayRef: upper and lower indices mismatch");
		lIndex = lower.indx;
159
	}
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183

	assgnexpr = arrayRef->refassgnexpr;
	if (assgnexpr != NULL)
	{
		dataPtr = (char *) ExecEvalExpr((Node *)
										assgnexpr, econtext,
										isNull, &dummy);
		if (*isNull)
			return (Datum) NULL;
		execConstByVal = arrayRef->refelembyval;
		execConstLen = arrayRef->refelemlength;
		if (lIndex == NULL)
			return (Datum) array_set(array_scanner, i, upper.indx, dataPtr,
									 arrayRef->refelembyval,
									 arrayRef->refelemlength,
									 arrayRef->refattrlength, isNull);
		return (Datum) array_assgn(array_scanner, i, upper.indx,
								   lower.indx,
								   (ArrayType *) dataPtr,
								   arrayRef->refelembyval,
								   arrayRef->refelemlength, isNull);
	}
	execConstByVal = arrayRef->refelembyval;
	execConstLen = arrayRef->refelemlength;
184
	if (lIndex == NULL)
185 186 187 188 189 190 191
		return (Datum) array_ref(array_scanner, i, upper.indx,
								 arrayRef->refelembyval,
								 arrayRef->refelemlength,
								 arrayRef->refattrlength, isNull);
	return (Datum) array_clip(array_scanner, i, upper.indx, lower.indx,
							  arrayRef->refelembyval,
							  arrayRef->refelemlength, isNull);
192 193 194 195
}


/* ----------------------------------------------------------------
196 197 198 199
 *		ExecEvalAggreg
 *
 *		Returns a Datum whose value is the value of the precomputed
 *		aggregate found in the given expression context.
200 201
 * ----------------------------------------------------------------
 */
202
static Datum
B
Bruce Momjian 已提交
203
ExecEvalAggreg(Aggreg *agg, ExprContext * econtext, bool * isNull)
204
{
205 206 207

	*isNull = econtext->ecxt_nulls[agg->aggno];
	return econtext->ecxt_values[agg->aggno];
208 209 210
}

/* ----------------------------------------------------------------
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
 *		ExecEvalVar
 *
 *		Returns a Datum whose value is the value of a range
 *		variable with respect to given expression context.
 *
 *
 *		As an entry condition, we expect that the the datatype the
 *		plan expects to get (as told by our "variable" argument) is in
 *		fact the datatype of the attribute the plan says to fetch (as
 *		seen in the current context, identified by our "econtext"
 *		argument).
 *
 *		If we fetch a Type A attribute and Caller treats it as if it
 *		were Type B, there will be undefined results (e.g. crash).
 *		One way these might mismatch now is that we're accessing a
 *		catalog class and the type information in the pg_attribute
 *		class does not match the hardcoded pg_attribute information
 *		(in pg_attribute.h) for the class in question.
229
 *
230
 *		We have an Assert to make sure this entry condition is met.
231 232
 *
 * ---------------------------------------------------------------- */
233
static Datum
234
ExecEvalVar(Var * variable, ExprContext * econtext, bool * isNull)
235
{
236
	Datum		result;
237
	TupleTableSlot *slot;
238 239 240 241 242 243
	AttrNumber	attnum;
	HeapTuple	heapTuple;
	TupleDesc	tuple_type;
	Buffer		buffer;
	bool		byval;
	int16		len;
244 245 246 247 248 249 250

	/* ----------------
	 *	get the slot we want
	 * ----------------
	 */
	switch (variable->varno)
	{
251 252 253
		case INNER:				/* get the tuple from the inner node */
			slot = econtext->ecxt_innertuple;
			break;
254

255 256 257
		case OUTER:				/* get the tuple from the outer node */
			slot = econtext->ecxt_outertuple;
			break;
258

259
		default:				/* get the tuple from the relation being
260
								 * scanned */
261 262
			slot = econtext->ecxt_scantuple;
			break;
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
	}

	/* ----------------
	 *	 extract tuple information from the slot
	 * ----------------
	 */
	heapTuple = slot->val;
	tuple_type = slot->ttc_tupleDescriptor;
	buffer = slot->ttc_buffer;

	attnum = variable->varattno;

	/* (See prolog for explanation of this Assert) */
	Assert(attnum <= 0 ||
		   (attnum - 1 <= tuple_type->natts - 1 &&
			tuple_type->attrs[attnum - 1] != NULL &&
			variable->vartype == tuple_type->attrs[attnum - 1]->atttypid))

	/*
	 * If the attribute number is invalid, then we are supposed to return
	 * the entire tuple, we give back a whole slot so that callers know
	 * what the tuple looks like.
	 */
		if (attnum == InvalidAttrNumber)
287
	{
288
		TupleTableSlot *tempSlot;
289 290
		TupleDesc	td;
		HeapTuple	tup;
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305

		tempSlot = makeNode(TupleTableSlot);
		tempSlot->ttc_shouldFree = false;
		tempSlot->ttc_descIsNew = true;
		tempSlot->ttc_tupleDescriptor = (TupleDesc) NULL,
			tempSlot->ttc_buffer = InvalidBuffer;
		tempSlot->ttc_whichplan = -1;

		tup = heap_copytuple(slot->val);
		td = CreateTupleDescCopy(slot->ttc_tupleDescriptor);

		ExecSetSlotDescriptor(tempSlot, td);

		ExecStoreTuple(tup, tempSlot, InvalidBuffer, true);
		return (Datum) tempSlot;
306
	}
307 308 309 310 311 312 313 314

	result = (Datum)
		heap_getattr(heapTuple, /* tuple containing attribute */
					 buffer,	/* buffer associated with tuple */
					 attnum,	/* attribute number of desired attribute */
					 tuple_type,/* tuple descriptor of tuple */
					 isNull);	/* return: is attribute null? */

315
	/* ----------------
316
	 *	return null if att is null
317 318
	 * ----------------
	 */
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
	if (*isNull)
		return (Datum) NULL;

	/* ----------------
	 *	 get length and type information..
	 *	 ??? what should we do about variable length attributes
	 *	 - variable length attributes have their length stored
	 *	   in the first 4 bytes of the memory pointed to by the
	 *	   returned value.. If we can determine that the type
	 *	   is a variable length type, we can do the right thing.
	 *	   -cim 9/15/89
	 * ----------------
	 */
	if (attnum < 0)
	{
		/* ----------------
		 *	If this is a pseudo-att, we get the type and fake the length.
		 *	There ought to be a routine to return the real lengths, so
		 *	we'll mark this one ... XXX -mao
		 * ----------------
		 */
		len = heap_sysattrlen(attnum);	/* XXX see -mao above */
		byval = heap_sysattrbyval(attnum);		/* XXX see -mao above */
	}
	else
	{
		len = tuple_type->attrs[attnum - 1]->attlen;
		byval = tuple_type->attrs[attnum - 1]->attbyval ? true : false;
	}

	execConstByVal = byval;
	execConstLen = len;

	return result;
353 354 355
}

/* ----------------------------------------------------------------
356
 *		ExecEvalParam
357
 *
358 359 360 361 362
 *		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)...
 *		so our job is to replace the param node with the datum
 *		containing the appropriate information ("sam").
363
 *
364 365 366 367 368
 *		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"
 *		   (in which case we shoud return a Const node with the
 *			isnull flag) ?	-cim 10/13/89
369
 *
370 371 372 373 374 375 376
 *		Minor modification: Param nodes now have an extra field,
 *		`paramkind' which specifies the type of parameter
 *		(see params.h). So while searching the paramList for
 *		a paramname/value pair, we have also to check for `kind'.
 *
 *		NOTE: The last entry in `paramList' is always an
 *		entry with kind == PARAM_INVALID.
377 378 379
 * ----------------------------------------------------------------
 */
Datum
380
ExecEvalParam(Param * expression, ExprContext * econtext, bool * isNull)
381
{
382

383 384 385 386 387
	char	   *thisParameterName;
	int			thisParameterKind;
	AttrNumber	thisParameterId;
	int			matchFound;
	ParamListInfo paramList;
388 389 390 391 392 393 394 395

	thisParameterName = expression->paramname;
	thisParameterKind = expression->paramkind;
	thisParameterId = expression->paramid;
	paramList = econtext->ecxt_param_list_info;

	*isNull = false;

396
	/*
397 398
	 * search the list with the parameter info to find a matching name. An
	 * entry with an InvalidName denotes the last element in the array.
399
	 */
400 401 402 403 404 405 406 407 408 409 410 411
	matchFound = 0;
	if (paramList != NULL)
	{

		/*
		 * search for an entry in 'paramList' that matches the
		 * `expression'.
		 */
		while (paramList->kind != PARAM_INVALID && !matchFound)
		{
			switch (thisParameterKind)
			{
412 413 414
				case PARAM_NAMED:
					if (thisParameterKind == paramList->kind &&
						strcmp(paramList->name, thisParameterName) == 0)
415
					{
416
						matchFound = 1;
417
					}
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
					break;
				case PARAM_NUM:
					if (thisParameterKind == paramList->kind &&
						paramList->id == thisParameterId)
					{
						matchFound = 1;
					}
					break;
				case PARAM_OLD:
				case PARAM_NEW:
					if (thisParameterKind == paramList->kind &&
						paramList->id == thisParameterId)
					{
						matchFound = 1;

						/*
						 * sanity check
						 */
						if (strcmp(paramList->name, thisParameterName) != 0)
						{
							elog(WARN,
								 "ExecEvalParam: new/old params with same id & diff names");
						}
					}
					break;
				default:
444

445 446 447 448 449
					/*
					 * oops! this is not supposed to happen!
					 */
					elog(WARN, "ExecEvalParam: invalid paramkind %d",
						 thisParameterKind);
450
			}
451 452 453 454 455 456 457 458 459 460
			if (!matchFound)
			{
				paramList++;
			}
		}						/* while */
	}							/* if */

	if (!matchFound)
	{

461
		/*
462 463
		 * ooops! we couldn't find this parameter in the parameter list.
		 * Signal an error
464
		 */
465 466 467 468
		elog(WARN, "ExecEvalParam: Unknown value for parameter %s",
			 thisParameterName);
	}

469
	/*
470
	 * return the value.
471
	 */
472
	if (paramList->isnull)
473
	{
474 475
		*isNull = true;
		return (Datum) NULL;
476
	}
477 478

	if (expression->param_tlist != NIL)
479
	{
480 481 482 483
		HeapTuple	tup;
		Datum		value;
		List	   *tlist = expression->param_tlist;
		TargetEntry *tle = (TargetEntry *) lfirst(tlist);
484 485 486 487 488 489
		TupleTableSlot *slot = (TupleTableSlot *) paramList->value;

		tup = slot->val;
		value = ProjectAttribute(slot->ttc_tupleDescriptor,
								 tle, tup, isNull);
		return value;
490
	}
491
	return (paramList->value);
492 493 494 495
}


/* ----------------------------------------------------------------
496
 *		ExecEvalOper / ExecEvalFunc support routines
497 498 499 500
 * ----------------------------------------------------------------
 */

/* ----------------
501 502
 *		GetAttributeByName
 *		GetAttributeByNum
503
 *
504 505 506 507
 *		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().
508 509
 * ----------------
 */
510
#ifdef NOT_USED
511
static char *
512 513 514
GetAttributeByNum(TupleTableSlot * slot,
				  AttrNumber attrno,
				  bool * isNull)
515
{
516
	Datum		retval;
517 518 519 520 521 522 523 524 525 526 527

	if (!AttributeNumberIsValid(attrno))
		elog(WARN, "GetAttributeByNum: Invalid attribute number");

	if (!AttrNumberIsForUserDefinedAttr(attrno))
		elog(WARN, "GetAttributeByNum: cannot access system attributes here");

	if (isNull == (bool *) NULL)
		elog(WARN, "GetAttributeByNum: a NULL isNull flag was passed");

	if (TupIsNull(slot))
528
	{
529 530
		*isNull = true;
		return (char *) NULL;
531
	}
532 533 534 535 536 537 538 539 540 541

	retval = (Datum)
		heap_getattr(slot->val,
					 slot->ttc_buffer,
					 attrno,
					 slot->ttc_tupleDescriptor,
					 isNull);
	if (*isNull)
		return (char *) NULL;
	return (char *) retval;
542
}
543

544
#endif
545 546

/* XXX char16 name for catalogs */
547
#ifdef NOT_USED
548
char	   *
549 550 551
att_by_num(TupleTableSlot * slot,
		   AttrNumber attrno,
		   bool * isNull)
552
{
553
	return (GetAttributeByNum(slot, attrno, isNull));
554
}
555

556
#endif
557

558
char	   *
559
GetAttributeByName(TupleTableSlot * slot, char *attname, bool * isNull)
560
{
561 562 563 564 565 566
	AttrNumber	attrno;
	TupleDesc	tupdesc;
	HeapTuple	tuple;
	Datum		retval;
	int			natts;
	int			i;
567 568 569 570 571 572 573 574

	if (attname == NULL)
		elog(WARN, "GetAttributeByName: Invalid attribute name");

	if (isNull == (bool *) NULL)
		elog(WARN, "GetAttributeByName: a NULL isNull flag was passed");

	if (TupIsNull(slot))
575
	{
576 577
		*isNull = true;
		return (char *) NULL;
578
	}
579 580 581 582 583 584 585 586 587 588 589 590 591 592

	tupdesc = slot->ttc_tupleDescriptor;
	tuple = slot->val;

	natts = tuple->t_natts;

	attrno = InvalidAttrNumber;
	for (i = 0; i < tupdesc->natts; i++)
	{
		if (namestrcmp(&(tupdesc->attrs[i]->attname), attname) == 0)
		{
			attrno = tupdesc->attrs[i]->attnum;
			break;
		}
593
	}
594 595 596 597 598 599 600 601 602 603 604 605 606

	if (attrno == InvalidAttrNumber)
		elog(WARN, "GetAttributeByName: attribute %s not found", attname);

	retval = (Datum)
		heap_getattr(slot->val,
					 slot->ttc_buffer,
					 attrno,
					 tupdesc,
					 isNull);
	if (*isNull)
		return (char *) NULL;
	return (char *) retval;
607 608 609
}

/* XXX char16 name for catalogs */
610
#ifdef NOT_USED
611
char	   *
612
att_by_name(TupleTableSlot * slot, char *attname, bool * isNull)
613
{
614
	return (GetAttributeByName(slot, attname, isNull));
615
}
616

617
#endif
618

619
static void
620
ExecEvalFuncArgs(FunctionCachePtr fcache,
621 622 623 624
				 ExprContext * econtext,
				 List * argList,
				 Datum argV[],
				 bool * argIsDone)
625
{
626 627 628 629
	int			i;
	bool		argIsNull,
			   *nullVect;
	List	   *arg;
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659

	nullVect = fcache->nullVect;

	i = 0;
	foreach(arg, argList)
	{
		/* ----------------
		 *	 evaluate the expression, in general functions cannot take
		 *	 sets as arguments but we make an exception in the case of
		 *	 nested dot expressions.  We have to watch out for this case
		 *	 here.
		 * ----------------
		 */
		argV[i] = (Datum)
			ExecEvalExpr((Node *) lfirst(arg),
						 econtext,
						 &argIsNull,
						 argIsDone);
		if (!(*argIsDone))
		{
			Assert(i == 0);
			fcache->setArg = (char *) argV[0];
			fcache->hasSetArg = true;
		}
		if (argIsNull)
			nullVect[i] = true;
		else
			nullVect[i] = false;
		i++;
	}
660 661 662
}

/* ----------------
663
 *		ExecMakeFunctionResult
664 665
 * ----------------
 */
666
static Datum
667 668 669 670 671
ExecMakeFunctionResult(Node * node,
					   List * arguments,
					   ExprContext * econtext,
					   bool * isNull,
					   bool * isDone)
672
{
673
	Datum		argv[MAXFMGRARGS];
674
	FunctionCachePtr fcache;
675 676 677
	Func	   *funcNode = NULL;
	Oper	   *operNode = NULL;
	bool		funcisset = false;
678 679 680 681 682 683 684 685 686

	/*
	 * This is kind of ugly, Func nodes now have targetlists so that we
	 * know when and what to project out from postquel function results.
	 * This means we have to pass the func node all the way down instead
	 * of using only the fcache struct as before.  ExecMakeFunctionResult
	 * becomes a little bit more of a dual personality as a result.
	 */
	if (IsA(node, Func))
687
	{
688 689
		funcNode = (Func *) node;
		fcache = funcNode->func_fcache;
690
	}
691
	else
692
	{
693 694
		operNode = (Oper *) node;
		fcache = operNode->op_fcache;
695
	}
696 697 698 699 700 701 702

	/* ----------------
	 *	arguments is a list of expressions to evaluate
	 *	before passing to the function manager.
	 *	We collect the results of evaluating the expressions
	 *	into a datum array (argv) and pass this array to arrayFmgr()
	 * ----------------
703
	 */
704 705
	if (fcache->nargs != 0)
	{
706
		bool		argDone;
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731

		if (fcache->nargs > MAXFMGRARGS)
			elog(WARN, "ExecMakeFunctionResult: too many arguments");

		/*
		 * If the setArg in the fcache is set we have an argument
		 * returning a set of tuples (i.e. a nested dot expression).  We
		 * don't want to evaluate the arguments again until the function
		 * is done. hasSetArg will always be false until we eval the args
		 * for the first time. We should set this in the parser.
		 */
		if ((fcache->hasSetArg) && fcache->setArg != NULL)
		{
			argv[0] = (Datum) fcache->setArg;
			argDone = false;
		}
		else
			ExecEvalFuncArgs(fcache, econtext, arguments, argv, &argDone);

		if ((fcache->hasSetArg) && (argDone))
		{
			if (isDone)
				*isDone = true;
			return (Datum) NULL;
		}
732
	}
733

734
	/*
735 736 737 738 739 740 741 742 743 744 745 746 747 748
	 * If this function is really a set, we have to diddle with things. If
	 * the function has already been called at least once, then the setArg
	 * field of the fcache holds the OID of this set in pg_proc.  (This is
	 * not quite legit, since the setArg field is really for functions
	 * which take sets of tuples as input - set functions take no inputs
	 * at all.	But it's a nice place to stash this value, for now.)
	 *
	 * If this is the first call of the set's function, then the call to
	 * ExecEvalFuncArgs above just returned the OID of the pg_proc tuple
	 * which defines this set.	So replace the existing funcid in the
	 * funcnode with the set's OID.  Also, we want a new fcache which
	 * points to the right function, so get that, now that we have the
	 * right OID.  Also zero out the argv, since the real set doesn't take
	 * any arguments.
749
	 */
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
	if (((Func *) node)->funcid == SetEvalRegProcedure)
	{
		funcisset = true;
		if (fcache->setArg)
		{
			argv[0] = 0;

			((Func *) node)->funcid = (Oid) PointerGetDatum(fcache->setArg);

		}
		else
		{
			((Func *) node)->funcid = (Oid) argv[0];
			setFcache(node, argv[0], NIL, econtext);
			fcache = ((Func *) node)->func_fcache;
			fcache->setArg = (char *) argv[0];
			argv[0] = (Datum) 0;
		}
768
	}
769 770 771 772 773 774 775 776

	/* ----------------
	 *	 now return the value gotten by calling the function manager,
	 *	 passing the function the evaluated parameter values.
	 * ----------------
	 */
	if (fcache->language == SQLlanguageId)
	{
777
		Datum		result;
778 779 780 781 782 783 784 785 786 787 788 789 790

		Assert(funcNode);
		result = postquel_function(funcNode, (char **) argv, isNull, isDone);

		/*
		 * finagle the situation where we are iterating through all
		 * results in a nested dot function (whose argument function
		 * returns a set of tuples) and the current function finally
		 * finishes.  We need to get the next argument in the set and run
		 * the function all over again.  This is getting unclean.
		 */
		if ((*isDone) && (fcache->hasSetArg))
		{
791
			bool		argDone;
792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827

			ExecEvalFuncArgs(fcache, econtext, arguments, argv, &argDone);

			if (argDone)
			{
				fcache->setArg = (char *) NULL;
				*isDone = true;
				result = (Datum) NULL;
			}
			else
				result = postquel_function(funcNode,
										   (char **) argv,
										   isNull,
										   isDone);
		}
		if (funcisset)
		{

			/*
			 * reset the funcid so that next call to this routine will
			 * still recognize this func as a set. Note that for now we
			 * assume that the set function in pg_proc must be a Postquel
			 * function - the funcid is not reset below for C functions.
			 */
			((Func *) node)->funcid = SetEvalRegProcedure;

			/*
			 * If we're done with the results of this function, get rid of
			 * its func cache.
			 */
			if (*isDone)
			{
				((Func *) node)->func_fcache = NULL;
			}
		}
		return result;
828
	}
829
	else
830
	{
831
		int			i;
832 833 834 835 836 837 838 839 840

		if (isDone)
			*isDone = true;
		for (i = 0; i < fcache->nargs; i++)
			if (fcache->nullVect[i] == true)
				*isNull = true;

		return ((Datum) fmgr_c(fcache->func, fcache->foid, fcache->nargs,
							   (FmgrValues *) argv, isNull));
841 842 843 844 845
	}
}


/* ----------------------------------------------------------------
846 847 848 849 850 851 852
 *		ExecEvalOper
 *		ExecEvalFunc
 *
 *		Evaluate the functional result of a list of arguments by calling the
 *		function manager.  Note that in the case of operator expressions, the
 *		optimizer had better have already replaced the operator OID with the
 *		appropriate function OID or we're hosed.
853 854
 *
 * old comments
855 856 857 858
 *		Presumably the function manager will not take null arguments, so we
 *		check for null arguments before sending the arguments to (fmgr).
 *
 *		Returns the value of the functional expression.
859 860 861 862
 * ----------------------------------------------------------------
 */

/* ----------------------------------------------------------------
863
 *		ExecEvalOper
864 865
 * ----------------------------------------------------------------
 */
866
static Datum
867
ExecEvalOper(Expr * opClause, ExprContext * econtext, bool * isNull)
868
{
869 870
	Oper	   *op;
	List	   *argList;
871
	FunctionCachePtr fcache;
872
	bool		isDone;
873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903

	/* ----------------
	 *	an opclause is a list (op args).  (I think)
	 *
	 *	we extract the oid of the function associated with
	 *	the op and then pass the work onto ExecMakeFunctionResult
	 *	which evaluates the arguments and returns the result of
	 *	calling the function on the evaluated arguments.
	 * ----------------
	 */
	op = (Oper *) opClause->oper;
	argList = opClause->args;

	/*
	 * get the fcache from the Oper node. If it is NULL, then initialize
	 * it
	 */
	fcache = op->op_fcache;
	if (fcache == NULL)
	{
		setFcache((Node *) op, op->opid, argList, econtext);
		fcache = op->op_fcache;
	}

	/* -----------
	 *	call ExecMakeFunctionResult() with a dummy isDone that we ignore.
	 *	We don't have operator whose arguments are sets.
	 * -----------
	 */
	return
		ExecMakeFunctionResult((Node *) op, argList, econtext, isNull, &isDone);
904 905 906
}

/* ----------------------------------------------------------------
907
 *		ExecEvalFunc
908 909 910
 * ----------------------------------------------------------------
 */

911
static Datum
912 913 914 915
ExecEvalFunc(Expr * funcClause,
			 ExprContext * econtext,
			 bool * isNull,
			 bool * isDone)
916
{
917 918
	Func	   *func;
	List	   *argList;
919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
	FunctionCachePtr fcache;

	/* ----------------
	 *	an funcclause is a list (func args).  (I think)
	 *
	 *	we extract the oid of the function associated with
	 *	the func node and then pass the work onto ExecMakeFunctionResult
	 *	which evaluates the arguments and returns the result of
	 *	calling the function on the evaluated arguments.
	 *
	 *	this is nearly identical to the ExecEvalOper code.
	 * ----------------
	 */
	func = (Func *) funcClause->oper;
	argList = funcClause->args;

	/*
	 * get the fcache from the Func node. If it is NULL, then initialize
	 * it
	 */
	fcache = func->func_fcache;
	if (fcache == NULL)
	{
		setFcache((Node *) func, func->funcid, argList, econtext);
		fcache = func->func_fcache;
	}

	return
		ExecMakeFunctionResult((Node *) func, argList, econtext, isNull, isDone);
948 949 950
}

/* ----------------------------------------------------------------
951 952 953
 *		ExecEvalNot
 *		ExecEvalOr
 *		ExecEvalAnd
954
 *
955 956 957 958 959 960 961 962 963
 *		Evaluate boolean expressions.  Evaluation of 'or' is
 *		short-circuited when the first true (or null) value is found.
 *
 *		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...
964 965
 * ----------------------------------------------------------------
 */
966
static Datum
967
ExecEvalNot(Expr * notclause, ExprContext * econtext, bool * isNull)
968
{
969 970 971
	Datum		expr_value;
	Node	   *clause;
	bool		isDone;
972 973

	clause = lfirst(notclause->args);
974 975

	/* ----------------
976 977
	 *	We don't iterate over sets in the quals, so pass in an isDone
	 *	flag, but ignore it.
978 979
	 * ----------------
	 */
980 981
	expr_value = ExecEvalExpr(clause, econtext, isNull, &isDone);

982
	/* ----------------
983 984
	 *	if the expression evaluates to null, then we just
	 *	cascade the null back to whoever called us.
985 986 987
	 * ----------------
	 */
	if (*isNull)
988 989
		return expr_value;

990
	/* ----------------
991 992
	 *	evaluation of 'not' is simple.. expr is false, then
	 *	return 'true' and vice versa.
993 994
	 * ----------------
	 */
995 996 997 998
	if (DatumGetInt32(expr_value) == 0)
		return (Datum) true;

	return (Datum) false;
999 1000 1001
}

/* ----------------------------------------------------------------
1002
 *		ExecEvalOr
1003 1004
 * ----------------------------------------------------------------
 */
1005
static Datum
1006
ExecEvalOr(Expr * orExpr, ExprContext * econtext, bool * isNull)
1007
{
1008 1009 1010 1011 1012
	List	   *clauses;
	List	   *clause;
	bool		isDone;
	bool		IsNull;
	Datum		const_value = 0;
1013 1014 1015 1016

	IsNull = false;
	clauses = orExpr->args;

1017
	/* ----------------
1018 1019 1020 1021 1022 1023 1024 1025 1026
	 *	we use three valued logic functions here...
	 *	we evaluate each of the clauses in turn,
	 *	as soon as one is true we return that
	 *	value.	If none is true and  none of the
	 *	clauses evaluate to NULL we return
	 *	the value of the last clause evaluated (which
	 *	should be false) with *isNull set to false else
	 *	if none is true and at least one clause evaluated
	 *	to NULL we set *isNull flag to true -
1027 1028
	 * ----------------
	 */
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
	foreach(clause, clauses)
	{

		/* ----------------
		 *	We don't iterate over sets in the quals, so pass in an isDone
		 *	flag, but ignore it.
		 * ----------------
		 */
		const_value = ExecEvalExpr((Node *) lfirst(clause),
								   econtext,
								   isNull,
								   &isDone);

		/* ----------------
		 *	if the expression evaluates to null, then we
		 *	remember it in the local IsNull flag, if none of the
		 *	clauses are true then we need to set *isNull
		 *	to true again.
		 * ----------------
		 */
		if (*isNull)
			IsNull = *isNull;

		/* ----------------
		 *	 if we have a true result, then we return it.
		 * ----------------
		 */
		if (DatumGetInt32(const_value) != 0)
			return const_value;
	}

	/* IsNull is true if at least one clause evaluated to NULL */
	*isNull = IsNull;
	return const_value;
}

/* ----------------------------------------------------------------
 *		ExecEvalAnd
 * ----------------------------------------------------------------
 */
1069
static Datum
1070 1071
ExecEvalAnd(Expr * andExpr, ExprContext * econtext, bool * isNull)
{
1072 1073 1074 1075 1076
	List	   *clauses;
	List	   *clause;
	Datum		const_value = 0;
	bool		isDone;
	bool		IsNull;
1077 1078 1079 1080 1081

	IsNull = false;

	clauses = andExpr->args;

1082
	/* ----------------
1083 1084 1085 1086 1087
	 *	we evaluate each of the clauses in turn,
	 *	as soon as one is false we return that
	 *	value.	If none are false or NULL then we return
	 *	the value of the last clause evaluated, which
	 *	should be true.
1088 1089
	 * ----------------
	 */
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
	foreach(clause, clauses)
	{

		/* ----------------
		 *	We don't iterate over sets in the quals, so pass in an isDone
		 *	flag, but ignore it.
		 * ----------------
		 */
		const_value = ExecEvalExpr((Node *) lfirst(clause),
								   econtext,
								   isNull,
								   &isDone);

		/* ----------------
		 *	if the expression evaluates to null, then we
		 *	remember it in IsNull, if none of the clauses after
		 *	this evaluates to false we will have to set *isNull
		 *	to true again.
		 * ----------------
		 */
		if (*isNull)
			IsNull = *isNull;

		/* ----------------
		 *	 if we have a false result, then we return it, since the
		 *	 conjunction must be false.
		 * ----------------
		 */
		if (DatumGetInt32(const_value) == 0)
			return const_value;
	}

	*isNull = IsNull;
	return const_value;
1124 1125
}

1126 1127 1128 1129
/* ----------------------------------------------------------------
 *		ExecEvalExpr
 *
 *		Recursively evaluate a targetlist or qualification expression.
1130
 *
1131 1132
 *		This routine is an inner loop routine and should be as fast
 *		as possible.
1133
 *
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
 *		Node comparison functions were replaced by macros for speed and to plug
 *		memory leaks incurred by using the planner's Lispy stuff for
 *		comparisons.  Order of evaluation of node comparisons IS IMPORTANT;
 *		the macros do no checks.  Order of evaluation:
 *
 *		o an isnull check, largely to avoid coredumps since greg doubts this
 *		  routine is called with a null ptr anyway in proper operation, but is
 *		  not completely sure...
 *		o ExactNodeType checks.
 *		o clause checks or other checks where we look at the lfirst of something.
1144 1145 1146
 * ----------------------------------------------------------------
 */
Datum
1147 1148 1149 1150
ExecEvalExpr(Node * expression,
			 ExprContext * econtext,
			 bool * isNull,
			 bool * isDone)
1151
{
1152
	Datum		retDatum = 0;
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175

	*isNull = false;

	/*
	 * Some callers don't care about is done and only want 1 result.  They
	 * indicate this by passing NULL
	 */
	if (isDone)
		*isDone = true;

	/* ----------------
	 *	here we dispatch the work to the appropriate type
	 *	of function given the type of our expression.
	 * ----------------
	 */
	if (expression == NULL)
	{
		*isNull = true;
		return (Datum) true;
	}

	switch (nodeTag(expression))
	{
1176 1177 1178 1179 1180 1181
		case T_Var:
			retDatum = (Datum) ExecEvalVar((Var *) expression, econtext, isNull);
			break;
		case T_Const:
			{
				Const	   *con = (Const *) expression;
1182

1183 1184 1185 1186 1187 1188 1189
				if (con->constisnull)
					*isNull = true;
				retDatum = con->constvalue;
				break;
			}
		case T_Param:
			retDatum = (Datum) ExecEvalParam((Param *) expression, econtext, isNull);
1190
			break;
1191 1192
		case T_Iter:
			retDatum = (Datum) ExecEvalIter((Iter *) expression,
1193 1194 1195
											econtext,
											isNull,
											isDone);
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
			break;
		case T_Aggreg:
			retDatum = (Datum) ExecEvalAggreg((Aggreg *) expression,
											  econtext,
											  isNull);
			break;
		case T_ArrayRef:
			retDatum = (Datum) ExecEvalArrayRef((ArrayRef *) expression,
												econtext,
												isNull,
												isDone);
			break;
		case T_Expr:
1209
			{
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
				Expr	   *expr = (Expr *) expression;

				switch (expr->opType)
				{
					case OP_EXPR:
						retDatum = (Datum) ExecEvalOper(expr, econtext, isNull);
						break;
					case FUNC_EXPR:
						retDatum = (Datum) ExecEvalFunc(expr, econtext, isNull, isDone);
						break;
					case OR_EXPR:
						retDatum = (Datum) ExecEvalOr(expr, econtext, isNull);
						break;
					case AND_EXPR:
						retDatum = (Datum) ExecEvalAnd(expr, econtext, isNull);
						break;
					case NOT_EXPR:
						retDatum = (Datum) ExecEvalNot(expr, econtext, isNull);
						break;
					default:
						elog(WARN, "ExecEvalExpr: unknown expression type");
						break;
				}
1233 1234
				break;
			}
1235 1236
		default:
			elog(WARN, "ExecEvalExpr: unknown expression type");
1237
			break;
1238
	}
1239 1240

	return retDatum;
1241 1242 1243
}

/* ----------------------------------------------------------------
1244
 *					 ExecQual / ExecTargetList
1245 1246 1247 1248
 * ----------------------------------------------------------------
 */

/* ----------------------------------------------------------------
1249
 *		ExecQualClause
1250
 *
1251 1252 1253 1254 1255 1256
 *		this is a workhorse for ExecQual.  ExecQual has to deal
 *		with a list of qualifications, so it passes each qualification
 *		in the list to this function one at a time.  ExecQualClause
 *		returns true when the qualification *fails* and false if
 *		the qualification succeeded (meaning we have to test the
 *		rest of the qualification)
1257 1258
 * ----------------------------------------------------------------
 */
1259
static bool
1260
ExecQualClause(Node * clause, ExprContext * econtext)
1261
{
1262 1263 1264
	Datum		expr_value;
	bool		isNull;
	bool		isDone;
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294

	/* when there is a null clause, consider the qualification to be true */
	if (clause == NULL)
		return true;

	/*
	 * pass isDone, but ignore it.	We don't iterate over multiple returns
	 * in the qualifications.
	 */
	expr_value = (Datum)
		ExecEvalExpr(clause, econtext, &isNull, &isDone);

	/* ----------------
	 *	this is interesting behaviour here.  When a clause evaluates
	 *	to null, then we consider this as passing the qualification.
	 *	it seems kind of like, if the qual is NULL, then there's no
	 *	qual..
	 * ----------------
	 */
	if (isNull)
		return true;

	/* ----------------
	 *	remember, we return true when the qualification fails..
	 * ----------------
	 */
	if (DatumGetInt32(expr_value) == 0)
		return true;

	return false;
1295 1296 1297
}

/* ----------------------------------------------------------------
1298 1299 1300 1301
 *		ExecQual
 *
 *		Evaluates a conjunctive boolean expression and returns t
 *		iff none of the subexpressions are false (or null).
1302 1303 1304
 * ----------------------------------------------------------------
 */
bool
1305
ExecQual(List * qual, ExprContext * econtext)
1306
{
1307 1308
	List	   *clause;
	bool		result;
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349

	/* ----------------
	 *	debugging stuff
	 * ----------------
	 */
	EV_printf("ExecQual: qual is ");
	EV_nodeDisplay(qual);
	EV_printf("\n");

	IncrProcessed();

	/* ----------------
	 *	return true immediately if no qual
	 * ----------------
	 */
	if (qual == NIL)
		return true;

	/* ----------------
	 *	a "qual" is a list of clauses.	To evaluate the
	 *	qual, we evaluate each of the clauses in the list.
	 *
	 *	ExecQualClause returns true when we know the qualification
	 *	*failed* so we just pass each clause in qual to it until
	 *	we know the qual failed or there are no more clauses.
	 * ----------------
	 */
	result = false;
	foreach(clause, qual)
	{
		result = ExecQualClause((Node *) lfirst(clause), econtext);
		if (result == true)
			break;
	}

	/* ----------------
	 *	if result is true, then it means a clause failed so we
	 *	return false.  if result is false then it means no clause
	 *	failed so we return true.
	 * ----------------
	 */
1350
	if (result == true)
1351 1352 1353
		return false;

	return true;
1354 1355 1356
}

int
1357
ExecTargetListLength(List * targetlist)
1358
{
1359 1360 1361
	int			len;
	List	   *tl;
	TargetEntry *curTle;
1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373

	len = 0;
	foreach(tl, targetlist)
	{
		curTle = lfirst(tl);

		if (curTle->resdom != NULL)
			len++;
		else
			len += curTle->fjoin->fj_nNodes;
	}
	return len;
1374 1375 1376
}

/* ----------------------------------------------------------------
1377 1378 1379 1380
 *		ExecTargetList
 *
 *		Evaluates a targetlist with respect to the current
 *		expression context and return a tuple.
1381 1382
 * ----------------------------------------------------------------
 */
1383
static HeapTuple
1384 1385 1386 1387 1388 1389
ExecTargetList(List * targetlist,
			   int nodomains,
			   TupleDesc targettype,
			   Datum * values,
			   ExprContext * econtext,
			   bool * isDone)
1390
{
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
	char		nulls_array[64];
	bool		fjNullArray[64];
	bool	   *fjIsNull;
	char	   *null_head;
	List	   *tl;
	TargetEntry *tle;
	Node	   *expr;
	Resdom	   *resdom;
	AttrNumber	resind;
	Datum		constvalue;
	HeapTuple	newTuple;
	bool		isNull;
1403

1404
	/* ----------------
1405
	 *	debugging stuff
1406 1407
	 * ----------------
	 */
1408 1409 1410 1411
	EV_printf("ExecTargetList: tl is ");
	EV_nodeDisplay(targetlist);
	EV_printf("\n");

1412
	/* ----------------
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
	 * Return a dummy tuple if the targetlist is empty .
	 * the dummy tuple is necessary to differentiate
	 * between passing and failing the qualification.
	 * ----------------
	 */
	if (targetlist == NIL)
	{
		/* ----------------
		 *		I now think that the only time this makes
		 *		any sence is when we run a delete query.  Then
		 *		we need to return something other than nil
		 *		so we know to delete the tuple associated
		 *		with the saved tupleid.. see what ExecutePlan
		 *		does with the returned tuple.. -cim 9/21/89
		 *
		 *		It could also happen in queries like:
		 *			retrieve (foo.all) where bar.a = 3
		 *
		 *		is this a new phenomenon? it might cause bogus behavior
		 *		if we try to free this tuple later!! I put a hook in
		 *		ExecProject to watch out for this case -mer 24 Aug 1992
		 * ----------------
		 */
		CXT1_printf("ExecTargetList: context is %d\n", CurrentMemoryContext);
		*isDone = true;
		return (HeapTuple) true;
	}

	/* ----------------
	 *	allocate an array of char's to hold the "null" information
	 *	only if we have a really large targetlist.	otherwise we use
	 *	the stack.
1445 1446
	 * ----------------
	 */
1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498
	if (nodomains > 64)
	{
		null_head = (char *) palloc(nodomains + 1);
		fjIsNull = (bool *) palloc(nodomains + 1);
	}
	else
	{
		null_head = &nulls_array[0];
		fjIsNull = &fjNullArray[0];
	}

	/* ----------------
	 *	evaluate all the expressions in the target list
	 * ----------------
	 */
	EV_printf("ExecTargetList: setting target list values\n");

	*isDone = true;
	foreach(tl, targetlist)
	{
		/* ----------------
		 *	  remember, a target list is a list of lists:
		 *
		 *		((<resdom | fjoin> expr) (<resdom | fjoin> expr) ...)
		 *
		 *	  tl is a pointer to successive cdr's of the targetlist
		 *	  tle is a pointer to the target list entry in tl
		 * ----------------
		 */
		tle = lfirst(tl);

		if (tle->resdom != NULL)
		{
			expr = tle->expr;
			resdom = tle->resdom;
			resind = resdom->resno - 1;
			constvalue = (Datum) ExecEvalExpr(expr,
											  econtext,
											  &isNull,
											  isDone);

			if ((IsA(expr, Iter)) && (*isDone))
				return (HeapTuple) NULL;

			values[resind] = constvalue;

			if (!isNull)
				null_head[resind] = ' ';
			else
				null_head[resind] = 'n';
		}
		else
1499
		{
1500 1501 1502 1503 1504 1505
			int			curNode;
			Resdom	   *fjRes;
			List	   *fjTlist = (List *) tle->expr;
			Fjoin	   *fjNode = tle->fjoin;
			int			nNodes = fjNode->fj_nNodes;
			DatumPtr	results = fjNode->fj_results;
1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531

			ExecEvalFjoin(tle, econtext, fjIsNull, isDone);
			if (*isDone)
				return (HeapTuple) NULL;

			/*
			 * get the result from the inner node
			 */
			fjRes = (Resdom *) fjNode->fj_innerNode;
			resind = fjRes->resno - 1;
			if (fjIsNull[0])
				null_head[resind] = 'n';
			else
			{
				null_head[resind] = ' ';
				values[resind] = results[0];
			}

			/*
			 * Get results from all of the outer nodes
			 */
			for (curNode = 1;
				 curNode < nNodes;
				 curNode++, fjTlist = lnext(fjTlist))
			{
#if 0							/* what is this?? */
1532
				Node	   *outernode = lfirst(fjTlist);
1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546

				fjRes = (Resdom *) outernode->iterexpr;
#endif
				resind = fjRes->resno - 1;
				if (fjIsNull[curNode])
				{
					null_head[resind] = 'n';
				}
				else
				{
					null_head[resind] = ' ';
					values[resind] = results[curNode];
				}
			}
1547 1548
		}
	}
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565

	/* ----------------
	 *	form the new result tuple (in the "normal" context)
	 * ----------------
	 */
	newTuple = (HeapTuple)
		heap_formtuple(targettype, values, null_head);

	/* ----------------
	 *	free the nulls array if we allocated one..
	 * ----------------
	 */
	if (nodomains > 64)
		pfree(null_head);

	return
		newTuple;
1566 1567 1568
}

/* ----------------------------------------------------------------
1569 1570 1571 1572
 *		ExecProject
 *
 *		projects a tuple based in projection info and stores
 *		it in the specified tuple table slot.
1573
 *
1574 1575 1576 1577 1578
 *		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
1579 1580 1581
 * ----------------------------------------------------------------
 */
TupleTableSlot *
1582
ExecProject(ProjectionInfo * projInfo, bool * isDone)
1583
{
1584
	TupleTableSlot *slot;
1585 1586 1587 1588 1589 1590
	List	   *targetlist;
	int			len;
	TupleDesc	tupType;
	Datum	   *tupValue;
	ExprContext *econtext;
	HeapTuple	newTuple;
1591 1592 1593 1594 1595 1596 1597

	/* ----------------
	 *	sanity checks
	 * ----------------
	 */
	if (projInfo == NULL)
		return (TupleTableSlot *) NULL;
1598

1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641
	/* ----------------
	 *	get the projection info we want
	 * ----------------
	 */
	slot = projInfo->pi_slot;
	targetlist = projInfo->pi_targetlist;
	len = projInfo->pi_len;
	tupType = slot->ttc_tupleDescriptor;

	tupValue = projInfo->pi_tupValue;
	econtext = projInfo->pi_exprContext;

	if (targetlist == NIL)
	{
		*isDone = true;
		return (TupleTableSlot *) NULL;
	}

	/* ----------------
	 *	form a new (result) tuple
	 * ----------------
	 */
	newTuple = ExecTargetList(targetlist,
							  len,
							  tupType,
							  tupValue,
							  econtext,
							  isDone);

	/* ----------------
	 *	store the tuple in the projection slot and return the slot.
	 *
	 *	If there's no projection target list we don't want to pfree
	 *	the bogus tuple that ExecTargetList passes back to us.
	 *		 -mer 24 Aug 1992
	 * ----------------
	 */
	return (TupleTableSlot *)
		ExecStoreTuple(newTuple,/* tuple to store */
					   slot,	/* slot to store in */
					   InvalidBuffer,	/* tuple has no buffer */
					   true);
}