clauses.c 58.3 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
B
Add:  
Bruce Momjian 已提交
7
 * Portions Copyright (c) 1994, Regents of the University of California
8 9 10
 *
 *
 * IDENTIFICATION
11
 *	  $Header: /cvsroot/pgsql/src/backend/optimizer/util/clauses.c,v 1.86 2001/06/19 22:39:11 tgl 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"
B
Bruce Momjian 已提交
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
static Node *eval_const_expressions_mutator(Node *node, void *context);
50
static Expr *simplify_op_or_func(Expr *expr, List *args);
51

52

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

	switch (type)
59
	{
60 61 62 63 64 65 66 67 68 69 70 71 72 73
		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;
74
	}
75 76 77 78
	expr->opType = type;
	expr->oper = oper;			/* ignored for AND, OR, NOT */
	expr->args = args;
	return expr;
79 80 81 82
}


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


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

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

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

126
/*
127
 * get_leftop
128
 *
129
 * Returns the left operand of a clause of the form (op expr expr)
130
 *		or (op expr)
131 132 133 134
 *
 * 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 *.
135
 */
136
Var *
137
get_leftop(Expr *clause)
138
{
139
	if (clause->args != NULL)
140
		return lfirst(clause->args);
141 142
	else
		return NULL;
143 144
}

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

/*****************************************************************************
161
 *		FUNC clause functions
162 163
 *****************************************************************************/

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

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

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

/*****************************************************************************
198
 *		OR clause functions
199 200
 *****************************************************************************/

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

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

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

/*****************************************************************************
234
 *		NOT clause functions
235 236
 *****************************************************************************/

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

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

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

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

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


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

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

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

317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
/*
 * 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));
}

334
/*
335 336 337 338 339 340 341
 * 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.
342 343 344 345 346
 */
Expr *
make_ands_explicit(List *andclauses)
{
	if (andclauses == NIL)
347 348
		return (Expr *) MAKEBOOLCONST(true, false);
	else if (lnext(andclauses) == NIL)
349 350 351 352
		return (Expr *) lfirst(andclauses);
	else
		return make_andclause(andclauses);
}
T
Thomas G. Lockhart 已提交
353

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

358 359 360
	/*
	 * 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,
361 362
	 * even though one might more reasonably think it FALSE.  Grumble. If
	 * this causes trouble, consider changing the parser's behavior.
363
	 */
364
	if (clause == NULL)
365
		return NIL;				/* NULL -> NIL list == TRUE */
366 367
	else if (and_clause((Node *) clause))
		return clause->args;
368
	else if (IsA(clause, Const) &&
369
			 !((Const *) clause)->constisnull &&
370
			 DatumGetBool(((Const *) clause)->constvalue))
371
		return NIL;				/* constant TRUE input -> NIL list */
372
	else
373
		return makeList1(clause);
374 375
}

T
Thomas G. Lockhart 已提交
376

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

381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
/*
 * 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))
399 400
		return true;			/* abort the tree traversal and return
								 * true */
401 402 403
	return expression_tree_walker(node, contain_agg_clause_walker, context);
}

404 405 406 407 408 409
/*
 * 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.
410 411
 *
 *	  Note: this also checks for nested aggregates, which are an error.
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
 */
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);
430

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

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

447 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

/*****************************************************************************
 *		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))
475 476
		return true;			/* abort the tree traversal and return
								 * true */
477 478 479 480 481 482 483
	return expression_tree_walker(node, contain_subplans_walker, context);
}

/*
 * pull_subplans
 *	  Recursively pulls all subplans from an expression tree.
 *
484
 *	  Returns list of subplan nodes found.	Note the nodes themselves are not
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
 *	  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);
}

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

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

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

544 545
	/*
	 * If we find an aggregate function, do not recurse into its
B
Bruce Momjian 已提交
546 547
	 * arguments.  Subplans invoked within aggregate calls are allowed to
	 * receive ungrouped variables.
548 549 550 551
	 */
	if (IsA(node, Aggref))
		return false;

552
	/*
553 554
	 * We can ignore Vars other than in subplan args lists, since the
	 * parser already checked 'em.
555 556 557
	 */
	if (is_subplan(node))
	{
558

559 560 561 562
		/*
		 * The args list of the subplan node represents attributes from
		 * outside passed into the sublink.
		 */
563
		List	   *t;
564 565 566 567

		foreach(t, ((Expr *) node)->args)
		{
			Node	   *thisarg = lfirst(t);
568 569
			Var		   *var;
			bool		contained_in_group_clause;
570 571
			List	   *gl;

572 573 574
			/*
			 * We do not care about args that are not local variables;
			 * params or outer-level vars are not our responsibility to
575 576
			 * check.  (The outer-level query passing them to us needs to
			 * worry, instead.)
577
			 */
578
			if (!IsA(thisarg, Var))
579 580 581 582 583 584 585 586 587
				continue;
			var = (Var *) thisarg;
			if (var->varlevelsup > 0)
				continue;

			/*
			 * Else, see if it is a grouping column.
			 */
			contained_in_group_clause = false;
588
			foreach(gl, context->groupClause)
589
			{
590 591
				GroupClause *gcl = lfirst(gl);
				Node	   *groupexpr;
592 593 594 595 596 597 598 599 600 601 602

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

			if (!contained_in_group_clause)
603 604
			{
				/* Found an ungrouped argument.  Complain. */
605 606
				RangeTblEntry *rte;
				char	   *attname;
607 608

				Assert(var->varno > 0 &&
609
					   (int) var->varno <= length(context->rtable));
610
				rte = rt_fetch(var->varno, context->rtable);
611
				attname = get_rte_attribute_name(rte, var->varattno);
612
				elog(ERROR, "Sub-SELECT uses un-GROUPed attribute %s.%s from outer query",
613
					 rte->eref->relname, attname);
614
			}
615 616 617
		}
	}
	return expression_tree_walker(node,
618
								check_subplans_for_ungrouped_vars_walker,
619 620 621 622
								  (void *) context);
}


623
/*****************************************************************************
624
 *		Check clauses for noncachable functions
625 626
 *****************************************************************************/

627 628 629 630 631
/*
 * contain_noncachable_functions
 *	  Recursively search for noncachable functions within a clause.
 *
 * Returns true if any noncachable function (or operator implemented by a
B
Bruce Momjian 已提交
632
 * noncachable function) is found.	This test is needed so that we don't
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
 * 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:
B
Bruce Momjian 已提交
657
				if (!op_iscachable(((Oper *) expr->oper)->opno))
658 659 660
					return true;
				break;
			case FUNC_EXPR:
B
Bruce Momjian 已提交
661
				if (!func_iscachable(((Func *) expr->oper)->funcid))
662 663 664 665 666 667 668 669 670 671 672 673 674 675
					return true;
				break;
			default:
				break;
		}
	}
	return expression_tree_walker(node, contain_noncachable_functions_walker,
								  context);
}


/*****************************************************************************
 *		Check for "pseudo-constant" clauses
 *****************************************************************************/
676 677

/*
678 679 680 681
 * 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
B
Bruce Momjian 已提交
682
 *	  Params and outer-level Vars.	However, its value will be constant over
683 684 685 686 687 688
 *	  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)
{
B
Bruce Momjian 已提交
689

690 691 692 693 694 695 696 697 698 699 700 701
	/*
	 * 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;
}

702
/*
703
 * pull_constant_clauses
704 705
 *		Scan through a list of qualifications and separate "constant" quals
 *		from those that are not.
706
 *
707 708
 * Returns a list of the pseudo-constant clauses in constantQual and the
 * remaining quals as the return value.
709 710
 */
List *
711
pull_constant_clauses(List *quals, List **constantQual)
712 713
{
	List	   *constqual = NIL;
714 715
	List	   *restqual = NIL;
	List	   *q;
716 717 718

	foreach(q, quals)
	{
B
Bruce Momjian 已提交
719
		Node	   *qual = (Node *) lfirst(q);
720

721
		if (is_pseudo_constant_clause(qual))
722
			constqual = lappend(constqual, qual);
723 724
		else
			restqual = lappend(restqual, qual);
725 726
	}
	*constantQual = constqual;
727
	return restqual;
728 729 730
}


731 732 733 734 735 736
/*****************************************************************************
 *																			 *
 *		General clause-manipulating routines								 *
 *																			 *
 *****************************************************************************/

737
/*
738
 * clause_relids_vars
739 740 741 742 743 744 745 746
 *	  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...
747 748 749
 *
 * Note that upper-level vars are ignored, since they normally will
 * become Params with respect to this query level.
750 751
 */
void
752
clause_get_relids_vars(Node *clause, Relids *relids, List **vars)
753
{
754
	List	   *clvars = pull_var_clause(clause, false);
755
	List	   *varno_list = NIL;
756
	List	   *var_list = NIL;
757
	List	   *i;
758

759
	foreach(i, clvars)
M
Marc G. Fournier 已提交
760
	{
761 762
		Var		   *var = (Var *) lfirst(i);
		List	   *vi;
763 764

		if (!intMember(var->varno, varno_list))
765
			varno_list = lconsi(var->varno, varno_list);
766 767
		foreach(vi, var_list)
		{
768
			Var		   *in_list = (Var *) lfirst(vi);
769

770
			if (in_list->varno == var->varno &&
V
Vadim B. Mikheev 已提交
771
				in_list->varattno == var->varattno)
772 773 774
				break;
		}
		if (vi == NIL)
775
			var_list = lcons(var, var_list);
M
Marc G. Fournier 已提交
776
	}
777
	freeList(clvars);
778

779 780
	*relids = varno_list;
	*vars = var_list;
781 782
}

783
/*
784 785
 * NumRelids
 *		(formerly clause_relids)
786
 *
787 788 789
 * Returns the number of different relations referenced in 'clause'.
 */
int
790
NumRelids(Node *clause)
791
{
792 793
	List	   *varno_list = pull_varnos(clause);
	int			result = length(varno_list);
794

795
	freeList(varno_list);
796
	return result;
797 798
}

799 800
/*--------------------
 * CommuteClause: commute a binary operator clause
801 802
 *
 * XXX the clause is destructively modified!
803 804
 *--------------------
 */
805
void
806
CommuteClause(Expr *clause)
807
{
808 809
	Oid			opoid;
	HeapTuple	optup;
810 811 812
	Form_pg_operator commuTup;
	Oper	   *commu;
	Node	   *temp;
813

814 815 816
	if (!is_opclause((Node *) clause) ||
		length(clause->args) != 2)
		elog(ERROR, "CommuteClause: applied to non-binary-operator clause");
817

818
	opoid = ((Oper *) clause->oper)->opno;
819

820 821 822 823 824
	optup = SearchSysCache(OPEROID,
						   ObjectIdGetDatum(get_commutator(opoid)),
						   0, 0, 0);
	if (!HeapTupleIsValid(optup))
		elog(ERROR, "CommuteClause: no commutator for operator %u", opoid);
825

826
	commuTup = (Form_pg_operator) GETSTRUCT(optup);
827

828
	commu = makeOper(optup->t_data->t_oid,
829
					 commuTup->oprcode,
830
					 commuTup->oprresult);
831

832 833
	ReleaseSysCache(optup);

834
	/*
835
	 * re-form the clause in-place!
836
	 */
837 838 839 840
	clause->oper = (Node *) commu;
	temp = lfirst(clause->args);
	lfirst(clause->args) = lsecond(clause->args);
	lsecond(clause->args) = temp;
841
}
842 843


844 845 846 847 848 849 850
/*--------------------
 * 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
851
 * the subexpression x is.	(XXX We assume that no such subexpression
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882
 * 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 *
883
eval_const_expressions_mutator(Node *node, void *context)
884 885 886 887 888 889 890 891
{
	if (node == NULL)
		return NULL;
	if (IsA(node, Expr))
	{
		Expr	   *expr = (Expr *) node;
		List	   *args;
		Const	   *const_input;
892
		Expr	   *newexpr;
893 894 895

		/*
		 * Reduce constants in the Expr's arguments.  We know args is
896 897
		 * either NIL or a List node, so we can call
		 * expression_tree_mutator directly rather than recursing to self.
898 899
		 */
		args = (List *) expression_tree_mutator((Node *) expr->args,
900
										  eval_const_expressions_mutator,
901 902 903 904 905 906
												(void *) context);

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

908
				/*
909 910
				 * Code for op/func case is pretty bulky, so split it out
				 * as a separate function.
911
				 */
912 913 914
				newexpr = simplify_op_or_func(expr, args);
				if (newexpr)	/* successfully simplified it */
					return (Node *) newexpr;
915

916
				/*
917 918
				 * else fall out to build new Expr node with simplified
				 * args
919
				 */
920 921
				break;
			case OR_EXPR:
922
				{
923

924 925 926 927 928 929 930 931 932
					/*----------
					 * 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.
					 *----------
933 934 935 936 937 938 939
					 */
					List	   *newargs = NIL;
					List	   *arg;
					bool		haveNull = false;
					bool		forceTrue = false;

					foreach(arg, args)
940
					{
941 942 943 944 945 946 947 948
						if (!IsA(lfirst(arg), Const))
						{
							newargs = lappend(newargs, lfirst(arg));
							continue;
						}
						const_input = (Const *) lfirst(arg);
						if (const_input->constisnull)
							haveNull = true;
949
						else if (DatumGetBool(const_input->constvalue))
950 951
							forceTrue = true;
						/* otherwise, we can drop the constant-false input */
952
					}
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972

					/*
					 * 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);
973 974 975
				}
			case AND_EXPR:
				{
976

977 978 979 980 981 982 983
					/*----------
					 * 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
984
					 * when no input is FALSE and at least one is NULL.
985
					 *----------
986 987 988 989 990 991 992
					 */
					List	   *newargs = NIL;
					List	   *arg;
					bool		haveNull = false;
					bool		forceFalse = false;

					foreach(arg, args)
993
					{
994 995 996 997 998 999 1000 1001
						if (!IsA(lfirst(arg), Const))
						{
							newargs = lappend(newargs, lfirst(arg));
							continue;
						}
						const_input = (Const *) lfirst(arg);
						if (const_input->constisnull)
							haveNull = true;
1002
						else if (!DatumGetBool(const_input->constvalue))
1003 1004
							forceFalse = true;
						/* otherwise, we can drop the constant-true input */
1005
					}
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025

					/*
					 * 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);
1026 1027 1028
				}
			case NOT_EXPR:
				Assert(length(args) == 1);
1029
				if (!IsA(lfirst(args), Const))
1030 1031 1032 1033 1034 1035
					break;
				const_input = (Const *) lfirst(args);
				/* NOT NULL => NULL */
				if (const_input->constisnull)
					return MAKEBOOLCONST(false, true);
				/* otherwise pretty easy */
1036
				return MAKEBOOLCONST(!DatumGetBool(const_input->constvalue),
1037 1038
									 false);
			case SUBPLAN_EXPR:
1039

1040 1041
				/*
				 * Safety measure per notes at head of this routine:
1042
				 * return a SubPlan unchanged.	Too late to do anything
1043
				 * with it.  The arglist simplification above was wasted
1044 1045
				 * work (the list probably only contains Var nodes
				 * anyway).
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
				 */
				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
1056 1057 1058 1059 1060
		 * 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...
1061 1062
		 */
		newexpr = makeNode(Expr);
1063 1064 1065 1066 1067
		newexpr->typeOid = expr->typeOid;
		newexpr->opType = expr->opType;
		newexpr->oper = expr->oper;
		newexpr->args = args;
		return (Node *) newexpr;
1068
	}
1069 1070
	if (IsA(node, RelabelType))
	{
1071

1072 1073
		/*
		 * If we can simplify the input to a constant, then we don't need
1074
		 * the RelabelType node anymore: just change the type field of the
1075
		 * Const node.	Otherwise, must copy the RelabelType node.
1076 1077 1078 1079 1080
		 */
		RelabelType *relabel = (RelabelType *) node;
		Node	   *arg;

		arg = eval_const_expressions_mutator(relabel->arg, context);
1081 1082

		/*
B
Bruce Momjian 已提交
1083 1084
		 * If we find stacked RelabelTypes (eg, from foo :: int :: oid) we
		 * can discard all but the top one.
1085 1086 1087 1088
		 */
		while (arg && IsA(arg, RelabelType))
			arg = ((RelabelType *) arg)->arg;

1089 1090
		if (arg && IsA(arg, Const))
		{
1091
			Const	   *con = (Const *) arg;
1092 1093

			con->consttype = relabel->resulttype;
1094

1095 1096 1097
			/*
			 * relabel's resulttypmod is discarded, which is OK for now;
			 * if the type actually needs a runtime length coercion then
1098 1099
			 * there should be a function call to do it just above this
			 * node.
1100
			 */
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
			return (Node *) con;
		}
		else
		{
			RelabelType *newrelabel = makeNode(RelabelType);

			newrelabel->arg = arg;
			newrelabel->resulttype = relabel->resulttype;
			newrelabel->resulttypmod = relabel->resulttypmod;
			return (Node *) newrelabel;
		}
	}
1113 1114
	if (IsA(node, CaseExpr))
	{
1115

T
Tom Lane 已提交
1116
		/*----------
1117
		 * CASE expressions can be simplified if there are constant
T
Tom Lane 已提交
1118 1119 1120 1121 1122 1123 1124 1125
		 * 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).
		 *----------
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
		 */
		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 *)
1138 1139 1140 1141
			expression_tree_mutator((Node *) lfirst(arg),
									eval_const_expressions_mutator,
									(void *) context);

1142 1143
			Assert(IsA(casewhen, CaseWhen));
			if (casewhen->expr == NULL ||
1144
				!IsA(casewhen->expr, Const))
1145 1146 1147 1148 1149 1150
			{
				newargs = lappend(newargs, casewhen);
				continue;
			}
			const_input = (Const *) casewhen->expr;
			if (const_input->constisnull ||
1151
				!DatumGetBool(const_input->constvalue))
1152
				continue;		/* drop alternative with FALSE condition */
1153

1154
			/*
1155
			 * Found a TRUE condition.	If it's the first (un-dropped)
1156 1157 1158 1159
			 * alternative, the CASE reduces to just this alternative.
			 */
			if (newargs == NIL)
				return casewhen->result;
1160

1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
			/*
			 * 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);
1171 1172 1173 1174 1175

		/*
		 * If no non-FALSE alternatives, CASE reduces to the default
		 * result
		 */
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
		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))
	{
1188

1189
		/*
1190 1191 1192 1193 1194
		 * 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?
1195 1196 1197 1198 1199
		 */
		Iter	   *iter = (Iter *) node;

		if (is_funcclause(iter->iterexpr))
		{
1200 1201 1202
			Expr	   *func = (Expr *) iter->iterexpr;
			Expr	   *newfunc;
			Iter	   *newiter;
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217

			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;
		}
	}
1218

1219 1220
	/*
	 * For any node type not handled above, we recurse using
1221 1222 1223 1224
	 * 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.
1225 1226 1227 1228 1229
	 */
	return expression_tree_mutator(node, eval_const_expressions_mutator,
								   (void *) context);
}

1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
/*
 * 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
1242
 * that here, not in the parser, since we wouldn't want it to happen until
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
 * 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;
1253 1254 1255 1256
	bool		proiscachable;
	bool		proisstrict;
	bool		proretset;
	int16		resultTypLen;
1257
	bool		resultTypByVal;
1258
	Expr	   *newexpr;
1259
	ExprContext *econtext;
1260
	Datum		const_val;
1261 1262
	bool		has_nonconst_input = false;
	bool		has_null_input = false;
1263 1264 1265
	bool		const_is_null;

	/*
1266
	 * Check for constant inputs and especially constant-NULL inputs.
1267 1268 1269
	 */
	foreach(arg, args)
	{
1270 1271 1272 1273
		if (IsA(lfirst(arg), Const))
			has_null_input |= ((Const *) lfirst(arg))->constisnull;
		else
			has_nonconst_input = true;
1274
	}
1275

1276 1277 1278 1279
	/*
	 * 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.
B
Bruce Momjian 已提交
1280 1281
	 * Otherwise, we can only simplify if all inputs are constants. We can
	 * skip the function lookup if neither case applies.
1282 1283 1284 1285
	 */
	if (has_nonconst_input && !has_null_input)
		return NULL;

1286
	/*
1287 1288
	 * Get the function procedure's OID and look to see whether it is
	 * marked proiscachable.
1289 1290 1291
	 *
	 * XXX would it be better to take the result type from the pg_proc tuple,
	 * rather than the Oper or Func node?
1292 1293 1294
	 */
	if (expr->opType == OP_EXPR)
	{
1295
		Oper	   *oper = (Oper *) expr->oper;
1296 1297 1298 1299 1300 1301 1302

		replace_opid(oper);		/* OK to scribble on input to this extent */
		funcid = oper->opid;
		result_typeid = oper->opresulttype;
	}
	else
	{
1303
		Func	   *func = (Func *) expr->oper;
1304 1305 1306 1307

		funcid = func->funcid;
		result_typeid = func->functype;
	}
B
Bruce Momjian 已提交
1308

1309
	/*
B
Bruce Momjian 已提交
1310 1311
	 * 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.
1312
	 */
1313 1314 1315
	func_tuple = SearchSysCache(PROCOID,
								ObjectIdGetDatum(funcid),
								0, 0, 0);
1316 1317 1318
	if (!HeapTupleIsValid(func_tuple))
		elog(ERROR, "Function OID %u does not exist", funcid);
	funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
1319 1320 1321 1322 1323 1324
	proiscachable = funcform->proiscachable;
	proisstrict = funcform->proisstrict;
	proretset = funcform->proretset;
	ReleaseSysCache(func_tuple);

	if (!proiscachable)
1325
		return NULL;
1326

1327 1328 1329
	/*
	 * Also check to make sure it doesn't return a set.
	 */
1330
	if (proretset)
1331
		return NULL;
1332

1333 1334 1335 1336
	/*
	 * Now that we know if the function is strict, we can finish the
	 * checks for simplifiable inputs that we started above.
	 */
1337
	if (proisstrict && has_null_input)
1338
	{
B
Bruce Momjian 已提交
1339

1340 1341 1342 1343
		/*
		 * It's strict and has NULL input, so must produce NULL output.
		 * Return a NULL constant of the right type.
		 */
1344
		return (Expr *) makeNullConst(result_typeid);
1345 1346 1347
	}

	/*
B
Bruce Momjian 已提交
1348 1349 1350
	 * 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.)
1351 1352 1353 1354
	 */
	if (has_nonconst_input)
		return NULL;

1355 1356 1357 1358 1359 1360
	/*
	 * 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.
	 *
1361 1362
	 * Build a new Expr node containing the already-simplified arguments. The
	 * only other setup needed here is the replace_opid() that we already
1363 1364 1365 1366 1367 1368 1369
	 * did for the OP_EXPR case.
	 */
	newexpr = makeNode(Expr);
	newexpr->typeOid = expr->typeOid;
	newexpr->opType = expr->opType;
	newexpr->oper = expr->oper;
	newexpr->args = args;
1370

1371
	/* Get info needed about result datatype */
1372
	get_typlenbyval(result_typeid, &resultTypLen, &resultTypByVal);
1373

1374
	/*
B
Bruce Momjian 已提交
1375 1376 1377 1378
	 * It is OK to pass a dummy econtext because none of the
	 * ExecEvalExpr() code used in this situation will use econtext.  That
	 * might seem fortuitous, but it's not so unreasonable --- a constant
	 * expression does not depend on context, by definition, n'est ce pas?
1379
	 */
1380 1381 1382
	econtext = MakeExprContext(NULL, CurrentMemoryContext);

	const_val = ExecEvalExprSwitchContext((Node *) newexpr, econtext,
1383
										  &const_is_null, NULL);
1384 1385 1386 1387 1388

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

	FreeExprContext(econtext);
1389
	pfree(newexpr);
1390

1391 1392 1393
	/*
	 * Make the constant result node.
	 */
1394
	return (Expr *) makeConst(result_typeid, resultTypLen,
1395
							  const_val, const_is_null,
1396
							  resultTypByVal, false, false);
1397 1398 1399
}


1400
/*
1401 1402 1403 1404 1405 1406 1407 1408 1409
 * 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
1410 1411 1412 1413 1414
 * logic to consolidate the redundant "boilerplate" code.  There are
 * two versions: expression_tree_walker() and expression_tree_mutator().
 */

/*--------------------
1415 1416
 * expression_tree_walker() is designed to support routines that traverse
 * a tree in a read-only fashion (although it will also work for routines
1417 1418
 * that modify nodes in-place but never add/delete/replace nodes).
 * A walker routine should look like this:
1419 1420 1421 1422 1423
 *
 * bool my_walker (Node *node, my_struct *context)
 * {
 *		if (node == NULL)
 *			return false;
B
Cleanup  
Bruce Momjian 已提交
1424
 *		// check for nodes that special work is required for, eg:
1425 1426 1427 1428 1429 1430 1431 1432
 *		if (IsA(node, Var))
 *		{
 *			... do special actions for Var nodes
 *		}
 *		else if (IsA(node, ...))
 *		{
 *			... do special actions for other node types
 *		}
B
Cleanup  
Bruce Momjian 已提交
1433
 *		// for any node type not specially processed, do:
1434 1435 1436 1437
 *		return expression_tree_walker(node, my_walker, (void *) context);
 * }
 *
 * The "context" argument points to a struct that holds whatever context
1438 1439
 * information the walker routine needs --- it can be used to return data
 * gathered by the walker, too.  This argument is not touched by
1440 1441 1442 1443 1444 1445 1446
 * 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
1447 1448
 * 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
1449
 * iff no invocation of the walker returned "true".
1450 1451 1452 1453 1454 1455 1456
 *
 * 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
1457
 * chooses to process TargetEntry nodes specially.)  Also, RangeTblRef,
1458 1459
 * FromExpr, JoinExpr, and SetOperationStmt nodes are handled, so that query
 * jointrees and setOperation trees can be processed without additional code.
1460 1461 1462 1463 1464 1465 1466
 *
 * 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
B
Bruce Momjian 已提交
1467
 * during an expression tree walk.	This is exactly the behavior wanted
1468 1469
 * in many cases --- and for those walkers that do want to recurse into
 * sub-selects, special behavior is typically needed anyway at the entry
B
Bruce Momjian 已提交
1470
 * to a sub-select (such as incrementing a depth counter).	A walker that
1471 1472 1473 1474 1475
 * wants to examine sub-selects should include code along the lines of:
 *
 *		if (IsA(node, Query))
 *		{
 *			adjust context for subquery;
1476
 *			result = query_tree_walker((Query *) node, my_walker, context,
B
Cleanup  
Bruce Momjian 已提交
1477
 *									   true); // to visit subquery RTEs too
1478 1479 1480
 *			restore context if needed;
 *			return result;
 *		}
1481
 *
1482 1483
 * query_tree_walker is a convenience routine (see below) that calls the
 * walker on all the expression subtrees of the given Query node.
1484
 *
1485 1486 1487 1488
 * 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.
1489 1490 1491 1492
 *--------------------
 */

bool
1493 1494 1495
expression_tree_walker(Node *node,
					   bool (*walker) (),
					   void *context)
1496 1497 1498 1499
{
	List	   *temp;

	/*
1500 1501
	 * The walker has already visited the current node, and so we need
	 * only recurse into any sub-nodes it has.
1502
	 *
1503 1504
	 * 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
1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
	 * 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:
1515
		case T_RangeTblRef:
1516 1517 1518 1519
			/* primitive node types with no subnodes */
			break;
		case T_Expr:
			{
1520
				Expr	   *expr = (Expr *) node;
1521

1522 1523
				if (expr->opType == SUBPLAN_EXPR)
				{
1524 1525 1526
					/* recurse to the SubLink node (skipping SubPlan!) */
					if (walker((Node *) ((SubPlan *) expr->oper)->sublink,
							   context))
1527 1528
						return true;
				}
1529 1530 1531 1532
				/* for all Expr node types, examine args list */
				if (expression_tree_walker((Node *) expr->args,
										   walker, context))
					return true;
1533 1534 1535 1536 1537 1538 1539 1540 1541
			}
			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;
1542

1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556
				/* 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;
1557 1558
		case T_FieldSelect:
			return walker(((FieldSelect *) node)->arg, context);
1559 1560
		case T_RelabelType:
			return walker(((RelabelType *) node)->arg, context);
1561 1562 1563
		case T_CaseExpr:
			{
				CaseExpr   *caseexpr = (CaseExpr *) node;
1564

1565 1566 1567 1568
				/* we assume walker doesn't care about CaseWhens, either */
				foreach(temp, caseexpr->args)
				{
					CaseWhen   *when = (CaseWhen *) lfirst(temp);
1569

1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582
					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;
1583 1584 1585 1586
		case T_NullTest:
			return walker(((NullTest *) node)->arg, context);
		case T_BooleanTest:
			return walker(((BooleanTest *) node)->arg, context);
1587
		case T_SubLink:
1588
			{
1589
				SubLink    *sublink = (SubLink *) node;
1590

1591 1592
				/*
				 * If the SubLink has already been processed by
1593
				 * subselect.c, it will have lefthand=NIL, and we need to
B
Bruce Momjian 已提交
1594 1595 1596 1597
				 * 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).
1598 1599
				 */
				if (sublink->lefthand)
1600 1601 1602 1603
				{
					if (walker((Node *) sublink->lefthand, context))
						return true;
				}
1604
				else
1605 1606 1607 1608
				{
					if (walker((Node *) sublink->oper, context))
						return true;
				}
B
Bruce Momjian 已提交
1609

1610
				/*
B
Bruce Momjian 已提交
1611 1612
				 * Also invoke the walker on the sublink's Query node, so
				 * it can recurse into the sub-query if it wants to.
1613 1614
				 */
				return walker(sublink->subselect, context);
1615 1616
			}
			break;
1617 1618 1619
		case T_Query:
			/* Do nothing with a sub-Query, per discussion above */
			break;
1620 1621 1622 1623 1624 1625 1626 1627 1628
		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);
1629 1630
		case T_FromExpr:
			{
B
Bruce Momjian 已提交
1631
				FromExpr   *from = (FromExpr *) node;
1632 1633 1634 1635 1636 1637 1638

				if (walker(from->fromlist, context))
					return true;
				if (walker(from->quals, context))
					return true;
			}
			break;
1639 1640
		case T_JoinExpr:
			{
B
Bruce Momjian 已提交
1641
				JoinExpr   *join = (JoinExpr *) node;
1642 1643 1644 1645 1646 1647 1648 1649 1650

				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;
B
Bruce Momjian 已提交
1651 1652 1653

				/*
				 * alias clause, using list, colnames list are deemed
1654 1655 1656 1657
				 * uninteresting.
				 */
			}
			break;
1658 1659 1660 1661 1662 1663 1664 1665 1666 1667
		case T_SetOperationStmt:
			{
				SetOperationStmt *setop = (SetOperationStmt *) node;

				if (walker(setop->larg, context))
					return true;
				if (walker(setop->rarg, context))
					return true;
			}
			break;
1668 1669 1670 1671 1672 1673 1674
		default:
			elog(ERROR, "expression_tree_walker: Unexpected node type %d",
				 nodeTag(node));
			break;
	}
	return false;
}
1675

1676 1677 1678 1679 1680 1681 1682 1683
/*
 * 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.
1684 1685 1686 1687 1688
 *
 * 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.
1689 1690 1691 1692
 */
bool
query_tree_walker(Query *query,
				  bool (*walker) (),
1693 1694
				  void *context,
				  bool visitQueryRTEs)
1695 1696 1697 1698 1699
{
	Assert(query != NULL && IsA(query, Query));

	if (walker((Node *) query->targetList, context))
		return true;
1700
	if (walker((Node *) query->jointree, context))
1701
		return true;
1702 1703
	if (walker(query->setOperations, context))
		return true;
1704 1705
	if (walker(query->havingQual, context))
		return true;
1706 1707
	if (visitQueryRTEs)
	{
B
Bruce Momjian 已提交
1708
		List	   *rt;
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718

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

			if (rte->subquery)
				if (walker(rte->subquery, context))
					return true;
		}
	}
1719 1720 1721 1722
	return false;
}


1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734
/*--------------------
 * 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;
B
Cleanup  
Bruce Momjian 已提交
1735
 *		// check for nodes that special work is required for, eg:
1736 1737 1738 1739 1740 1741 1742 1743
 *		if (IsA(node, Var))
 *		{
 *			... create and return modified copy of Var node
 *		}
 *		else if (IsA(node, ...))
 *		{
 *			... do special transformations of other node types
 *		}
B
Cleanup  
Bruce Momjian 已提交
1744
 *		// for any node type not specially processed, do:
1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770
 *		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
1771 1772
 * can force appropriate behavior by recognizing subplan expression nodes
 * and doing the right thing.
1773 1774 1775 1776 1777 1778 1779 1780 1781 1782
 *
 * 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 *
1783 1784 1785
expression_tree_mutator(Node *node,
						Node *(*mutator) (),
						void *context)
1786
{
1787

1788
	/*
1789 1790
	 * The mutator has already decided not to modify the current node, but
	 * we must call the mutator for any sub-nodes.
1791 1792 1793 1794 1795 1796
	 */

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

1797
#define CHECKFLATCOPY(newnode, node, nodetype)	\
1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812
	( 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:
1813
		case T_RangeTblRef:
1814 1815 1816 1817
			/* primitive node types with no subnodes */
			return (Node *) copyObject(node);
		case T_Expr:
			{
1818 1819
				Expr	   *expr = (Expr *) node;
				Expr	   *newnode;
1820 1821 1822 1823 1824

				FLATCOPY(newnode, expr, Expr);

				if (expr->opType == SUBPLAN_EXPR)
				{
1825 1826
					SubLink    *oldsublink = ((SubPlan *) expr->oper)->sublink;
					SubPlan    *newsubplan;
1827 1828 1829 1830 1831 1832

					/* 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);
1833 1834 1835 1836 1837

					/*
					 * transform args list (params to be passed to
					 * subplan)
					 */
1838 1839
					MUTATE(newnode->args, expr->args, List *);
					/* transform sublink's oper list as well */
1840 1841 1842 1843 1844 1845
					MUTATE(newsubplan->sublink->oper, oldsublink->oper, List *);

					/*
					 * but not the subplan itself, which is referenced
					 * as-is
					 */
1846 1847 1848
				}
				else
				{
1849 1850 1851 1852

					/*
					 * for other Expr node types, just transform args
					 * list, linking to original oper node (OK?)
1853 1854 1855 1856 1857 1858 1859 1860
					 */
					MUTATE(newnode->args, expr->args, List *);
				}
				return (Node *) newnode;
			}
			break;
		case T_Aggref:
			{
1861 1862
				Aggref	   *aggref = (Aggref *) node;
				Aggref	   *newnode;
1863 1864 1865 1866 1867 1868 1869 1870

				FLATCOPY(newnode, aggref, Aggref);
				MUTATE(newnode->target, aggref->target, Node *);
				return (Node *) newnode;
			}
			break;
		case T_Iter:
			{
1871 1872
				Iter	   *iter = (Iter *) node;
				Iter	   *newnode;
1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895

				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;
1896 1897 1898 1899 1900 1901 1902 1903 1904 1905
		case T_FieldSelect:
			{
				FieldSelect *fselect = (FieldSelect *) node;
				FieldSelect *newnode;

				FLATCOPY(newnode, fselect, FieldSelect);
				MUTATE(newnode->arg, fselect->arg, Node *);
				return (Node *) newnode;
			}
			break;
1906 1907 1908 1909 1910 1911 1912 1913 1914 1915
		case T_RelabelType:
			{
				RelabelType *relabel = (RelabelType *) node;
				RelabelType *newnode;

				FLATCOPY(newnode, relabel, RelabelType);
				MUTATE(newnode->arg, relabel->arg, Node *);
				return (Node *) newnode;
			}
			break;
1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939
		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;
1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959
		case T_NullTest:
			{
				NullTest *ntest = (NullTest *) node;
				NullTest *newnode;

				FLATCOPY(newnode, ntest, NullTest);
				MUTATE(newnode->arg, ntest->arg, Node *);
				return (Node *) newnode;
			}
			break;
		case T_BooleanTest:
			{
				BooleanTest *btest = (BooleanTest *) node;
				BooleanTest *newnode;

				FLATCOPY(newnode, btest, BooleanTest);
				MUTATE(newnode->arg, btest->arg, Node *);
				return (Node *) newnode;
			}
			break;
1960 1961
		case T_SubLink:
			{
1962 1963 1964 1965 1966

				/*
				 * 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.
1967
				 */
1968 1969
				SubLink    *sublink = (SubLink *) node;
				SubLink    *newnode;
1970 1971 1972 1973 1974 1975 1976 1977

				FLATCOPY(newnode, sublink, SubLink);
				MUTATE(newnode->lefthand, sublink->lefthand, List *);
				return (Node *) newnode;
			}
			break;
		case T_List:
			{
1978 1979 1980 1981 1982 1983

				/*
				 * 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!
1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998
				 */
				List	   *resultlist = NIL;
				List	   *temp;

				foreach(temp, (List *) node)
				{
					resultlist = lappend(resultlist,
										 mutator((Node *) lfirst(temp),
												 context));
				}
				return (Node *) resultlist;
			}
			break;
		case T_TargetEntry:
			{
1999 2000 2001 2002 2003 2004 2005

				/*
				 * We mutate the expression, but not the resdom, by
				 * default.
				 */
				TargetEntry *targetentry = (TargetEntry *) node;
				TargetEntry *newnode;
2006 2007 2008 2009 2010 2011

				FLATCOPY(newnode, targetentry, TargetEntry);
				MUTATE(newnode->expr, targetentry->expr, Node *);
				return (Node *) newnode;
			}
			break;
2012 2013
		case T_FromExpr:
			{
B
Bruce Momjian 已提交
2014 2015
				FromExpr   *from = (FromExpr *) node;
				FromExpr   *newnode;
2016 2017 2018 2019 2020 2021 2022

				FLATCOPY(newnode, from, FromExpr);
				MUTATE(newnode->fromlist, from->fromlist, List *);
				MUTATE(newnode->quals, from->quals, Node *);
				return (Node *) newnode;
			}
			break;
2023 2024
		case T_JoinExpr:
			{
B
Bruce Momjian 已提交
2025 2026
				JoinExpr   *join = (JoinExpr *) node;
				JoinExpr   *newnode;
2027 2028 2029 2030 2031 2032 2033 2034 2035 2036

				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;
2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047
		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;
2048 2049 2050 2051 2052 2053 2054 2055
		default:
			elog(ERROR, "expression_tree_mutator: Unexpected node type %d",
				 nodeTag(node));
			break;
	}
	/* can't get here, but keep compiler happy */
	return NULL;
}
2056 2057 2058 2059 2060 2061 2062 2063


/*
 * 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
B
Bruce Momjian 已提交
2064
 * mutator intends to descend into subqueries.	It is also useful for
2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089
 * 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)
	{
B
Bruce Momjian 已提交
2090 2091
		List	   *newrt = NIL;
		List	   *rt;
2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110

		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;
	}
}