clauses.c 62.1 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * clauses.c
4
 *	  routines to manipulate qualification clauses
5
 *
6
 * Portions Copyright (c) 1996-2001, 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
Bruce Momjian's avatar
Bruce Momjian committed
11
 *	  $Header: /cvsroot/pgsql/src/backend/optimizer/util/clauses.c,v 1.81 2001/02/12 18:46:40 momjian Exp $
12 13
 *
 * HISTORY
14 15
 *	  AUTHOR			DATE			MAJOR EVENT
 *	  Andrew Yu			Nov 3, 1994		clause.c and clauses.c combined
16 17 18 19 20 21
 *
 *-------------------------------------------------------------------------
 */

#include "postgres.h"

22
#include "catalog/pg_operator.h"
23 24 25
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "executor/executor.h"
26 27 28
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/clauses.h"
29
#include "optimizer/tlist.h"
30
#include "optimizer/var.h"
31
#include "parser/parsetree.h"
32
#include "utils/datum.h"
Bruce Momjian's avatar
Bruce Momjian committed
33
#include "utils/lsyscache.h"
34
#include "utils/syscache.h"
35

36

37 38 39 40 41
/* note that pg_type.h hardwires size of bool as 1 ... duplicate it */
#define MAKEBOOLCONST(val,isnull) \
	((Node *) makeConst(BOOLOID, 1, (Datum) (val), \
						(isnull), true, false, false))

42
static bool contain_agg_clause_walker(Node *node, void *context);
43
static bool pull_agg_clause_walker(Node *node, List **listptr);
44 45
static bool contain_subplans_walker(Node *node, void *context);
static bool pull_subplans_walker(Node *node, List **listptr);
46
static bool check_subplans_for_ungrouped_vars_walker(Node *node,
47
										 Query *context);
48
static bool contain_noncachable_functions_walker(Node *node, void *context);
49 50
static int	is_single_func(Node *node);
static Node *eval_const_expressions_mutator(Node *node, void *context);
51
static Expr *simplify_op_or_func(Expr *expr, List *args);
52

53

54
Expr *
55
make_clause(int type, Node *oper, List *args)
56
{
57 58 59
	Expr	   *expr = makeNode(Expr);

	switch (type)
60
	{
61 62 63 64 65 66 67 68 69 70 71 72 73 74
		case AND_EXPR:
		case OR_EXPR:
		case NOT_EXPR:
			expr->typeOid = BOOLOID;
			break;
		case OP_EXPR:
			expr->typeOid = ((Oper *) oper)->opresulttype;
			break;
		case FUNC_EXPR:
			expr->typeOid = ((Func *) oper)->functype;
			break;
		default:
			elog(ERROR, "make_clause: unsupported type %d", type);
			break;
75
	}
76 77 78 79
	expr->opType = type;
	expr->oper = oper;			/* ignored for AND, OR, NOT */
	expr->args = args;
	return expr;
80 81 82 83
}


/*****************************************************************************
84
 *		OPERATOR clause functions
85 86 87
 *****************************************************************************/


88
/*
89
 * is_opclause
90
 *
91
 * Returns t iff the clause is an operator clause:
92
 *				(op expr expr) or (op expr).
93 94
 *
 * [historical note: is_clause has the exact functionality and is used
95 96
 *		throughout the code. They're renamed to is_opclause for clarity.
 *												- ay 10/94.]
97 98
 */
bool
99
is_opclause(Node *clause)
100
{
101
	return (clause != NULL &&
102 103
			IsA(clause, Expr) &&
			((Expr *) clause)->opType == OP_EXPR);
104 105
}

106
/*
107
 * make_opclause
108 109 110
 *	  Creates a clause given its operator left operand and right
 *	  operand (if it is non-null).
 *
111
 */
112
Expr *
113
make_opclause(Oper *op, Var *leftop, Var *rightop)
114
{
115
	Expr	   *expr = makeNode(Expr);
116

117
	expr->typeOid = op->opresulttype;
118 119
	expr->opType = OP_EXPR;
	expr->oper = (Node *) op;
120
	if (rightop)
121
		expr->args = makeList2(leftop, rightop);
122
	else
123
		expr->args = makeList1(leftop);
124
	return expr;
125 126
}

127
/*
128
 * get_leftop
129
 *
130
 * Returns the left operand of a clause of the form (op expr expr)
131
 *		or (op expr)
132 133 134 135
 *
 * NB: for historical reasons, the result is declared Var *, even
 * though many callers can cope with results that are not Vars.
 * The result really ought to be declared Expr * or Node *.
136
 */
137
Var *
138
get_leftop(Expr *clause)
139
{
140
	if (clause->args != NULL)
141
		return lfirst(clause->args);
142 143
	else
		return NULL;
144 145
}

146
/*
147
 * get_rightop
148
 *
149
 * Returns the right operand in a clause of the form (op expr expr).
150
 * NB: result will be NULL if applied to a unary op clause.
151
 */
152
Var *
153
get_rightop(Expr *clause)
154
{
155
	if (clause->args != NULL && lnext(clause->args) != NULL)
156
		return lfirst(lnext(clause->args));
157 158
	else
		return NULL;
159 160 161
}

/*****************************************************************************
162
 *		FUNC clause functions
163 164
 *****************************************************************************/

165
/*
166
 * is_funcclause
167
 *
168
 * Returns t iff the clause is a function clause: (func { expr }).
169
 *
170 171
 */
bool
172
is_funcclause(Node *clause)
173
{
174
	return (clause != NULL &&
175
			IsA(clause, Expr) &&
176
			((Expr *) clause)->opType == FUNC_EXPR);
177 178
}

179
/*
180
 * make_funcclause
181
 *
182 183
 * Creates a function clause given the FUNC node and the functional
 * arguments.
184
 *
185
 */
186
Expr *
187
make_funcclause(Func *func, List *funcargs)
188
{
189
	Expr	   *expr = makeNode(Expr);
190

191
	expr->typeOid = func->functype;
192 193 194 195
	expr->opType = FUNC_EXPR;
	expr->oper = (Node *) func;
	expr->args = funcargs;
	return expr;
196 197 198
}

/*****************************************************************************
199
 *		OR clause functions
200 201
 *****************************************************************************/

202
/*
203
 * or_clause
204
 *
205
 * Returns t iff the clause is an 'or' clause: (OR { expr }).
206
 *
207 208
 */
bool
209
or_clause(Node *clause)
210
{
211 212 213
	return (clause != NULL &&
			IsA(clause, Expr) &&
			((Expr *) clause)->opType == OR_EXPR);
214 215
}

216
/*
217
 * make_orclause
218
 *
219
 * Creates an 'or' clause given a list of its subclauses.
220
 *
221
 */
222
Expr *
223
make_orclause(List *orclauses)
224
{
225
	Expr	   *expr = makeNode(Expr);
226

227
	expr->typeOid = BOOLOID;
228 229 230 231
	expr->opType = OR_EXPR;
	expr->oper = NULL;
	expr->args = orclauses;
	return expr;
232 233 234
}

/*****************************************************************************
235
 *		NOT clause functions
236 237
 *****************************************************************************/

238
/*
239
 * not_clause
240
 *
241
 * Returns t iff this is a 'not' clause: (NOT expr).
242
 *
243 244
 */
bool
245
not_clause(Node *clause)
246
{
247
	return (clause != NULL &&
248
			IsA(clause, Expr) &&
249
			((Expr *) clause)->opType == NOT_EXPR);
250 251
}

252
/*
253
 * make_notclause
254
 *
255
 * Create a 'not' clause given the expression to be negated.
256
 *
257
 */
258
Expr *
259
make_notclause(Expr *notclause)
260
{
261
	Expr	   *expr = makeNode(Expr);
262

263
	expr->typeOid = BOOLOID;
264 265
	expr->opType = NOT_EXPR;
	expr->oper = NULL;
266
	expr->args = makeList1(notclause);
267
	return expr;
268 269
}

270
/*
271
 * get_notclausearg
272
 *
273
 * Retrieve the clause within a 'not' clause
274
 *
275
 */
276
Expr *
277
get_notclausearg(Expr *notclause)
278
{
279
	return lfirst(notclause->args);
280 281 282
}

/*****************************************************************************
283
 *		AND clause functions
284 285 286
 *****************************************************************************/


287
/*
288
 * and_clause
289
 *
290
 * Returns t iff its argument is an 'and' clause: (AND { expr }).
291
 *
292 293
 */
bool
294
and_clause(Node *clause)
295
{
296
	return (clause != NULL &&
297
			IsA(clause, Expr) &&
298
			((Expr *) clause)->opType == AND_EXPR);
299
}
300 301

/*
302
 * make_andclause
303
 *
304 305
 * Create an 'and' clause given its arguments in a list.
 */
306
Expr *
307
make_andclause(List *andclauses)
308
{
309
	Expr	   *expr = makeNode(Expr);
310

311
	expr->typeOid = BOOLOID;
312 313 314 315
	expr->opType = AND_EXPR;
	expr->oper = NULL;
	expr->args = andclauses;
	return expr;
316 317
}

318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
/*
 * make_and_qual
 *
 * Variant of make_andclause for ANDing two qual conditions together.
 * Qual conditions have the property that a NULL nodetree is interpreted
 * as 'true'.
 */
Node *
make_and_qual(Node *qual1, Node *qual2)
{
	if (qual1 == NULL)
		return qual2;
	if (qual2 == NULL)
		return qual1;
	return (Node *) make_andclause(makeList2(qual1, qual2));
}

335
/*
336 337 338 339 340 341 342
 * Sometimes (such as in the result of canonicalize_qual or the input of
 * ExecQual), we use lists of expression nodes with implicit AND semantics.
 *
 * These functions convert between an AND-semantics expression list and the
 * ordinary representation of a boolean expression.
 *
 * Note that an empty list is considered equivalent to TRUE.
343 344 345 346 347
 */
Expr *
make_ands_explicit(List *andclauses)
{
	if (andclauses == NIL)
348 349
		return (Expr *) MAKEBOOLCONST(true, false);
	else if (lnext(andclauses) == NIL)
350 351 352 353
		return (Expr *) lfirst(andclauses);
	else
		return make_andclause(andclauses);
}
354

355 356 357
List *
make_ands_implicit(Expr *clause)
{
358

359 360 361
	/*
	 * NB: because the parser sets the qual field to NULL in a query that
	 * has no WHERE clause, we must consider a NULL input clause as TRUE,
362 363
	 * even though one might more reasonably think it FALSE.  Grumble. If
	 * this causes trouble, consider changing the parser's behavior.
364
	 */
365
	if (clause == NULL)
366
		return NIL;				/* NULL -> NIL list == TRUE */
367 368
	else if (and_clause((Node *) clause))
		return clause->args;
369
	else if (IsA(clause, Const) &&
370
			 !((Const *) clause)->constisnull &&
371
			 DatumGetBool(((Const *) clause)->constvalue))
372
		return NIL;				/* constant TRUE input -> NIL list */
373
	else
374
		return makeList1(clause);
375 376
}

377

378
/*****************************************************************************
379
 *		Aggregate-function clause manipulation
380 381
 *****************************************************************************/

382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
/*
 * contain_agg_clause
 *	  Recursively search for Aggref nodes within a clause.
 *
 *	  Returns true if any aggregate found.
 */
bool
contain_agg_clause(Node *clause)
{
	return contain_agg_clause_walker(clause, NULL);
}

static bool
contain_agg_clause_walker(Node *node, void *context)
{
	if (node == NULL)
		return false;
	if (IsA(node, Aggref))
400 401
		return true;			/* abort the tree traversal and return
								 * true */
402 403 404
	return expression_tree_walker(node, contain_agg_clause_walker, context);
}

405 406 407 408 409 410
/*
 * pull_agg_clause
 *	  Recursively pulls all Aggref nodes from an expression tree.
 *
 *	  Returns list of Aggref nodes found.  Note the nodes themselves are not
 *	  copied, only referenced.
411 412
 *
 *	  Note: this also checks for nested aggregates, which are an error.
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
 */
List *
pull_agg_clause(Node *clause)
{
	List	   *result = NIL;

	pull_agg_clause_walker(clause, &result);
	return result;
}

static bool
pull_agg_clause_walker(Node *node, List **listptr)
{
	if (node == NULL)
		return false;
	if (IsA(node, Aggref))
	{
		*listptr = lappend(*listptr, node);
431

432 433 434
		/*
		 * Complain if the aggregate's argument contains any aggregates;
		 * nested agg functions are semantically nonsensical.
435
		 */
436 437
		if (contain_agg_clause(((Aggref *) node)->target))
			elog(ERROR, "Aggregate function calls may not be nested");
438

439 440 441 442
		/*
		 * Having checked that, we need not recurse into the argument.
		 */
		return false;
443 444 445 446 447
	}
	return expression_tree_walker(node, pull_agg_clause_walker,
								  (void *) listptr);
}

448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475

/*****************************************************************************
 *		Subplan clause manipulation
 *****************************************************************************/

/*
 * contain_subplans
 *	  Recursively search for subplan nodes within a clause.
 *
 * If we see a SubLink node, we will return TRUE.  This is only possible if
 * the expression tree hasn't yet been transformed by subselect.c.  We do not
 * know whether the node will produce a true subplan or just an initplan,
 * but we make the conservative assumption that it will be a subplan.
 *
 * Returns true if any subplan found.
 */
bool
contain_subplans(Node *clause)
{
	return contain_subplans_walker(clause, NULL);
}

static bool
contain_subplans_walker(Node *node, void *context)
{
	if (node == NULL)
		return false;
	if (is_subplan(node) || IsA(node, SubLink))
476 477
		return true;			/* abort the tree traversal and return
								 * true */
478 479 480 481 482 483 484
	return expression_tree_walker(node, contain_subplans_walker, context);
}

/*
 * pull_subplans
 *	  Recursively pulls all subplans from an expression tree.
 *
485
 *	  Returns list of subplan nodes found.	Note the nodes themselves are not
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
 *	  copied, only referenced.
 */
List *
pull_subplans(Node *clause)
{
	List	   *result = NIL;

	pull_subplans_walker(clause, &result);
	return result;
}

static bool
pull_subplans_walker(Node *node, List **listptr)
{
	if (node == NULL)
		return false;
	if (is_subplan(node))
	{
		*listptr = lappend(*listptr, ((Expr *) node)->oper);
		/* fall through to check args to subplan */
	}
	return expression_tree_walker(node, pull_subplans_walker,
								  (void *) listptr);
}

511 512 513
/*
 * check_subplans_for_ungrouped_vars
 *		Check for subplans that are being passed ungrouped variables as
514
 *		parameters; generate an error message if any are found.
515 516
 *
 * In most contexts, ungrouped variables will be detected by the parser (see
517 518
 * parse_agg.c, check_ungrouped_columns()). But that routine currently does
 * not check subplans, because the necessary info is not computed until the
519 520
 * planner runs.  So we do it here, after we have processed sublinks into
 * subplans.  This ought to be cleaned up someday.
521 522
 *
 * 'clause' is the expression tree to be searched for subplans.
523 524
 * 'query' provides the GROUP BY list, the target list that the group clauses
 * refer to, and the range table.
525
 */
526
void
527
check_subplans_for_ungrouped_vars(Node *clause,
528
								  Query *query)
529
{
530 531 532 533 534

	/*
	 * No special setup needed; context for walker is just the Query
	 * pointer
	 */
535
	check_subplans_for_ungrouped_vars_walker(clause, query);
536 537 538 539
}

static bool
check_subplans_for_ungrouped_vars_walker(Node *node,
540
										 Query *context)
541 542 543
{
	if (node == NULL)
		return false;
544

545
	/*
546 547
	 * We can ignore Vars other than in subplan args lists, since the
	 * parser already checked 'em.
548 549 550
	 */
	if (is_subplan(node))
	{
551

552 553 554 555
		/*
		 * The args list of the subplan node represents attributes from
		 * outside passed into the sublink.
		 */
556
		List	   *t;
557 558 559 560

		foreach(t, ((Expr *) node)->args)
		{
			Node	   *thisarg = lfirst(t);
561 562
			Var		   *var;
			bool		contained_in_group_clause;
563 564
			List	   *gl;

565 566 567
			/*
			 * We do not care about args that are not local variables;
			 * params or outer-level vars are not our responsibility to
568 569
			 * check.  (The outer-level query passing them to us needs to
			 * worry, instead.)
570
			 */
571
			if (!IsA(thisarg, Var))
572 573 574 575 576 577 578 579 580
				continue;
			var = (Var *) thisarg;
			if (var->varlevelsup > 0)
				continue;

			/*
			 * Else, see if it is a grouping column.
			 */
			contained_in_group_clause = false;
581
			foreach(gl, context->groupClause)
582
			{
583 584
				GroupClause *gcl = lfirst(gl);
				Node	   *groupexpr;
585 586 587 588 589 590 591 592 593 594 595

				groupexpr = get_sortgroupclause_expr(gcl,
													 context->targetList);
				if (equal(thisarg, groupexpr))
				{
					contained_in_group_clause = true;
					break;
				}
			}

			if (!contained_in_group_clause)
596 597
			{
				/* Found an ungrouped argument.  Complain. */
598 599
				RangeTblEntry *rte;
				char	   *attname;
600 601

				Assert(var->varno > 0 &&
602
					   (int) var->varno <= length(context->rtable));
603
				rte = rt_fetch(var->varno, context->rtable);
604
				attname = get_rte_attribute_name(rte, var->varattno);
605
				elog(ERROR, "Sub-SELECT uses un-GROUPed attribute %s.%s from outer query",
606
					 rte->eref->relname, attname);
607
			}
608 609 610
		}
	}
	return expression_tree_walker(node,
611
								check_subplans_for_ungrouped_vars_walker,
612 613 614 615
								  (void *) context);
}


616
/*****************************************************************************
617
 *		Check clauses for noncachable functions
618 619
 *****************************************************************************/

620 621 622 623 624 625 626 627 628 629 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 660 661 662 663 664 665 666 667 668
/*
 * contain_noncachable_functions
 *	  Recursively search for noncachable functions within a clause.
 *
 * Returns true if any noncachable function (or operator implemented by a
 * noncachable function) is found.  This test is needed so that we don't
 * mistakenly think that something like "WHERE random() < 0.5" can be treated
 * as a constant qualification.
 *
 * XXX we do not examine sublinks/subplans to see if they contain uses of
 * noncachable functions.  It's not real clear if that is correct or not...
 */
bool
contain_noncachable_functions(Node *clause)
{
	return contain_noncachable_functions_walker(clause, NULL);
}

static bool
contain_noncachable_functions_walker(Node *node, void *context)
{
	if (node == NULL)
		return false;
	if (IsA(node, Expr))
	{
		Expr	   *expr = (Expr *) node;

		switch (expr->opType)
		{
			case OP_EXPR:
				if (! op_iscachable(((Oper *) expr->oper)->opno))
					return true;
				break;
			case FUNC_EXPR:
				if (! func_iscachable(((Func *) expr->oper)->funcid))
					return true;
				break;
			default:
				break;
		}
	}
	return expression_tree_walker(node, contain_noncachable_functions_walker,
								  context);
}


/*****************************************************************************
 *		Check for "pseudo-constant" clauses
 *****************************************************************************/
669 670

/*
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
 * is_pseudo_constant_clause
 *	  Detect whether a clause is "constant", ie, it contains no variables
 *	  of the current query level and no uses of noncachable functions.
 *	  Such a clause is not necessarily a true constant: it can still contain
 *	  Params and outer-level Vars.  However, its value will be constant over
 *	  any one scan of the current query, so it can be used as an indexscan
 *	  key or (if a top-level qual) can be pushed up to become a gating qual.
 */
bool
is_pseudo_constant_clause(Node *clause)
{
	/*
	 * We could implement this check in one recursive scan.  But since the
	 * check for noncachable functions is both moderately expensive and
	 * unlikely to fail, it seems better to look for Vars first and only
	 * check for noncachable functions if we find no Vars.
	 */
	if (!contain_var_clause(clause) &&
		!contain_noncachable_functions(clause))
		return true;
	return false;
}

694
/*
695
 * pull_constant_clauses
696 697
 *		Scan through a list of qualifications and separate "constant" quals
 *		from those that are not.
698
 *
699 700
 * Returns a list of the pseudo-constant clauses in constantQual and the
 * remaining quals as the return value.
701 702
 */
List *
703
pull_constant_clauses(List *quals, List **constantQual)
704 705
{
	List	   *constqual = NIL;
706 707
	List	   *restqual = NIL;
	List	   *q;
708 709 710

	foreach(q, quals)
	{
711
		Node   *qual = (Node *) lfirst(q);
712

713
		if (is_pseudo_constant_clause(qual))
714
			constqual = lappend(constqual, qual);
715 716
		else
			restqual = lappend(restqual, qual);
717 718
	}
	*constantQual = constqual;
719
	return restqual;
720 721 722
}


723 724 725 726 727 728
/*****************************************************************************
 *																			 *
 *		General clause-manipulating routines								 *
 *																			 *
 *****************************************************************************/

729
/*
730
 * clause_relids_vars
731 732 733 734 735 736 737 738
 *	  Retrieves distinct relids and vars appearing within a clause.
 *
 * '*relids' is set to an integer list of all distinct "varno"s appearing
 *		in Vars within the clause.
 * '*vars' is set to a list of all distinct Vars appearing within the clause.
 *		Var nodes are considered distinct if they have different varno
 *		or varattno values.  If there are several occurrences of the same
 *		varno/varattno, you get a randomly chosen one...
739 740 741
 *
 * Note that upper-level vars are ignored, since they normally will
 * become Params with respect to this query level.
742 743
 */
void
744
clause_get_relids_vars(Node *clause, Relids *relids, List **vars)
745
{
746
	List	   *clvars = pull_var_clause(clause, false);
747
	List	   *varno_list = NIL;
748
	List	   *var_list = NIL;
749
	List	   *i;
750

751
	foreach(i, clvars)
752
	{
753 754
		Var		   *var = (Var *) lfirst(i);
		List	   *vi;
755 756

		if (!intMember(var->varno, varno_list))
757
			varno_list = lconsi(var->varno, varno_list);
758 759
		foreach(vi, var_list)
		{
760
			Var		   *in_list = (Var *) lfirst(vi);
761

762
			if (in_list->varno == var->varno &&
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
763
				in_list->varattno == var->varattno)
764 765 766
				break;
		}
		if (vi == NIL)
767
			var_list = lcons(var, var_list);
768
	}
769
	freeList(clvars);
770

771 772
	*relids = varno_list;
	*vars = var_list;
773 774
}

775
/*
776 777
 * NumRelids
 *		(formerly clause_relids)
778
 *
779 780 781
 * Returns the number of different relations referenced in 'clause'.
 */
int
782
NumRelids(Node *clause)
783
{
784 785
	List	   *varno_list = pull_varnos(clause);
	int			result = length(varno_list);
786

787
	freeList(varno_list);
788
	return result;
789 790
}

791
/*
792
 * get_relattval
793 794 795 796 797 798 799 800
 *		Extract information from a restriction or join clause for
 *		selectivity estimation.  The inputs are an expression
 *		and a relation number (which can be 0 if we don't care which
 *		relation is used; that'd normally be the case for restriction
 *		clauses, where the caller already knows that only one relation
 *		is referenced in the clause).  The routine checks that the
 *		expression is of the form (var op something) or (something op var)
 *		where the var is an attribute of the specified relation, or
801
 *		a function of a var of the specified relation.	If so, it
802 803 804 805 806 807
 *		returns the following info:
 *			the found relation number (same as targetrelid unless that is 0)
 *			the found var number (or InvalidAttrNumber if a function)
 *			if the "something" is a constant, the value of the constant
 *			flags indicating whether a constant was found, and on which side.
 *		Default values are returned if the expression is too complicated,
808 809 810
 *		specifically 0 for the relid and attno, 0 for the constant value.
 *
 *		Note that negative attno values are *not* invalid, but represent
811
 *		system attributes such as OID.	It's sufficient to check for relid=0
812
 *		to determine whether the routine succeeded.
813 814
 */
void
815
get_relattval(Node *clause,
816
			  int targetrelid,
817
			  int *relid,
Bruce Momjian's avatar
Bruce Momjian committed
818
			  AttrNumber *attno,
819
			  Datum *constval,
820
			  int *flag)
821
{
822
	Var		   *left,
823 824 825
			   *right,
			   *other;
	int			funcvarno;
826

827
	/* Careful; the passed clause might not be a binary operator at all */
828

829 830
	if (!is_opclause(clause))
		goto default_results;
831

832 833
	left = get_leftop((Expr *) clause);
	right = get_rightop((Expr *) clause);
834

835 836
	if (!right)
		goto default_results;
837

838 839 840 841 842 843 844
	/* Ignore any binary-compatible relabeling */

	if (IsA(left, RelabelType))
		left = (Var *) ((RelabelType *) left)->arg;
	if (IsA(right, RelabelType))
		right = (Var *) ((RelabelType *) right)->arg;

845 846 847 848
	/* First look for the var or func */

	if (IsA(left, Var) &&
		(targetrelid == 0 || targetrelid == left->varno))
849 850 851
	{
		*relid = left->varno;
		*attno = left->varattno;
852
		*flag = SEL_RIGHT;
853
	}
854 855
	else if (IsA(right, Var) &&
			 (targetrelid == 0 || targetrelid == right->varno))
856
	{
857 858 859
		*relid = right->varno;
		*attno = right->varattno;
		*flag = 0;
860
	}
861 862
	else if ((funcvarno = is_single_func((Node *) left)) != 0 &&
			 (targetrelid == 0 || targetrelid == funcvarno))
863
	{
864
		*relid = funcvarno;
865
		*attno = InvalidAttrNumber;
866
		*flag = SEL_RIGHT;
867
	}
868 869
	else if ((funcvarno = is_single_func((Node *) right)) != 0 &&
			 (targetrelid == 0 || targetrelid == funcvarno))
870
	{
871 872 873
		*relid = funcvarno;
		*attno = InvalidAttrNumber;
		*flag = 0;
874
	}
875
	else
876
	{
877 878
		/* Duh, it's too complicated for me... */
default_results:
879 880
		*relid = 0;
		*attno = 0;
881
		*constval = 0;
882 883
		*flag = 0;
		return;
884 885
	}

886 887 888 889
	/* OK, we identified the var or func; now look at the other side */

	other = (*flag == 0) ? left : right;

890 891
	if (IsA(other, Const) &&
		!((Const *) other)->constisnull)
892 893 894
	{
		*constval = ((Const *) other)->constvalue;
		*flag |= SEL_CONSTANT;
895 896
	}
	else
897
		*constval = 0;
898 899
}

900
/*
901
 * is_single_func
902 903
 *	 If the given expression is a function of a single relation,
 *	 return the relation number; else return 0
904
 */
905 906
static int
is_single_func(Node *node)
907 908 909
{
	if (is_funcclause(node))
	{
910
		List	   *varnos = pull_varnos(node);
911

912
		if (length(varnos) == 1)
913
		{
914
			int			funcvarno = lfirsti(varnos);
915 916

			freeList(varnos);
917 918
			return funcvarno;
		}
919
		freeList(varnos);
920 921 922 923 924 925
	}
	return 0;
}

/*
 * get_rels_atts
926
 *
927
 * Returns the info
928 929 930
 *				( relid1 attno1 relid2 attno2 )
 *		for a joinclause.
 *
931
 * If the clause is not of the form (var op var) or if any of the vars
932
 * refer to nested attributes, then zeroes are returned.
933
 *
934 935
 */
void
936
get_rels_atts(Node *clause,
937
			  int *relid1,
Bruce Momjian's avatar
Bruce Momjian committed
938
			  AttrNumber *attno1,
939
			  int *relid2,
Bruce Momjian's avatar
Bruce Momjian committed
940
			  AttrNumber *attno2)
941
{
942
	/* set default values */
943 944 945 946
	*relid1 = 0;
	*attno1 = 0;
	*relid2 = 0;
	*attno2 = 0;
947

948 949
	if (is_opclause(clause))
	{
Bruce Momjian's avatar
Bruce Momjian committed
950 951
		Var		   *left = get_leftop((Expr *) clause);
		Var		   *right = get_rightop((Expr *) clause);
952

953
		if (left && right)
954
		{
955
			int			funcvarno;
956

957 958 959 960 961 962
			/* Ignore any binary-compatible relabeling */
			if (IsA(left, RelabelType))
				left = (Var *) ((RelabelType *) left)->arg;
			if (IsA(right, RelabelType))
				right = (Var *) ((RelabelType *) right)->arg;

963
			if (IsA(left, Var))
964 965
			{
				*relid1 = left->varno;
966
				*attno1 = left->varattno;
967
			}
968
			else if ((funcvarno = is_single_func((Node *) left)) != 0)
969
			{
970 971 972
				*relid1 = funcvarno;
				*attno1 = InvalidAttrNumber;
			}
973

974 975
			if (IsA(right, Var))
			{
976
				*relid2 = right->varno;
977 978 979 980 981 982
				*attno2 = right->varattno;
			}
			else if ((funcvarno = is_single_func((Node *) right)) != 0)
			{
				*relid2 = funcvarno;
				*attno2 = InvalidAttrNumber;
983
			}
984
		}
985 986 987
	}
}

988 989
/*--------------------
 * CommuteClause: commute a binary operator clause
990 991
 *
 * XXX the clause is destructively modified!
992 993
 *--------------------
 */
994
void
995
CommuteClause(Expr *clause)
996
{
997 998
	Oid			opoid;
	HeapTuple	optup;
999 1000 1001
	Form_pg_operator commuTup;
	Oper	   *commu;
	Node	   *temp;
1002

1003 1004 1005
	if (!is_opclause((Node *) clause) ||
		length(clause->args) != 2)
		elog(ERROR, "CommuteClause: applied to non-binary-operator clause");
1006

1007
	opoid = ((Oper *) clause->oper)->opno;
1008

1009 1010 1011 1012 1013
	optup = SearchSysCache(OPEROID,
						   ObjectIdGetDatum(get_commutator(opoid)),
						   0, 0, 0);
	if (!HeapTupleIsValid(optup))
		elog(ERROR, "CommuteClause: no commutator for operator %u", opoid);
1014

1015
	commuTup = (Form_pg_operator) GETSTRUCT(optup);
1016

1017
	commu = makeOper(optup->t_data->t_oid,
1018
					 commuTup->oprcode,
1019
					 commuTup->oprresult);
1020

1021 1022
	ReleaseSysCache(optup);

1023
	/*
1024
	 * re-form the clause in-place!
1025
	 */
1026 1027 1028 1029
	clause->oper = (Node *) commu;
	temp = lfirst(clause->args);
	lfirst(clause->args) = lsecond(clause->args);
	lsecond(clause->args) = temp;
1030
}
1031 1032


1033 1034 1035 1036 1037 1038 1039
/*--------------------
 * eval_const_expressions
 *
 * Reduce any recognizably constant subexpressions of the given
 * expression tree, for example "2 + 2" => "4".  More interestingly,
 * we can reduce certain boolean expressions even when they contain
 * non-constant subexpressions: "x OR true" => "true" no matter what
1040
 * the subexpression x is.	(XXX We assume that no such subexpression
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 1069 1070 1071
 * will have important side-effects, which is not necessarily a good
 * assumption in the presence of user-defined functions; do we need a
 * pg_proc flag that prevents discarding the execution of a function?)
 *
 * We do understand that certain functions may deliver non-constant
 * results even with constant inputs, "nextval()" being the classic
 * example.  Functions that are not marked "proiscachable" in pg_proc
 * will not be pre-evaluated here, although we will reduce their
 * arguments as far as possible.  Functions that are the arguments
 * of Iter nodes are also not evaluated.
 *
 * We assume that the tree has already been type-checked and contains
 * only operators and functions that are reasonable to try to execute.
 *
 * This routine should be invoked before converting sublinks to subplans
 * (subselect.c's SS_process_sublinks()).  The converted form contains
 * bogus "Const" nodes that are actually placeholders where the executor
 * will insert values from the inner plan, and obviously we mustn't try
 * to reduce the expression as though these were really constants.
 * As a safeguard, if we happen to find an already-converted SubPlan node,
 * we will return it unchanged rather than recursing into it.
 *--------------------
 */
Node *
eval_const_expressions(Node *node)
{
	/* no context or special setup needed, so away we go... */
	return eval_const_expressions_mutator(node, NULL);
}

static Node *
1072
eval_const_expressions_mutator(Node *node, void *context)
1073 1074 1075 1076 1077 1078 1079 1080
{
	if (node == NULL)
		return NULL;
	if (IsA(node, Expr))
	{
		Expr	   *expr = (Expr *) node;
		List	   *args;
		Const	   *const_input;
1081
		Expr	   *newexpr;
1082 1083 1084

		/*
		 * Reduce constants in the Expr's arguments.  We know args is
1085 1086
		 * either NIL or a List node, so we can call
		 * expression_tree_mutator directly rather than recursing to self.
1087 1088
		 */
		args = (List *) expression_tree_mutator((Node *) expr->args,
1089
										  eval_const_expressions_mutator,
1090 1091 1092 1093 1094 1095
												(void *) context);

		switch (expr->opType)
		{
			case OP_EXPR:
			case FUNC_EXPR:
1096

1097
				/*
1098 1099
				 * Code for op/func case is pretty bulky, so split it out
				 * as a separate function.
1100
				 */
1101 1102 1103
				newexpr = simplify_op_or_func(expr, args);
				if (newexpr)	/* successfully simplified it */
					return (Node *) newexpr;
1104

1105
				/*
1106 1107
				 * else fall out to build new Expr node with simplified
				 * args
1108
				 */
1109 1110
				break;
			case OR_EXPR:
1111
				{
1112

1113 1114 1115 1116 1117 1118 1119 1120 1121
					/*----------
					 * OR arguments are handled as follows:
					 *	non constant: keep
					 *	FALSE: drop (does not affect result)
					 *	TRUE: force result to TRUE
					 *	NULL: keep only one
					 * We keep one NULL input because ExecEvalOr returns NULL
					 * when no input is TRUE and at least one is NULL.
					 *----------
1122 1123 1124 1125 1126 1127 1128
					 */
					List	   *newargs = NIL;
					List	   *arg;
					bool		haveNull = false;
					bool		forceTrue = false;

					foreach(arg, args)
1129
					{
1130 1131 1132 1133 1134 1135 1136 1137
						if (!IsA(lfirst(arg), Const))
						{
							newargs = lappend(newargs, lfirst(arg));
							continue;
						}
						const_input = (Const *) lfirst(arg);
						if (const_input->constisnull)
							haveNull = true;
1138
						else if (DatumGetBool(const_input->constvalue))
1139 1140
							forceTrue = true;
						/* otherwise, we can drop the constant-false input */
1141
					}
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161

					/*
					 * We could return TRUE before falling out of the
					 * loop, but this coding method will be easier to
					 * adapt if we ever add a notion of non-removable
					 * functions. We'd need to check all the inputs for
					 * non-removability.
					 */
					if (forceTrue)
						return MAKEBOOLCONST(true, false);
					if (haveNull)
						newargs = lappend(newargs, MAKEBOOLCONST(false, true));
					/* If all the inputs are FALSE, result is FALSE */
					if (newargs == NIL)
						return MAKEBOOLCONST(false, false);
					/* If only one nonconst-or-NULL input, it's the result */
					if (lnext(newargs) == NIL)
						return (Node *) lfirst(newargs);
					/* Else we still need an OR node */
					return (Node *) make_orclause(newargs);
1162 1163 1164
				}
			case AND_EXPR:
				{
1165

1166 1167 1168 1169 1170 1171 1172
					/*----------
					 * AND arguments are handled as follows:
					 *	non constant: keep
					 *	TRUE: drop (does not affect result)
					 *	FALSE: force result to FALSE
					 *	NULL: keep only one
					 * We keep one NULL input because ExecEvalAnd returns NULL
1173
					 * when no input is FALSE and at least one is NULL.
1174
					 *----------
1175 1176 1177 1178 1179 1180 1181
					 */
					List	   *newargs = NIL;
					List	   *arg;
					bool		haveNull = false;
					bool		forceFalse = false;

					foreach(arg, args)
1182
					{
1183 1184 1185 1186 1187 1188 1189 1190
						if (!IsA(lfirst(arg), Const))
						{
							newargs = lappend(newargs, lfirst(arg));
							continue;
						}
						const_input = (Const *) lfirst(arg);
						if (const_input->constisnull)
							haveNull = true;
1191
						else if (!DatumGetBool(const_input->constvalue))
1192 1193
							forceFalse = true;
						/* otherwise, we can drop the constant-true input */
1194
					}
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214

					/*
					 * We could return FALSE before falling out of the
					 * loop, but this coding method will be easier to
					 * adapt if we ever add a notion of non-removable
					 * functions. We'd need to check all the inputs for
					 * non-removability.
					 */
					if (forceFalse)
						return MAKEBOOLCONST(false, false);
					if (haveNull)
						newargs = lappend(newargs, MAKEBOOLCONST(false, true));
					/* If all the inputs are TRUE, result is TRUE */
					if (newargs == NIL)
						return MAKEBOOLCONST(true, false);
					/* If only one nonconst-or-NULL input, it's the result */
					if (lnext(newargs) == NIL)
						return (Node *) lfirst(newargs);
					/* Else we still need an AND node */
					return (Node *) make_andclause(newargs);
1215 1216 1217
				}
			case NOT_EXPR:
				Assert(length(args) == 1);
1218
				if (!IsA(lfirst(args), Const))
1219 1220 1221 1222 1223 1224
					break;
				const_input = (Const *) lfirst(args);
				/* NOT NULL => NULL */
				if (const_input->constisnull)
					return MAKEBOOLCONST(false, true);
				/* otherwise pretty easy */
1225
				return MAKEBOOLCONST(!DatumGetBool(const_input->constvalue),
1226 1227
									 false);
			case SUBPLAN_EXPR:
1228

1229 1230
				/*
				 * Safety measure per notes at head of this routine:
1231
				 * return a SubPlan unchanged.	Too late to do anything
1232
				 * with it.  The arglist simplification above was wasted
1233 1234
				 * work (the list probably only contains Var nodes
				 * anyway).
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
				 */
				return (Node *) expr;
			default:
				elog(ERROR, "eval_const_expressions: unexpected opType %d",
					 (int) expr->opType);
				break;
		}

		/*
		 * If we break out of the above switch on opType, then the
1245 1246 1247 1248 1249
		 * expression cannot be simplified any further, so build and
		 * return a replacement Expr node using the possibly-simplified
		 * arguments and the original oper node. Can't use make_clause()
		 * here because we want to be sure the typeOid field is
		 * preserved...
1250 1251
		 */
		newexpr = makeNode(Expr);
1252 1253 1254 1255 1256
		newexpr->typeOid = expr->typeOid;
		newexpr->opType = expr->opType;
		newexpr->oper = expr->oper;
		newexpr->args = args;
		return (Node *) newexpr;
1257
	}
1258 1259
	if (IsA(node, RelabelType))
	{
1260

1261 1262
		/*
		 * If we can simplify the input to a constant, then we don't need
1263
		 * the RelabelType node anymore: just change the type field of the
1264
		 * Const node.	Otherwise, must copy the RelabelType node.
1265 1266 1267 1268 1269
		 */
		RelabelType *relabel = (RelabelType *) node;
		Node	   *arg;

		arg = eval_const_expressions_mutator(relabel->arg, context);
1270 1271 1272 1273 1274 1275 1276 1277

		/*
		 * If we find stacked RelabelTypes (eg, from foo :: int :: oid)
		 * we can discard all but the top one.
		 */
		while (arg && IsA(arg, RelabelType))
			arg = ((RelabelType *) arg)->arg;

1278 1279
		if (arg && IsA(arg, Const))
		{
1280
			Const	   *con = (Const *) arg;
1281 1282

			con->consttype = relabel->resulttype;
1283

1284 1285 1286
			/*
			 * relabel's resulttypmod is discarded, which is OK for now;
			 * if the type actually needs a runtime length coercion then
1287 1288
			 * there should be a function call to do it just above this
			 * node.
1289
			 */
1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
			return (Node *) con;
		}
		else
		{
			RelabelType *newrelabel = makeNode(RelabelType);

			newrelabel->arg = arg;
			newrelabel->resulttype = relabel->resulttype;
			newrelabel->resulttypmod = relabel->resulttypmod;
			return (Node *) newrelabel;
		}
	}
1302 1303
	if (IsA(node, CaseExpr))
	{
1304

1305
		/*
1306 1307 1308 1309 1310 1311 1312
		 * CASE expressions can be simplified if there are constant
		 * condition clauses: FALSE (or NULL): drop the alternative TRUE:
		 * drop all remaining alternatives If the first non-FALSE
		 * alternative is a constant TRUE, we can simplify the entire CASE
		 * to that alternative's expression. If there are no non-FALSE
		 * alternatives, we simplify the entire CASE to the default result
		 * (ELSE result).
1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
		 */
		CaseExpr   *caseexpr = (CaseExpr *) node;
		CaseExpr   *newcase;
		List	   *newargs = NIL;
		Node	   *defresult;
		Const	   *const_input;
		List	   *arg;

		foreach(arg, caseexpr->args)
		{
			/* Simplify this alternative's condition and result */
			CaseWhen   *casewhen = (CaseWhen *)
1325 1326 1327 1328
			expression_tree_mutator((Node *) lfirst(arg),
									eval_const_expressions_mutator,
									(void *) context);

1329 1330
			Assert(IsA(casewhen, CaseWhen));
			if (casewhen->expr == NULL ||
1331
				!IsA(casewhen->expr, Const))
1332 1333 1334 1335 1336 1337
			{
				newargs = lappend(newargs, casewhen);
				continue;
			}
			const_input = (Const *) casewhen->expr;
			if (const_input->constisnull ||
1338
				!DatumGetBool(const_input->constvalue))
1339
				continue;		/* drop alternative with FALSE condition */
1340

1341
			/*
1342
			 * Found a TRUE condition.	If it's the first (un-dropped)
1343 1344 1345 1346
			 * alternative, the CASE reduces to just this alternative.
			 */
			if (newargs == NIL)
				return casewhen->result;
1347

1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
			/*
			 * Otherwise, add it to the list, and drop all the rest.
			 */
			newargs = lappend(newargs, casewhen);
			break;
		}

		/* Simplify the default result */
		defresult = eval_const_expressions_mutator(caseexpr->defresult,
												   context);
1358 1359 1360 1361 1362

		/*
		 * If no non-FALSE alternatives, CASE reduces to the default
		 * result
		 */
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
		if (newargs == NIL)
			return defresult;
		/* Otherwise we need a new CASE node */
		newcase = makeNode(CaseExpr);
		newcase->casetype = caseexpr->casetype;
		newcase->arg = NULL;
		newcase->args = newargs;
		newcase->defresult = defresult;
		return (Node *) newcase;
	}
	if (IsA(node, Iter))
	{
1375

1376
		/*
1377 1378 1379 1380 1381
		 * The argument of an Iter is normally a function call. We must
		 * not try to eliminate the function, but we can try to simplify
		 * its arguments.  If, by chance, the arg is NOT a function then
		 * we go ahead and try to simplify it (by falling into
		 * expression_tree_mutator). Is that the right thing?
1382 1383 1384 1385 1386
		 */
		Iter	   *iter = (Iter *) node;

		if (is_funcclause(iter->iterexpr))
		{
1387 1388 1389
			Expr	   *func = (Expr *) iter->iterexpr;
			Expr	   *newfunc;
			Iter	   *newiter;
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404

			newfunc = makeNode(Expr);
			newfunc->typeOid = func->typeOid;
			newfunc->opType = func->opType;
			newfunc->oper = func->oper;
			newfunc->args = (List *)
				expression_tree_mutator((Node *) func->args,
										eval_const_expressions_mutator,
										(void *) context);
			newiter = makeNode(Iter);
			newiter->iterexpr = (Node *) newfunc;
			newiter->itertype = iter->itertype;
			return (Node *) newiter;
		}
	}
1405

1406 1407
	/*
	 * For any node type not handled above, we recurse using
1408 1409 1410 1411
	 * expression_tree_mutator, which will copy the node unchanged but try
	 * to simplify its arguments (if any) using this routine. For example:
	 * we cannot eliminate an ArrayRef node, but we might be able to
	 * simplify constant expressions in its subscripts.
1412 1413 1414 1415 1416
	 */
	return expression_tree_mutator(node, eval_const_expressions_mutator,
								   (void *) context);
}

1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
/*
 * Subroutine for eval_const_expressions: try to evaluate an op or func
 *
 * Inputs are the op or func Expr node, and the pre-simplified argument list.
 * Returns a simplified expression if successful, or NULL if cannot
 * simplify the op/func.
 *
 * XXX Possible future improvement: if the func is SQL-language, and its
 * definition is simply "SELECT expression", we could parse and substitute
 * the expression here.  This would avoid much runtime overhead, and perhaps
 * expose opportunities for constant-folding within the expression even if
 * not all the func's input args are constants.  It'd be appropriate to do
1429
 * that here, not in the parser, since we wouldn't want it to happen until
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
 * after rule substitution/rewriting.
 */
static Expr *
simplify_op_or_func(Expr *expr, List *args)
{
	List	   *arg;
	Oid			funcid;
	Oid			result_typeid;
	HeapTuple	func_tuple;
	Form_pg_proc funcform;
1440 1441 1442 1443
	bool		proiscachable;
	bool		proisstrict;
	bool		proretset;
	int16		resultTypLen;
1444
	bool		resultTypByVal;
1445
	Expr	   *newexpr;
1446
	ExprContext *econtext;
1447
	Datum		const_val;
1448 1449
	bool		has_nonconst_input = false;
	bool		has_null_input = false;
1450 1451 1452
	bool		const_is_null;

	/*
1453
	 * Check for constant inputs and especially constant-NULL inputs.
1454 1455 1456
	 */
	foreach(arg, args)
	{
1457 1458 1459 1460
		if (IsA(lfirst(arg), Const))
			has_null_input |= ((Const *) lfirst(arg))->constisnull;
		else
			has_nonconst_input = true;
1461
	}
1462

1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
	/*
	 * If the function is strict and has a constant-NULL input, it will
	 * never be called at all, so we can replace the call by a NULL
	 * constant even if there are other inputs that aren't constant.
	 * Otherwise, we can only simplify if all inputs are constants.
	 * We can skip the function lookup if neither case applies.
	 */
	if (has_nonconst_input && !has_null_input)
		return NULL;

1473
	/*
1474 1475
	 * Get the function procedure's OID and look to see whether it is
	 * marked proiscachable.
1476 1477 1478
	 *
	 * XXX would it be better to take the result type from the pg_proc tuple,
	 * rather than the Oper or Func node?
1479 1480 1481
	 */
	if (expr->opType == OP_EXPR)
	{
1482
		Oper	   *oper = (Oper *) expr->oper;
1483 1484 1485 1486 1487 1488 1489

		replace_opid(oper);		/* OK to scribble on input to this extent */
		funcid = oper->opid;
		result_typeid = oper->opresulttype;
	}
	else
	{
1490
		Func	   *func = (Func *) expr->oper;
1491 1492 1493 1494

		funcid = func->funcid;
		result_typeid = func->functype;
	}
1495 1496 1497 1498
	/*
	 * we could use func_iscachable() here, but we need several fields
	 * out of the func tuple, so might as well just look it up once.
	 */
1499 1500 1501
	func_tuple = SearchSysCache(PROCOID,
								ObjectIdGetDatum(funcid),
								0, 0, 0);
1502 1503 1504
	if (!HeapTupleIsValid(func_tuple))
		elog(ERROR, "Function OID %u does not exist", funcid);
	funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
1505 1506 1507 1508 1509 1510
	proiscachable = funcform->proiscachable;
	proisstrict = funcform->proisstrict;
	proretset = funcform->proretset;
	ReleaseSysCache(func_tuple);

	if (!proiscachable)
1511
		return NULL;
1512

1513 1514 1515
	/*
	 * Also check to make sure it doesn't return a set.
	 */
1516
	if (proretset)
1517
		return NULL;
1518

1519 1520 1521 1522
	/*
	 * Now that we know if the function is strict, we can finish the
	 * checks for simplifiable inputs that we started above.
	 */
1523
	if (proisstrict && has_null_input)
1524 1525 1526 1527 1528
	{
		/*
		 * It's strict and has NULL input, so must produce NULL output.
		 * Return a NULL constant of the right type.
		 */
1529
		return (Expr *) makeNullConst(result_typeid);
1530 1531 1532 1533 1534 1535 1536 1537 1538 1539
	}

	/*
	 * Otherwise, can simplify only if all inputs are constants.
	 * (For a non-strict function, constant NULL inputs are treated
	 * the same as constant non-NULL inputs.)
	 */
	if (has_nonconst_input)
		return NULL;

1540 1541 1542 1543 1544 1545
	/*
	 * OK, looks like we can simplify this operator/function.
	 *
	 * We use the executor's routine ExecEvalExpr() to avoid duplication of
	 * code and ensure we get the same result as the executor would get.
	 *
1546 1547
	 * Build a new Expr node containing the already-simplified arguments. The
	 * only other setup needed here is the replace_opid() that we already
1548 1549 1550 1551 1552 1553 1554
	 * did for the OP_EXPR case.
	 */
	newexpr = makeNode(Expr);
	newexpr->typeOid = expr->typeOid;
	newexpr->opType = expr->opType;
	newexpr->oper = expr->oper;
	newexpr->args = args;
1555

1556
	/* Get info needed about result datatype */
1557
	get_typlenbyval(result_typeid, &resultTypLen, &resultTypByVal);
1558

1559
	/*
1560
	 * It is OK to pass a dummy econtext because none of the ExecEvalExpr()
1561
	 * code used in this situation will use econtext.  That might seem
1562 1563
	 * fortuitous, but it's not so unreasonable --- a constant expression
	 * does not depend on context, by definition, n'est ce pas?
1564
	 */
1565 1566 1567
	econtext = MakeExprContext(NULL, CurrentMemoryContext);

	const_val = ExecEvalExprSwitchContext((Node *) newexpr, econtext,
1568
										  &const_is_null, NULL);
1569 1570 1571 1572 1573

	/* Must copy result out of sub-context used by expression eval */
	const_val = datumCopy(const_val, resultTypByVal, resultTypLen);

	FreeExprContext(econtext);
1574
	pfree(newexpr);
1575

1576 1577 1578
	/*
	 * Make the constant result node.
	 */
1579
	return (Expr *) makeConst(result_typeid, resultTypLen,
1580
							  const_val, const_is_null,
1581
							  resultTypByVal, false, false);
1582 1583 1584
}


1585
/*
1586 1587 1588 1589 1590 1591 1592 1593 1594
 * Standard expression-tree walking support
 *
 * We used to have near-duplicate code in many different routines that
 * understood how to recurse through an expression node tree.  That was
 * a pain to maintain, and we frequently had bugs due to some particular
 * routine neglecting to support a particular node type.  In most cases,
 * these routines only actually care about certain node types, and don't
 * care about other types except insofar as they have to recurse through
 * non-primitive node types.  Therefore, we now provide generic tree-walking
1595 1596 1597 1598 1599
 * logic to consolidate the redundant "boilerplate" code.  There are
 * two versions: expression_tree_walker() and expression_tree_mutator().
 */

/*--------------------
1600 1601
 * expression_tree_walker() is designed to support routines that traverse
 * a tree in a read-only fashion (although it will also work for routines
1602 1603
 * that modify nodes in-place but never add/delete/replace nodes).
 * A walker routine should look like this:
1604 1605 1606 1607 1608
 *
 * bool my_walker (Node *node, my_struct *context)
 * {
 *		if (node == NULL)
 *			return false;
Bruce Momjian's avatar
Bruce Momjian committed
1609
 *		// check for nodes that special work is required for, eg:
1610 1611 1612 1613 1614 1615 1616 1617
 *		if (IsA(node, Var))
 *		{
 *			... do special actions for Var nodes
 *		}
 *		else if (IsA(node, ...))
 *		{
 *			... do special actions for other node types
 *		}
Bruce Momjian's avatar
Bruce Momjian committed
1618
 *		// for any node type not specially processed, do:
1619 1620 1621 1622
 *		return expression_tree_walker(node, my_walker, (void *) context);
 * }
 *
 * The "context" argument points to a struct that holds whatever context
1623 1624
 * information the walker routine needs --- it can be used to return data
 * gathered by the walker, too.  This argument is not touched by
1625 1626 1627 1628 1629 1630 1631
 * expression_tree_walker, but it is passed down to recursive sub-invocations
 * of my_walker.  The tree walk is started from a setup routine that
 * fills in the appropriate context struct, calls my_walker with the top-level
 * node of the tree, and then examines the results.
 *
 * The walker routine should return "false" to continue the tree walk, or
 * "true" to abort the walk and immediately return "true" to the top-level
1632 1633
 * caller.	This can be used to short-circuit the traversal if the walker
 * has found what it came for.	"false" is returned to the top-level caller
1634
 * iff no invocation of the walker returned "true".
1635 1636 1637 1638 1639 1640 1641
 *
 * The node types handled by expression_tree_walker include all those
 * normally found in target lists and qualifier clauses during the planning
 * stage.  In particular, it handles List nodes since a cnf-ified qual clause
 * will have List structure at the top level, and it handles TargetEntry nodes
 * so that a scan of a target list can be handled without additional code.
 * (But only the "expr" part of a TargetEntry is examined, unless the walker
1642
 * chooses to process TargetEntry nodes specially.)  Also, RangeTblRef,
1643 1644
 * FromExpr, JoinExpr, and SetOperationStmt nodes are handled, so that query
 * jointrees and setOperation trees can be processed without additional code.
1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660
 *
 * expression_tree_walker will handle SubLink and SubPlan nodes by recursing
 * normally into the "lefthand" arguments (which belong to the outer plan).
 * It will also call the walker on the sub-Query node; however, when
 * expression_tree_walker itself is called on a Query node, it does nothing
 * and returns "false".  The net effect is that unless the walker does
 * something special at a Query node, sub-selects will not be visited
 * during an expression tree walk.  This is exactly the behavior wanted
 * in many cases --- and for those walkers that do want to recurse into
 * sub-selects, special behavior is typically needed anyway at the entry
 * to a sub-select (such as incrementing a depth counter).  A walker that
 * wants to examine sub-selects should include code along the lines of:
 *
 *		if (IsA(node, Query))
 *		{
 *			adjust context for subquery;
1661
 *			result = query_tree_walker((Query *) node, my_walker, context,
Bruce Momjian's avatar
Bruce Momjian committed
1662
 *									   true); // to visit subquery RTEs too
1663 1664 1665
 *			restore context if needed;
 *			return result;
 *		}
1666
 *
1667 1668
 * query_tree_walker is a convenience routine (see below) that calls the
 * walker on all the expression subtrees of the given Query node.
1669
 *
1670 1671 1672 1673
 * NOTE: currently, because make_subplan() clears the subselect link in
 * a SubLink node, it is not actually possible to recurse into subselects
 * of an already-planned expression tree.  This is OK for current uses,
 * but ought to be cleaned up when we redesign querytree processing.
1674 1675 1676 1677
 *--------------------
 */

bool
1678 1679 1680
expression_tree_walker(Node *node,
					   bool (*walker) (),
					   void *context)
1681 1682 1683 1684
{
	List	   *temp;

	/*
1685 1686
	 * The walker has already visited the current node, and so we need
	 * only recurse into any sub-nodes it has.
1687
	 *
1688 1689
	 * We assume that the walker is not interested in List nodes per se, so
	 * when we expect a List we just recurse directly to self without
1690 1691 1692 1693 1694 1695 1696 1697 1698 1699
	 * bothering to call the walker.
	 */
	if (node == NULL)
		return false;
	switch (nodeTag(node))
	{
		case T_Ident:
		case T_Const:
		case T_Var:
		case T_Param:
1700
		case T_RangeTblRef:
1701 1702 1703 1704
			/* primitive node types with no subnodes */
			break;
		case T_Expr:
			{
1705
				Expr	   *expr = (Expr *) node;
1706

1707 1708
				if (expr->opType == SUBPLAN_EXPR)
				{
1709 1710 1711
					/* recurse to the SubLink node (skipping SubPlan!) */
					if (walker((Node *) ((SubPlan *) expr->oper)->sublink,
							   context))
1712 1713
						return true;
				}
1714 1715 1716 1717
				/* for all Expr node types, examine args list */
				if (expression_tree_walker((Node *) expr->args,
										   walker, context))
					return true;
1718 1719 1720 1721 1722 1723 1724 1725 1726
			}
			break;
		case T_Aggref:
			return walker(((Aggref *) node)->target, context);
		case T_Iter:
			return walker(((Iter *) node)->iterexpr, context);
		case T_ArrayRef:
			{
				ArrayRef   *aref = (ArrayRef *) node;
1727

1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741
				/* recurse directly for upper/lower array index lists */
				if (expression_tree_walker((Node *) aref->refupperindexpr,
										   walker, context))
					return true;
				if (expression_tree_walker((Node *) aref->reflowerindexpr,
										   walker, context))
					return true;
				/* walker must see the refexpr and refassgnexpr, however */
				if (walker(aref->refexpr, context))
					return true;
				if (walker(aref->refassgnexpr, context))
					return true;
			}
			break;
1742 1743
		case T_FieldSelect:
			return walker(((FieldSelect *) node)->arg, context);
1744 1745
		case T_RelabelType:
			return walker(((RelabelType *) node)->arg, context);
1746 1747 1748
		case T_CaseExpr:
			{
				CaseExpr   *caseexpr = (CaseExpr *) node;
1749

1750 1751 1752 1753
				/* we assume walker doesn't care about CaseWhens, either */
				foreach(temp, caseexpr->args)
				{
					CaseWhen   *when = (CaseWhen *) lfirst(temp);
1754

1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767
					Assert(IsA(when, CaseWhen));
					if (walker(when->expr, context))
						return true;
					if (walker(when->result, context))
						return true;
				}
				/* caseexpr->arg should be null, but we'll check it anyway */
				if (walker(caseexpr->arg, context))
					return true;
				if (walker(caseexpr->defresult, context))
					return true;
			}
			break;
1768
		case T_SubLink:
1769
			{
1770
				SubLink    *sublink = (SubLink *) node;
1771

1772 1773
				/*
				 * If the SubLink has already been processed by
1774 1775 1776 1777
				 * subselect.c, it will have lefthand=NIL, and we need to
				 * scan the oper list.  Otherwise we only need to look at
				 * the lefthand list (the incomplete Oper nodes in the oper
				 * list are deemed uninteresting, perhaps even confusing).
1778 1779
				 */
				if (sublink->lefthand)
1780 1781 1782 1783
				{
					if (walker((Node *) sublink->lefthand, context))
						return true;
				}
1784
				else
1785 1786 1787 1788 1789 1790 1791 1792 1793
				{
					if (walker((Node *) sublink->oper, context))
						return true;
				}
				/*
				 * Also invoke the walker on the sublink's Query node,
				 * so it can recurse into the sub-query if it wants to.
				 */
				return walker(sublink->subselect, context);
1794 1795
			}
			break;
1796 1797 1798
		case T_Query:
			/* Do nothing with a sub-Query, per discussion above */
			break;
1799 1800 1801 1802 1803 1804 1805 1806 1807
		case T_List:
			foreach(temp, (List *) node)
			{
				if (walker((Node *) lfirst(temp), context))
					return true;
			}
			break;
		case T_TargetEntry:
			return walker(((TargetEntry *) node)->expr, context);
1808 1809 1810 1811 1812 1813 1814 1815 1816 1817
		case T_FromExpr:
			{
				FromExpr    *from = (FromExpr *) node;

				if (walker(from->fromlist, context))
					return true;
				if (walker(from->quals, context))
					return true;
			}
			break;
1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834
		case T_JoinExpr:
			{
				JoinExpr    *join = (JoinExpr *) node;

				if (walker(join->larg, context))
					return true;
				if (walker(join->rarg, context))
					return true;
				if (walker(join->quals, context))
					return true;
				if (walker((Node *) join->colvars, context))
					return true;
				/* alias clause, using list, colnames list are deemed
				 * uninteresting.
				 */
			}
			break;
1835 1836 1837 1838 1839 1840 1841 1842 1843 1844
		case T_SetOperationStmt:
			{
				SetOperationStmt *setop = (SetOperationStmt *) node;

				if (walker(setop->larg, context))
					return true;
				if (walker(setop->rarg, context))
					return true;
			}
			break;
1845 1846 1847 1848 1849 1850 1851
		default:
			elog(ERROR, "expression_tree_walker: Unexpected node type %d",
				 nodeTag(node));
			break;
	}
	return false;
}
1852

1853 1854 1855 1856 1857 1858 1859 1860
/*
 * query_tree_walker --- initiate a walk of a Query's expressions
 *
 * This routine exists just to reduce the number of places that need to know
 * where all the expression subtrees of a Query are.  Note it can be used
 * for starting a walk at top level of a Query regardless of whether the
 * walker intends to descend into subqueries.  It is also useful for
 * descending into subqueries within a walker.
1861 1862 1863 1864 1865
 *
 * If visitQueryRTEs is true, the walker will also be called on sub-Query
 * nodes present in subquery rangetable entries of the given Query.  This
 * is optional since some callers handle those sub-queries separately,
 * or don't really want to see subqueries anyway.
1866 1867 1868 1869
 */
bool
query_tree_walker(Query *query,
				  bool (*walker) (),
1870 1871
				  void *context,
				  bool visitQueryRTEs)
1872 1873 1874 1875 1876
{
	Assert(query != NULL && IsA(query, Query));

	if (walker((Node *) query->targetList, context))
		return true;
1877
	if (walker((Node *) query->jointree, context))
1878
		return true;
1879 1880
	if (walker(query->setOperations, context))
		return true;
1881 1882
	if (walker(query->havingQual, context))
		return true;
1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895
	if (visitQueryRTEs)
	{
		List   *rt;

		foreach(rt, query->rtable)
		{
			RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);

			if (rte->subquery)
				if (walker(rte->subquery, context))
					return true;
		}
	}
1896 1897 1898 1899
	return false;
}


1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911
/*--------------------
 * expression_tree_mutator() is designed to support routines that make a
 * modified copy of an expression tree, with some nodes being added,
 * removed, or replaced by new subtrees.  The original tree is (normally)
 * not changed.  Each recursion level is responsible for returning a copy of
 * (or appropriately modified substitute for) the subtree it is handed.
 * A mutator routine should look like this:
 *
 * Node * my_mutator (Node *node, my_struct *context)
 * {
 *		if (node == NULL)
 *			return NULL;
Bruce Momjian's avatar
Bruce Momjian committed
1912
 *		// check for nodes that special work is required for, eg:
1913 1914 1915 1916 1917 1918 1919 1920
 *		if (IsA(node, Var))
 *		{
 *			... create and return modified copy of Var node
 *		}
 *		else if (IsA(node, ...))
 *		{
 *			... do special transformations of other node types
 *		}
Bruce Momjian's avatar
Bruce Momjian committed
1921
 *		// for any node type not specially processed, do:
1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947
 *		return expression_tree_mutator(node, my_mutator, (void *) context);
 * }
 *
 * The "context" argument points to a struct that holds whatever context
 * information the mutator routine needs --- it can be used to return extra
 * data gathered by the mutator, too.  This argument is not touched by
 * expression_tree_mutator, but it is passed down to recursive sub-invocations
 * of my_mutator.  The tree walk is started from a setup routine that
 * fills in the appropriate context struct, calls my_mutator with the
 * top-level node of the tree, and does any required post-processing.
 *
 * Each level of recursion must return an appropriately modified Node.
 * If expression_tree_mutator() is called, it will make an exact copy
 * of the given Node, but invoke my_mutator() to copy the sub-node(s)
 * of that Node.  In this way, my_mutator() has full control over the
 * copying process but need not directly deal with expression trees
 * that it has no interest in.
 *
 * Just as for expression_tree_walker, the node types handled by
 * expression_tree_mutator include all those normally found in target lists
 * and qualifier clauses during the planning stage.
 *
 * expression_tree_mutator will handle a SUBPLAN_EXPR node by recursing into
 * the args and slink->oper lists (which belong to the outer plan), but it
 * will simply copy the link to the inner plan, since that's typically what
 * expression tree mutators want.  A mutator that wants to modify the subplan
1948 1949
 * can force appropriate behavior by recognizing subplan expression nodes
 * and doing the right thing.
1950 1951 1952 1953 1954 1955 1956 1957 1958 1959
 *
 * Bare SubLink nodes (without a SUBPLAN_EXPR) are handled by recursing into
 * the "lefthand" argument list only.  (A bare SubLink should be seen only if
 * the tree has not yet been processed by subselect.c.)  Again, this can be
 * overridden by the mutator, but it seems to be the most useful default
 * behavior.
 *--------------------
 */

Node *
1960 1961 1962
expression_tree_mutator(Node *node,
						Node *(*mutator) (),
						void *context)
1963
{
1964

1965
	/*
1966 1967
	 * The mutator has already decided not to modify the current node, but
	 * we must call the mutator for any sub-nodes.
1968 1969 1970 1971 1972 1973
	 */

#define FLATCOPY(newnode, node, nodetype)  \
	( (newnode) = makeNode(nodetype), \
	  memcpy((newnode), (node), sizeof(nodetype)) )

1974
#define CHECKFLATCOPY(newnode, node, nodetype)	\
1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989
	( AssertMacro(IsA((node), nodetype)), \
	  (newnode) = makeNode(nodetype), \
	  memcpy((newnode), (node), sizeof(nodetype)) )

#define MUTATE(newfield, oldfield, fieldtype)  \
		( (newfield) = (fieldtype) mutator((Node *) (oldfield), context) )

	if (node == NULL)
		return NULL;
	switch (nodeTag(node))
	{
		case T_Ident:
		case T_Const:
		case T_Var:
		case T_Param:
1990
		case T_RangeTblRef:
1991 1992 1993 1994
			/* primitive node types with no subnodes */
			return (Node *) copyObject(node);
		case T_Expr:
			{
1995 1996
				Expr	   *expr = (Expr *) node;
				Expr	   *newnode;
1997 1998 1999 2000 2001

				FLATCOPY(newnode, expr, Expr);

				if (expr->opType == SUBPLAN_EXPR)
				{
2002 2003
					SubLink    *oldsublink = ((SubPlan *) expr->oper)->sublink;
					SubPlan    *newsubplan;
2004 2005 2006 2007 2008 2009

					/* flat-copy the oper node, which is a SubPlan */
					CHECKFLATCOPY(newsubplan, expr->oper, SubPlan);
					newnode->oper = (Node *) newsubplan;
					/* likewise its SubLink node */
					CHECKFLATCOPY(newsubplan->sublink, oldsublink, SubLink);
2010 2011 2012 2013 2014

					/*
					 * transform args list (params to be passed to
					 * subplan)
					 */
2015 2016
					MUTATE(newnode->args, expr->args, List *);
					/* transform sublink's oper list as well */
2017 2018 2019 2020 2021 2022
					MUTATE(newsubplan->sublink->oper, oldsublink->oper, List *);

					/*
					 * but not the subplan itself, which is referenced
					 * as-is
					 */
2023 2024 2025
				}
				else
				{
2026 2027 2028 2029

					/*
					 * for other Expr node types, just transform args
					 * list, linking to original oper node (OK?)
2030 2031 2032 2033 2034 2035 2036 2037
					 */
					MUTATE(newnode->args, expr->args, List *);
				}
				return (Node *) newnode;
			}
			break;
		case T_Aggref:
			{
2038 2039
				Aggref	   *aggref = (Aggref *) node;
				Aggref	   *newnode;
2040 2041 2042 2043 2044 2045 2046 2047

				FLATCOPY(newnode, aggref, Aggref);
				MUTATE(newnode->target, aggref->target, Node *);
				return (Node *) newnode;
			}
			break;
		case T_Iter:
			{
2048 2049
				Iter	   *iter = (Iter *) node;
				Iter	   *newnode;
2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072

				FLATCOPY(newnode, iter, Iter);
				MUTATE(newnode->iterexpr, iter->iterexpr, Node *);
				return (Node *) newnode;
			}
			break;
		case T_ArrayRef:
			{
				ArrayRef   *arrayref = (ArrayRef *) node;
				ArrayRef   *newnode;

				FLATCOPY(newnode, arrayref, ArrayRef);
				MUTATE(newnode->refupperindexpr, arrayref->refupperindexpr,
					   List *);
				MUTATE(newnode->reflowerindexpr, arrayref->reflowerindexpr,
					   List *);
				MUTATE(newnode->refexpr, arrayref->refexpr,
					   Node *);
				MUTATE(newnode->refassgnexpr, arrayref->refassgnexpr,
					   Node *);
				return (Node *) newnode;
			}
			break;
2073 2074 2075 2076 2077 2078 2079 2080 2081 2082
		case T_FieldSelect:
			{
				FieldSelect *fselect = (FieldSelect *) node;
				FieldSelect *newnode;

				FLATCOPY(newnode, fselect, FieldSelect);
				MUTATE(newnode->arg, fselect->arg, Node *);
				return (Node *) newnode;
			}
			break;
2083 2084 2085 2086 2087 2088 2089 2090 2091 2092
		case T_RelabelType:
			{
				RelabelType *relabel = (RelabelType *) node;
				RelabelType *newnode;

				FLATCOPY(newnode, relabel, RelabelType);
				MUTATE(newnode->arg, relabel->arg, Node *);
				return (Node *) newnode;
			}
			break;
2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118
		case T_CaseExpr:
			{
				CaseExpr   *caseexpr = (CaseExpr *) node;
				CaseExpr   *newnode;

				FLATCOPY(newnode, caseexpr, CaseExpr);
				MUTATE(newnode->args, caseexpr->args, List *);
				/* caseexpr->arg should be null, but we'll check it anyway */
				MUTATE(newnode->arg, caseexpr->arg, Node *);
				MUTATE(newnode->defresult, caseexpr->defresult, Node *);
				return (Node *) newnode;
			}
			break;
		case T_CaseWhen:
			{
				CaseWhen   *casewhen = (CaseWhen *) node;
				CaseWhen   *newnode;

				FLATCOPY(newnode, casewhen, CaseWhen);
				MUTATE(newnode->expr, casewhen->expr, Node *);
				MUTATE(newnode->result, casewhen->result, Node *);
				return (Node *) newnode;
			}
			break;
		case T_SubLink:
			{
2119 2120 2121 2122 2123

				/*
				 * A "bare" SubLink (note we will not come here if we
				 * found a SUBPLAN_EXPR node above it).  Transform the
				 * lefthand side, but not the oper list nor the subquery.
2124
				 */
2125 2126
				SubLink    *sublink = (SubLink *) node;
				SubLink    *newnode;
2127 2128 2129 2130 2131 2132 2133 2134

				FLATCOPY(newnode, sublink, SubLink);
				MUTATE(newnode->lefthand, sublink->lefthand, List *);
				return (Node *) newnode;
			}
			break;
		case T_List:
			{
2135 2136 2137 2138 2139 2140

				/*
				 * We assume the mutator isn't interested in the list
				 * nodes per se, so just invoke it on each list element.
				 * NOTE: this would fail badly on a list with integer
				 * elements!
2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155
				 */
				List	   *resultlist = NIL;
				List	   *temp;

				foreach(temp, (List *) node)
				{
					resultlist = lappend(resultlist,
										 mutator((Node *) lfirst(temp),
												 context));
				}
				return (Node *) resultlist;
			}
			break;
		case T_TargetEntry:
			{
2156 2157 2158 2159 2160 2161 2162

				/*
				 * We mutate the expression, but not the resdom, by
				 * default.
				 */
				TargetEntry *targetentry = (TargetEntry *) node;
				TargetEntry *newnode;
2163 2164 2165 2166 2167 2168

				FLATCOPY(newnode, targetentry, TargetEntry);
				MUTATE(newnode->expr, targetentry->expr, Node *);
				return (Node *) newnode;
			}
			break;
2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179
		case T_FromExpr:
			{
				FromExpr *from = (FromExpr *) node;
				FromExpr *newnode;

				FLATCOPY(newnode, from, FromExpr);
				MUTATE(newnode->fromlist, from->fromlist, List *);
				MUTATE(newnode->quals, from->quals, Node *);
				return (Node *) newnode;
			}
			break;
2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193
		case T_JoinExpr:
			{
				JoinExpr *join = (JoinExpr *) node;
				JoinExpr *newnode;

				FLATCOPY(newnode, join, JoinExpr);
				MUTATE(newnode->larg, join->larg, Node *);
				MUTATE(newnode->rarg, join->rarg, Node *);
				MUTATE(newnode->quals, join->quals, Node *);
				MUTATE(newnode->colvars, join->colvars, List *);
				/* We do not mutate alias, using, or colnames by default */
				return (Node *) newnode;
			}
			break;
2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204
		case T_SetOperationStmt:
			{
				SetOperationStmt *setop = (SetOperationStmt *) node;
				SetOperationStmt *newnode;

				FLATCOPY(newnode, setop, SetOperationStmt);
				MUTATE(newnode->larg, setop->larg, Node *);
				MUTATE(newnode->rarg, setop->rarg, Node *);
				return (Node *) newnode;
			}
			break;
2205 2206 2207 2208 2209 2210 2211 2212
		default:
			elog(ERROR, "expression_tree_mutator: Unexpected node type %d",
				 nodeTag(node));
			break;
	}
	/* can't get here, but keep compiler happy */
	return NULL;
}
2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267


/*
 * query_tree_mutator --- initiate modification of a Query's expressions
 *
 * This routine exists just to reduce the number of places that need to know
 * where all the expression subtrees of a Query are.  Note it can be used
 * for starting a walk at top level of a Query regardless of whether the
 * mutator intends to descend into subqueries.  It is also useful for
 * descending into subqueries within a mutator.
 *
 * The specified Query node is modified-in-place; do a FLATCOPY() beforehand
 * if you don't want to change the original.  All substructure is safely
 * copied, however.
 *
 * If visitQueryRTEs is true, the mutator will also be called on sub-Query
 * nodes present in subquery rangetable entries of the given Query.  This
 * is optional since some callers handle those sub-queries separately,
 * or don't really want to see subqueries anyway.
 */
void
query_tree_mutator(Query *query,
				   Node *(*mutator) (),
				   void *context,
				   bool visitQueryRTEs)
{
	Assert(query != NULL && IsA(query, Query));

	MUTATE(query->targetList, query->targetList, List *);
	MUTATE(query->jointree, query->jointree, FromExpr *);
	MUTATE(query->setOperations, query->setOperations, Node *);
	MUTATE(query->havingQual, query->havingQual, Node *);
	if (visitQueryRTEs)
	{
		List   *newrt = NIL;
		List   *rt;

		foreach(rt, query->rtable)
		{
			RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);

			if (rte->subquery)
			{
				RangeTblEntry *newrte;

				FLATCOPY(newrte, rte, RangeTblEntry);
				CHECKFLATCOPY(newrte->subquery, rte->subquery, Query);
				MUTATE(newrte->subquery, newrte->subquery, Query *);
				rte = newrte;
			}
			newrt = lappend(newrt, rte);
		}
		query->rtable = newrt;
	}
}