clauses.c 111 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * clauses.c
4
 *	  routines to manipulate qualification clauses
5
 *
6
 * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
Bruce Momjian's avatar
Add:  
Bruce Momjian committed
7
 * Portions Copyright (c) 1994, Regents of the University of California
8 9 10
 *
 *
 * IDENTIFICATION
11
 *	  $PostgreSQL: pgsql/src/backend/optimizer/util/clauses.c,v 1.207 2006/01/31 21:39:24 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 "access/heapam.h"
23
#include "catalog/pg_aggregate.h"
24
#include "catalog/pg_language.h"
25
#include "catalog/pg_operator.h"
26 27 28
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "executor/executor.h"
29
#include "executor/functions.h"
30
#include "miscadmin.h"
31 32
#include "nodes/makefuncs.h"
#include "optimizer/clauses.h"
33
#include "optimizer/cost.h"
34
#include "optimizer/planmain.h"
35
#include "optimizer/planner.h"
36
#include "optimizer/var.h"
37
#include "parser/analyze.h"
38
#include "parser/parse_clause.h"
39
#include "parser/parse_coerce.h"
40
#include "parser/parse_expr.h"
41 42 43
#include "tcop/tcopprot.h"
#include "utils/acl.h"
#include "utils/builtins.h"
44
#include "utils/datum.h"
Bruce Momjian's avatar
Bruce Momjian committed
45
#include "utils/lsyscache.h"
46
#include "utils/memutils.h"
47
#include "utils/syscache.h"
48
#include "utils/typcache.h"
49

50

51 52 53
typedef struct
{
	List	   *active_fns;
54
	Node	   *case_val;
55 56 57
	bool		estimate;
} eval_const_expressions_context;

58 59 60 61 62
typedef struct
{
	int			nargs;
	List	   *args;
	int		   *usecounts;
63
} substitute_actual_parameters_context;
64

65
static bool contain_agg_clause_walker(Node *node, void *context);
66
static bool count_agg_clauses_walker(Node *node, AggClauseCounts *counts);
67
static bool expression_returns_set_walker(Node *node, void *context);
68
static bool contain_subplans_walker(Node *node, void *context);
69 70
static bool contain_mutable_functions_walker(Node *node, void *context);
static bool contain_volatile_functions_walker(Node *node, void *context);
71
static bool contain_nonstrict_functions_walker(Node *node, void *context);
72
static Relids find_nonnullable_rels_walker(Node *node, bool top_level);
73
static bool set_coercionform_dontcare_walker(Node *node, void *context);
74
static Node *eval_const_expressions_mutator(Node *node,
Bruce Momjian's avatar
Bruce Momjian committed
75
							   eval_const_expressions_context *context);
76
static List *simplify_or_arguments(List *args,
77
					  eval_const_expressions_context *context,
Bruce Momjian's avatar
Bruce Momjian committed
78
					  bool *haveNull, bool *forceTrue);
79
static List *simplify_and_arguments(List *args,
80
					   eval_const_expressions_context *context,
Bruce Momjian's avatar
Bruce Momjian committed
81
					   bool *haveNull, bool *forceFalse);
82
static Expr *simplify_boolean_equality(List *args);
83
static Expr *simplify_function(Oid funcid, Oid result_type, List *args,
Bruce Momjian's avatar
Bruce Momjian committed
84 85
				  bool allow_inline,
				  eval_const_expressions_context *context);
86
static Expr *evaluate_function(Oid funcid, Oid result_type, List *args,
87 88
				  HeapTuple func_tuple,
				  eval_const_expressions_context *context);
89
static Expr *inline_function(Oid funcid, Oid result_type, List *args,
Bruce Momjian's avatar
Bruce Momjian committed
90 91
				HeapTuple func_tuple,
				eval_const_expressions_context *context);
92
static Node *substitute_actual_parameters(Node *expr, int nargs, List *args,
Bruce Momjian's avatar
Bruce Momjian committed
93
							 int *usecounts);
94
static Node *substitute_actual_parameters_mutator(Node *node,
95
							  substitute_actual_parameters_context *context);
96
static void sql_inline_error_callback(void *arg);
97
static Expr *evaluate_expr(Expr *expr, Oid result_type);
98

99 100

/*****************************************************************************
101
 *		OPERATOR clause functions
102 103
 *****************************************************************************/

104
/*
105
 * make_opclause
106 107
 *	  Creates an operator clause given its operator info, left operand,
 *	  and right operand (pass NULL to create single-operand clause).
108
 */
109
Expr *
110 111
make_opclause(Oid opno, Oid opresulttype, bool opretset,
			  Expr *leftop, Expr *rightop)
112
{
113
	OpExpr	   *expr = makeNode(OpExpr);
114

115 116 117 118
	expr->opno = opno;
	expr->opfuncid = InvalidOid;
	expr->opresulttype = opresulttype;
	expr->opretset = opretset;
119
	if (rightop)
120
		expr->args = list_make2(leftop, rightop);
121
	else
122
		expr->args = list_make1(leftop);
123
	return (Expr *) 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
Node *
133
get_leftop(Expr *clause)
134
{
Bruce Momjian's avatar
Bruce Momjian committed
135
	OpExpr	   *expr = (OpExpr *) clause;
136

137
	if (expr->args != NIL)
138
		return linitial(expr->args);
139 140
	else
		return NULL;
141 142
}

143
/*
144
 * get_rightop
145
 *
146
 * Returns the right operand in a clause of the form (op expr expr).
147
 * NB: result will be NULL if applied to a unary op clause.
148
 */
149
Node *
150
get_rightop(Expr *clause)
151
{
Bruce Momjian's avatar
Bruce Momjian committed
152
	OpExpr	   *expr = (OpExpr *) clause;
153

154 155
	if (list_length(expr->args) >= 2)
		return lsecond(expr->args);
156 157
	else
		return NULL;
158 159 160
}

/*****************************************************************************
161
 *		NOT clause functions
162 163
 *****************************************************************************/

164
/*
165
 * not_clause
166
 *
167
 * Returns t iff this is a 'not' clause: (NOT expr).
168 169
 */
bool
170
not_clause(Node *clause)
171
{
172
	return (clause != NULL &&
173 174
			IsA(clause, BoolExpr) &&
			((BoolExpr *) clause)->boolop == NOT_EXPR);
175 176
}

177
/*
178
 * make_notclause
179
 *
180
 * Create a 'not' clause given the expression to be negated.
181
 */
182
Expr *
183
make_notclause(Expr *notclause)
184
{
185
	BoolExpr   *expr = makeNode(BoolExpr);
186

187
	expr->boolop = NOT_EXPR;
188
	expr->args = list_make1(notclause);
189
	return (Expr *) expr;
190 191
}

192
/*
193
 * get_notclausearg
194
 *
195
 * Retrieve the clause within a 'not' clause
196
 */
197 198
Expr *
get_notclausearg(Expr *notclause)
199
{
200
	return linitial(((BoolExpr *) notclause)->args);
201 202
}

203 204 205 206
/*****************************************************************************
 *		OR clause functions
 *****************************************************************************/

207
/*
208
 * or_clause
209
 *
210
 * Returns t iff the clause is an 'or' clause: (OR { expr }).
211
 */
212 213
bool
or_clause(Node *clause)
214
{
215 216 217
	return (clause != NULL &&
			IsA(clause, BoolExpr) &&
			((BoolExpr *) clause)->boolop == OR_EXPR);
218 219
}

220
/*
221
 * make_orclause
222
 *
223
 * Creates an 'or' clause given a list of its subclauses.
224
 */
225
Expr *
226
make_orclause(List *orclauses)
227
{
228 229 230 231 232
	BoolExpr   *expr = makeNode(BoolExpr);

	expr->boolop = OR_EXPR;
	expr->args = orclauses;
	return (Expr *) expr;
233 234 235
}

/*****************************************************************************
236
 *		AND clause functions
237 238 239
 *****************************************************************************/


240
/*
241
 * and_clause
242
 *
243 244 245
 * Returns t iff its argument is an 'and' clause: (AND { expr }).
 */
bool
246
and_clause(Node *clause)
247
{
248
	return (clause != NULL &&
249 250
			IsA(clause, BoolExpr) &&
			((BoolExpr *) clause)->boolop == AND_EXPR);
251
}
252 253

/*
254
 * make_andclause
255
 *
256
 * Creates an 'and' clause given a list of its subclauses.
257
 */
258
Expr *
259
make_andclause(List *andclauses)
260
{
261
	BoolExpr   *expr = makeNode(BoolExpr);
262

263
	expr->boolop = AND_EXPR;
264
	expr->args = andclauses;
265
	return (Expr *) expr;
266 267
}

268 269 270 271 272 273
/*
 * 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'.
274 275 276
 *
 * NB: this makes no attempt to preserve AND/OR flatness; so it should not
 * be used on a qual that has already been run through prepqual.c.
277 278 279 280 281 282 283 284
 */
Node *
make_and_qual(Node *qual1, Node *qual2)
{
	if (qual1 == NULL)
		return qual2;
	if (qual2 == NULL)
		return qual1;
285
	return (Node *) make_andclause(list_make2(qual1, qual2));
286 287
}

288
/*
289 290
 * Sometimes (such as in the input of ExecQual), we use lists of expression
 * nodes with implicit AND semantics.
291 292 293 294 295
 *
 * 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.
296 297 298 299 300
 */
Expr *
make_ands_explicit(List *andclauses)
{
	if (andclauses == NIL)
301
		return (Expr *) makeBoolConst(true, false);
302
	else if (list_length(andclauses) == 1)
303
		return (Expr *) linitial(andclauses);
304 305 306
	else
		return make_andclause(andclauses);
}
307

308 309 310
List *
make_ands_implicit(Expr *clause)
{
311
	/*
312 313 314 315
	 * 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, even
	 * though one might more reasonably think it FALSE.  Grumble. If this
	 * causes trouble, consider changing the parser's behavior.
316
	 */
317
	if (clause == NULL)
318
		return NIL;				/* NULL -> NIL list == TRUE */
319
	else if (and_clause((Node *) clause))
320
		return ((BoolExpr *) clause)->args;
321
	else if (IsA(clause, Const) &&
322
			 !((Const *) clause)->constisnull &&
323
			 DatumGetBool(((Const *) clause)->constvalue))
324
		return NIL;				/* constant TRUE input -> NIL list */
325
	else
326
		return list_make1(clause);
327 328
}

329

330
/*****************************************************************************
331
 *		Aggregate-function clause manipulation
332 333
 *****************************************************************************/

334 335 336 337 338
/*
 * contain_agg_clause
 *	  Recursively search for Aggref nodes within a clause.
 *
 *	  Returns true if any aggregate found.
339 340 341 342 343 344 345
 *
 * This does not descend into subqueries, and so should be used only after
 * reduction of sublinks to subplans, or in contexts where it's known there
 * are no subqueries.  There mustn't be outer-aggregate references either.
 *
 * (If you want something like this but able to deal with subqueries,
 * see rewriteManip.c's checkExprHasAggs().)
346 347 348 349 350 351 352 353 354 355 356 357 358
 */
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))
359 360
	{
		Assert(((Aggref *) node)->agglevelsup == 0);
361
		return true;			/* abort the tree traversal and return true */
362 363
	}
	Assert(!IsA(node, SubLink));
364 365 366
	return expression_tree_walker(node, contain_agg_clause_walker, context);
}

367
/*
368
 * count_agg_clauses
369
 *	  Recursively count the Aggref nodes in an expression tree.
370 371
 *
 *	  Note: this also checks for nested aggregates, which are an error.
372
 *
373 374 375 376 377 378 379 380
 * We not only count the nodes, but attempt to estimate the total space
 * needed for their transition state values if all are evaluated in parallel
 * (as would be done in a HashAgg plan).  See AggClauseCounts for the exact
 * set of statistics returned.
 *
 * NOTE that the counts are ADDED to those already in *counts ... so the
 * caller is responsible for zeroing the struct initially.
 *
381 382 383
 * This does not descend into subqueries, and so should be used only after
 * reduction of sublinks to subplans, or in contexts where it's known there
 * are no subqueries.  There mustn't be outer-aggregate references either.
384
 */
385 386
void
count_agg_clauses(Node *clause, AggClauseCounts *counts)
387
{
388 389
	/* no setup needed */
	count_agg_clauses_walker(clause, counts);
390 391 392
}

static bool
393
count_agg_clauses_walker(Node *node, AggClauseCounts *counts)
394 395 396 397 398
{
	if (node == NULL)
		return false;
	if (IsA(node, Aggref))
	{
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
		Aggref	   *aggref = (Aggref *) node;
		Oid			inputType;
		HeapTuple	aggTuple;
		Form_pg_aggregate aggform;
		Oid			aggtranstype;

		Assert(aggref->agglevelsup == 0);
		counts->numAggs++;
		if (aggref->aggdistinct)
			counts->numDistinctAggs++;

		inputType = exprType((Node *) aggref->target);

		/* fetch aggregate transition datatype from pg_aggregate */
		aggTuple = SearchSysCache(AGGFNOID,
								  ObjectIdGetDatum(aggref->aggfnoid),
								  0, 0, 0);
		if (!HeapTupleIsValid(aggTuple))
			elog(ERROR, "cache lookup failed for aggregate %u",
				 aggref->aggfnoid);
		aggform = (Form_pg_aggregate) GETSTRUCT(aggTuple);
		aggtranstype = aggform->aggtranstype;
		ReleaseSysCache(aggTuple);

		/* resolve actual type of transition state, if polymorphic */
		if (aggtranstype == ANYARRAYOID || aggtranstype == ANYELEMENTOID)
		{
			/* have to fetch the agg's declared input type... */
427
			Oid		   *agg_arg_types;
428 429 430
			int			agg_nargs;

			(void) get_func_signature(aggref->aggfnoid,
431
									  &agg_arg_types, &agg_nargs);
432 433 434 435
			Assert(agg_nargs == 1);
			aggtranstype = resolve_generic_type(aggtranstype,
												inputType,
												agg_arg_types[0]);
436
			pfree(agg_arg_types);
437 438 439 440
		}

		/*
		 * If the transition type is pass-by-value then it doesn't add
441 442 443
		 * anything to the required size of the hashtable.	If it is
		 * pass-by-reference then we have to add the estimated size of the
		 * value itself, plus palloc overhead.
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
		 */
		if (!get_typbyval(aggtranstype))
		{
			int32		aggtranstypmod;
			int32		avgwidth;

			/*
			 * If transition state is of same type as input, assume it's the
			 * same typmod (same width) as well.  This works for cases like
			 * MAX/MIN and is probably somewhat reasonable otherwise.
			 */
			if (aggtranstype == inputType)
				aggtranstypmod = exprTypmod((Node *) aggref->target);
			else
				aggtranstypmod = -1;

			avgwidth = get_typavgwidth(aggtranstype, aggtranstypmod);
			avgwidth = MAXALIGN(avgwidth);

			counts->transitionSpace += avgwidth + 2 * sizeof(void *);
		}
465

466 467 468
		/*
		 * Complain if the aggregate's argument contains any aggregates;
		 * nested agg functions are semantically nonsensical.
469
		 */
470
		if (contain_agg_clause((Node *) aggref->target))
471 472
			ereport(ERROR,
					(errcode(ERRCODE_GROUPING_ERROR),
473
					 errmsg("aggregate function calls may not be nested")));
474

475 476 477 478
		/*
		 * Having checked that, we need not recurse into the argument.
		 */
		return false;
479
	}
480
	Assert(!IsA(node, SubLink));
481 482
	return expression_tree_walker(node, count_agg_clauses_walker,
								  (void *) counts);
483 484
}

485

486
/*****************************************************************************
487
 *		Support for expressions returning sets
488 489 490
 *****************************************************************************/

/*
491
 * expression_returns_set
492
 *	  Test whether an expression returns a set result.
493
 *
494 495 496
 * Because we use expression_tree_walker(), this can also be applied to
 * whole targetlists; it'll produce TRUE if any one of the tlist items
 * returns a set.
497 498
 */
bool
499
expression_returns_set(Node *clause)
500
{
501
	return expression_returns_set_walker(clause, NULL);
502 503 504
}

static bool
505
expression_returns_set_walker(Node *node, void *context)
506 507 508
{
	if (node == NULL)
		return false;
509
	if (IsA(node, FuncExpr))
510
	{
511
		FuncExpr   *expr = (FuncExpr *) node;
512

513 514 515 516 517 518
		if (expr->funcretset)
			return true;
		/* else fall through to check args */
	}
	if (IsA(node, OpExpr))
	{
Bruce Momjian's avatar
Bruce Momjian committed
519
		OpExpr	   *expr = (OpExpr *) node;
520 521 522 523 524 525 526

		if (expr->opretset)
			return true;
		/* else fall through to check args */
	}

	/* Avoid recursion for some cases that can't return a set */
527 528
	if (IsA(node, Aggref))
		return false;
529 530
	if (IsA(node, DistinctExpr))
		return false;
531 532
	if (IsA(node, ScalarArrayOpExpr))
		return false;
533 534
	if (IsA(node, BoolExpr))
		return false;
535 536
	if (IsA(node, SubLink))
		return false;
537
	if (IsA(node, SubPlan))
538
		return false;
539 540
	if (IsA(node, ArrayExpr))
		return false;
541 542
	if (IsA(node, RowExpr))
		return false;
543 544
	if (IsA(node, RowCompareExpr))
		return false;
545 546
	if (IsA(node, CoalesceExpr))
		return false;
547 548
	if (IsA(node, MinMaxExpr))
		return false;
549 550
	if (IsA(node, NullIfExpr))
		return false;
551

552 553
	return expression_tree_walker(node, expression_returns_set_walker,
								  context);
554 555
}

556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
/*****************************************************************************
 *		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;
582
	if (IsA(node, SubPlan) ||
583
		IsA(node, SubLink))
584
		return true;			/* abort the tree traversal and return true */
585 586 587
	return expression_tree_walker(node, contain_subplans_walker, context);
}

588

589
/*****************************************************************************
590
 *		Check clauses for mutable functions
591 592
 *****************************************************************************/

593
/*
594 595
 * contain_mutable_functions
 *	  Recursively search for mutable functions within a clause.
596
 *
597 598
 * Returns true if any mutable function (or operator implemented by a
 * mutable function) is found.	This test is needed so that we don't
599 600 601
 * mistakenly think that something like "WHERE random() < 0.5" can be treated
 * as a constant qualification.
 *
602
 * XXX we do not examine sub-selects to see if they contain uses of
603
 * mutable functions.  It's not real clear if that is correct or not...
604 605
 */
bool
606
contain_mutable_functions(Node *clause)
607
{
608
	return contain_mutable_functions_walker(clause, NULL);
609 610 611
}

static bool
612
contain_mutable_functions_walker(Node *node, void *context)
613 614 615
{
	if (node == NULL)
		return false;
616
	if (IsA(node, FuncExpr))
617
	{
618
		FuncExpr   *expr = (FuncExpr *) node;
619

620 621 622 623 624 625
		if (func_volatile(expr->funcid) != PROVOLATILE_IMMUTABLE)
			return true;
		/* else fall through to check args */
	}
	if (IsA(node, OpExpr))
	{
Bruce Momjian's avatar
Bruce Momjian committed
626
		OpExpr	   *expr = (OpExpr *) node;
627 628 629 630 631 632 633

		if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE)
			return true;
		/* else fall through to check args */
	}
	if (IsA(node, DistinctExpr))
	{
Bruce Momjian's avatar
Bruce Momjian committed
634
		DistinctExpr *expr = (DistinctExpr *) node;
635 636 637 638

		if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE)
			return true;
		/* else fall through to check args */
639
	}
640 641
	if (IsA(node, ScalarArrayOpExpr))
	{
Bruce Momjian's avatar
Bruce Momjian committed
642
		ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
643 644 645 646 647

		if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE)
			return true;
		/* else fall through to check args */
	}
648 649
	if (IsA(node, NullIfExpr))
	{
Bruce Momjian's avatar
Bruce Momjian committed
650
		NullIfExpr *expr = (NullIfExpr *) node;
651 652 653 654 655

		if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE)
			return true;
		/* else fall through to check args */
	}
656
	if (IsA(node, RowCompareExpr))
657
	{
658
		RowCompareExpr *rcexpr = (RowCompareExpr *) node;
659
		ListCell   *opid;
660

661
		foreach(opid, rcexpr->opnos)
662
		{
663
			if (op_volatile(lfirst_oid(opid)) != PROVOLATILE_IMMUTABLE)
664 665 666 667
				return true;
		}
		/* else fall through to check args */
	}
668 669 670 671 672 673 674 675 676 677 678 679 680 681
	return expression_tree_walker(node, contain_mutable_functions_walker,
								  context);
}


/*****************************************************************************
 *		Check clauses for volatile functions
 *****************************************************************************/

/*
 * contain_volatile_functions
 *	  Recursively search for volatile functions within a clause.
 *
 * Returns true if any volatile function (or operator implemented by a
Bruce Momjian's avatar
Bruce Momjian committed
682
 * volatile function) is found. This test prevents invalid conversions
683 684
 * of volatile expressions into indexscan quals.
 *
685
 * XXX we do not examine sub-selects to see if they contain uses of
Bruce Momjian's avatar
Bruce Momjian committed
686
 * volatile functions.	It's not real clear if that is correct or not...
687 688 689 690 691 692 693 694 695 696 697 698
 */
bool
contain_volatile_functions(Node *clause)
{
	return contain_volatile_functions_walker(clause, NULL);
}

static bool
contain_volatile_functions_walker(Node *node, void *context)
{
	if (node == NULL)
		return false;
699
	if (IsA(node, FuncExpr))
700
	{
701
		FuncExpr   *expr = (FuncExpr *) node;
702

703 704 705 706 707 708
		if (func_volatile(expr->funcid) == PROVOLATILE_VOLATILE)
			return true;
		/* else fall through to check args */
	}
	if (IsA(node, OpExpr))
	{
Bruce Momjian's avatar
Bruce Momjian committed
709
		OpExpr	   *expr = (OpExpr *) node;
710 711 712 713 714 715 716

		if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE)
			return true;
		/* else fall through to check args */
	}
	if (IsA(node, DistinctExpr))
	{
Bruce Momjian's avatar
Bruce Momjian committed
717
		DistinctExpr *expr = (DistinctExpr *) node;
718 719 720 721

		if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE)
			return true;
		/* else fall through to check args */
722
	}
723 724
	if (IsA(node, ScalarArrayOpExpr))
	{
Bruce Momjian's avatar
Bruce Momjian committed
725
		ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
726 727 728 729 730

		if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE)
			return true;
		/* else fall through to check args */
	}
731 732
	if (IsA(node, NullIfExpr))
	{
Bruce Momjian's avatar
Bruce Momjian committed
733
		NullIfExpr *expr = (NullIfExpr *) node;
734 735 736 737 738

		if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE)
			return true;
		/* else fall through to check args */
	}
739
	if (IsA(node, RowCompareExpr))
740
	{
741 742
		/* RowCompare probably can't have volatile ops, but check anyway */
		RowCompareExpr *rcexpr = (RowCompareExpr *) node;
743
		ListCell   *opid;
744

745
		foreach(opid, rcexpr->opnos)
746
		{
747
			if (op_volatile(lfirst_oid(opid)) == PROVOLATILE_VOLATILE)
748 749 750 751
				return true;
		}
		/* else fall through to check args */
	}
752
	return expression_tree_walker(node, contain_volatile_functions_walker,
753 754 755 756
								  context);
}


757 758 759 760 761 762 763 764 765 766 767
/*****************************************************************************
 *		Check clauses for nonstrict functions
 *****************************************************************************/

/*
 * contain_nonstrict_functions
 *	  Recursively search for nonstrict functions within a clause.
 *
 * Returns true if any nonstrict construct is found --- ie, anything that
 * could produce non-NULL output with a NULL input.
 *
768 769 770
 * The idea here is that the caller has verified that the expression contains
 * one or more Var or Param nodes (as appropriate for the caller's need), and
 * now wishes to prove that the expression result will be NULL if any of these
Bruce Momjian's avatar
Bruce Momjian committed
771
 * inputs is NULL.	If we return false, then the proof succeeded.
772 773 774 775 776 777 778 779 780 781 782 783
 */
bool
contain_nonstrict_functions(Node *clause)
{
	return contain_nonstrict_functions_walker(clause, NULL);
}

static bool
contain_nonstrict_functions_walker(Node *node, void *context)
{
	if (node == NULL)
		return false;
784 785 786 787 788
	if (IsA(node, Aggref))
	{
		/* an aggregate could return non-null with null input */
		return true;
	}
789 790
	if (IsA(node, ArrayRef))
	{
791
		/* array assignment is nonstrict, but subscripting is strict */
792 793 794 795
		if (((ArrayRef *) node)->refassgnexpr != NULL)
			return true;
		/* else fall through to check args */
	}
796 797 798 799 800 801 802 803 804 805
	if (IsA(node, FuncExpr))
	{
		FuncExpr   *expr = (FuncExpr *) node;

		if (!func_strict(expr->funcid))
			return true;
		/* else fall through to check args */
	}
	if (IsA(node, OpExpr))
	{
Bruce Momjian's avatar
Bruce Momjian committed
806
		OpExpr	   *expr = (OpExpr *) node;
807 808 809 810 811 812 813 814 815 816

		if (!op_strict(expr->opno))
			return true;
		/* else fall through to check args */
	}
	if (IsA(node, DistinctExpr))
	{
		/* IS DISTINCT FROM is inherently non-strict */
		return true;
	}
817 818 819 820 821
	if (IsA(node, ScalarArrayOpExpr))
	{
		/* inherently non-strict, consider null scalar and empty array */
		return true;
	}
822
	if (IsA(node, BoolExpr))
823
	{
824
		BoolExpr   *expr = (BoolExpr *) node;
825

826
		switch (expr->boolop)
827 828
		{
			case AND_EXPR:
829 830
			case OR_EXPR:
				/* AND, OR are inherently non-strict */
831 832 833 834 835
				return true;
			default:
				break;
		}
	}
836 837 838 839 840 841 842
	if (IsA(node, SubLink))
	{
		/* In some cases a sublink might be strict, but in general not */
		return true;
	}
	if (IsA(node, SubPlan))
		return true;
843 844
	if (IsA(node, FieldStore))
		return true;
845 846
	if (IsA(node, CaseExpr))
		return true;
847 848
	if (IsA(node, CaseWhen))
		return true;
849 850
	if (IsA(node, ArrayExpr))
		return true;
851 852
	if (IsA(node, RowExpr))
		return true;
853 854
	if (IsA(node, RowCompareExpr))
		return true;
855 856
	if (IsA(node, CoalesceExpr))
		return true;
857 858
	if (IsA(node, MinMaxExpr))
		return true;
859 860
	if (IsA(node, NullIfExpr))
		return true;
861 862 863 864 865 866 867 868 869
	if (IsA(node, NullTest))
		return true;
	if (IsA(node, BooleanTest))
		return true;
	return expression_tree_walker(node, contain_nonstrict_functions_walker,
								  context);
}


870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994
/*
 * find_nonnullable_rels
 *		Determine which base rels are forced nonnullable by given clause.
 *
 * Returns the set of all Relids that are referenced in the clause in such
 * a way that the clause cannot possibly return TRUE if any of these Relids
 * is an all-NULL row.  (It is OK to err on the side of conservatism; hence
 * the analysis here is simplistic.)
 *
 * The semantics here are subtly different from contain_nonstrict_functions:
 * that function is concerned with NULL results from arbitrary expressions,
 * but here we assume that the input is a Boolean expression, and wish to
 * see if NULL inputs will provably cause a FALSE-or-NULL result.  We expect
 * the expression to have been AND/OR flattened and converted to implicit-AND
 * format.
 *
 * We don't use expression_tree_walker here because we don't want to
 * descend through very many kinds of nodes; only the ones we can be sure
 * are strict.	We can descend through the top level of implicit AND'ing,
 * but not through any explicit ANDs (or ORs) below that, since those are not
 * strict constructs.  The List case handles the top-level implicit AND list
 * as well as lists of arguments to strict operators/functions.
 */
Relids
find_nonnullable_rels(Node *clause)
{
	return find_nonnullable_rels_walker(clause, true);
}

static Relids
find_nonnullable_rels_walker(Node *node, bool top_level)
{
	Relids		result = NULL;

	if (node == NULL)
		return NULL;
	if (IsA(node, Var))
	{
		Var		   *var = (Var *) node;

		if (var->varlevelsup == 0)
			result = bms_make_singleton(var->varno);
	}
	else if (IsA(node, List))
	{
		ListCell   *l;

		foreach(l, (List *) node)
		{
			result = bms_join(result,
							  find_nonnullable_rels_walker(lfirst(l),
														   top_level));
		}
	}
	else if (IsA(node, FuncExpr))
	{
		FuncExpr   *expr = (FuncExpr *) node;

		if (func_strict(expr->funcid))
			result = find_nonnullable_rels_walker((Node *) expr->args, false);
	}
	else if (IsA(node, OpExpr))
	{
		OpExpr	   *expr = (OpExpr *) node;

		if (op_strict(expr->opno))
			result = find_nonnullable_rels_walker((Node *) expr->args, false);
	}
	else if (IsA(node, ScalarArrayOpExpr))
	{
		/* Strict if it's "foo op ANY array" and op is strict */
		ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;

		if (expr->useOr && op_strict(expr->opno))
			result = find_nonnullable_rels_walker((Node *) expr->args, false);
	}
	else if (IsA(node, BoolExpr))
	{
		BoolExpr   *expr = (BoolExpr *) node;

		/* NOT is strict, others are not */
		if (expr->boolop == NOT_EXPR)
			result = find_nonnullable_rels_walker((Node *) expr->args, false);
	}
	else if (IsA(node, RelabelType))
	{
		RelabelType *expr = (RelabelType *) node;

		result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
	}
	else if (IsA(node, ConvertRowtypeExpr))
	{
		/* not clear this is useful, but it can't hurt */
		ConvertRowtypeExpr *expr = (ConvertRowtypeExpr *) node;

		result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
	}
	else if (IsA(node, NullTest))
	{
		NullTest   *expr = (NullTest *) node;

		/*
		 * IS NOT NULL can be considered strict, but only at top level; else
		 * we might have something like NOT (x IS NOT NULL).
		 */
		if (top_level && expr->nulltesttype == IS_NOT_NULL)
			result = find_nonnullable_rels_walker((Node *) expr->arg, false);
	}
	else if (IsA(node, BooleanTest))
	{
		BooleanTest *expr = (BooleanTest *) node;

		/*
		 * Appropriate boolean tests are strict at top level.
		 */
		if (top_level &&
			(expr->booltesttype == IS_TRUE ||
			 expr->booltesttype == IS_FALSE ||
			 expr->booltesttype == IS_NOT_UNKNOWN))
			result = find_nonnullable_rels_walker((Node *) expr->arg, false);
	}
	return result;
}


995 996 997
/*****************************************************************************
 *		Check for "pseudo-constant" clauses
 *****************************************************************************/
998 999

/*
1000 1001
 * is_pseudo_constant_clause
 *	  Detect whether a clause is "constant", ie, it contains no variables
1002
 *	  of the current query level and no uses of volatile functions.
1003
 *	  Such a clause is not necessarily a true constant: it can still contain
1004
 *	  Params and outer-level Vars, not to mention functions whose results
Bruce Momjian's avatar
Bruce Momjian committed
1005
 *	  may vary from one statement to the next.	However, the clause's value
1006 1007 1008
 *	  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.
1009 1010 1011 1012 1013 1014
 */
bool
is_pseudo_constant_clause(Node *clause)
{
	/*
	 * We could implement this check in one recursive scan.  But since the
1015 1016 1017
	 * check for volatile functions is both moderately expensive and unlikely
	 * to fail, it seems better to look for Vars first and only check for
	 * volatile functions if we find no Vars.
1018 1019
	 */
	if (!contain_var_clause(clause) &&
1020
		!contain_volatile_functions(clause))
1021 1022 1023 1024
		return true;
	return false;
}

1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
/*
 * is_pseudo_constant_clause_relids
 *	  Same as above, except caller already has available the var membership
 *	  of the clause; this lets us avoid the contain_var_clause() scan.
 */
bool
is_pseudo_constant_clause_relids(Node *clause, Relids relids)
{
	if (bms_is_empty(relids) &&
		!contain_volatile_functions(clause))
		return true;
	return false;
}

1039
/*
1040
 * pull_constant_clauses
1041 1042
 *		Scan through a list of qualifications and separate "constant" quals
 *		from those that are not.
1043
 *
1044 1045
 * Returns a list of the pseudo-constant clauses in constantQual and the
 * remaining quals as the return value.
1046 1047
 */
List *
1048
pull_constant_clauses(List *quals, List **constantQual)
1049
{
1050 1051
	List	   *constqual = NIL,
			   *restqual = NIL;
1052
	ListCell   *q;
1053 1054 1055

	foreach(q, quals)
	{
1056
		Node	   *qual = (Node *) lfirst(q);
1057

1058
		if (is_pseudo_constant_clause(qual))
1059
			constqual = lappend(constqual, qual);
1060
		else
1061
			restqual = lappend(restqual, qual);
1062
	}
1063 1064
	*constantQual = constqual;
	return restqual;
1065 1066 1067
}


1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
/*****************************************************************************
 *		Tests on clauses of queries
 *
 * Possibly this code should go someplace else, since this isn't quite the
 * same meaning of "clause" as is used elsewhere in this module.  But I can't
 * think of a better place for it...
 *****************************************************************************/

/*
 * Test whether a query uses DISTINCT ON, ie, has a distinct-list that is
1078
 * not the same as the set of output columns.
1079 1080 1081 1082
 */
bool
has_distinct_on_clause(Query *query)
{
1083
	ListCell   *l;
1084 1085 1086 1087

	/* Is there a DISTINCT clause at all? */
	if (query->distinctClause == NIL)
		return false;
1088

1089
	/*
1090
	 * If the DISTINCT list contains all the nonjunk targetlist items, and
1091 1092 1093 1094 1095 1096
	 * nothing else (ie, no junk tlist items), then it's a simple DISTINCT,
	 * else it's DISTINCT ON.  We do not require the lists to be in the same
	 * order (since the parser may have adjusted the DISTINCT clause ordering
	 * to agree with ORDER BY).  Furthermore, a non-DISTINCT junk tlist item
	 * that is in the sortClause is also evidence of DISTINCT ON, since we
	 * don't allow ORDER BY on junk tlist items when plain DISTINCT is used.
1097 1098 1099
	 *
	 * This code assumes that the DISTINCT list is valid, ie, all its entries
	 * match some entry of the tlist.
1100
	 */
1101
	foreach(l, query->targetList)
1102
	{
1103
		TargetEntry *tle = (TargetEntry *) lfirst(l);
1104

1105
		if (tle->ressortgroupref == 0)
1106
		{
1107
			if (tle->resjunk)
1108
				continue;		/* we can ignore unsorted junk cols */
1109
			return true;		/* definitely not in DISTINCT list */
1110
		}
1111
		if (targetIsInSortList(tle, query->distinctClause))
1112
		{
1113
			if (tle->resjunk)
1114 1115 1116 1117 1118 1119
				return true;	/* junk TLE in DISTINCT means DISTINCT ON */
			/* else this TLE is okay, keep looking */
		}
		else
		{
			/* This TLE is not in DISTINCT list */
1120
			if (!tle->resjunk)
1121
				return true;	/* non-junk, non-DISTINCT, so DISTINCT ON */
1122
			if (targetIsInSortList(tle, query->sortClause))
1123 1124
				return true;	/* sorted, non-distinct junk */
			/* unsorted junk is okay, keep looking */
1125 1126 1127 1128 1129 1130
		}
	}
	/* It's a simple DISTINCT */
	return false;
}

1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
/*
 * Test whether a query uses simple DISTINCT, ie, has a distinct-list that
 * is the same as the set of output columns.
 */
bool
has_distinct_clause(Query *query)
{
	/* Is there a DISTINCT clause at all? */
	if (query->distinctClause == NIL)
		return false;

	/* It's DISTINCT if it's not DISTINCT ON */
	return !has_distinct_on_clause(query);
}

1146

1147 1148 1149 1150 1151 1152
/*****************************************************************************
 *																			 *
 *		General clause-manipulating routines								 *
 *																			 *
 *****************************************************************************/

1153
/*
1154 1155
 * NumRelids
 *		(formerly clause_relids)
1156
 *
1157 1158 1159
 * Returns the number of different relations referenced in 'clause'.
 */
int
1160
NumRelids(Node *clause)
1161
{
1162 1163
	Relids		varnos = pull_varnos(clause);
	int			result = bms_num_members(varnos);
1164

1165
	bms_free(varnos);
1166
	return result;
1167 1168
}

1169
/*
1170
 * CommuteOpExpr: commute a binary operator clause
1171 1172
 *
 * XXX the clause is destructively modified!
1173
 */
1174
void
1175
CommuteOpExpr(OpExpr *clause)
1176
{
1177
	Oid			opoid;
1178
	Node	   *temp;
1179

1180
	/* Sanity checks: caller is at fault if these fail */
1181
	if (!is_opclause(clause) ||
1182
		list_length(clause->args) != 2)
1183
		elog(ERROR, "cannot commute non-binary-operator clause");
1184

1185
	opoid = get_commutator(clause->opno);
1186

1187
	if (!OidIsValid(opoid))
1188
		elog(ERROR, "could not find commutator for operator %u",
1189
			 clause->opno);
1190

1191
	/*
1192
	 * modify the clause in-place!
1193
	 */
1194 1195 1196 1197
	clause->opno = opoid;
	clause->opfuncid = InvalidOid;
	/* opresulttype and opretset are assumed not to change */

1198 1199
	temp = linitial(clause->args);
	linitial(clause->args) = lsecond(clause->args);
1200
	lsecond(clause->args) = temp;
1201
}
1202

1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
/*
 * CommuteRowCompareExpr: commute a RowCompareExpr clause
 *
 * XXX the clause is destructively modified!
 */
void
CommuteRowCompareExpr(RowCompareExpr *clause)
{
	List	   *newops;
	List	   *temp;
	ListCell   *l;

	/* Sanity checks: caller is at fault if these fail */
	if (!IsA(clause, RowCompareExpr))
		elog(ERROR, "expected a RowCompareExpr");

	/* Build list of commuted operators */
	newops = NIL;
	foreach(l, clause->opnos)
	{
		Oid			opoid = lfirst_oid(l);

		opoid = get_commutator(opoid);
		if (!OidIsValid(opoid))
			elog(ERROR, "could not find commutator for operator %u",
				 lfirst_oid(l));
		newops = lappend_oid(newops, opoid);
	}

	/*
	 * modify the clause in-place!
	 */
	switch (clause->rctype)
	{
		case ROWCOMPARE_LT:
			clause->rctype = ROWCOMPARE_GT;
			break;
		case ROWCOMPARE_LE:
			clause->rctype = ROWCOMPARE_GE;
			break;
		case ROWCOMPARE_GE:
			clause->rctype = ROWCOMPARE_LE;
			break;
		case ROWCOMPARE_GT:
			clause->rctype = ROWCOMPARE_LT;
			break;
		default:
			elog(ERROR, "unexpected RowCompare type: %d",
				 (int) clause->rctype);
			break;
	}

	clause->opnos = newops;
	/*
	 * Note: we don't bother to update the opclasses list, but just set
	 * it to empty.  This is OK since this routine is currently only used
	 * for index quals, and the index machinery won't use the opclass
	 * information.  The original opclass list is NOT valid if we have
	 * commuted any cross-type comparisons, so don't leave it in place.
	 */
	clause->opclasses = NIL;	/* XXX */

	temp = clause->largs;
	clause->largs = clause->rargs;
	clause->rargs = temp;
}

1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
/*
 * strip_implicit_coercions: remove implicit coercions at top level of tree
 *
 * Note: there isn't any useful thing we can do with a RowExpr here, so
 * just return it unchanged, even if it's marked as an implicit coercion.
 */
Node *
strip_implicit_coercions(Node *node)
{
	if (node == NULL)
		return NULL;
	if (IsA(node, FuncExpr))
	{
		FuncExpr   *f = (FuncExpr *) node;

		if (f->funcformat == COERCE_IMPLICIT_CAST)
			return strip_implicit_coercions(linitial(f->args));
	}
	else if (IsA(node, RelabelType))
	{
		RelabelType *r = (RelabelType *) node;

		if (r->relabelformat == COERCE_IMPLICIT_CAST)
			return strip_implicit_coercions((Node *) r->arg);
	}
1295 1296 1297 1298 1299 1300 1301
	else if (IsA(node, ConvertRowtypeExpr))
	{
		ConvertRowtypeExpr *c = (ConvertRowtypeExpr *) node;

		if (c->convertformat == COERCE_IMPLICIT_CAST)
			return strip_implicit_coercions((Node *) c->arg);
	}
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
	else if (IsA(node, CoerceToDomain))
	{
		CoerceToDomain *c = (CoerceToDomain *) node;

		if (c->coercionformat == COERCE_IMPLICIT_CAST)
			return strip_implicit_coercions((Node *) c->arg);
	}
	return node;
}

1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
/*
 * set_coercionform_dontcare: set all CoercionForm fields to COERCE_DONTCARE
 *
 * This is used to make index expressions and index predicates more easily
 * comparable to clauses of queries.  CoercionForm is not semantically
 * significant (for cases where it does matter, the significant info is
 * coded into the coercion function arguments) so we can ignore it during
 * comparisons.  Thus, for example, an index on "foo::int4" can match an
 * implicit coercion to int4.
 *
 * Caution: the passed expression tree is modified in-place.
 */
void
set_coercionform_dontcare(Node *node)
{
	(void) set_coercionform_dontcare_walker(node, NULL);
}

static bool
set_coercionform_dontcare_walker(Node *node, void *context)
{
	if (node == NULL)
		return false;
	if (IsA(node, FuncExpr))
		((FuncExpr *) node)->funcformat = COERCE_DONTCARE;
1337
	else if (IsA(node, RelabelType))
1338
		((RelabelType *) node)->relabelformat = COERCE_DONTCARE;
1339 1340 1341
	else if (IsA(node, ConvertRowtypeExpr))
		((ConvertRowtypeExpr *) node)->convertformat = COERCE_DONTCARE;
	else if (IsA(node, RowExpr))
1342
		((RowExpr *) node)->row_format = COERCE_DONTCARE;
1343
	else if (IsA(node, CoerceToDomain))
1344 1345 1346 1347 1348
		((CoerceToDomain *) node)->coercionformat = COERCE_DONTCARE;
	return expression_tree_walker(node, set_coercionform_dontcare_walker,
								  context);
}

1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375
/*
 * Helper for eval_const_expressions: check that datatype of an attribute
 * is still what it was when the expression was parsed.  This is needed to
 * guard against improper simplification after ALTER COLUMN TYPE.  (XXX we
 * may well need to make similar checks elsewhere?)
 */
static bool
rowtype_field_matches(Oid rowtypeid, int fieldnum,
					  Oid expectedtype, int32 expectedtypmod)
{
	TupleDesc	tupdesc;
	Form_pg_attribute attr;

	/* No issue for RECORD, since there is no way to ALTER such a type */
	if (rowtypeid == RECORDOID)
		return true;
	tupdesc = lookup_rowtype_tupdesc(rowtypeid, -1);
	if (fieldnum <= 0 || fieldnum > tupdesc->natts)
		return false;
	attr = tupdesc->attrs[fieldnum - 1];
	if (attr->attisdropped ||
		attr->atttypid != expectedtype ||
		attr->atttypmod != expectedtypmod)
		return false;
	return true;
}

1376

1377 1378 1379 1380 1381 1382 1383
/*--------------------
 * 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
1384
 * the subexpression x is.	(XXX We assume that no such subexpression
1385 1386 1387 1388 1389 1390
 * 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
1391
 * example.  Functions that are not marked "immutable" in pg_proc
1392
 * will not be pre-evaluated here, although we will reduce their
1393
 * arguments as far as possible.
1394 1395 1396
 *
 * We assume that the tree has already been type-checked and contains
 * only operators and functions that are reasonable to try to execute.
1397 1398 1399
 *
 * NOTE: the planner assumes that this will always flatten nested AND and
 * OR clauses into N-argument form.  See comments in prepqual.c.
1400 1401 1402 1403 1404
 *--------------------
 */
Node *
eval_const_expressions(Node *node)
{
1405 1406 1407
	eval_const_expressions_context context;

	context.active_fns = NIL;	/* nothing being recursively simplified */
1408
	context.case_val = NULL;	/* no CASE being examined */
1409 1410 1411 1412
	context.estimate = false;	/* safe transformations only */
	return eval_const_expressions_mutator(node, &context);
}

1413
/*--------------------
1414 1415 1416 1417 1418 1419 1420
 * estimate_expression_value
 *
 * This function attempts to estimate the value of an expression for
 * planning purposes.  It is in essence a more aggressive version of
 * eval_const_expressions(): we will perform constant reductions that are
 * not necessarily 100% safe, but are reasonable for estimation purposes.
 *
1421 1422
 * Currently the extra steps that are taken in this mode are:
 * 1. Substitute values for Params, where a bound Param value has been made
1423
 *	  available by the caller of planner().
1424 1425
 * 2. Fold stable, as well as immutable, functions to constants.
 *--------------------
1426 1427 1428 1429 1430 1431 1432
 */
Node *
estimate_expression_value(Node *node)
{
	eval_const_expressions_context context;

	context.active_fns = NIL;	/* nothing being recursively simplified */
1433
	context.case_val = NULL;	/* no CASE being examined */
1434 1435
	context.estimate = true;	/* unsafe transformations OK */
	return eval_const_expressions_mutator(node, &context);
1436 1437 1438
}

static Node *
1439 1440
eval_const_expressions_mutator(Node *node,
							   eval_const_expressions_context *context)
1441 1442 1443
{
	if (node == NULL)
		return NULL;
1444 1445 1446 1447 1448
	if (IsA(node, Param))
	{
		Param	   *param = (Param *) node;

		/* OK to try to substitute value? */
1449
		if (context->estimate && param->paramkind != PARAM_EXEC &&
1450 1451
			PlannerBoundParamList != NULL)
		{
1452
			ParamListInfo paramInfo;
1453 1454

			/* Search to see if we've been given a value for this Param */
1455 1456 1457 1458 1459 1460
			paramInfo = lookupParam(PlannerBoundParamList,
									param->paramkind,
									param->paramname,
									param->paramid,
									true);
			if (paramInfo)
1461 1462
			{
				/*
1463 1464 1465 1466 1467
				 * Found it, so return a Const representing the param value.
				 * Note that we don't copy pass-by-ref datatypes, so the Const
				 * will only be valid as long as the bound parameter list
				 * exists. This is okay for intended uses of
				 * estimate_expression_value().
1468 1469 1470 1471
				 */
				int16		typLen;
				bool		typByVal;

1472
				Assert(paramInfo->ptype == param->paramtype);
1473 1474 1475
				get_typlenbyval(param->paramtype, &typLen, &typByVal);
				return (Node *) makeConst(param->paramtype,
										  (int) typLen,
1476 1477
										  paramInfo->value,
										  paramInfo->isnull,
1478 1479 1480 1481 1482 1483
										  typByVal);
			}
		}
		/* Not replaceable, so just copy the Param (no need to recurse) */
		return (Node *) copyObject(param);
	}
1484
	if (IsA(node, FuncExpr))
1485
	{
1486
		FuncExpr   *expr = (FuncExpr *) node;
1487
		List	   *args;
1488 1489 1490 1491 1492
		Expr	   *simple;
		FuncExpr   *newexpr;

		/*
		 * Reduce constants in the FuncExpr's arguments.  We know args is
1493 1494
		 * either NIL or a List node, so we can call expression_tree_mutator
		 * directly rather than recursing to self.
1495 1496
		 */
		args = (List *) expression_tree_mutator((Node *) expr->args,
1497
											  eval_const_expressions_mutator,
1498
												(void *) context);
Bruce Momjian's avatar
Bruce Momjian committed
1499

1500
		/*
1501 1502
		 * Code for op/func reduction is pretty bulky, so split it out as a
		 * separate function.
1503
		 */
1504
		simple = simplify_function(expr->funcid, expr->funcresulttype, args,
1505
								   true, context);
1506 1507
		if (simple)				/* successfully simplified it */
			return (Node *) simple;
Bruce Momjian's avatar
Bruce Momjian committed
1508

1509 1510
		/*
		 * The expression cannot be simplified any further, so build and
1511 1512
		 * return a replacement FuncExpr node using the possibly-simplified
		 * arguments.
1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527
		 */
		newexpr = makeNode(FuncExpr);
		newexpr->funcid = expr->funcid;
		newexpr->funcresulttype = expr->funcresulttype;
		newexpr->funcretset = expr->funcretset;
		newexpr->funcformat = expr->funcformat;
		newexpr->args = args;
		return (Node *) newexpr;
	}
	if (IsA(node, OpExpr))
	{
		OpExpr	   *expr = (OpExpr *) node;
		List	   *args;
		Expr	   *simple;
		OpExpr	   *newexpr;
1528 1529

		/*
1530 1531 1532
		 * Reduce constants in the OpExpr's arguments.  We know args is either
		 * NIL or a List node, so we can call expression_tree_mutator directly
		 * rather than recursing to self.
1533 1534
		 */
		args = (List *) expression_tree_mutator((Node *) expr->args,
1535
											  eval_const_expressions_mutator,
1536
												(void *) context);
Bruce Momjian's avatar
Bruce Momjian committed
1537

1538
		/*
1539 1540
		 * Need to get OID of underlying function.	Okay to scribble on input
		 * to this extent.
1541 1542
		 */
		set_opfuncid(expr);
Bruce Momjian's avatar
Bruce Momjian committed
1543

1544
		/*
1545 1546
		 * Code for op/func reduction is pretty bulky, so split it out as a
		 * separate function.
1547
		 */
1548
		simple = simplify_function(expr->opfuncid, expr->opresulttype, args,
1549
								   true, context);
1550 1551
		if (simple)				/* successfully simplified it */
			return (Node *) simple;
Bruce Momjian's avatar
Bruce Momjian committed
1552

1553
		/*
1554 1555
		 * If the operator is boolean equality, we know how to simplify cases
		 * involving one constant and one non-constant argument.
1556 1557 1558 1559 1560 1561 1562 1563
		 */
		if (expr->opno == BooleanEqualOperator)
		{
			simple = simplify_boolean_equality(args);
			if (simple)			/* successfully simplified it */
				return (Node *) simple;
		}

1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580
		/*
		 * The expression cannot be simplified any further, so build and
		 * return a replacement OpExpr node using the possibly-simplified
		 * arguments.
		 */
		newexpr = makeNode(OpExpr);
		newexpr->opno = expr->opno;
		newexpr->opfuncid = expr->opfuncid;
		newexpr->opresulttype = expr->opresulttype;
		newexpr->opretset = expr->opretset;
		newexpr->args = args;
		return (Node *) newexpr;
	}
	if (IsA(node, DistinctExpr))
	{
		DistinctExpr *expr = (DistinctExpr *) node;
		List	   *args;
1581
		ListCell   *arg;
1582 1583 1584 1585 1586 1587 1588
		bool		has_null_input = false;
		bool		all_null_input = true;
		bool		has_nonconst_input = false;
		Expr	   *simple;
		DistinctExpr *newexpr;

		/*
1589 1590 1591
		 * Reduce constants in the DistinctExpr's arguments.  We know args is
		 * either NIL or a List node, so we can call expression_tree_mutator
		 * directly rather than recursing to self.
1592 1593
		 */
		args = (List *) expression_tree_mutator((Node *) expr->args,
1594
											  eval_const_expressions_mutator,
1595
												(void *) context);
1596

1597
		/*
Bruce Momjian's avatar
Bruce Momjian committed
1598
		 * We must do our own check for NULLs because DistinctExpr has
1599
		 * different results for NULL input than the underlying operator does.
1600 1601
		 */
		foreach(arg, args)
1602
		{
1603 1604 1605 1606 1607 1608 1609 1610
			if (IsA(lfirst(arg), Const))
			{
				has_null_input |= ((Const *) lfirst(arg))->constisnull;
				all_null_input &= ((Const *) lfirst(arg))->constisnull;
			}
			else
				has_nonconst_input = true;
		}
1611

1612 1613 1614 1615 1616
		/* all constants? then can optimize this out */
		if (!has_nonconst_input)
		{
			/* all nulls? then not distinct */
			if (all_null_input)
1617
				return makeBoolConst(false, false);
1618

1619 1620
			/* one null? then distinct */
			if (has_null_input)
1621
				return makeBoolConst(true, false);
1622

1623 1624
			/* otherwise try to evaluate the '=' operator */
			/* (NOT okay to try to inline it, though!) */
1625

1626
			/*
1627 1628
			 * Need to get OID of underlying function.	Okay to scribble on
			 * input to this extent.
1629
			 */
1630
			set_opfuncid((OpExpr *) expr);		/* rely on struct equivalence */
Bruce Momjian's avatar
Bruce Momjian committed
1631

1632
			/*
1633 1634
			 * Code for op/func reduction is pretty bulky, so split it out as
			 * a separate function.
1635
			 */
1636
			simple = simplify_function(expr->opfuncid, expr->opresulttype,
1637
									   args, false, context);
1638
			if (simple)			/* successfully simplified it */
1639 1640 1641 1642 1643
			{
				/*
				 * Since the underlying operator is "=", must negate its
				 * result
				 */
Bruce Momjian's avatar
Bruce Momjian committed
1644
				Const	   *csimple = (Const *) simple;
1645 1646 1647 1648 1649 1650

				Assert(IsA(csimple, Const));
				csimple->constvalue =
					BoolGetDatum(!DatumGetBool(csimple->constvalue));
				return (Node *) csimple;
			}
1651
		}
1652

1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671
		/*
		 * The expression cannot be simplified any further, so build and
		 * return a replacement DistinctExpr node using the
		 * possibly-simplified arguments.
		 */
		newexpr = makeNode(DistinctExpr);
		newexpr->opno = expr->opno;
		newexpr->opfuncid = expr->opfuncid;
		newexpr->opresulttype = expr->opresulttype;
		newexpr->opretset = expr->opretset;
		newexpr->args = args;
		return (Node *) newexpr;
	}
	if (IsA(node, BoolExpr))
	{
		BoolExpr   *expr = (BoolExpr *) node;

		switch (expr->boolop)
		{
1672
			case OR_EXPR:
1673
				{
1674
					List	   *newargs;
1675 1676 1677
					bool		haveNull = false;
					bool		forceTrue = false;

1678
					newargs = simplify_or_arguments(expr->args, context,
1679
													&haveNull, &forceTrue);
1680
					if (forceTrue)
1681
						return makeBoolConst(true, false);
1682
					if (haveNull)
1683
						newargs = lappend(newargs, makeBoolConst(false, true));
1684
					/* If all the inputs are FALSE, result is FALSE */
1685
					if (newargs == NIL)
1686
						return makeBoolConst(false, false);
1687
					/* If only one nonconst-or-NULL input, it's the result */
1688
					if (list_length(newargs) == 1)
1689
						return (Node *) linitial(newargs);
1690
					/* Else we still need an OR node */
1691
					return (Node *) make_orclause(newargs);
1692 1693 1694
				}
			case AND_EXPR:
				{
1695
					List	   *newargs;
1696 1697 1698
					bool		haveNull = false;
					bool		forceFalse = false;

1699
					newargs = simplify_and_arguments(expr->args, context,
1700
													 &haveNull, &forceFalse);
1701
					if (forceFalse)
1702
						return makeBoolConst(false, false);
1703
					if (haveNull)
1704
						newargs = lappend(newargs, makeBoolConst(false, true));
1705
					/* If all the inputs are TRUE, result is TRUE */
1706
					if (newargs == NIL)
1707
						return makeBoolConst(true, false);
1708
					/* If only one nonconst-or-NULL input, it's the result */
1709
					if (list_length(newargs) == 1)
1710
						return (Node *) linitial(newargs);
1711
					/* Else we still need an AND node */
1712
					return (Node *) make_andclause(newargs);
1713 1714
				}
			case NOT_EXPR:
1715
				{
1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738
					Node	   *arg;

					Assert(list_length(expr->args) == 1);
					arg = eval_const_expressions_mutator(linitial(expr->args),
														 context);
					if (IsA(arg, Const))
					{
						Const	   *const_input = (Const *) arg;

						/* NOT NULL => NULL */
						if (const_input->constisnull)
							return makeBoolConst(false, true);
						/* otherwise pretty easy */
						return makeBoolConst(!DatumGetBool(const_input->constvalue),
											 false);
					}
					else if (not_clause(arg))
					{
						/* Cancel NOT/NOT */
						return (Node *) get_notclausearg((Expr *) arg);
					}
					/* Else we still need a NOT node */
					return (Node *) make_notclause((Expr *) arg);
1739
				}
1740
			default:
1741
				elog(ERROR, "unrecognized boolop: %d",
1742
					 (int) expr->boolop);
1743 1744
				break;
		}
1745
	}
1746
	if (IsA(node, SubPlan))
1747
	{
1748
		/*
Bruce Momjian's avatar
Bruce Momjian committed
1749
		 * Return a SubPlan unchanged --- too late to do anything with it.
1750
		 *
1751 1752
		 * XXX should we ereport() here instead?  Probably this routine should
		 * never be invoked after SubPlan creation.
1753
		 */
1754
		return node;
1755
	}
1756 1757 1758
	if (IsA(node, RelabelType))
	{
		/*
1759 1760 1761
		 * If we can simplify the input to a constant, then we don't need the
		 * RelabelType node anymore: just change the type field of the Const
		 * node.  Otherwise, must copy the RelabelType node.
1762 1763 1764 1765
		 */
		RelabelType *relabel = (RelabelType *) node;
		Node	   *arg;

1766
		arg = eval_const_expressions_mutator((Node *) relabel->arg,
1767
											 context);
1768 1769

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

1776 1777
		if (arg && IsA(arg, Const))
		{
1778
			Const	   *con = (Const *) arg;
1779 1780

			con->consttype = relabel->resulttype;
1781

1782
			/*
1783 1784 1785
			 * relabel's resulttypmod is discarded, which is OK for now; if
			 * the type actually needs a runtime length coercion then there
			 * should be a function call to do it just above this node.
1786
			 */
1787 1788 1789 1790 1791 1792
			return (Node *) con;
		}
		else
		{
			RelabelType *newrelabel = makeNode(RelabelType);

1793
			newrelabel->arg = (Expr *) arg;
1794 1795 1796 1797 1798
			newrelabel->resulttype = relabel->resulttype;
			newrelabel->resulttypmod = relabel->resulttypmod;
			return (Node *) newrelabel;
		}
	}
1799 1800
	if (IsA(node, CaseExpr))
	{
1801
		/*----------
1802
		 * CASE expressions can be simplified if there are constant
1803 1804 1805 1806 1807 1808 1809
		 * 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).
1810
		 *
1811 1812 1813 1814 1815 1816
		 * If we have a simple-form CASE with constant test expression,
		 * we substitute the constant value for contained CaseTestExpr
		 * placeholder nodes, so that we have the opportunity to reduce
		 * constant test conditions.  For example this allows
		 *		CASE 0 WHEN 0 THEN 1 ELSE 1/0 END
		 * to reduce to 1 rather than drawing a divide-by-0 error.
1817
		 *----------
1818 1819 1820
		 */
		CaseExpr   *caseexpr = (CaseExpr *) node;
		CaseExpr   *newcase;
1821
		Node	   *save_case_val;
1822
		Node	   *newarg;
1823
		List	   *newargs;
1824 1825
		bool		const_true_cond;
		Node	   *defresult = NULL;
1826
		ListCell   *arg;
1827

1828 1829
		/* Simplify the test expression, if any */
		newarg = eval_const_expressions_mutator((Node *) caseexpr->arg,
1830
												context);
1831

1832 1833 1834 1835 1836 1837 1838
		/* Set up for contained CaseTestExpr nodes */
		save_case_val = context->case_val;
		if (newarg && IsA(newarg, Const))
			context->case_val = newarg;
		else
			context->case_val = NULL;

1839
		/* Simplify the WHEN clauses */
1840
		newargs = NIL;
1841
		const_true_cond = false;
1842 1843
		foreach(arg, caseexpr->args)
		{
1844 1845 1846 1847 1848 1849 1850 1851 1852 1853
			CaseWhen   *oldcasewhen = (CaseWhen *) lfirst(arg);
			Node	   *casecond;
			Node	   *caseresult;

			Assert(IsA(oldcasewhen, CaseWhen));

			/* Simplify this alternative's test condition */
			casecond =
				eval_const_expressions_mutator((Node *) oldcasewhen->expr,
											   context);
1854

1855
			/*
1856 1857
			 * If the test condition is constant FALSE (or NULL), then drop
			 * this WHEN clause completely, without processing the result.
1858
			 */
1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873
			if (casecond && IsA(casecond, Const))
			{
				Const	   *const_input = (Const *) casecond;

				if (const_input->constisnull ||
					!DatumGetBool(const_input->constvalue))
					continue;	/* drop alternative with FALSE condition */
				/* Else it's constant TRUE */
				const_true_cond = true;
			}

			/* Simplify this alternative's result value */
			caseresult =
				eval_const_expressions_mutator((Node *) oldcasewhen->result,
											   context);
1874

1875 1876 1877 1878 1879 1880 1881 1882 1883 1884
			/* If non-constant test condition, emit a new WHEN node */
			if (!const_true_cond)
			{
				CaseWhen   *newcasewhen = makeNode(CaseWhen);

				newcasewhen->expr = (Expr *) casecond;
				newcasewhen->result = (Expr *) caseresult;
				newargs = lappend(newargs, newcasewhen);
				continue;
			}
1885

1886
			/*
1887
			 * Found a TRUE condition, so none of the remaining alternatives
1888
			 * can be reached.	We treat the result as the default result.
1889
			 */
1890
			defresult = caseresult;
1891 1892 1893
			break;
		}

1894 1895 1896 1897 1898
		/* Simplify the default result, unless we replaced it above */
		if (!const_true_cond)
			defresult =
				eval_const_expressions_mutator((Node *) caseexpr->defresult,
											   context);
1899

1900 1901 1902
		context->case_val = save_case_val;

		/* If no non-FALSE alternatives, CASE reduces to the default result */
1903
		if (newargs == NIL)
1904 1905 1906 1907
			return defresult;
		/* Otherwise we need a new CASE node */
		newcase = makeNode(CaseExpr);
		newcase->casetype = caseexpr->casetype;
1908
		newcase->arg = (Expr *) newarg;
1909
		newcase->args = newargs;
1910
		newcase->defresult = (Expr *) defresult;
1911 1912
		return (Node *) newcase;
	}
1913 1914 1915
	if (IsA(node, CaseTestExpr))
	{
		/*
1916 1917 1918
		 * If we know a constant test value for the current CASE construct,
		 * substitute it for the placeholder.  Else just return the
		 * placeholder as-is.
1919 1920 1921 1922 1923 1924
		 */
		if (context->case_val)
			return copyObject(context->case_val);
		else
			return copyObject(node);
	}
1925 1926
	if (IsA(node, ArrayExpr))
	{
Bruce Momjian's avatar
Bruce Momjian committed
1927 1928 1929
		ArrayExpr  *arrayexpr = (ArrayExpr *) node;
		ArrayExpr  *newarray;
		bool		all_const = true;
1930
		List	   *newelems;
1931
		ListCell   *element;
1932

1933
		newelems = NIL;
1934 1935
		foreach(element, arrayexpr->elements)
		{
Bruce Momjian's avatar
Bruce Momjian committed
1936
			Node	   *e;
1937 1938

			e = eval_const_expressions_mutator((Node *) lfirst(element),
1939
											   context);
1940 1941
			if (!IsA(e, Const))
				all_const = false;
1942
			newelems = lappend(newelems, e);
1943 1944 1945 1946 1947
		}

		newarray = makeNode(ArrayExpr);
		newarray->array_typeid = arrayexpr->array_typeid;
		newarray->element_typeid = arrayexpr->element_typeid;
1948
		newarray->elements = newelems;
1949
		newarray->multidims = arrayexpr->multidims;
1950 1951 1952 1953 1954 1955 1956

		if (all_const)
			return (Node *) evaluate_expr((Expr *) newarray,
										  newarray->array_typeid);

		return (Node *) newarray;
	}
1957 1958 1959 1960
	if (IsA(node, CoalesceExpr))
	{
		CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
		CoalesceExpr *newcoalesce;
1961
		List	   *newargs;
1962
		ListCell   *arg;
1963

1964
		newargs = NIL;
1965 1966
		foreach(arg, coalesceexpr->args)
		{
Bruce Momjian's avatar
Bruce Momjian committed
1967
			Node	   *e;
1968 1969

			e = eval_const_expressions_mutator((Node *) lfirst(arg),
1970
											   context);
Bruce Momjian's avatar
Bruce Momjian committed
1971 1972 1973 1974 1975

			/*
			 * We can remove null constants from the list. For a non-null
			 * constant, if it has not been preceded by any other
			 * non-null-constant expressions then that is the result.
1976 1977 1978 1979 1980
			 */
			if (IsA(e, Const))
			{
				if (((Const *) e)->constisnull)
					continue;	/* drop null constant */
1981
				if (newargs == NIL)
1982 1983
					return e;	/* first expr */
			}
1984
			newargs = lappend(newargs, e);
1985 1986
		}

1987 1988 1989 1990
		/* If all the arguments were constant null, the result is just null */
		if (newargs == NIL)
			return (Node *) makeNullConst(coalesceexpr->coalescetype);

1991 1992
		newcoalesce = makeNode(CoalesceExpr);
		newcoalesce->coalescetype = coalesceexpr->coalescetype;
1993
		newcoalesce->args = newargs;
1994 1995
		return (Node *) newcoalesce;
	}
1996 1997 1998
	if (IsA(node, FieldSelect))
	{
		/*
1999 2000 2001 2002 2003
		 * We can optimize field selection from a whole-row Var into a simple
		 * Var.  (This case won't be generated directly by the parser, because
		 * ParseComplexProjection short-circuits it. But it can arise while
		 * simplifying functions.)	Also, we can optimize field selection from
		 * a RowExpr construct.
2004
		 *
2005 2006
		 * We must however check that the declared type of the field is still
		 * the same as when the FieldSelect was created --- this can change if
2007
		 * someone did ALTER COLUMN TYPE on the rowtype.
2008 2009
		 */
		FieldSelect *fselect = (FieldSelect *) node;
2010 2011
		FieldSelect *newfselect;
		Node	   *arg;
2012

2013
		arg = eval_const_expressions_mutator((Node *) fselect->arg,
2014
											 context);
2015 2016
		if (arg && IsA(arg, Var) &&
			((Var *) arg)->varattno == InvalidAttrNumber)
2017
		{
2018 2019 2020 2021 2022 2023 2024 2025 2026
			if (rowtype_field_matches(((Var *) arg)->vartype,
									  fselect->fieldnum,
									  fselect->resulttype,
									  fselect->resulttypmod))
				return (Node *) makeVar(((Var *) arg)->varno,
										fselect->fieldnum,
										fselect->resulttype,
										fselect->resulttypmod,
										((Var *) arg)->varlevelsup);
2027
		}
2028 2029
		if (arg && IsA(arg, RowExpr))
		{
Bruce Momjian's avatar
Bruce Momjian committed
2030
			RowExpr    *rowexpr = (RowExpr *) arg;
2031 2032

			if (fselect->fieldnum > 0 &&
2033
				fselect->fieldnum <= list_length(rowexpr->args))
2034
			{
Bruce Momjian's avatar
Bruce Momjian committed
2035
				Node	   *fld = (Node *) list_nth(rowexpr->args,
2036
													fselect->fieldnum - 1);
2037 2038 2039 2040 2041 2042 2043 2044 2045

				if (rowtype_field_matches(rowexpr->row_typeid,
										  fselect->fieldnum,
										  fselect->resulttype,
										  fselect->resulttypmod) &&
					fselect->resulttype == exprType(fld) &&
					fselect->resulttypmod == exprTypmod(fld))
					return fld;
			}
2046 2047 2048 2049 2050 2051 2052
		}
		newfselect = makeNode(FieldSelect);
		newfselect->arg = (Expr *) arg;
		newfselect->fieldnum = fselect->fieldnum;
		newfselect->resulttype = fselect->resulttype;
		newfselect->resulttypmod = fselect->resulttypmod;
		return (Node *) newfselect;
2053
	}
2054

2055 2056
	/*
	 * For any node type not handled above, we recurse using
2057 2058 2059 2060
	 * 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.
2061 2062
	 */
	return expression_tree_mutator(node, eval_const_expressions_mutator,
2063
								   (void *) context);
2064 2065
}

2066
/*
2067 2068 2069 2070
 * Subroutine for eval_const_expressions: process arguments of an OR clause
 *
 * This includes flattening of nested ORs as well as recursion to
 * eval_const_expressions to simplify the OR arguments.
2071
 *
2072
 * After simplification, OR arguments are handled as follows:
2073 2074 2075 2076 2077
 *		non constant: keep
 *		FALSE: drop (does not affect result)
 *		TRUE: force result to TRUE
 *		NULL: keep only one
 * We must keep one NULL input because ExecEvalOr returns NULL when no input
2078 2079
 * is TRUE and at least one is NULL.  We don't actually include the NULL
 * here, that's supposed to be done by the caller.
2080 2081 2082 2083 2084 2085
 *
 * The output arguments *haveNull and *forceTrue must be initialized FALSE
 * by the caller.  They will be set TRUE if a null constant or true constant,
 * respectively, is detected anywhere in the argument list.
 */
static List *
2086 2087 2088
simplify_or_arguments(List *args,
					  eval_const_expressions_context *context,
					  bool *haveNull, bool *forceTrue)
2089 2090
{
	List	   *newargs = NIL;
2091
	List	   *unprocessed_args;
2092

2093 2094 2095
	/*
	 * Since the parser considers OR to be a binary operator, long OR lists
	 * become deeply nested expressions.  We must flatten these into long
2096
	 * argument lists of a single OR operator.	To avoid blowing out the stack
2097 2098 2099 2100 2101 2102
	 * with recursion of eval_const_expressions, we resort to some tenseness
	 * here: we keep a list of not-yet-processed inputs, and handle flattening
	 * of nested ORs by prepending to the to-do list instead of recursing.
	 */
	unprocessed_args = list_copy(args);
	while (unprocessed_args)
2103
	{
2104 2105 2106 2107 2108 2109 2110
		Node	   *arg = (Node *) linitial(unprocessed_args);

		unprocessed_args = list_delete_first(unprocessed_args);

		/* flatten nested ORs as per above comment */
		if (or_clause(arg))
		{
2111
			List	   *subargs = list_copy(((BoolExpr *) arg)->args);
2112 2113 2114 2115 2116 2117

			/* overly tense code to avoid leaking unused list header */
			if (!unprocessed_args)
				unprocessed_args = subargs;
			else
			{
2118
				List	   *oldhdr = unprocessed_args;
2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129

				unprocessed_args = list_concat(subargs, unprocessed_args);
				pfree(oldhdr);
			}
			continue;
		}

		/* If it's not an OR, simplify it */
		arg = eval_const_expressions_mutator(arg, context);

		/*
2130 2131 2132 2133
		 * It is unlikely but not impossible for simplification of a non-OR
		 * clause to produce an OR.  Recheck, but don't be too tense about it
		 * since it's not a mainstream case. In particular we don't worry
		 * about const-simplifying the input twice.
2134 2135 2136
		 */
		if (or_clause(arg))
		{
2137
			List	   *subargs = list_copy(((BoolExpr *) arg)->args);
2138 2139 2140 2141

			unprocessed_args = list_concat(subargs, unprocessed_args);
			continue;
		}
2142

2143
		/*
2144 2145
		 * OK, we have a const-simplified non-OR argument.	Process it per
		 * comments above.
2146
		 */
2147 2148
		if (IsA(arg, Const))
		{
Bruce Momjian's avatar
Bruce Momjian committed
2149
			Const	   *const_input = (Const *) arg;
2150 2151 2152 2153 2154 2155

			if (const_input->constisnull)
				*haveNull = true;
			else if (DatumGetBool(const_input->constvalue))
			{
				*forceTrue = true;
Bruce Momjian's avatar
Bruce Momjian committed
2156

2157 2158 2159 2160 2161 2162 2163 2164
				/*
				 * Once we detect a TRUE result we can just exit the loop
				 * immediately.  However, if we ever add a notion of
				 * non-removable functions, we'd need to keep scanning.
				 */
				return NIL;
			}
			/* otherwise, we can drop the constant-false input */
2165
			continue;
2166
		}
2167 2168 2169

		/* else emit the simplified arg into the result list */
		newargs = lappend(newargs, arg);
2170 2171 2172 2173 2174 2175
	}

	return newargs;
}

/*
2176
 * Subroutine for eval_const_expressions: process arguments of an AND clause
2177
 *
2178 2179 2180 2181
 * This includes flattening of nested ANDs as well as recursion to
 * eval_const_expressions to simplify the AND arguments.
 *
 * After simplification, AND arguments are handled as follows:
2182 2183 2184 2185 2186
 *		non constant: keep
 *		TRUE: drop (does not affect result)
 *		FALSE: force result to FALSE
 *		NULL: keep only one
 * We must keep one NULL input because ExecEvalAnd returns NULL when no input
2187 2188
 * is FALSE and at least one is NULL.  We don't actually include the NULL
 * here, that's supposed to be done by the caller.
2189 2190 2191 2192 2193 2194
 *
 * The output arguments *haveNull and *forceFalse must be initialized FALSE
 * by the caller.  They will be set TRUE if a null constant or false constant,
 * respectively, is detected anywhere in the argument list.
 */
static List *
2195 2196 2197
simplify_and_arguments(List *args,
					   eval_const_expressions_context *context,
					   bool *haveNull, bool *forceFalse)
2198 2199
{
	List	   *newargs = NIL;
2200
	List	   *unprocessed_args;
2201

2202 2203 2204
	/* See comments in simplify_or_arguments */
	unprocessed_args = list_copy(args);
	while (unprocessed_args)
2205
	{
2206 2207 2208 2209 2210 2211 2212
		Node	   *arg = (Node *) linitial(unprocessed_args);

		unprocessed_args = list_delete_first(unprocessed_args);

		/* flatten nested ANDs as per above comment */
		if (and_clause(arg))
		{
2213
			List	   *subargs = list_copy(((BoolExpr *) arg)->args);
2214 2215 2216 2217 2218 2219

			/* overly tense code to avoid leaking unused list header */
			if (!unprocessed_args)
				unprocessed_args = subargs;
			else
			{
2220
				List	   *oldhdr = unprocessed_args;
2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231

				unprocessed_args = list_concat(subargs, unprocessed_args);
				pfree(oldhdr);
			}
			continue;
		}

		/* If it's not an AND, simplify it */
		arg = eval_const_expressions_mutator(arg, context);

		/*
2232 2233 2234 2235
		 * It is unlikely but not impossible for simplification of a non-AND
		 * clause to produce an AND.  Recheck, but don't be too tense about it
		 * since it's not a mainstream case. In particular we don't worry
		 * about const-simplifying the input twice.
2236 2237 2238
		 */
		if (and_clause(arg))
		{
2239
			List	   *subargs = list_copy(((BoolExpr *) arg)->args);
2240

2241 2242 2243 2244 2245
			unprocessed_args = list_concat(subargs, unprocessed_args);
			continue;
		}

		/*
2246 2247
		 * OK, we have a const-simplified non-AND argument.  Process it per
		 * comments above.
2248
		 */
2249 2250
		if (IsA(arg, Const))
		{
Bruce Momjian's avatar
Bruce Momjian committed
2251
			Const	   *const_input = (Const *) arg;
2252 2253 2254 2255 2256 2257

			if (const_input->constisnull)
				*haveNull = true;
			else if (!DatumGetBool(const_input->constvalue))
			{
				*forceFalse = true;
Bruce Momjian's avatar
Bruce Momjian committed
2258

2259 2260 2261 2262 2263 2264 2265 2266
				/*
				 * Once we detect a FALSE result we can just exit the loop
				 * immediately.  However, if we ever add a notion of
				 * non-removable functions, we'd need to keep scanning.
				 */
				return NIL;
			}
			/* otherwise, we can drop the constant-true input */
2267
			continue;
2268
		}
2269 2270 2271

		/* else emit the simplified arg into the result list */
		newargs = lappend(newargs, arg);
2272 2273 2274 2275 2276
	}

	return newargs;
}

2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304
/*
 * Subroutine for eval_const_expressions: try to simplify boolean equality
 *
 * Input is the list of simplified arguments to the operator.
 * Returns a simplified expression if successful, or NULL if cannot
 * simplify the expression.
 *
 * The idea here is to reduce "x = true" to "x" and "x = false" to "NOT x".
 * This is only marginally useful in itself, but doing it in constant folding
 * ensures that we will recognize the two forms as being equivalent in, for
 * example, partial index matching.
 *
 * We come here only if simplify_function has failed; therefore we cannot
 * see two constant inputs, nor a constant-NULL input.
 */
static Expr *
simplify_boolean_equality(List *args)
{
	Expr	   *leftop;
	Expr	   *rightop;

	Assert(list_length(args) == 2);
	leftop = linitial(args);
	rightop = lsecond(args);
	if (leftop && IsA(leftop, Const))
	{
		Assert(!((Const *) leftop)->constisnull);
		if (DatumGetBool(((Const *) leftop)->constvalue))
2305
			return rightop;		/* true = foo */
2306 2307 2308 2309 2310 2311 2312
		else
			return make_notclause(rightop);		/* false = foo */
	}
	if (rightop && IsA(rightop, Const))
	{
		Assert(!((Const *) rightop)->constisnull);
		if (DatumGetBool(((Const *) rightop)->constvalue))
2313
			return leftop;		/* foo = true */
2314 2315 2316 2317 2318 2319
		else
			return make_notclause(leftop);		/* foo = false */
	}
	return NULL;
}

2320
/*
2321 2322
 * Subroutine for eval_const_expressions: try to simplify a function call
 * (which might originally have been an operator; we don't care)
2323
 *
2324 2325
 * Inputs are the function OID, actual result type OID (which is needed for
 * polymorphic functions), and the pre-simplified argument list;
2326
 * also the context data for eval_const_expressions.
2327 2328
 *
 * Returns a simplified expression if successful, or NULL if cannot
2329
 * simplify the function call.
2330 2331
 */
static Expr *
2332
simplify_function(Oid funcid, Oid result_type, List *args,
2333 2334
				  bool allow_inline,
				  eval_const_expressions_context *context)
2335 2336
{
	HeapTuple	func_tuple;
2337
	Expr	   *newexpr;
2338 2339

	/*
2340 2341 2342 2343 2344 2345
	 * We have two strategies for simplification: either execute the function
	 * to deliver a constant result, or expand in-line the body of the
	 * function definition (which only works for simple SQL-language
	 * functions, but that is a common case).  In either case we need access
	 * to the function's pg_proc tuple, so fetch it just once to use in both
	 * attempts.
2346
	 */
2347 2348 2349
	func_tuple = SearchSysCache(PROCOID,
								ObjectIdGetDatum(funcid),
								0, 0, 0);
2350
	if (!HeapTupleIsValid(func_tuple))
2351
		elog(ERROR, "cache lookup failed for function %u", funcid);
2352

2353 2354
	newexpr = evaluate_function(funcid, result_type, args,
								func_tuple, context);
2355 2356

	if (!newexpr && allow_inline)
2357
		newexpr = inline_function(funcid, result_type, args,
2358
								  func_tuple, context);
2359

2360 2361
	ReleaseSysCache(func_tuple);

2362 2363 2364 2365
	return newexpr;
}

/*
2366
 * evaluate_function: try to pre-evaluate a function call
2367 2368 2369
 *
 * We can do this if the function is strict and has any constant-null inputs
 * (just return a null constant), or if the function is immutable and has all
2370 2371
 * constant inputs (call it and return the result as a Const node).  In
 * estimation mode we are willing to pre-evaluate stable functions too.
2372 2373
 *
 * Returns a simplified expression if successful, or NULL if cannot
2374
 * simplify the function.
2375 2376
 */
static Expr *
2377
evaluate_function(Oid funcid, Oid result_type, List *args,
2378 2379
				  HeapTuple func_tuple,
				  eval_const_expressions_context *context)
2380 2381 2382 2383
{
	Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
	bool		has_nonconst_input = false;
	bool		has_null_input = false;
2384
	ListCell   *arg;
2385
	FuncExpr   *newexpr;
2386

2387
	/*
2388
	 * Can't simplify if it returns a set.
2389
	 */
2390
	if (funcform->proretset)
2391
		return NULL;
2392

2393
	/*
2394 2395
	 * Can't simplify if it returns RECORD.  The immediate problem is that it
	 * will be needing an expected tupdesc which we can't supply here.
2396 2397 2398
	 *
	 * In the case where it has OUT parameters, it could get by without an
	 * expected tupdesc, but we still have issues: get_expr_result_type()
2399 2400 2401 2402
	 * doesn't know how to extract type info from a RECORD constant, and in
	 * the case of a NULL function result there doesn't seem to be any clean
	 * way to fix that.  In view of the likelihood of there being still other
	 * gotchas, seems best to leave the function call unreduced.
2403
	 */
2404
	if (funcform->prorettype == RECORDOID)
2405 2406
		return NULL;

2407
	/*
2408
	 * Check for constant inputs and especially constant-NULL inputs.
2409
	 */
2410
	foreach(arg, args)
2411
	{
2412 2413 2414 2415
		if (IsA(lfirst(arg), Const))
			has_null_input |= ((Const *) lfirst(arg))->constisnull;
		else
			has_nonconst_input = true;
2416 2417 2418
	}

	/*
2419 2420 2421 2422
	 * 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, and even if the
	 * function is not otherwise immutable.
2423
	 */
2424
	if (funcform->proisstrict && has_null_input)
2425
		return (Expr *) makeNullConst(result_type);
2426 2427

	/*
2428 2429 2430
	 * 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.)
2431
	 */
2432 2433 2434 2435
	if (has_nonconst_input)
		return NULL;

	/*
2436 2437 2438 2439 2440
	 * Ordinarily we are only allowed to simplify immutable functions. But for
	 * purposes of estimation, we consider it okay to simplify functions that
	 * are merely stable; the risk that the result might change from planning
	 * time to execution time is worth taking in preference to not being able
	 * to estimate the value at all.
2441 2442
	 */
	if (funcform->provolatile == PROVOLATILE_IMMUTABLE)
2443
		 /* okay */ ;
2444
	else if (context->estimate && funcform->provolatile == PROVOLATILE_STABLE)
2445
		 /* okay */ ;
2446
	else
2447 2448
		return NULL;

2449 2450 2451
	/*
	 * OK, looks like we can simplify this operator/function.
	 *
2452
	 * Build a new FuncExpr node containing the already-simplified arguments.
2453
	 */
2454 2455
	newexpr = makeNode(FuncExpr);
	newexpr->funcid = funcid;
2456
	newexpr->funcresulttype = result_type;
2457
	newexpr->funcretset = false;
2458
	newexpr->funcformat = COERCE_DONTCARE;		/* doesn't matter */
2459
	newexpr->args = args;
2460

2461
	return evaluate_expr((Expr *) newexpr, result_type);
2462 2463
}

2464
/*
2465
 * inline_function: try to expand a function call inline
2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476
 *
 * If the function is a sufficiently simple SQL-language function
 * (just "SELECT expression"), then we can inline it and avoid the rather
 * high per-call overhead of SQL functions.  Furthermore, this can expose
 * opportunities for constant-folding within the function expression.
 *
 * We have to beware of some special cases however.  A directly or
 * indirectly recursive function would cause us to recurse forever,
 * so we keep track of which functions we are already expanding and
 * do not re-expand them.  Also, if a parameter is used more than once
 * in the SQL-function body, we require it not to contain any volatile
2477
 * functions (volatiles might deliver inconsistent answers) nor to be
Bruce Momjian's avatar
Bruce Momjian committed
2478
 * unreasonably expensive to evaluate.	The expensiveness check not only
2479 2480 2481 2482
 * prevents us from doing multiple evaluations of an expensive parameter
 * at runtime, but is a safety value to limit growth of an expression due
 * to repeated inlining.
 *
2483 2484 2485 2486
 * We must also beware of changing the volatility or strictness status of
 * functions by inlining them.
 *
 * Returns a simplified expression if successful, or NULL if cannot
2487
 * simplify the function.
2488 2489
 */
static Expr *
2490
inline_function(Oid funcid, Oid result_type, List *args,
2491 2492
				HeapTuple func_tuple,
				eval_const_expressions_context *context)
2493 2494
{
	Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
2495
	bool		polymorphic = false;
2496
	Oid		   *argtypes;
2497 2498 2499 2500 2501
	char	   *src;
	Datum		tmp;
	bool		isNull;
	MemoryContext oldcxt;
	MemoryContext mycxt;
2502
	ErrorContextCallback sqlerrcontext;
2503 2504 2505 2506 2507
	List	   *raw_parsetree_list;
	List	   *querytree_list;
	Query	   *querytree;
	Node	   *newexpr;
	int		   *usecounts;
2508
	ListCell   *arg;
2509 2510 2511
	int			i;

	/*
2512 2513
	 * Forget it if the function is not SQL-language or has other showstopper
	 * properties.	(The nargs check is just paranoia.)
2514 2515 2516 2517
	 */
	if (funcform->prolang != SQLlanguageId ||
		funcform->prosecdef ||
		funcform->proretset ||
2518
		funcform->pronargs != list_length(args))
2519 2520 2521
		return NULL;

	/* Check for recursive function, and give up trying to expand if so */
2522
	if (list_member_oid(context->active_fns, funcid))
2523 2524 2525 2526 2527 2528
		return NULL;

	/* Check permission to call function (fail later, if not) */
	if (pg_proc_aclcheck(funcid, GetUserId(), ACL_EXECUTE) != ACLCHECK_OK)
		return NULL;

2529
	/*
2530 2531
	 * Setup error traceback support for ereport().  This is so that we can
	 * finger the function that bad information came from.
2532 2533
	 */
	sqlerrcontext.callback = sql_inline_error_callback;
2534
	sqlerrcontext.arg = func_tuple;
2535 2536 2537
	sqlerrcontext.previous = error_context_stack;
	error_context_stack = &sqlerrcontext;

2538
	/*
2539 2540
	 * Make a temporary memory context, so that we don't leak all the stuff
	 * that parsing might create.
2541 2542
	 */
	mycxt = AllocSetContextCreate(CurrentMemoryContext,
2543
								  "inline_function",
2544 2545 2546 2547 2548
								  ALLOCSET_DEFAULT_MINSIZE,
								  ALLOCSET_DEFAULT_INITSIZE,
								  ALLOCSET_DEFAULT_MAXSIZE);
	oldcxt = MemoryContextSwitchTo(mycxt);

2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566
	/* Check for polymorphic arguments, and substitute actual arg types */
	argtypes = (Oid *) palloc(funcform->pronargs * sizeof(Oid));
	memcpy(argtypes, funcform->proargtypes.values,
		   funcform->pronargs * sizeof(Oid));
	for (i = 0; i < funcform->pronargs; i++)
	{
		if (argtypes[i] == ANYARRAYOID ||
			argtypes[i] == ANYELEMENTOID)
		{
			polymorphic = true;
			argtypes[i] = exprType((Node *) list_nth(args, i));
		}
	}

	if (funcform->prorettype == ANYARRAYOID ||
		funcform->prorettype == ANYELEMENTOID)
		polymorphic = true;

2567 2568 2569 2570 2571 2572
	/* Fetch and parse the function body */
	tmp = SysCacheGetAttr(PROCOID,
						  func_tuple,
						  Anum_pg_proc_prosrc,
						  &isNull);
	if (isNull)
2573
		elog(ERROR, "null prosrc for function %u", funcid);
2574 2575 2576
	src = DatumGetCString(DirectFunctionCall1(textout, tmp));

	/*
2577 2578 2579 2580
	 * We just do parsing and parse analysis, not rewriting, because rewriting
	 * will not affect table-free-SELECT-only queries, which is all that we
	 * care about.	Also, we can punt as soon as we detect more than one
	 * command in the function body.
2581
	 */
2582
	raw_parsetree_list = pg_parse_query(src);
2583
	if (list_length(raw_parsetree_list) != 1)
2584 2585
		goto fail;

2586
	querytree_list = parse_analyze(linitial(raw_parsetree_list),
2587
								   argtypes, funcform->pronargs);
2588

2589
	if (list_length(querytree_list) != 1)
2590 2591
		goto fail;

2592
	querytree = (Query *) linitial(querytree_list);
2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612

	/*
	 * The single command must be a simple "SELECT expression".
	 */
	if (!IsA(querytree, Query) ||
		querytree->commandType != CMD_SELECT ||
		querytree->resultRelation != 0 ||
		querytree->into ||
		querytree->hasAggs ||
		querytree->hasSubLinks ||
		querytree->rtable ||
		querytree->jointree->fromlist ||
		querytree->jointree->quals ||
		querytree->groupClause ||
		querytree->havingQual ||
		querytree->distinctClause ||
		querytree->sortClause ||
		querytree->limitOffset ||
		querytree->limitCount ||
		querytree->setOperations ||
2613
		list_length(querytree->targetList) != 1)
2614 2615
		goto fail;

2616
	newexpr = (Node *) ((TargetEntry *) linitial(querytree->targetList))->expr;
2617

2618
	/*
2619 2620 2621 2622 2623 2624
	 * If the function has any arguments declared as polymorphic types, then
	 * it wasn't type-checked at definition time; must do so now. (This will
	 * raise an error if wrong, but that's okay since the function would fail
	 * at runtime anyway.  Note we do not try this until we have verified that
	 * no rewriting was needed; that's probably not important, but let's be
	 * careful.)
2625 2626
	 */
	if (polymorphic)
2627
		(void) check_sql_fn_retval(funcid, result_type, querytree_list, NULL);
2628

2629
	/*
2630 2631 2632 2633 2634 2635 2636
	 * Additional validity checks on the expression.  It mustn't return a set,
	 * and it mustn't be more volatile than the surrounding function (this is
	 * to avoid breaking hacks that involve pretending a function is immutable
	 * when it really ain't).  If the surrounding function is declared strict,
	 * then the expression must contain only strict constructs and must use
	 * all of the function parameters (this is overkill, but an exact analysis
	 * is hard).
2637 2638 2639 2640 2641 2642 2643 2644
	 */
	if (expression_returns_set(newexpr))
		goto fail;

	if (funcform->provolatile == PROVOLATILE_IMMUTABLE &&
		contain_mutable_functions(newexpr))
		goto fail;
	else if (funcform->provolatile == PROVOLATILE_STABLE &&
Bruce Momjian's avatar
Bruce Momjian committed
2645
			 contain_volatile_functions(newexpr))
2646 2647 2648 2649 2650 2651 2652
		goto fail;

	if (funcform->proisstrict &&
		contain_nonstrict_functions(newexpr))
		goto fail;

	/*
2653 2654 2655 2656
	 * We may be able to do it; there are still checks on parameter usage to
	 * make, but those are most easily done in combination with the actual
	 * substitution of the inputs.	So start building expression with inputs
	 * substituted.
2657
	 */
2658
	usecounts = (int *) palloc0(funcform->pronargs * sizeof(int));
2659 2660 2661 2662 2663 2664 2665
	newexpr = substitute_actual_parameters(newexpr, funcform->pronargs,
										   args, usecounts);

	/* Now check for parameter usage */
	i = 0;
	foreach(arg, args)
	{
Bruce Momjian's avatar
Bruce Momjian committed
2666
		Node	   *param = lfirst(arg);
2667 2668 2669 2670 2671 2672 2673 2674 2675

		if (usecounts[i] == 0)
		{
			/* Param not used at all: uncool if func is strict */
			if (funcform->proisstrict)
				goto fail;
		}
		else if (usecounts[i] != 1)
		{
2676 2677 2678 2679
			/* Param used multiple times: uncool if expensive or volatile */
			QualCost	eval_cost;

			/*
2680 2681
			 * We define "expensive" as "contains any subplan or more than 10
			 * operators".  Note that the subplan search has to be done
2682 2683 2684 2685 2686
			 * explicitly, since cost_qual_eval() will barf on unplanned
			 * subselects.
			 */
			if (contain_subplans(param))
				goto fail;
2687
			cost_qual_eval(&eval_cost, list_make1(param));
2688 2689 2690
			if (eval_cost.startup + eval_cost.per_tuple >
				10 * cpu_operator_cost)
				goto fail;
Bruce Momjian's avatar
Bruce Momjian committed
2691

2692 2693 2694 2695 2696
			/*
			 * Check volatility last since this is more expensive than the
			 * above tests
			 */
			if (contain_volatile_functions(param))
2697 2698 2699 2700 2701 2702
				goto fail;
		}
		i++;
	}

	/*
2703 2704
	 * Whew --- we can make the substitution.  Copy the modified expression
	 * out of the temporary memory context, and clean up.
2705 2706 2707 2708 2709 2710 2711 2712
	 */
	MemoryContextSwitchTo(oldcxt);

	newexpr = copyObject(newexpr);

	MemoryContextDelete(mycxt);

	/*
2713 2714
	 * Recursively try to simplify the modified expression.  Here we must add
	 * the current function to the context list of active functions.
2715
	 */
2716 2717 2718
	context->active_fns = lcons_oid(funcid, context->active_fns);
	newexpr = eval_const_expressions_mutator(newexpr, context);
	context->active_fns = list_delete_first(context->active_fns);
2719

2720 2721
	error_context_stack = sqlerrcontext.previous;

2722 2723 2724 2725 2726 2727
	return (Expr *) newexpr;

	/* Here if func is not inlinable: release temp memory and return NULL */
fail:
	MemoryContextSwitchTo(oldcxt);
	MemoryContextDelete(mycxt);
2728
	error_context_stack = sqlerrcontext.previous;
2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741

	return NULL;
}

/*
 * Replace Param nodes by appropriate actual parameters
 */
static Node *
substitute_actual_parameters(Node *expr, int nargs, List *args,
							 int *usecounts)
{
	substitute_actual_parameters_context context;

Bruce Momjian's avatar
Bruce Momjian committed
2742
	context.nargs = nargs;
2743 2744 2745 2746 2747 2748 2749 2750
	context.args = args;
	context.usecounts = usecounts;

	return substitute_actual_parameters_mutator(expr, &context);
}

static Node *
substitute_actual_parameters_mutator(Node *node,
2751
							   substitute_actual_parameters_context *context)
2752 2753 2754 2755 2756 2757 2758 2759
{
	if (node == NULL)
		return NULL;
	if (IsA(node, Param))
	{
		Param	   *param = (Param *) node;

		if (param->paramkind != PARAM_NUM)
2760
			elog(ERROR, "unexpected paramkind: %d", param->paramkind);
2761
		if (param->paramid <= 0 || param->paramid > context->nargs)
2762
			elog(ERROR, "invalid paramid: %d", param->paramid);
2763 2764 2765 2766 2767 2768

		/* Count usage of parameter */
		context->usecounts[param->paramid - 1]++;

		/* Select the appropriate actual arg and replace the Param with it */
		/* We don't need to copy at this time (it'll get done later) */
2769
		return list_nth(context->args, param->paramid - 1);
2770 2771 2772 2773 2774
	}
	return expression_tree_mutator(node, substitute_actual_parameters_mutator,
								   (void *) context);
}

2775 2776 2777 2778 2779 2780
/*
 * error context callback to let us supply a call-stack traceback
 */
static void
sql_inline_error_callback(void *arg)
{
Bruce Momjian's avatar
Bruce Momjian committed
2781
	HeapTuple	func_tuple = (HeapTuple) arg;
2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801
	Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
	int			syntaxerrposition;

	/* If it's a syntax error, convert to internal syntax error report */
	syntaxerrposition = geterrposition();
	if (syntaxerrposition > 0)
	{
		bool		isnull;
		Datum		tmp;
		char	   *prosrc;

		tmp = SysCacheGetAttr(PROCOID, func_tuple, Anum_pg_proc_prosrc,
							  &isnull);
		if (isnull)
			elog(ERROR, "null prosrc");
		prosrc = DatumGetCString(DirectFunctionCall1(textout, tmp));
		errposition(0);
		internalerrposition(syntaxerrposition);
		internalerrquery(prosrc);
	}
2802 2803 2804 2805 2806

	errcontext("SQL function \"%s\" during inlining",
			   NameStr(funcform->proname));
}

2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839
/*
 * evaluate_expr: pre-evaluate a constant expression
 *
 * We use the executor's routine ExecEvalExpr() to avoid duplication of
 * code and ensure we get the same result as the executor would get.
 */
static Expr *
evaluate_expr(Expr *expr, Oid result_type)
{
	EState	   *estate;
	ExprState  *exprstate;
	MemoryContext oldcontext;
	Datum		const_val;
	bool		const_is_null;
	int16		resultTypLen;
	bool		resultTypByVal;

	/*
	 * To use the executor, we need an EState.
	 */
	estate = CreateExecutorState();

	/* We can use the estate's working context to avoid memory leaks. */
	oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);

	/*
	 * Prepare expr for execution.
	 */
	exprstate = ExecPrepareExpr(expr, estate);

	/*
	 * And evaluate it.
	 *
2840 2841 2842 2843
	 * It is OK to use a default 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?
2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869
	 */
	const_val = ExecEvalExprSwitchContext(exprstate,
										  GetPerTupleExprContext(estate),
										  &const_is_null, NULL);

	/* Get info needed about result datatype */
	get_typlenbyval(result_type, &resultTypLen, &resultTypByVal);

	/* Get back to outer memory context */
	MemoryContextSwitchTo(oldcontext);

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

	/* Release all the junk we just created */
	FreeExecutorState(estate);

	/*
	 * Make the constant result node.
	 */
	return (Expr *) makeConst(result_type, resultTypLen,
							  const_val, const_is_null,
							  resultTypByVal);
}

2870

2871
/*
2872 2873 2874 2875 2876 2877 2878 2879 2880
 * 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
2881 2882 2883 2884 2885
 * logic to consolidate the redundant "boilerplate" code.  There are
 * two versions: expression_tree_walker() and expression_tree_mutator().
 */

/*--------------------
2886 2887
 * expression_tree_walker() is designed to support routines that traverse
 * a tree in a read-only fashion (although it will also work for routines
2888 2889
 * that modify nodes in-place but never add/delete/replace nodes).
 * A walker routine should look like this:
2890 2891 2892 2893 2894
 *
 * bool my_walker (Node *node, my_struct *context)
 * {
 *		if (node == NULL)
 *			return false;
Bruce Momjian's avatar
Bruce Momjian committed
2895
 *		// check for nodes that special work is required for, eg:
2896 2897 2898 2899 2900 2901 2902 2903
 *		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
2904
 *		// for any node type not specially processed, do:
2905 2906 2907 2908
 *		return expression_tree_walker(node, my_walker, (void *) context);
 * }
 *
 * The "context" argument points to a struct that holds whatever context
2909 2910
 * information the walker routine needs --- it can be used to return data
 * gathered by the walker, too.  This argument is not touched by
2911 2912 2913 2914 2915 2916 2917
 * 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
2918 2919
 * 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
2920
 * iff no invocation of the walker returned "true".
2921 2922 2923 2924 2925 2926 2927
 *
 * 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
2928
 * chooses to process TargetEntry nodes specially.)  Also, RangeTblRef,
2929 2930
 * FromExpr, JoinExpr, and SetOperationStmt nodes are handled, so that query
 * jointrees and setOperation trees can be processed without additional code.
2931
 *
2932 2933
 * expression_tree_walker will handle SubLink nodes by recursing normally
 * into the "testexpr" subtree (which is an expression belonging to the outer
2934 2935 2936 2937 2938 2939 2940 2941 2942
 * 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:
2943 2944 2945 2946
 *
 *		if (IsA(node, Query))
 *		{
 *			adjust context for subquery;
2947
 *			result = query_tree_walker((Query *) node, my_walker, context,
2948
 *									   0); // adjust flags as needed
2949 2950 2951
 *			restore context if needed;
 *			return result;
 *		}
2952
 *
2953 2954
 * query_tree_walker is a convenience routine (see below) that calls the
 * walker on all the expression subtrees of the given Query node.
2955
 *
2956
 * expression_tree_walker will handle SubPlan nodes by recursing normally
2957
 * into the "testexpr" and the "args" list (which are expressions belonging to
Bruce Momjian's avatar
Bruce Momjian committed
2958
 * the outer plan).  It will not touch the completed subplan, however.	Since
2959 2960 2961
 * there is no link to the original Query, it is not possible to recurse into
 * subselects of an already-planned expression tree.  This is OK for current
 * uses, but may need to be revisited in future.
2962 2963 2964 2965
 *--------------------
 */

bool
2966 2967 2968
expression_tree_walker(Node *node,
					   bool (*walker) (),
					   void *context)
2969
{
2970
	ListCell   *temp;
2971 2972

	/*
2973 2974
	 * The walker has already visited the current node, and so we need only
	 * recurse into any sub-nodes it has.
2975
	 *
2976 2977 2978
	 * 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
	 * bothering to call the walker.
2979 2980 2981
	 */
	if (node == NULL)
		return false;
2982 2983 2984 2985

	/* Guard against stack overflow due to overly complex expressions */
	check_stack_depth();

2986 2987 2988
	switch (nodeTag(node))
	{
		case T_Var:
2989
		case T_Const:
2990
		case T_Param:
2991
		case T_CoerceToDomainValue:
2992
		case T_CaseTestExpr:
2993
		case T_SetToDefault:
2994
		case T_RangeTblRef:
2995 2996
		case T_OuterJoinInfo:
			/* primitive node types with no expression subnodes */
2997
			break;
2998 2999 3000 3001 3002
		case T_Aggref:
			return walker(((Aggref *) node)->target, context);
		case T_ArrayRef:
			{
				ArrayRef   *aref = (ArrayRef *) node;
3003

3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017
				/* 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;
3018
		case T_FuncExpr:
3019
			{
3020
				FuncExpr   *expr = (FuncExpr *) node;
3021

3022 3023 3024 3025 3026 3027 3028 3029
				if (expression_tree_walker((Node *) expr->args,
										   walker, context))
					return true;
			}
			break;
		case T_OpExpr:
			{
				OpExpr	   *expr = (OpExpr *) node;
3030

3031 3032
				if (expression_tree_walker((Node *) expr->args,
										   walker, context))
3033
					return true;
3034 3035 3036 3037 3038 3039 3040 3041
			}
			break;
		case T_DistinctExpr:
			{
				DistinctExpr *expr = (DistinctExpr *) node;

				if (expression_tree_walker((Node *) expr->args,
										   walker, context))
3042 3043 3044
					return true;
			}
			break;
3045 3046 3047 3048 3049 3050 3051 3052 3053
		case T_ScalarArrayOpExpr:
			{
				ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;

				if (expression_tree_walker((Node *) expr->args,
										   walker, context))
					return true;
			}
			break;
3054 3055 3056 3057 3058 3059 3060 3061
		case T_BoolExpr:
			{
				BoolExpr   *expr = (BoolExpr *) node;

				if (expression_tree_walker((Node *) expr->args,
										   walker, context))
					return true;
			}
3062
			break;
3063
		case T_SubLink:
3064
			{
3065
				SubLink    *sublink = (SubLink *) node;
3066

3067
				if (expression_tree_walker(sublink->testexpr,
3068 3069
										   walker, context))
					return true;
Bruce Momjian's avatar
Bruce Momjian committed
3070

3071
				/*
3072 3073
				 * Also invoke the walker on the sublink's Query node, so it
				 * can recurse into the sub-query if it wants to.
3074 3075
				 */
				return walker(sublink->subselect, context);
3076 3077
			}
			break;
3078
		case T_SubPlan:
3079
			{
Bruce Momjian's avatar
Bruce Momjian committed
3080
				SubPlan    *subplan = (SubPlan *) node;
3081

3082 3083
				/* recurse into the testexpr, but not into the Plan */
				if (expression_tree_walker(subplan->testexpr,
3084
										   walker, context))
3085 3086
					return true;
				/* also examine args list */
3087
				if (expression_tree_walker((Node *) subplan->args,
3088 3089 3090 3091 3092 3093
										   walker, context))
					return true;
			}
			break;
		case T_FieldSelect:
			return walker(((FieldSelect *) node)->arg, context);
3094 3095
		case T_FieldStore:
			{
Bruce Momjian's avatar
Bruce Momjian committed
3096
				FieldStore *fstore = (FieldStore *) node;
3097 3098 3099 3100 3101 3102 3103

				if (walker(fstore->arg, context))
					return true;
				if (walker(fstore->newvals, context))
					return true;
			}
			break;
3104 3105
		case T_RelabelType:
			return walker(((RelabelType *) node)->arg, context);
3106 3107
		case T_ConvertRowtypeExpr:
			return walker(((ConvertRowtypeExpr *) node)->arg, context);
3108 3109 3110 3111
		case T_CaseExpr:
			{
				CaseExpr   *caseexpr = (CaseExpr *) node;

3112 3113
				if (walker(caseexpr->arg, context))
					return true;
3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128
				/* we assume walker doesn't care about CaseWhens, either */
				foreach(temp, caseexpr->args)
				{
					CaseWhen   *when = (CaseWhen *) lfirst(temp);

					Assert(IsA(when, CaseWhen));
					if (walker(when->expr, context))
						return true;
					if (walker(when->result, context))
						return true;
				}
				if (walker(caseexpr->defresult, context))
					return true;
			}
			break;
3129 3130
		case T_ArrayExpr:
			return walker(((ArrayExpr *) node)->elements, context);
3131 3132
		case T_RowExpr:
			return walker(((RowExpr *) node)->args, context);
3133 3134 3135 3136 3137 3138 3139 3140 3141 3142
		case T_RowCompareExpr:
			{
				RowCompareExpr *rcexpr = (RowCompareExpr *) node;

				if (walker(rcexpr->largs, context))
					return true;
				if (walker(rcexpr->rargs, context))
					return true;
			}
			break;
3143 3144
		case T_CoalesceExpr:
			return walker(((CoalesceExpr *) node)->args, context);
3145 3146
		case T_MinMaxExpr:
			return walker(((MinMaxExpr *) node)->args, context);
3147 3148
		case T_NullIfExpr:
			return walker(((NullIfExpr *) node)->args, context);
3149 3150 3151 3152
		case T_NullTest:
			return walker(((NullTest *) node)->arg, context);
		case T_BooleanTest:
			return walker(((BooleanTest *) node)->arg, context);
3153 3154
		case T_CoerceToDomain:
			return walker(((CoerceToDomain *) node)->arg, context);
3155 3156
		case T_TargetEntry:
			return walker(((TargetEntry *) node)->expr, context);
3157 3158 3159
		case T_Query:
			/* Do nothing with a sub-Query, per discussion above */
			break;
3160 3161 3162 3163 3164 3165 3166
		case T_List:
			foreach(temp, (List *) node)
			{
				if (walker((Node *) lfirst(temp), context))
					return true;
			}
			break;
3167 3168
		case T_FromExpr:
			{
3169
				FromExpr   *from = (FromExpr *) node;
3170 3171 3172 3173 3174 3175 3176

				if (walker(from->fromlist, context))
					return true;
				if (walker(from->quals, context))
					return true;
			}
			break;
3177 3178
		case T_JoinExpr:
			{
3179
				JoinExpr   *join = (JoinExpr *) node;
3180 3181 3182 3183 3184 3185 3186

				if (walker(join->larg, context))
					return true;
				if (walker(join->rarg, context))
					return true;
				if (walker(join->quals, context))
					return true;
Bruce Momjian's avatar
Bruce Momjian committed
3187

3188
				/*
3189
				 * alias clause, using list are deemed uninteresting.
3190 3191 3192
				 */
			}
			break;
3193 3194 3195 3196 3197 3198 3199 3200 3201 3202
		case T_SetOperationStmt:
			{
				SetOperationStmt *setop = (SetOperationStmt *) node;

				if (walker(setop->larg, context))
					return true;
				if (walker(setop->rarg, context))
					return true;
			}
			break;
3203 3204 3205 3206 3207 3208 3209 3210 3211
		case T_InClauseInfo:
			{
				InClauseInfo *ininfo = (InClauseInfo *) node;

				if (expression_tree_walker((Node *) ininfo->sub_targetlist,
										   walker, context))
					return true;
			}
			break;
3212 3213 3214 3215 3216 3217 3218 3219 3220
		case T_AppendRelInfo:
			{
				AppendRelInfo *appinfo = (AppendRelInfo *) node;

				if (expression_tree_walker((Node *) appinfo->translated_vars,
										   walker, context))
					return true;
			}
			break;
3221
		default:
3222 3223
			elog(ERROR, "unrecognized node type: %d",
				 (int) nodeTag(node));
3224 3225 3226 3227
			break;
	}
	return false;
}
3228

3229 3230 3231 3232 3233 3234 3235 3236
/*
 * 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.
3237
 *
3238 3239 3240 3241 3242
 * Some callers want to suppress visitation of certain items in the sub-Query,
 * typically because they need to process them specially, or don't actually
 * want to recurse into subqueries.  This is supported by the flags argument,
 * which is the bitwise OR of flag values to suppress visitation of
 * indicated items.  (More flag bits may be added as needed.)
3243 3244 3245 3246
 */
bool
query_tree_walker(Query *query,
				  bool (*walker) (),
3247
				  void *context,
3248
				  int flags)
3249 3250 3251 3252 3253
{
	Assert(query != NULL && IsA(query, Query));

	if (walker((Node *) query->targetList, context))
		return true;
3254
	if (walker((Node *) query->jointree, context))
3255
		return true;
3256 3257
	if (walker(query->setOperations, context))
		return true;
3258 3259
	if (walker(query->havingQual, context))
		return true;
3260 3261 3262 3263
	if (walker(query->limitOffset, context))
		return true;
	if (walker(query->limitCount, context))
		return true;
3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282
	if (range_table_walker(query->rtable, walker, context, flags))
		return true;
	return false;
}

/*
 * range_table_walker is just the part of query_tree_walker that scans
 * a query's rangetable.  This is split out since it can be useful on
 * its own.
 */
bool
range_table_walker(List *rtable,
				   bool (*walker) (),
				   void *context,
				   int flags)
{
	ListCell   *rt;

	foreach(rt, rtable)
3283
	{
3284
		RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
3285

3286
		switch (rte->rtekind)
3287
		{
3288 3289 3290 3291 3292
			case RTE_RELATION:
			case RTE_SPECIAL:
				/* nothing to do */
				break;
			case RTE_SUBQUERY:
Bruce Momjian's avatar
Bruce Momjian committed
3293
				if (!(flags & QTW_IGNORE_RT_SUBQUERIES))
3294 3295 3296 3297
					if (walker(rte->subquery, context))
						return true;
				break;
			case RTE_JOIN:
Bruce Momjian's avatar
Bruce Momjian committed
3298
				if (!(flags & QTW_IGNORE_JOINALIASES))
3299 3300
					if (walker(rte->joinaliasvars, context))
						return true;
3301
				break;
3302 3303 3304 3305
			case RTE_FUNCTION:
				if (walker(rte->funcexpr, context))
					return true;
				break;
3306 3307
		}
	}
3308 3309 3310 3311
	return false;
}


3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323
/*--------------------
 * 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
3324
 *		// check for nodes that special work is required for, eg:
3325 3326 3327 3328 3329 3330 3331 3332
 *		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
3333
 *		// for any node type not specially processed, do:
3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355
 *		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.
 *
3356
 * expression_tree_mutator will handle SubLink nodes by recursing normally
3357
 * into the "testexpr" subtree (which is an expression belonging to the outer
3358 3359 3360 3361 3362 3363 3364 3365
 * plan).  It will also call the mutator on the sub-Query node; however, when
 * expression_tree_mutator itself is called on a Query node, it does nothing
 * and returns the unmodified Query node.  The net effect is that unless the
 * mutator does something special at a Query node, sub-selects will not be
 * visited or modified; the original sub-select will be linked to by the new
 * SubLink node.  Mutators that want to descend into sub-selects will usually
 * do so by recognizing Query nodes and calling query_tree_mutator (below).
 *
3366 3367
 * expression_tree_mutator will handle a SubPlan node by recursing into the
 * "testexpr" and the "args" list (which belong to the outer plan), but it
3368 3369
 * 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
3370
 * can force appropriate behavior by recognizing SubPlan expression nodes
3371
 * and doing the right thing.
3372 3373 3374 3375
 *--------------------
 */

Node *
3376 3377 3378
expression_tree_mutator(Node *node,
						Node *(*mutator) (),
						void *context)
3379 3380
{
	/*
3381 3382
	 * The mutator has already decided not to modify the current node, but we
	 * must call the mutator for any sub-nodes.
3383 3384 3385 3386 3387 3388
	 */

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

3389
#define CHECKFLATCOPY(newnode, node, nodetype)	\
3390 3391 3392 3393 3394 3395 3396 3397 3398
	( 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;
3399 3400 3401 3402

	/* Guard against stack overflow due to overly complex expressions */
	check_stack_depth();

3403 3404 3405
	switch (nodeTag(node))
	{
		case T_Var:
3406
		case T_Const:
3407
		case T_Param:
3408
		case T_CoerceToDomainValue:
3409
		case T_CaseTestExpr:
3410
		case T_SetToDefault:
3411
		case T_RangeTblRef:
3412 3413
		case T_OuterJoinInfo:
			/* primitive node types with no expression subnodes */
3414
			return (Node *) copyObject(node);
3415 3416
		case T_Aggref:
			{
3417 3418
				Aggref	   *aggref = (Aggref *) node;
				Aggref	   *newnode;
3419 3420

				FLATCOPY(newnode, aggref, Aggref);
3421
				MUTATE(newnode->target, aggref->target, Expr *);
3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435
				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,
3436
					   Expr *);
3437
				MUTATE(newnode->refassgnexpr, arrayref->refassgnexpr,
3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463
					   Expr *);
				return (Node *) newnode;
			}
			break;
		case T_FuncExpr:
			{
				FuncExpr   *expr = (FuncExpr *) node;
				FuncExpr   *newnode;

				FLATCOPY(newnode, expr, FuncExpr);
				MUTATE(newnode->args, expr->args, List *);
				return (Node *) newnode;
			}
			break;
		case T_OpExpr:
			{
				OpExpr	   *expr = (OpExpr *) node;
				OpExpr	   *newnode;

				FLATCOPY(newnode, expr, OpExpr);
				MUTATE(newnode->args, expr->args, List *);
				return (Node *) newnode;
			}
			break;
		case T_DistinctExpr:
			{
Bruce Momjian's avatar
Bruce Momjian committed
3464 3465
				DistinctExpr *expr = (DistinctExpr *) node;
				DistinctExpr *newnode;
3466 3467 3468 3469 3470 3471

				FLATCOPY(newnode, expr, DistinctExpr);
				MUTATE(newnode->args, expr->args, List *);
				return (Node *) newnode;
			}
			break;
3472 3473
		case T_ScalarArrayOpExpr:
			{
Bruce Momjian's avatar
Bruce Momjian committed
3474 3475
				ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
				ScalarArrayOpExpr *newnode;
3476 3477 3478 3479 3480 3481

				FLATCOPY(newnode, expr, ScalarArrayOpExpr);
				MUTATE(newnode->args, expr->args, List *);
				return (Node *) newnode;
			}
			break;
3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497
		case T_BoolExpr:
			{
				BoolExpr   *expr = (BoolExpr *) node;
				BoolExpr   *newnode;

				FLATCOPY(newnode, expr, BoolExpr);
				MUTATE(newnode->args, expr->args, List *);
				return (Node *) newnode;
			}
			break;
		case T_SubLink:
			{
				SubLink    *sublink = (SubLink *) node;
				SubLink    *newnode;

				FLATCOPY(newnode, sublink, SubLink);
3498
				MUTATE(newnode->testexpr, sublink->testexpr, Node *);
Bruce Momjian's avatar
Bruce Momjian committed
3499

3500
				/*
3501 3502
				 * Also invoke the mutator on the sublink's Query node, so it
				 * can recurse into the sub-query if it wants to.
3503 3504
				 */
				MUTATE(newnode->subselect, sublink->subselect, Node *);
3505 3506 3507
				return (Node *) newnode;
			}
			break;
3508
		case T_SubPlan:
3509
			{
Bruce Momjian's avatar
Bruce Momjian committed
3510 3511
				SubPlan    *subplan = (SubPlan *) node;
				SubPlan    *newnode;
3512

3513
				FLATCOPY(newnode, subplan, SubPlan);
3514 3515
				/* transform testexpr */
				MUTATE(newnode->testexpr, subplan->testexpr, Node *);
3516
				/* transform args list (params to be passed to subplan) */
3517 3518
				MUTATE(newnode->args, subplan->args, List *);
				/* but not the sub-Plan itself, which is referenced as-is */
3519 3520 3521
				return (Node *) newnode;
			}
			break;
3522 3523 3524 3525 3526 3527
		case T_FieldSelect:
			{
				FieldSelect *fselect = (FieldSelect *) node;
				FieldSelect *newnode;

				FLATCOPY(newnode, fselect, FieldSelect);
3528
				MUTATE(newnode->arg, fselect->arg, Expr *);
3529 3530 3531
				return (Node *) newnode;
			}
			break;
3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543
		case T_FieldStore:
			{
				FieldStore *fstore = (FieldStore *) node;
				FieldStore *newnode;

				FLATCOPY(newnode, fstore, FieldStore);
				MUTATE(newnode->arg, fstore->arg, Expr *);
				MUTATE(newnode->newvals, fstore->newvals, List *);
				newnode->fieldnums = list_copy(fstore->fieldnums);
				return (Node *) newnode;
			}
			break;
3544 3545 3546 3547 3548 3549
		case T_RelabelType:
			{
				RelabelType *relabel = (RelabelType *) node;
				RelabelType *newnode;

				FLATCOPY(newnode, relabel, RelabelType);
3550
				MUTATE(newnode->arg, relabel->arg, Expr *);
3551 3552 3553
				return (Node *) newnode;
			}
			break;
3554 3555 3556 3557 3558 3559 3560 3561 3562 3563
		case T_ConvertRowtypeExpr:
			{
				ConvertRowtypeExpr *convexpr = (ConvertRowtypeExpr *) node;
				ConvertRowtypeExpr *newnode;

				FLATCOPY(newnode, convexpr, ConvertRowtypeExpr);
				MUTATE(newnode->arg, convexpr->arg, Expr *);
				return (Node *) newnode;
			}
			break;
3564 3565 3566 3567 3568 3569
		case T_CaseExpr:
			{
				CaseExpr   *caseexpr = (CaseExpr *) node;
				CaseExpr   *newnode;

				FLATCOPY(newnode, caseexpr, CaseExpr);
3570
				MUTATE(newnode->arg, caseexpr->arg, Expr *);
3571
				MUTATE(newnode->args, caseexpr->args, List *);
3572
				MUTATE(newnode->defresult, caseexpr->defresult, Expr *);
3573 3574 3575 3576 3577 3578 3579 3580 3581
				return (Node *) newnode;
			}
			break;
		case T_CaseWhen:
			{
				CaseWhen   *casewhen = (CaseWhen *) node;
				CaseWhen   *newnode;

				FLATCOPY(newnode, casewhen, CaseWhen);
3582 3583
				MUTATE(newnode->expr, casewhen->expr, Expr *);
				MUTATE(newnode->result, casewhen->result, Expr *);
3584 3585 3586
				return (Node *) newnode;
			}
			break;
3587 3588
		case T_ArrayExpr:
			{
Bruce Momjian's avatar
Bruce Momjian committed
3589 3590
				ArrayExpr  *arrayexpr = (ArrayExpr *) node;
				ArrayExpr  *newnode;
3591 3592 3593 3594 3595 3596

				FLATCOPY(newnode, arrayexpr, ArrayExpr);
				MUTATE(newnode->elements, arrayexpr->elements, List *);
				return (Node *) newnode;
			}
			break;
3597 3598
		case T_RowExpr:
			{
Bruce Momjian's avatar
Bruce Momjian committed
3599 3600
				RowExpr    *rowexpr = (RowExpr *) node;
				RowExpr    *newnode;
3601 3602 3603 3604 3605 3606

				FLATCOPY(newnode, rowexpr, RowExpr);
				MUTATE(newnode->args, rowexpr->args, List *);
				return (Node *) newnode;
			}
			break;
3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617
		case T_RowCompareExpr:
			{
				RowCompareExpr    *rcexpr = (RowCompareExpr *) node;
				RowCompareExpr    *newnode;

				FLATCOPY(newnode, rcexpr, RowCompareExpr);
				MUTATE(newnode->largs, rcexpr->largs, List *);
				MUTATE(newnode->rargs, rcexpr->rargs, List *);
				return (Node *) newnode;
			}
			break;
3618 3619 3620 3621 3622 3623 3624 3625 3626 3627
		case T_CoalesceExpr:
			{
				CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
				CoalesceExpr *newnode;

				FLATCOPY(newnode, coalesceexpr, CoalesceExpr);
				MUTATE(newnode->args, coalesceexpr->args, List *);
				return (Node *) newnode;
			}
			break;
3628 3629 3630 3631 3632 3633 3634 3635 3636 3637
		case T_MinMaxExpr:
			{
				MinMaxExpr *minmaxexpr = (MinMaxExpr *) node;
				MinMaxExpr *newnode;

				FLATCOPY(newnode, minmaxexpr, MinMaxExpr);
				MUTATE(newnode->args, minmaxexpr->args, List *);
				return (Node *) newnode;
			}
			break;
3638 3639
		case T_NullIfExpr:
			{
Bruce Momjian's avatar
Bruce Momjian committed
3640 3641
				NullIfExpr *expr = (NullIfExpr *) node;
				NullIfExpr *newnode;
3642 3643 3644 3645 3646 3647

				FLATCOPY(newnode, expr, NullIfExpr);
				MUTATE(newnode->args, expr->args, List *);
				return (Node *) newnode;
			}
			break;
3648 3649
		case T_NullTest:
			{
3650 3651
				NullTest   *ntest = (NullTest *) node;
				NullTest   *newnode;
3652 3653

				FLATCOPY(newnode, ntest, NullTest);
3654
				MUTATE(newnode->arg, ntest->arg, Expr *);
3655 3656 3657 3658 3659 3660 3661 3662 3663
				return (Node *) newnode;
			}
			break;
		case T_BooleanTest:
			{
				BooleanTest *btest = (BooleanTest *) node;
				BooleanTest *newnode;

				FLATCOPY(newnode, btest, BooleanTest);
3664
				MUTATE(newnode->arg, btest->arg, Expr *);
3665 3666 3667
				return (Node *) newnode;
			}
			break;
3668
		case T_CoerceToDomain:
3669
			{
3670 3671
				CoerceToDomain *ctest = (CoerceToDomain *) node;
				CoerceToDomain *newnode;
3672

3673
				FLATCOPY(newnode, ctest, CoerceToDomain);
3674
				MUTATE(newnode->arg, ctest->arg, Expr *);
3675 3676 3677
				return (Node *) newnode;
			}
			break;
3678
		case T_TargetEntry:
3679
			{
3680 3681
				TargetEntry *targetentry = (TargetEntry *) node;
				TargetEntry *newnode;
3682

3683 3684
				FLATCOPY(newnode, targetentry, TargetEntry);
				MUTATE(newnode->expr, targetentry->expr, Expr *);
3685 3686 3687
				return (Node *) newnode;
			}
			break;
3688 3689 3690
		case T_Query:
			/* Do nothing with a sub-Query, per discussion above */
			return node;
3691 3692
		case T_List:
			{
3693
				/*
3694 3695 3696
				 * 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!
3697
				 */
3698
				List	   *resultlist;
3699
				ListCell   *temp;
3700

3701
				resultlist = NIL;
3702 3703
				foreach(temp, (List *) node)
				{
3704 3705 3706
					resultlist = lappend(resultlist,
										 mutator((Node *) lfirst(temp),
												 context));
3707
				}
3708
				return (Node *) resultlist;
3709 3710
			}
			break;
3711 3712
		case T_FromExpr:
			{
3713 3714
				FromExpr   *from = (FromExpr *) node;
				FromExpr   *newnode;
3715 3716 3717 3718 3719 3720 3721

				FLATCOPY(newnode, from, FromExpr);
				MUTATE(newnode->fromlist, from->fromlist, List *);
				MUTATE(newnode->quals, from->quals, Node *);
				return (Node *) newnode;
			}
			break;
3722 3723
		case T_JoinExpr:
			{
3724 3725
				JoinExpr   *join = (JoinExpr *) node;
				JoinExpr   *newnode;
3726 3727 3728 3729 3730

				FLATCOPY(newnode, join, JoinExpr);
				MUTATE(newnode->larg, join->larg, Node *);
				MUTATE(newnode->rarg, join->rarg, Node *);
				MUTATE(newnode->quals, join->quals, Node *);
3731
				/* We do not mutate alias or using by default */
3732 3733 3734
				return (Node *) newnode;
			}
			break;
3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745
		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;
3746 3747 3748 3749 3750 3751 3752 3753 3754 3755
		case T_InClauseInfo:
			{
				InClauseInfo *ininfo = (InClauseInfo *) node;
				InClauseInfo *newnode;

				FLATCOPY(newnode, ininfo, InClauseInfo);
				MUTATE(newnode->sub_targetlist, ininfo->sub_targetlist, List *);
				return (Node *) newnode;
			}
			break;
3756 3757 3758 3759 3760 3761 3762 3763 3764 3765
		case T_AppendRelInfo:
			{
				AppendRelInfo *appinfo = (AppendRelInfo *) node;
				AppendRelInfo *newnode;

				FLATCOPY(newnode, appinfo, AppendRelInfo);
				MUTATE(newnode->translated_vars, appinfo->translated_vars, List *);
				return (Node *) newnode;
			}
			break;
3766
		default:
3767 3768
			elog(ERROR, "unrecognized node type: %d",
				 (int) nodeTag(node));
3769 3770 3771 3772 3773
			break;
	}
	/* can't get here, but keep compiler happy */
	return NULL;
}
3774 3775 3776 3777 3778 3779 3780 3781


/*
 * 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
3782
 * mutator intends to descend into subqueries.	It is also useful for
3783 3784
 * descending into subqueries within a mutator.
 *
3785
 * Some callers want to suppress mutating of certain items in the Query,
3786 3787 3788 3789
 * typically because they need to process them specially, or don't actually
 * want to recurse into subqueries.  This is supported by the flags argument,
 * which is the bitwise OR of flag values to suppress mutating of
 * indicated items.  (More flag bits may be added as needed.)
3790 3791
 *
 * Normally the Query node itself is copied, but some callers want it to be
Bruce Momjian's avatar
Bruce Momjian committed
3792
 * modified in-place; they must pass QTW_DONT_COPY_QUERY in flags.	All
3793
 * modified substructure is safely copied in any case.
3794
 */
3795
Query *
3796 3797 3798
query_tree_mutator(Query *query,
				   Node *(*mutator) (),
				   void *context,
3799
				   int flags)
3800 3801 3802
{
	Assert(query != NULL && IsA(query, Query));

Bruce Momjian's avatar
Bruce Momjian committed
3803
	if (!(flags & QTW_DONT_COPY_QUERY))
3804
	{
Bruce Momjian's avatar
Bruce Momjian committed
3805
		Query	   *newquery;
3806 3807 3808 3809 3810

		FLATCOPY(newquery, query, Query);
		query = newquery;
	}

3811 3812 3813 3814
	MUTATE(query->targetList, query->targetList, List *);
	MUTATE(query->jointree, query->jointree, FromExpr *);
	MUTATE(query->setOperations, query->setOperations, Node *);
	MUTATE(query->havingQual, query->havingQual, Node *);
3815 3816
	MUTATE(query->limitOffset, query->limitOffset, Node *);
	MUTATE(query->limitCount, query->limitCount, Node *);
3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836
	query->rtable = range_table_mutator(query->rtable,
										mutator, context, flags);
	return query;
}

/*
 * range_table_mutator is just the part of query_tree_mutator that processes
 * a query's rangetable.  This is split out since it can be useful on
 * its own.
 */
List *
range_table_mutator(List *rtable,
					Node *(*mutator) (),
					void *context,
					int flags)
{
	List	   *newrt = NIL;
	ListCell   *rt;

	foreach(rt, rtable)
3837
	{
3838 3839
		RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
		RangeTblEntry *newrte;
3840

3841
		FLATCOPY(newrte, rte, RangeTblEntry);
3842
		switch (rte->rtekind)
3843
		{
3844 3845
			case RTE_RELATION:
			case RTE_SPECIAL:
3846
				/* we don't bother to copy eref, aliases, etc; OK? */
3847 3848
				break;
			case RTE_SUBQUERY:
Bruce Momjian's avatar
Bruce Momjian committed
3849
				if (!(flags & QTW_IGNORE_RT_SUBQUERIES))
3850 3851 3852 3853
				{
					CHECKFLATCOPY(newrte->subquery, rte->subquery, Query);
					MUTATE(newrte->subquery, newrte->subquery, Query *);
				}
3854 3855 3856 3857 3858
				else
				{
					/* else, copy RT subqueries as-is */
					newrte->subquery = copyObject(rte->subquery);
				}
3859 3860
				break;
			case RTE_JOIN:
Bruce Momjian's avatar
Bruce Momjian committed
3861
				if (!(flags & QTW_IGNORE_JOINALIASES))
3862
					MUTATE(newrte->joinaliasvars, rte->joinaliasvars, List *);
3863 3864 3865 3866 3867
				else
				{
					/* else, copy join aliases as-is */
					newrte->joinaliasvars = copyObject(rte->joinaliasvars);
				}
3868
				break;
3869 3870 3871
			case RTE_FUNCTION:
				MUTATE(newrte->funcexpr, rte->funcexpr, Node *);
				break;
3872
		}
3873
		newrt = lappend(newrt, newrte);
3874
	}
3875
	return newrt;
3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921
}

/*
 * query_or_expression_tree_walker --- hybrid form
 *
 * This routine will invoke query_tree_walker if called on a Query node,
 * else will invoke the walker directly.  This is a useful way of starting
 * the recursion when the walker's normal change of state is not appropriate
 * for the outermost Query node.
 */
bool
query_or_expression_tree_walker(Node *node,
								bool (*walker) (),
								void *context,
								int flags)
{
	if (node && IsA(node, Query))
		return query_tree_walker((Query *) node,
								 walker,
								 context,
								 flags);
	else
		return walker(node, context);
}

/*
 * query_or_expression_tree_mutator --- hybrid form
 *
 * This routine will invoke query_tree_mutator if called on a Query node,
 * else will invoke the mutator directly.  This is a useful way of starting
 * the recursion when the mutator's normal change of state is not appropriate
 * for the outermost Query node.
 */
Node *
query_or_expression_tree_mutator(Node *node,
								 Node *(*mutator) (),
								 void *context,
								 int flags)
{
	if (node && IsA(node, Query))
		return (Node *) query_tree_mutator((Query *) node,
										   mutator,
										   context,
										   flags);
	else
		return mutator(node, context);
3922
}