clauses.c 125 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * clauses.c
4
 *	  routines to manipulate qualification clauses
5
 *
6
 * Portions Copyright (c) 1996-2007, 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.246 2007/06/11 01:16:23 tgl Exp $
12 13
 *
 * HISTORY
14 15
 *	  AUTHOR			DATE			MAJOR EVENT
 *	  Andrew Yu			Nov 3, 1994		clause.c and clauses.c combined
16 17 18 19 20 21
 *
 *-------------------------------------------------------------------------
 */

#include "postgres.h"

22
#include "catalog/pg_aggregate.h"
23
#include "catalog/pg_language.h"
24
#include "catalog/pg_operator.h"
25 26 27
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "executor/executor.h"
28
#include "executor/functions.h"
29
#include "miscadmin.h"
30 31
#include "nodes/makefuncs.h"
#include "optimizer/clauses.h"
32
#include "optimizer/cost.h"
33
#include "optimizer/planmain.h"
34
#include "optimizer/planner.h"
35
#include "optimizer/var.h"
36
#include "parser/analyze.h"
37
#include "parser/parse_clause.h"
38
#include "parser/parse_coerce.h"
39
#include "parser/parse_expr.h"
40 41 42
#include "tcop/tcopprot.h"
#include "utils/acl.h"
#include "utils/builtins.h"
43
#include "utils/datum.h"
Bruce Momjian's avatar
Bruce Momjian committed
44
#include "utils/lsyscache.h"
45
#include "utils/memutils.h"
46
#include "utils/syscache.h"
47
#include "utils/typcache.h"
48

49

50 51
typedef struct
{
52
	ParamListInfo boundParams;
53
	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 expression_returns_set_rows_walker(Node *node, double *count);
69
static bool contain_subplans_walker(Node *node, void *context);
70 71
static bool contain_mutable_functions_walker(Node *node, void *context);
static bool contain_volatile_functions_walker(Node *node, void *context);
72
static bool contain_nonstrict_functions_walker(Node *node, void *context);
73
static Relids find_nonnullable_rels_walker(Node *node, bool top_level);
74
static bool is_strict_saop(ScalarArrayOpExpr *expr, bool falseOK);
75
static bool set_coercionform_dontcare_walker(Node *node, void *context);
76
static Node *eval_const_expressions_mutator(Node *node,
Bruce Momjian's avatar
Bruce Momjian committed
77
							   eval_const_expressions_context *context);
78
static List *simplify_or_arguments(List *args,
79
					  eval_const_expressions_context *context,
Bruce Momjian's avatar
Bruce Momjian committed
80
					  bool *haveNull, bool *forceTrue);
81
static List *simplify_and_arguments(List *args,
82
					   eval_const_expressions_context *context,
Bruce Momjian's avatar
Bruce Momjian committed
83
					   bool *haveNull, bool *forceFalse);
84
static Expr *simplify_boolean_equality(List *args);
85 86
static Expr *simplify_function(Oid funcid,
				  Oid result_type, int32 result_typmod, List *args,
Bruce Momjian's avatar
Bruce Momjian committed
87 88
				  bool allow_inline,
				  eval_const_expressions_context *context);
89 90
static Expr *evaluate_function(Oid funcid,
				  Oid result_type, int32 result_typmod, List *args,
91 92
				  HeapTuple func_tuple,
				  eval_const_expressions_context *context);
93
static Expr *inline_function(Oid funcid, Oid result_type, List *args,
Bruce Momjian's avatar
Bruce Momjian committed
94 95
				HeapTuple func_tuple,
				eval_const_expressions_context *context);
96
static Node *substitute_actual_parameters(Node *expr, int nargs, List *args,
Bruce Momjian's avatar
Bruce Momjian committed
97
							 int *usecounts);
98
static Node *substitute_actual_parameters_mutator(Node *node,
99
							  substitute_actual_parameters_context *context);
100
static void sql_inline_error_callback(void *arg);
101
static Expr *evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod);
102

103 104

/*****************************************************************************
105
 *		OPERATOR clause functions
106 107
 *****************************************************************************/

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

119 120 121 122
	expr->opno = opno;
	expr->opfuncid = InvalidOid;
	expr->opresulttype = opresulttype;
	expr->opretset = opretset;
123
	if (rightop)
124
		expr->args = list_make2(leftop, rightop);
125
	else
126
		expr->args = list_make1(leftop);
127
	return (Expr *) expr;
128 129
}

130
/*
131
 * get_leftop
132
 *
133
 * Returns the left operand of a clause of the form (op expr expr)
134
 *		or (op expr)
135
 */
136
Node *
137
get_leftop(Expr *clause)
138
{
Bruce Momjian's avatar
Bruce Momjian committed
139
	OpExpr	   *expr = (OpExpr *) clause;
140

141
	if (expr->args != NIL)
142
		return linitial(expr->args);
143 144
	else
		return NULL;
145 146
}

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

158 159
	if (list_length(expr->args) >= 2)
		return lsecond(expr->args);
160 161
	else
		return NULL;
162 163 164
}

/*****************************************************************************
165
 *		NOT clause functions
166 167
 *****************************************************************************/

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

181
/*
182
 * make_notclause
183
 *
184
 * Create a 'not' clause given the expression to be negated.
185
 */
186
Expr *
187
make_notclause(Expr *notclause)
188
{
189
	BoolExpr   *expr = makeNode(BoolExpr);
190

191
	expr->boolop = NOT_EXPR;
192
	expr->args = list_make1(notclause);
193
	return (Expr *) expr;
194 195
}

196
/*
197
 * get_notclausearg
198
 *
199
 * Retrieve the clause within a 'not' clause
200
 */
201 202
Expr *
get_notclausearg(Expr *notclause)
203
{
204
	return linitial(((BoolExpr *) notclause)->args);
205 206
}

207 208 209 210
/*****************************************************************************
 *		OR clause functions
 *****************************************************************************/

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

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

	expr->boolop = OR_EXPR;
	expr->args = orclauses;
	return (Expr *) expr;
237 238 239
}

/*****************************************************************************
240
 *		AND clause functions
241 242 243
 *****************************************************************************/


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

/*
258
 * make_andclause
259
 *
260
 * Creates an 'and' clause given a list of its subclauses.
261
 */
262
Expr *
263
make_andclause(List *andclauses)
264
{
265
	BoolExpr   *expr = makeNode(BoolExpr);
266

267
	expr->boolop = AND_EXPR;
268
	expr->args = andclauses;
269
	return (Expr *) expr;
270 271
}

272 273 274 275 276 277
/*
 * 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'.
278 279 280
 *
 * 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.
281 282 283 284 285 286 287 288
 */
Node *
make_and_qual(Node *qual1, Node *qual2)
{
	if (qual1 == NULL)
		return qual2;
	if (qual2 == NULL)
		return qual1;
289
	return (Node *) make_andclause(list_make2(qual1, qual2));
290 291
}

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

312 313 314
List *
make_ands_implicit(Expr *clause)
{
315
	/*
316 317 318 319
	 * 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.
320
	 */
321
	if (clause == NULL)
322
		return NIL;				/* NULL -> NIL list == TRUE */
323
	else if (and_clause((Node *) clause))
324
		return ((BoolExpr *) clause)->args;
325
	else if (IsA(clause, Const) &&
326
			 !((Const *) clause)->constisnull &&
327
			 DatumGetBool(((Const *) clause)->constvalue))
328
		return NIL;				/* constant TRUE input -> NIL list */
329
	else
330
		return list_make1(clause);
331 332
}

333

334
/*****************************************************************************
335
 *		Aggregate-function clause manipulation
336 337
 *****************************************************************************/

338 339 340 341 342
/*
 * contain_agg_clause
 *	  Recursively search for Aggref nodes within a clause.
 *
 *	  Returns true if any aggregate found.
343 344 345 346 347 348 349
 *
 * 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().)
350 351 352 353 354 355 356 357 358 359 360 361 362
 */
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))
363 364
	{
		Assert(((Aggref *) node)->agglevelsup == 0);
365
		return true;			/* abort the tree traversal and return true */
366 367
	}
	Assert(!IsA(node, SubLink));
368 369 370
	return expression_tree_walker(node, contain_agg_clause_walker, context);
}

371
/*
372
 * count_agg_clauses
373
 *	  Recursively count the Aggref nodes in an expression tree.
374 375
 *
 *	  Note: this also checks for nested aggregates, which are an error.
376
 *
377 378 379 380 381 382 383 384
 * 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.
 *
385 386 387
 * 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.
388
 */
389 390
void
count_agg_clauses(Node *clause, AggClauseCounts *counts)
391
{
392 393
	/* no setup needed */
	count_agg_clauses_walker(clause, counts);
394 395 396
}

static bool
397
count_agg_clauses_walker(Node *node, AggClauseCounts *counts)
398 399 400 401 402
{
	if (node == NULL)
		return false;
	if (IsA(node, Aggref))
	{
403
		Aggref	   *aggref = (Aggref *) node;
404 405
		Oid		   *inputTypes;
		int			numArguments;
406 407 408
		HeapTuple	aggTuple;
		Form_pg_aggregate aggform;
		Oid			aggtranstype;
409
		int			i;
Bruce Momjian's avatar
Bruce Momjian committed
410
		ListCell   *l;
411 412 413 414 415 416

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

417 418 419 420 421 422 423 424
		/* extract argument types */
		numArguments = list_length(aggref->args);
		inputTypes = (Oid *) palloc(sizeof(Oid) * numArguments);
		i = 0;
		foreach(l, aggref->args)
		{
			inputTypes[i++] = exprType((Node *) lfirst(l));
		}
425 426 427 428 429 430 431 432 433 434 435 436 437

		/* 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 */
438
		if (IsPolymorphicType(aggtranstype))
439
		{
440 441
			/* have to fetch the agg's declared input types... */
			Oid		   *declaredArgTypes;
442 443 444
			int			agg_nargs;

			(void) get_func_signature(aggref->aggfnoid,
445 446 447 448 449 450 451
									  &declaredArgTypes, &agg_nargs);
			Assert(agg_nargs == numArguments);
			aggtranstype = enforce_generic_type_consistency(inputTypes,
															declaredArgTypes,
															agg_nargs,
															aggtranstype);
			pfree(declaredArgTypes);
452 453 454 455
		}

		/*
		 * If the transition type is pass-by-value then it doesn't add
456 457 458
		 * 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.
459 460 461 462 463 464 465
		 */
		if (!get_typbyval(aggtranstype))
		{
			int32		aggtranstypmod;
			int32		avgwidth;

			/*
466 467 468
			 * If transition state is of same type as first input, assume it's
			 * the same typmod (same width) as well.  This works for cases
			 * like MAX/MIN and is probably somewhat reasonable otherwise.
469
			 */
470 471
			if (numArguments > 0 && aggtranstype == inputTypes[0])
				aggtranstypmod = exprTypmod((Node *) linitial(aggref->args));
472 473 474 475 476 477 478 479
			else
				aggtranstypmod = -1;

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

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

481
		/*
482
		 * Complain if the aggregate's arguments contain any aggregates;
483
		 * nested agg functions are semantically nonsensical.
484
		 */
485
		if (contain_agg_clause((Node *) aggref->args))
486 487
			ereport(ERROR,
					(errcode(ERRCODE_GROUPING_ERROR),
488
					 errmsg("aggregate function calls cannot be nested")));
489

490 491 492 493
		/*
		 * Having checked that, we need not recurse into the argument.
		 */
		return false;
494
	}
495
	Assert(!IsA(node, SubLink));
496 497
	return expression_tree_walker(node, count_agg_clauses_walker,
								  (void *) counts);
498 499
}

500

501
/*****************************************************************************
502
 *		Support for expressions returning sets
503 504 505
 *****************************************************************************/

/*
506
 * expression_returns_set
507
 *	  Test whether an expression returns a set result.
508
 *
509 510 511
 * 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.
512 513
 */
bool
514
expression_returns_set(Node *clause)
515
{
516
	return expression_returns_set_walker(clause, NULL);
517 518 519
}

static bool
520
expression_returns_set_walker(Node *node, void *context)
521 522 523
{
	if (node == NULL)
		return false;
524
	if (IsA(node, FuncExpr))
525
	{
526
		FuncExpr   *expr = (FuncExpr *) node;
527

528 529 530 531 532 533
		if (expr->funcretset)
			return true;
		/* else fall through to check args */
	}
	if (IsA(node, OpExpr))
	{
Bruce Momjian's avatar
Bruce Momjian committed
534
		OpExpr	   *expr = (OpExpr *) node;
535 536 537 538 539 540 541

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

	/* Avoid recursion for some cases that can't return a set */
542 543
	if (IsA(node, Aggref))
		return false;
544 545
	if (IsA(node, DistinctExpr))
		return false;
546 547
	if (IsA(node, ScalarArrayOpExpr))
		return false;
548 549
	if (IsA(node, BoolExpr))
		return false;
550 551
	if (IsA(node, SubLink))
		return false;
552
	if (IsA(node, SubPlan))
553
		return false;
554 555
	if (IsA(node, ArrayExpr))
		return false;
556 557
	if (IsA(node, RowExpr))
		return false;
558 559
	if (IsA(node, RowCompareExpr))
		return false;
560 561
	if (IsA(node, CoalesceExpr))
		return false;
562 563
	if (IsA(node, MinMaxExpr))
		return false;
564 565
	if (IsA(node, XmlExpr))
		return false;
566 567
	if (IsA(node, NullIfExpr))
		return false;
568

569 570
	return expression_tree_walker(node, expression_returns_set_walker,
								  context);
571 572
}

573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
/*
 * expression_returns_set_rows
 *	  Estimate the number of rows in a set result.
 *
 * We use the product of the rowcount estimates of all the functions in
 * the given tree.  The result is 1 if there are no set-returning functions.
 */
double
expression_returns_set_rows(Node *clause)
{
	double		result = 1;

	(void) expression_returns_set_rows_walker(clause, &result);
	return result;
}

static bool
expression_returns_set_rows_walker(Node *node, double *count)
{
	if (node == NULL)
		return false;
	if (IsA(node, FuncExpr))
	{
		FuncExpr   *expr = (FuncExpr *) node;

		if (expr->funcretset)
			*count *= get_func_rows(expr->funcid);
	}
	if (IsA(node, OpExpr))
	{
		OpExpr	   *expr = (OpExpr *) node;

		if (expr->opretset)
		{
			set_opfuncid(expr);
			*count *= get_func_rows(expr->opfuncid);
		}
	}

	/* Avoid recursion for some cases that can't return a set */
	if (IsA(node, Aggref))
		return false;
	if (IsA(node, DistinctExpr))
		return false;
	if (IsA(node, ScalarArrayOpExpr))
		return false;
	if (IsA(node, BoolExpr))
		return false;
	if (IsA(node, SubLink))
		return false;
	if (IsA(node, SubPlan))
		return false;
	if (IsA(node, ArrayExpr))
		return false;
	if (IsA(node, RowExpr))
		return false;
	if (IsA(node, RowCompareExpr))
		return false;
	if (IsA(node, CoalesceExpr))
		return false;
	if (IsA(node, MinMaxExpr))
		return false;
	if (IsA(node, XmlExpr))
		return false;
	if (IsA(node, NullIfExpr))
		return false;

	return expression_tree_walker(node, expression_returns_set_rows_walker,
								  (void *) count);
}


645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
/*****************************************************************************
 *		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;
671
	if (IsA(node, SubPlan) ||
672
		IsA(node, SubLink))
673
		return true;			/* abort the tree traversal and return true */
674 675 676
	return expression_tree_walker(node, contain_subplans_walker, context);
}

677

678
/*****************************************************************************
679
 *		Check clauses for mutable functions
680 681
 *****************************************************************************/

682
/*
683 684
 * contain_mutable_functions
 *	  Recursively search for mutable functions within a clause.
685
 *
686 687
 * Returns true if any mutable function (or operator implemented by a
 * mutable function) is found.	This test is needed so that we don't
688 689 690
 * mistakenly think that something like "WHERE random() < 0.5" can be treated
 * as a constant qualification.
 *
691
 * XXX we do not examine sub-selects to see if they contain uses of
692
 * mutable functions.  It's not real clear if that is correct or not...
693 694
 */
bool
695
contain_mutable_functions(Node *clause)
696
{
697
	return contain_mutable_functions_walker(clause, NULL);
698 699 700
}

static bool
701
contain_mutable_functions_walker(Node *node, void *context)
702 703 704
{
	if (node == NULL)
		return false;
705
	if (IsA(node, FuncExpr))
706
	{
707
		FuncExpr   *expr = (FuncExpr *) node;
708

709 710 711 712
		if (func_volatile(expr->funcid) != PROVOLATILE_IMMUTABLE)
			return true;
		/* else fall through to check args */
	}
713
	else if (IsA(node, OpExpr))
714
	{
Bruce Momjian's avatar
Bruce Momjian committed
715
		OpExpr	   *expr = (OpExpr *) node;
716 717 718 719 720

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

		if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE)
			return true;
		/* else fall through to check args */
728
	}
729
	else if (IsA(node, ScalarArrayOpExpr))
730
	{
Bruce Momjian's avatar
Bruce Momjian committed
731
		ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
732 733 734 735 736

		if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE)
			return true;
		/* else fall through to check args */
	}
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
	else if (IsA(node, CoerceViaIO))
	{
		CoerceViaIO *expr = (CoerceViaIO *) node;
		Oid		iofunc;
		Oid		typioparam;
		bool	typisvarlena;

		/* check the result type's input function */
		getTypeInputInfo(expr->resulttype,
						 &iofunc, &typioparam);
		if (func_volatile(iofunc) != PROVOLATILE_IMMUTABLE)
			return true;
		/* check the input type's output function */
		getTypeOutputInfo(exprType((Node *) expr->arg),
						  &iofunc, &typisvarlena);
		if (func_volatile(iofunc) != PROVOLATILE_IMMUTABLE)
			return true;
		/* else fall through to check args */
	}
756 757 758 759 760 761 762 763 764 765
	else if (IsA(node, ArrayCoerceExpr))
	{
		ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;

		if (OidIsValid(expr->elemfuncid) &&
			func_volatile(expr->elemfuncid) != PROVOLATILE_IMMUTABLE)
			return true;
		/* else fall through to check args */
	}
	else if (IsA(node, NullIfExpr))
766
	{
Bruce Momjian's avatar
Bruce Momjian committed
767
		NullIfExpr *expr = (NullIfExpr *) node;
768 769 770 771 772

		if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE)
			return true;
		/* else fall through to check args */
	}
773
	else if (IsA(node, RowCompareExpr))
774
	{
775
		RowCompareExpr *rcexpr = (RowCompareExpr *) node;
776
		ListCell   *opid;
777

778
		foreach(opid, rcexpr->opnos)
779
		{
780
			if (op_volatile(lfirst_oid(opid)) != PROVOLATILE_IMMUTABLE)
781 782 783 784
				return true;
		}
		/* else fall through to check args */
	}
785 786 787 788 789 790 791 792 793 794 795 796 797 798
	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
799
 * volatile function) is found. This test prevents invalid conversions
800 801
 * of volatile expressions into indexscan quals.
 *
802
 * XXX we do not examine sub-selects to see if they contain uses of
Bruce Momjian's avatar
Bruce Momjian committed
803
 * volatile functions.	It's not real clear if that is correct or not...
804 805 806 807 808 809 810 811 812 813 814 815
 */
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;
816
	if (IsA(node, FuncExpr))
817
	{
818
		FuncExpr   *expr = (FuncExpr *) node;
819

820 821 822 823
		if (func_volatile(expr->funcid) == PROVOLATILE_VOLATILE)
			return true;
		/* else fall through to check args */
	}
824
	else if (IsA(node, OpExpr))
825
	{
Bruce Momjian's avatar
Bruce Momjian committed
826
		OpExpr	   *expr = (OpExpr *) node;
827 828 829 830 831

		if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE)
			return true;
		/* else fall through to check args */
	}
832
	else if (IsA(node, DistinctExpr))
833
	{
Bruce Momjian's avatar
Bruce Momjian committed
834
		DistinctExpr *expr = (DistinctExpr *) node;
835 836 837 838

		if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE)
			return true;
		/* else fall through to check args */
839
	}
840
	else if (IsA(node, ScalarArrayOpExpr))
841
	{
Bruce Momjian's avatar
Bruce Momjian committed
842
		ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
843 844 845 846 847

		if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE)
			return true;
		/* else fall through to check args */
	}
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
	else if (IsA(node, CoerceViaIO))
	{
		CoerceViaIO *expr = (CoerceViaIO *) node;
		Oid		iofunc;
		Oid		typioparam;
		bool	typisvarlena;

		/* check the result type's input function */
		getTypeInputInfo(expr->resulttype,
						 &iofunc, &typioparam);
		if (func_volatile(iofunc) == PROVOLATILE_VOLATILE)
			return true;
		/* check the input type's output function */
		getTypeOutputInfo(exprType((Node *) expr->arg),
						  &iofunc, &typisvarlena);
		if (func_volatile(iofunc) == PROVOLATILE_VOLATILE)
			return true;
		/* else fall through to check args */
	}
867 868 869 870 871 872 873 874 875 876
	else if (IsA(node, ArrayCoerceExpr))
	{
		ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;

		if (OidIsValid(expr->elemfuncid) &&
			func_volatile(expr->elemfuncid) == PROVOLATILE_VOLATILE)
			return true;
		/* else fall through to check args */
	}
	else if (IsA(node, NullIfExpr))
877
	{
Bruce Momjian's avatar
Bruce Momjian committed
878
		NullIfExpr *expr = (NullIfExpr *) node;
879 880 881 882 883

		if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE)
			return true;
		/* else fall through to check args */
	}
884
	else if (IsA(node, RowCompareExpr))
885
	{
886 887
		/* RowCompare probably can't have volatile ops, but check anyway */
		RowCompareExpr *rcexpr = (RowCompareExpr *) node;
888
		ListCell   *opid;
889

890
		foreach(opid, rcexpr->opnos)
891
		{
892
			if (op_volatile(lfirst_oid(opid)) == PROVOLATILE_VOLATILE)
893 894 895 896
				return true;
		}
		/* else fall through to check args */
	}
897
	return expression_tree_walker(node, contain_volatile_functions_walker,
898 899 900 901
								  context);
}


902 903 904 905 906 907 908 909 910 911 912
/*****************************************************************************
 *		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.
 *
913 914 915
 * 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
916
 * inputs is NULL.	If we return false, then the proof succeeded.
917 918 919 920 921 922 923 924 925 926 927 928
 */
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;
929 930 931 932 933
	if (IsA(node, Aggref))
	{
		/* an aggregate could return non-null with null input */
		return true;
	}
934 935
	if (IsA(node, ArrayRef))
	{
936
		/* array assignment is nonstrict, but subscripting is strict */
937 938 939 940
		if (((ArrayRef *) node)->refassgnexpr != NULL)
			return true;
		/* else fall through to check args */
	}
941 942 943 944 945 946 947 948 949 950
	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
951
		OpExpr	   *expr = (OpExpr *) node;
952 953 954 955 956 957 958 959 960 961

		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;
	}
962 963
	if (IsA(node, ScalarArrayOpExpr))
	{
964 965 966 967 968
		ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;

		if (!is_strict_saop(expr, false))
			return true;
		/* else fall through to check args */
969
	}
970
	if (IsA(node, BoolExpr))
971
	{
972
		BoolExpr   *expr = (BoolExpr *) node;
973

974
		switch (expr->boolop)
975 976
		{
			case AND_EXPR:
977 978
			case OR_EXPR:
				/* AND, OR are inherently non-strict */
979 980 981 982 983
				return true;
			default:
				break;
		}
	}
984 985 986 987 988 989 990
	if (IsA(node, SubLink))
	{
		/* In some cases a sublink might be strict, but in general not */
		return true;
	}
	if (IsA(node, SubPlan))
		return true;
991
	/* ArrayCoerceExpr is strict at the array level, regardless of elemfunc */
992 993
	if (IsA(node, FieldStore))
		return true;
994 995
	if (IsA(node, CaseExpr))
		return true;
996 997
	if (IsA(node, ArrayExpr))
		return true;
998 999
	if (IsA(node, RowExpr))
		return true;
1000 1001
	if (IsA(node, RowCompareExpr))
		return true;
1002 1003
	if (IsA(node, CoalesceExpr))
		return true;
1004 1005
	if (IsA(node, MinMaxExpr))
		return true;
1006 1007
	if (IsA(node, XmlExpr))
		return true;
1008 1009
	if (IsA(node, NullIfExpr))
		return true;
1010 1011 1012 1013 1014 1015 1016 1017 1018
	if (IsA(node, NullTest))
		return true;
	if (IsA(node, BooleanTest))
		return true;
	return expression_tree_walker(node, contain_nonstrict_functions_walker,
								  context);
}


1019 1020 1021 1022 1023 1024
/*
 * 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
Bruce Momjian's avatar
Bruce Momjian committed
1025
 * is an all-NULL row.	(It is OK to err on the side of conservatism; hence
1026 1027 1028 1029 1030 1031 1032 1033 1034
 * 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.
 *
1035 1036 1037 1038 1039 1040 1041
 * top_level is TRUE while scanning top-level AND/OR structure; here, showing
 * the result is either FALSE or NULL is good enough.  top_level is FALSE when
 * we have descended below a NOT or a strict function: now we must be able to
 * prove that the subexpression goes to NULL.
 *
 * 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.
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
 */
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;
1053
	ListCell   *l;
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065

	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))
	{
1066 1067 1068 1069 1070 1071 1072 1073 1074
		/*
		 * At top level, we are examining an implicit-AND list: if any of
		 * the arms produces FALSE-or-NULL then the result is FALSE-or-NULL.
		 * If not at top level, we are examining the arguments of a strict
		 * function: if any of them produce NULL then the result of the
		 * function must be NULL.  So in both cases, the set of nonnullable
		 * rels is the union of those found in the arms, and we pass down
		 * the top_level flag unmodified.
		 */
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
		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))
	{
		ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;

1100
		if (is_strict_saop(expr, true))
1101 1102 1103 1104 1105 1106
			result = find_nonnullable_rels_walker((Node *) expr->args, false);
	}
	else if (IsA(node, BoolExpr))
	{
		BoolExpr   *expr = (BoolExpr *) node;

1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
		switch (expr->boolop)
		{
			case AND_EXPR:
				/* At top level we can just recurse (to the List case) */
				if (top_level)
				{
					result = find_nonnullable_rels_walker((Node *) expr->args,
														  top_level);
					break;
				}
				/*
				 * Below top level, even if one arm produces NULL, the result
				 * could be FALSE (hence not NULL).  However, if *all* the
				 * arms produce NULL then the result is NULL, so we can
				 * take the intersection of the sets of nonnullable rels,
				 * just as for OR.  Fall through to share code.
				 */
				/* FALL THRU */
			case OR_EXPR:
				/*
				 * OR is strict if all of its arms are, so we can take the
				 * intersection of the sets of nonnullable rels for each arm.
				 * This works for both values of top_level.
				 */
				foreach(l, expr->args)
				{
					Relids		subresult;

					subresult = find_nonnullable_rels_walker(lfirst(l),
															 top_level);
					if (result == NULL)				/* first subresult? */
						result = subresult;
					else
						result = bms_int_members(result, subresult);
					/*
					 * If the intersection is empty, we can stop looking.
					 * This also justifies the test for first-subresult above.
					 */
					if (bms_is_empty(result))
						break;
				}
				break;
			case NOT_EXPR:
				/* NOT will return null if its arg is null */
				result = find_nonnullable_rels_walker((Node *) expr->args,
													  false);
				break;
			default:
				elog(ERROR, "unrecognized boolop: %d", (int) expr->boolop);
				break;
		}
1158 1159 1160 1161 1162 1163 1164
	}
	else if (IsA(node, RelabelType))
	{
		RelabelType *expr = (RelabelType *) node;

		result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
	}
1165 1166 1167 1168 1169 1170 1171
	else if (IsA(node, CoerceViaIO))
	{
		/* not clear this is useful, but it can't hurt */
		CoerceViaIO *expr = (CoerceViaIO *) node;

		result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
	}
1172 1173 1174 1175 1176 1177 1178
	else if (IsA(node, ArrayCoerceExpr))
	{
		/* ArrayCoerceExpr is strict at the array level */
		ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;

		result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
	}
1179 1180 1181 1182 1183 1184 1185 1186 1187
	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))
	{
1188
		/* IS NOT NULL can be considered strict, but only at top level */
1189 1190 1191 1192 1193 1194 1195
		NullTest   *expr = (NullTest *) node;

		if (top_level && expr->nulltesttype == IS_NOT_NULL)
			result = find_nonnullable_rels_walker((Node *) expr->arg, false);
	}
	else if (IsA(node, BooleanTest))
	{
1196
		/* Boolean tests that reject NULL are strict at top level */
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
		BooleanTest *expr = (BooleanTest *) node;

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

1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
/*
 * Can we treat a ScalarArrayOpExpr as strict?
 *
 * If "falseOK" is true, then a "false" result can be considered strict,
 * else we need to guarantee an actual NULL result for NULL input.
 *
 * "foo op ALL array" is strict if the op is strict *and* we can prove
 * that the array input isn't an empty array.  We can check that
 * for the cases of an array constant and an ARRAY[] construct.
 *
 * "foo op ANY array" is strict in the falseOK sense if the op is strict.
 * If not falseOK, the test is the same as for "foo op ALL array".
 */
static bool
is_strict_saop(ScalarArrayOpExpr *expr, bool falseOK)
{
Bruce Momjian's avatar
Bruce Momjian committed
1224
	Node	   *rightop;
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

	/* The contained operator must be strict. */
	if (!op_strict(expr->opno))
		return false;
	/* If ANY and falseOK, that's all we need to check. */
	if (expr->useOr && falseOK)
		return true;
	/* Else, we have to see if the array is provably non-empty. */
	Assert(list_length(expr->args) == 2);
	rightop = (Node *) lsecond(expr->args);
	if (rightop && IsA(rightop, Const))
	{
		Datum		arraydatum = ((Const *) rightop)->constvalue;
		bool		arrayisnull = ((Const *) rightop)->constisnull;
		ArrayType  *arrayval;
		int			nitems;

		if (arrayisnull)
			return false;
		arrayval = DatumGetArrayTypeP(arraydatum);
		nitems = ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
		if (nitems > 0)
			return true;
	}
	else if (rightop && IsA(rightop, ArrayExpr))
	{
		ArrayExpr  *arrayexpr = (ArrayExpr *) rightop;

		if (arrayexpr->elements != NIL && !arrayexpr->multidims)
			return true;
	}
	return false;
}

1259

1260 1261 1262
/*****************************************************************************
 *		Check for "pseudo-constant" clauses
 *****************************************************************************/
1263 1264

/*
1265
 * is_pseudo_constant_clause
1266 1267 1268
 *	  Detect whether an expression is "pseudo constant", ie, it contains no
 *	  variables of the current query level and no uses of volatile functions.
 *	  Such an expr is not necessarily a true constant: it can still contain
1269
 *	  Params and outer-level Vars, not to mention functions whose results
1270
 *	  may vary from one statement to the next.	However, the expr's value
1271
 *	  will be constant over any one scan of the current query, so it can be
1272
 *	  used as, eg, an indexscan key.
1273 1274 1275 1276 1277 1278
 *
 * CAUTION: this function omits to test for one very important class of
 * not-constant expressions, namely aggregates (Aggrefs).  In current usage
 * this is only applied to WHERE clauses and so a check for Aggrefs would be
 * a waste of cycles; but be sure to also check contain_agg_clause() if you
 * want to know about pseudo-constness in other contexts.
1279 1280 1281 1282 1283 1284
 */
bool
is_pseudo_constant_clause(Node *clause)
{
	/*
	 * We could implement this check in one recursive scan.  But since the
1285 1286 1287
	 * 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.
1288 1289
	 */
	if (!contain_var_clause(clause) &&
1290
		!contain_volatile_functions(clause))
1291 1292 1293 1294
		return true;
	return false;
}

1295 1296 1297
/*
 * is_pseudo_constant_clause_relids
 *	  Same as above, except caller already has available the var membership
1298
 *	  of the expression; this lets us avoid the contain_var_clause() scan.
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
 */
bool
is_pseudo_constant_clause_relids(Node *clause, Relids relids)
{
	if (bms_is_empty(relids) &&
		!contain_volatile_functions(clause))
		return true;
	return false;
}

1309

1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
/*****************************************************************************
 *		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
1320
 * not the same as the set of output columns.
1321 1322 1323 1324
 */
bool
has_distinct_on_clause(Query *query)
{
1325
	ListCell   *l;
1326 1327 1328 1329

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

1331
	/*
1332
	 * If the DISTINCT list contains all the nonjunk targetlist items, and
1333 1334 1335 1336 1337 1338
	 * 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.
1339 1340 1341
	 *
	 * This code assumes that the DISTINCT list is valid, ie, all its entries
	 * match some entry of the tlist.
1342
	 */
1343
	foreach(l, query->targetList)
1344
	{
1345
		TargetEntry *tle = (TargetEntry *) lfirst(l);
1346

1347
		if (tle->ressortgroupref == 0)
1348
		{
1349
			if (tle->resjunk)
1350
				continue;		/* we can ignore unsorted junk cols */
1351
			return true;		/* definitely not in DISTINCT list */
1352
		}
1353
		if (targetIsInSortList(tle, InvalidOid, query->distinctClause))
1354
		{
1355
			if (tle->resjunk)
1356 1357 1358 1359 1360 1361
				return true;	/* junk TLE in DISTINCT means DISTINCT ON */
			/* else this TLE is okay, keep looking */
		}
		else
		{
			/* This TLE is not in DISTINCT list */
1362
			if (!tle->resjunk)
1363
				return true;	/* non-junk, non-DISTINCT, so DISTINCT ON */
1364
			if (targetIsInSortList(tle, InvalidOid, query->sortClause))
1365 1366
				return true;	/* sorted, non-distinct junk */
			/* unsorted junk is okay, keep looking */
1367 1368 1369 1370 1371 1372
		}
	}
	/* It's a simple DISTINCT */
	return false;
}

1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387
/*
 * 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);
}

1388

1389 1390 1391 1392 1393 1394
/*****************************************************************************
 *																			 *
 *		General clause-manipulating routines								 *
 *																			 *
 *****************************************************************************/

1395
/*
1396 1397
 * NumRelids
 *		(formerly clause_relids)
1398
 *
1399 1400 1401
 * Returns the number of different relations referenced in 'clause'.
 */
int
1402
NumRelids(Node *clause)
1403
{
1404 1405
	Relids		varnos = pull_varnos(clause);
	int			result = bms_num_members(varnos);
1406

1407
	bms_free(varnos);
1408
	return result;
1409 1410
}

1411
/*
1412
 * CommuteOpExpr: commute a binary operator clause
1413 1414
 *
 * XXX the clause is destructively modified!
1415
 */
1416
void
1417
CommuteOpExpr(OpExpr *clause)
1418
{
1419
	Oid			opoid;
1420
	Node	   *temp;
1421

1422
	/* Sanity checks: caller is at fault if these fail */
1423
	if (!is_opclause(clause) ||
1424
		list_length(clause->args) != 2)
1425
		elog(ERROR, "cannot commute non-binary-operator clause");
1426

1427
	opoid = get_commutator(clause->opno);
1428

1429
	if (!OidIsValid(opoid))
1430
		elog(ERROR, "could not find commutator for operator %u",
1431
			 clause->opno);
1432

1433
	/*
1434
	 * modify the clause in-place!
1435
	 */
1436 1437 1438 1439
	clause->opno = opoid;
	clause->opfuncid = InvalidOid;
	/* opresulttype and opretset are assumed not to change */

1440 1441
	temp = linitial(clause->args);
	linitial(clause->args) = lsecond(clause->args);
1442
	lsecond(clause->args) = temp;
1443
}
1444

1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497
/*
 * 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;
Bruce Momjian's avatar
Bruce Momjian committed
1498

1499
	/*
1500 1501
	 * Note: we need not change the opfamilies list; we assume any btree
	 * opfamily containing an operator will also contain its commutator.
1502 1503 1504 1505 1506 1507 1508
	 */

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

1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533
/*
 * 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);
	}
1534 1535 1536 1537 1538 1539 1540
	else if (IsA(node, CoerceViaIO))
	{
		CoerceViaIO *c = (CoerceViaIO *) node;

		if (c->coerceformat == COERCE_IMPLICIT_CAST)
			return strip_implicit_coercions((Node *) c->arg);
	}
1541 1542 1543 1544 1545 1546 1547
	else if (IsA(node, ArrayCoerceExpr))
	{
		ArrayCoerceExpr *c = (ArrayCoerceExpr *) node;

		if (c->coerceformat == COERCE_IMPLICIT_CAST)
			return strip_implicit_coercions((Node *) c->arg);
	}
1548 1549 1550 1551 1552 1553 1554
	else if (IsA(node, ConvertRowtypeExpr))
	{
		ConvertRowtypeExpr *c = (ConvertRowtypeExpr *) node;

		if (c->convertformat == COERCE_IMPLICIT_CAST)
			return strip_implicit_coercions((Node *) c->arg);
	}
1555 1556 1557 1558 1559 1560 1561 1562 1563 1564
	else if (IsA(node, CoerceToDomain))
	{
		CoerceToDomain *c = (CoerceToDomain *) node;

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

1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589
/*
 * 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;
1590
	else if (IsA(node, RelabelType))
1591
		((RelabelType *) node)->relabelformat = COERCE_DONTCARE;
1592 1593
	else if (IsA(node, CoerceViaIO))
		((CoerceViaIO *) node)->coerceformat = COERCE_DONTCARE;
1594 1595
	else if (IsA(node, ArrayCoerceExpr))
		((ArrayCoerceExpr *) node)->coerceformat = COERCE_DONTCARE;
1596 1597 1598
	else if (IsA(node, ConvertRowtypeExpr))
		((ConvertRowtypeExpr *) node)->convertformat = COERCE_DONTCARE;
	else if (IsA(node, RowExpr))
1599
		((RowExpr *) node)->row_format = COERCE_DONTCARE;
1600
	else if (IsA(node, CoerceToDomain))
1601 1602 1603 1604 1605
		((CoerceToDomain *) node)->coercionformat = COERCE_DONTCARE;
	return expression_tree_walker(node, set_coercionform_dontcare_walker,
								  context);
}

1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623
/*
 * 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)
1624 1625
	{
		ReleaseTupleDesc(tupdesc);
1626
		return false;
1627
	}
1628 1629 1630 1631
	attr = tupdesc->attrs[fieldnum - 1];
	if (attr->attisdropped ||
		attr->atttypid != expectedtype ||
		attr->atttypmod != expectedtypmod)
1632 1633
	{
		ReleaseTupleDesc(tupdesc);
1634
		return false;
1635 1636
	}
	ReleaseTupleDesc(tupdesc);
1637 1638 1639
	return true;
}

1640

1641 1642 1643 1644 1645 1646 1647
/*--------------------
 * 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
1648
 * the subexpression x is.	(XXX We assume that no such subexpression
1649 1650 1651 1652 1653 1654
 * 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
1655
 * example.  Functions that are not marked "immutable" in pg_proc
1656
 * will not be pre-evaluated here, although we will reduce their
1657
 * arguments as far as possible.
1658 1659 1660
 *
 * We assume that the tree has already been type-checked and contains
 * only operators and functions that are reasonable to try to execute.
1661 1662 1663
 *
 * NOTE: the planner assumes that this will always flatten nested AND and
 * OR clauses into N-argument form.  See comments in prepqual.c.
1664 1665 1666 1667 1668
 *--------------------
 */
Node *
eval_const_expressions(Node *node)
{
1669 1670
	eval_const_expressions_context context;

1671
	context.boundParams = NULL;	/* don't use any bound params */
1672
	context.active_fns = NIL;	/* nothing being recursively simplified */
1673
	context.case_val = NULL;	/* no CASE being examined */
1674 1675 1676 1677
	context.estimate = false;	/* safe transformations only */
	return eval_const_expressions_mutator(node, &context);
}

1678
/*--------------------
1679 1680 1681 1682 1683 1684 1685
 * 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.
 *
1686 1687
 * Currently the extra steps that are taken in this mode are:
 * 1. Substitute values for Params, where a bound Param value has been made
1688 1689 1690
 *	  available by the caller of planner(), even if the Param isn't marked
 *	  constant.  This effectively means that we plan using the first supplied
 *	  value of the Param.
1691 1692
 * 2. Fold stable, as well as immutable, functions to constants.
 *--------------------
1693 1694
 */
Node *
1695
estimate_expression_value(PlannerInfo *root, Node *node)
1696 1697 1698
{
	eval_const_expressions_context context;

1699
	context.boundParams = root->glob->boundParams;	/* bound Params */
1700
	context.active_fns = NIL;	/* nothing being recursively simplified */
1701
	context.case_val = NULL;	/* no CASE being examined */
1702 1703
	context.estimate = true;	/* unsafe transformations OK */
	return eval_const_expressions_mutator(node, &context);
1704 1705 1706
}

static Node *
1707 1708
eval_const_expressions_mutator(Node *node,
							   eval_const_expressions_context *context)
1709 1710 1711
{
	if (node == NULL)
		return NULL;
1712 1713 1714 1715
	if (IsA(node, Param))
	{
		Param	   *param = (Param *) node;

1716 1717
		/* Look to see if we've been given a value for this Param */
		if (param->paramkind == PARAM_EXTERN &&
1718
			context->boundParams != NULL &&
1719
			param->paramid > 0 &&
1720
			param->paramid <= context->boundParams->numParams)
1721
		{
1722
			ParamExternData *prm = &context->boundParams->params[param->paramid - 1];
1723

1724 1725 1726 1727
			if (OidIsValid(prm->ptype))
			{
				/* OK to substitute parameter value? */
				if (context->estimate || (prm->pflags & PARAM_FLAG_CONST))
1728 1729
				{
					/*
1730 1731 1732 1733
					 * Return a Const representing the param value.  Must copy
					 * pass-by-ref datatypes, since the Param might be in a
					 * memory context shorter-lived than our output plan
					 * should be.
1734 1735 1736
					 */
					int16		typLen;
					bool		typByVal;
1737
					Datum		pval;
1738 1739 1740

					Assert(prm->ptype == param->paramtype);
					get_typlenbyval(param->paramtype, &typLen, &typByVal);
1741 1742 1743 1744
					if (prm->isnull || typByVal)
						pval = prm->value;
					else
						pval = datumCopy(prm->value, typByVal, typLen);
1745
					return (Node *) makeConst(param->paramtype,
1746
											  param->paramtypmod,
1747
											  (int) typLen,
1748
											  pval,
1749 1750 1751
											  prm->isnull,
											  typByVal);
				}
1752 1753 1754 1755 1756
			}
		}
		/* Not replaceable, so just copy the Param (no need to recurse) */
		return (Node *) copyObject(param);
	}
1757
	if (IsA(node, FuncExpr))
1758
	{
1759
		FuncExpr   *expr = (FuncExpr *) node;
1760
		List	   *args;
1761 1762 1763 1764 1765
		Expr	   *simple;
		FuncExpr   *newexpr;

		/*
		 * Reduce constants in the FuncExpr's arguments.  We know args is
1766 1767
		 * either NIL or a List node, so we can call expression_tree_mutator
		 * directly rather than recursing to self.
1768 1769
		 */
		args = (List *) expression_tree_mutator((Node *) expr->args,
1770
											  eval_const_expressions_mutator,
1771
												(void *) context);
Bruce Momjian's avatar
Bruce Momjian committed
1772

1773
		/*
1774
		 * Code for op/func reduction is pretty bulky, so split it out as a
1775 1776 1777
		 * separate function.  Note: exprTypmod normally returns -1 for a
		 * FuncExpr, but not when the node is recognizably a length coercion;
		 * we want to preserve the typmod in the eventual Const if so.
1778
		 */
1779 1780 1781
		simple = simplify_function(expr->funcid,
								   expr->funcresulttype, exprTypmod(node),
								   args,
1782
								   true, context);
1783 1784
		if (simple)				/* successfully simplified it */
			return (Node *) simple;
Bruce Momjian's avatar
Bruce Momjian committed
1785

1786 1787
		/*
		 * The expression cannot be simplified any further, so build and
1788 1789
		 * return a replacement FuncExpr node using the possibly-simplified
		 * arguments.
1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804
		 */
		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;
1805 1806

		/*
1807 1808 1809
		 * 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.
1810 1811
		 */
		args = (List *) expression_tree_mutator((Node *) expr->args,
1812
											  eval_const_expressions_mutator,
1813
												(void *) context);
Bruce Momjian's avatar
Bruce Momjian committed
1814

1815
		/*
1816 1817
		 * Need to get OID of underlying function.	Okay to scribble on input
		 * to this extent.
1818 1819
		 */
		set_opfuncid(expr);
Bruce Momjian's avatar
Bruce Momjian committed
1820

1821
		/*
1822 1823
		 * Code for op/func reduction is pretty bulky, so split it out as a
		 * separate function.
1824
		 */
1825 1826 1827
		simple = simplify_function(expr->opfuncid,
								   expr->opresulttype, -1,
								   args,
1828
								   true, context);
1829 1830
		if (simple)				/* successfully simplified it */
			return (Node *) simple;
Bruce Momjian's avatar
Bruce Momjian committed
1831

1832
		/*
1833 1834
		 * If the operator is boolean equality, we know how to simplify cases
		 * involving one constant and one non-constant argument.
1835 1836 1837 1838 1839 1840 1841 1842
		 */
		if (expr->opno == BooleanEqualOperator)
		{
			simple = simplify_boolean_equality(args);
			if (simple)			/* successfully simplified it */
				return (Node *) simple;
		}

1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859
		/*
		 * 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;
1860
		ListCell   *arg;
1861 1862 1863 1864 1865 1866 1867
		bool		has_null_input = false;
		bool		all_null_input = true;
		bool		has_nonconst_input = false;
		Expr	   *simple;
		DistinctExpr *newexpr;

		/*
1868 1869 1870
		 * 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.
1871 1872
		 */
		args = (List *) expression_tree_mutator((Node *) expr->args,
1873
											  eval_const_expressions_mutator,
1874
												(void *) context);
1875

1876
		/*
Bruce Momjian's avatar
Bruce Momjian committed
1877
		 * We must do our own check for NULLs because DistinctExpr has
1878
		 * different results for NULL input than the underlying operator does.
1879 1880
		 */
		foreach(arg, args)
1881
		{
1882 1883 1884 1885 1886 1887 1888 1889
			if (IsA(lfirst(arg), Const))
			{
				has_null_input |= ((Const *) lfirst(arg))->constisnull;
				all_null_input &= ((Const *) lfirst(arg))->constisnull;
			}
			else
				has_nonconst_input = true;
		}
1890

1891 1892 1893 1894 1895
		/* all constants? then can optimize this out */
		if (!has_nonconst_input)
		{
			/* all nulls? then not distinct */
			if (all_null_input)
1896
				return makeBoolConst(false, false);
1897

1898 1899
			/* one null? then distinct */
			if (has_null_input)
1900
				return makeBoolConst(true, false);
1901

1902 1903
			/* otherwise try to evaluate the '=' operator */
			/* (NOT okay to try to inline it, though!) */
1904

1905
			/*
1906 1907
			 * Need to get OID of underlying function.	Okay to scribble on
			 * input to this extent.
1908
			 */
1909
			set_opfuncid((OpExpr *) expr);		/* rely on struct equivalence */
Bruce Momjian's avatar
Bruce Momjian committed
1910

1911
			/*
1912 1913
			 * Code for op/func reduction is pretty bulky, so split it out as
			 * a separate function.
1914
			 */
1915 1916 1917 1918
			simple = simplify_function(expr->opfuncid,
									   expr->opresulttype, -1,
									   args,
									   false, context);
1919
			if (simple)			/* successfully simplified it */
1920 1921 1922 1923 1924
			{
				/*
				 * Since the underlying operator is "=", must negate its
				 * result
				 */
Bruce Momjian's avatar
Bruce Momjian committed
1925
				Const	   *csimple = (Const *) simple;
1926 1927 1928 1929 1930 1931

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

1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952
		/*
		 * 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)
		{
1953
			case OR_EXPR:
1954
				{
1955
					List	   *newargs;
1956 1957 1958
					bool		haveNull = false;
					bool		forceTrue = false;

1959
					newargs = simplify_or_arguments(expr->args, context,
1960
													&haveNull, &forceTrue);
1961
					if (forceTrue)
1962
						return makeBoolConst(true, false);
1963
					if (haveNull)
1964
						newargs = lappend(newargs, makeBoolConst(false, true));
1965
					/* If all the inputs are FALSE, result is FALSE */
1966
					if (newargs == NIL)
1967
						return makeBoolConst(false, false);
1968
					/* If only one nonconst-or-NULL input, it's the result */
1969
					if (list_length(newargs) == 1)
1970
						return (Node *) linitial(newargs);
1971
					/* Else we still need an OR node */
1972
					return (Node *) make_orclause(newargs);
1973 1974 1975
				}
			case AND_EXPR:
				{
1976
					List	   *newargs;
1977 1978 1979
					bool		haveNull = false;
					bool		forceFalse = false;

1980
					newargs = simplify_and_arguments(expr->args, context,
1981
													 &haveNull, &forceFalse);
1982
					if (forceFalse)
1983
						return makeBoolConst(false, false);
1984
					if (haveNull)
1985
						newargs = lappend(newargs, makeBoolConst(false, true));
1986
					/* If all the inputs are TRUE, result is TRUE */
1987
					if (newargs == NIL)
1988
						return makeBoolConst(true, false);
1989
					/* If only one nonconst-or-NULL input, it's the result */
1990
					if (list_length(newargs) == 1)
1991
						return (Node *) linitial(newargs);
1992
					/* Else we still need an AND node */
1993
					return (Node *) make_andclause(newargs);
1994 1995
				}
			case NOT_EXPR:
1996
				{
1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019
					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);
2020
				}
2021
			default:
2022
				elog(ERROR, "unrecognized boolop: %d",
2023
					 (int) expr->boolop);
2024 2025
				break;
		}
2026
	}
2027
	if (IsA(node, SubPlan))
2028
	{
2029
		/*
Bruce Momjian's avatar
Bruce Momjian committed
2030
		 * Return a SubPlan unchanged --- too late to do anything with it.
2031
		 *
2032 2033
		 * XXX should we ereport() here instead?  Probably this routine should
		 * never be invoked after SubPlan creation.
2034
		 */
2035
		return node;
2036
	}
2037 2038 2039
	if (IsA(node, RelabelType))
	{
		/*
2040 2041 2042
		 * 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.
2043 2044 2045 2046
		 */
		RelabelType *relabel = (RelabelType *) node;
		Node	   *arg;

2047
		arg = eval_const_expressions_mutator((Node *) relabel->arg,
2048
											 context);
2049 2050

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

2057 2058
		if (arg && IsA(arg, Const))
		{
2059
			Const	   *con = (Const *) arg;
2060 2061

			con->consttype = relabel->resulttype;
2062
			con->consttypmod = relabel->resulttypmod;
2063 2064 2065 2066 2067 2068
			return (Node *) con;
		}
		else
		{
			RelabelType *newrelabel = makeNode(RelabelType);

2069
			newrelabel->arg = (Expr *) arg;
2070 2071
			newrelabel->resulttype = relabel->resulttype;
			newrelabel->resulttypmod = relabel->resulttypmod;
2072
			newrelabel->relabelformat = relabel->relabelformat;
2073 2074 2075
			return (Node *) newrelabel;
		}
	}
2076 2077
	if (IsA(node, CaseExpr))
	{
2078
		/*----------
2079
		 * CASE expressions can be simplified if there are constant
2080 2081 2082 2083 2084 2085 2086
		 * 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).
2087
		 *
2088 2089 2090 2091 2092 2093
		 * 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.
2094
		 *----------
2095 2096 2097
		 */
		CaseExpr   *caseexpr = (CaseExpr *) node;
		CaseExpr   *newcase;
2098
		Node	   *save_case_val;
2099
		Node	   *newarg;
2100
		List	   *newargs;
2101 2102
		bool		const_true_cond;
		Node	   *defresult = NULL;
2103
		ListCell   *arg;
2104

2105 2106
		/* Simplify the test expression, if any */
		newarg = eval_const_expressions_mutator((Node *) caseexpr->arg,
2107
												context);
2108

2109 2110 2111 2112 2113 2114 2115
		/* 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;

2116
		/* Simplify the WHEN clauses */
2117
		newargs = NIL;
2118
		const_true_cond = false;
2119 2120
		foreach(arg, caseexpr->args)
		{
2121 2122 2123 2124 2125 2126 2127 2128 2129 2130
			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);
2131

2132
			/*
2133 2134
			 * If the test condition is constant FALSE (or NULL), then drop
			 * this WHEN clause completely, without processing the result.
2135
			 */
2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150
			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);
2151

2152 2153 2154 2155 2156 2157 2158 2159 2160 2161
			/* 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;
			}
2162

2163
			/*
2164
			 * Found a TRUE condition, so none of the remaining alternatives
2165
			 * can be reached.	We treat the result as the default result.
2166
			 */
2167
			defresult = caseresult;
2168 2169 2170
			break;
		}

2171 2172 2173 2174 2175
		/* Simplify the default result, unless we replaced it above */
		if (!const_true_cond)
			defresult =
				eval_const_expressions_mutator((Node *) caseexpr->defresult,
											   context);
2176

2177 2178 2179
		context->case_val = save_case_val;

		/* If no non-FALSE alternatives, CASE reduces to the default result */
2180
		if (newargs == NIL)
2181 2182 2183 2184
			return defresult;
		/* Otherwise we need a new CASE node */
		newcase = makeNode(CaseExpr);
		newcase->casetype = caseexpr->casetype;
2185
		newcase->arg = (Expr *) newarg;
2186
		newcase->args = newargs;
2187
		newcase->defresult = (Expr *) defresult;
2188 2189
		return (Node *) newcase;
	}
2190 2191 2192
	if (IsA(node, CaseTestExpr))
	{
		/*
2193 2194 2195
		 * If we know a constant test value for the current CASE construct,
		 * substitute it for the placeholder.  Else just return the
		 * placeholder as-is.
2196 2197 2198 2199 2200 2201
		 */
		if (context->case_val)
			return copyObject(context->case_val);
		else
			return copyObject(node);
	}
2202 2203
	if (IsA(node, ArrayExpr))
	{
Bruce Momjian's avatar
Bruce Momjian committed
2204 2205 2206
		ArrayExpr  *arrayexpr = (ArrayExpr *) node;
		ArrayExpr  *newarray;
		bool		all_const = true;
2207
		List	   *newelems;
2208
		ListCell   *element;
2209

2210
		newelems = NIL;
2211 2212
		foreach(element, arrayexpr->elements)
		{
Bruce Momjian's avatar
Bruce Momjian committed
2213
			Node	   *e;
2214 2215

			e = eval_const_expressions_mutator((Node *) lfirst(element),
2216
											   context);
2217 2218
			if (!IsA(e, Const))
				all_const = false;
2219
			newelems = lappend(newelems, e);
2220 2221 2222 2223 2224
		}

		newarray = makeNode(ArrayExpr);
		newarray->array_typeid = arrayexpr->array_typeid;
		newarray->element_typeid = arrayexpr->element_typeid;
2225
		newarray->elements = newelems;
2226
		newarray->multidims = arrayexpr->multidims;
2227 2228 2229

		if (all_const)
			return (Node *) evaluate_expr((Expr *) newarray,
2230 2231
										  newarray->array_typeid,
										  exprTypmod(node));
2232 2233 2234

		return (Node *) newarray;
	}
2235 2236 2237 2238
	if (IsA(node, CoalesceExpr))
	{
		CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
		CoalesceExpr *newcoalesce;
2239
		List	   *newargs;
2240
		ListCell   *arg;
2241

2242
		newargs = NIL;
2243 2244
		foreach(arg, coalesceexpr->args)
		{
Bruce Momjian's avatar
Bruce Momjian committed
2245
			Node	   *e;
2246 2247

			e = eval_const_expressions_mutator((Node *) lfirst(arg),
2248
											   context);
Bruce Momjian's avatar
Bruce Momjian committed
2249 2250 2251 2252 2253

			/*
			 * 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.
2254 2255 2256 2257 2258
			 */
			if (IsA(e, Const))
			{
				if (((Const *) e)->constisnull)
					continue;	/* drop null constant */
2259
				if (newargs == NIL)
2260 2261
					return e;	/* first expr */
			}
2262
			newargs = lappend(newargs, e);
2263 2264
		}

2265 2266 2267 2268
		/* If all the arguments were constant null, the result is just null */
		if (newargs == NIL)
			return (Node *) makeNullConst(coalesceexpr->coalescetype);

2269 2270
		newcoalesce = makeNode(CoalesceExpr);
		newcoalesce->coalescetype = coalesceexpr->coalescetype;
2271
		newcoalesce->args = newargs;
2272 2273
		return (Node *) newcoalesce;
	}
2274 2275 2276
	if (IsA(node, FieldSelect))
	{
		/*
2277 2278 2279 2280 2281
		 * 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.
2282
		 *
2283 2284
		 * 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
2285
		 * someone did ALTER COLUMN TYPE on the rowtype.
2286 2287
		 */
		FieldSelect *fselect = (FieldSelect *) node;
2288 2289
		FieldSelect *newfselect;
		Node	   *arg;
2290

2291
		arg = eval_const_expressions_mutator((Node *) fselect->arg,
2292
											 context);
2293 2294
		if (arg && IsA(arg, Var) &&
			((Var *) arg)->varattno == InvalidAttrNumber)
2295
		{
2296 2297 2298 2299 2300 2301 2302 2303 2304
			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);
2305
		}
2306 2307
		if (arg && IsA(arg, RowExpr))
		{
Bruce Momjian's avatar
Bruce Momjian committed
2308
			RowExpr    *rowexpr = (RowExpr *) arg;
2309 2310

			if (fselect->fieldnum > 0 &&
2311
				fselect->fieldnum <= list_length(rowexpr->args))
2312
			{
Bruce Momjian's avatar
Bruce Momjian committed
2313
				Node	   *fld = (Node *) list_nth(rowexpr->args,
2314
													fselect->fieldnum - 1);
2315 2316 2317 2318 2319 2320 2321 2322 2323

				if (rowtype_field_matches(rowexpr->row_typeid,
										  fselect->fieldnum,
										  fselect->resulttype,
										  fselect->resulttypmod) &&
					fselect->resulttype == exprType(fld) &&
					fselect->resulttypmod == exprTypmod(fld))
					return fld;
			}
2324 2325 2326 2327 2328 2329 2330
		}
		newfselect = makeNode(FieldSelect);
		newfselect->arg = (Expr *) arg;
		newfselect->fieldnum = fselect->fieldnum;
		newfselect->resulttype = fselect->resulttype;
		newfselect->resulttypmod = fselect->resulttypmod;
		return (Node *) newfselect;
2331
	}
2332 2333 2334 2335 2336 2337 2338 2339 2340 2341
	if (IsA(node, NullTest))
	{
		NullTest   *ntest = (NullTest *) node;
		NullTest   *newntest;
		Node	   *arg;

		arg = eval_const_expressions_mutator((Node *) ntest->arg,
											 context);
		if (arg && IsA(arg, RowExpr))
		{
Bruce Momjian's avatar
Bruce Momjian committed
2342 2343 2344
			RowExpr    *rarg = (RowExpr *) arg;
			List	   *newargs = NIL;
			ListCell   *l;
2345 2346 2347 2348 2349 2350 2351 2352

			/*
			 * We break ROW(...) IS [NOT] NULL into separate tests on its
			 * component fields.  This form is usually more efficient to
			 * evaluate, as well as being more amenable to optimization.
			 */
			foreach(l, rarg->args)
			{
Bruce Momjian's avatar
Bruce Momjian committed
2353
				Node	   *relem = (Node *) lfirst(l);
2354 2355

				/*
Bruce Momjian's avatar
Bruce Momjian committed
2356 2357
				 * A constant field refutes the whole NullTest if it's of the
				 * wrong nullness; else we can discard it.
2358 2359 2360
				 */
				if (relem && IsA(relem, Const))
				{
Bruce Momjian's avatar
Bruce Momjian committed
2361
					Const	   *carg = (Const *) relem;
2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384

					if (carg->constisnull ?
						(ntest->nulltesttype == IS_NOT_NULL) :
						(ntest->nulltesttype == IS_NULL))
						return makeBoolConst(false, false);
					continue;
				}
				newntest = makeNode(NullTest);
				newntest->arg = (Expr *) relem;
				newntest->nulltesttype = ntest->nulltesttype;
				newargs = lappend(newargs, newntest);
			}
			/* If all the inputs were constants, result is TRUE */
			if (newargs == NIL)
				return makeBoolConst(true, false);
			/* If only one nonconst input, it's the result */
			if (list_length(newargs) == 1)
				return (Node *) linitial(newargs);
			/* Else we need an AND node */
			return (Node *) make_andclause(newargs);
		}
		if (arg && IsA(arg, Const))
		{
Bruce Momjian's avatar
Bruce Momjian committed
2385 2386
			Const	   *carg = (Const *) arg;
			bool		result;
2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398

			switch (ntest->nulltesttype)
			{
				case IS_NULL:
					result = carg->constisnull;
					break;
				case IS_NOT_NULL:
					result = !carg->constisnull;
					break;
				default:
					elog(ERROR, "unrecognized nulltesttype: %d",
						 (int) ntest->nulltesttype);
Bruce Momjian's avatar
Bruce Momjian committed
2399
					result = false;		/* keep compiler quiet */
2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410
					break;
			}

			return makeBoolConst(result, false);
		}

		newntest = makeNode(NullTest);
		newntest->arg = (Expr *) arg;
		newntest->nulltesttype = ntest->nulltesttype;
		return (Node *) newntest;
	}
2411 2412 2413 2414 2415 2416 2417 2418 2419 2420
	if (IsA(node, BooleanTest))
	{
		BooleanTest *btest = (BooleanTest *) node;
		BooleanTest *newbtest;
		Node	   *arg;

		arg = eval_const_expressions_mutator((Node *) btest->arg,
											 context);
		if (arg && IsA(arg, Const))
		{
Bruce Momjian's avatar
Bruce Momjian committed
2421 2422
			Const	   *carg = (Const *) arg;
			bool		result;
2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450

			switch (btest->booltesttype)
			{
				case IS_TRUE:
					result = (!carg->constisnull &&
							  DatumGetBool(carg->constvalue));
					break;
				case IS_NOT_TRUE:
					result = (carg->constisnull ||
							  !DatumGetBool(carg->constvalue));
					break;
				case IS_FALSE:
					result = (!carg->constisnull &&
							  !DatumGetBool(carg->constvalue));
					break;
				case IS_NOT_FALSE:
					result = (carg->constisnull ||
							  DatumGetBool(carg->constvalue));
					break;
				case IS_UNKNOWN:
					result = carg->constisnull;
					break;
				case IS_NOT_UNKNOWN:
					result = !carg->constisnull;
					break;
				default:
					elog(ERROR, "unrecognized booltesttype: %d",
						 (int) btest->booltesttype);
Bruce Momjian's avatar
Bruce Momjian committed
2451
					result = false;		/* keep compiler quiet */
2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462
					break;
			}

			return makeBoolConst(result, false);
		}

		newbtest = makeNode(BooleanTest);
		newbtest->arg = (Expr *) arg;
		newbtest->booltesttype = btest->booltesttype;
		return (Node *) newbtest;
	}
2463

2464 2465
	/*
	 * For any node type not handled above, we recurse using
2466 2467 2468 2469
	 * 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.
2470 2471
	 */
	return expression_tree_mutator(node, eval_const_expressions_mutator,
2472
								   (void *) context);
2473 2474
}

2475
/*
2476 2477 2478 2479
 * 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.
2480
 *
2481
 * After simplification, OR arguments are handled as follows:
2482 2483 2484 2485 2486
 *		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
2487 2488
 * 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.
2489 2490 2491 2492 2493 2494
 *
 * 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 *
2495 2496 2497
simplify_or_arguments(List *args,
					  eval_const_expressions_context *context,
					  bool *haveNull, bool *forceTrue)
2498 2499
{
	List	   *newargs = NIL;
2500
	List	   *unprocessed_args;
2501

2502 2503 2504
	/*
	 * Since the parser considers OR to be a binary operator, long OR lists
	 * become deeply nested expressions.  We must flatten these into long
2505
	 * argument lists of a single OR operator.	To avoid blowing out the stack
2506 2507 2508 2509 2510 2511
	 * 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)
2512
	{
2513 2514 2515 2516 2517 2518 2519
		Node	   *arg = (Node *) linitial(unprocessed_args);

		unprocessed_args = list_delete_first(unprocessed_args);

		/* flatten nested ORs as per above comment */
		if (or_clause(arg))
		{
2520
			List	   *subargs = list_copy(((BoolExpr *) arg)->args);
2521 2522 2523 2524 2525 2526

			/* overly tense code to avoid leaking unused list header */
			if (!unprocessed_args)
				unprocessed_args = subargs;
			else
			{
2527
				List	   *oldhdr = unprocessed_args;
2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538

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

		/*
2539 2540 2541 2542
		 * 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.
2543 2544 2545
		 */
		if (or_clause(arg))
		{
2546
			List	   *subargs = list_copy(((BoolExpr *) arg)->args);
2547 2548 2549 2550

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

2552
		/*
2553 2554
		 * OK, we have a const-simplified non-OR argument.	Process it per
		 * comments above.
2555
		 */
2556 2557
		if (IsA(arg, Const))
		{
Bruce Momjian's avatar
Bruce Momjian committed
2558
			Const	   *const_input = (Const *) arg;
2559 2560 2561 2562 2563 2564

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

2566 2567 2568 2569 2570 2571 2572 2573
				/*
				 * 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 */
2574
			continue;
2575
		}
2576 2577 2578

		/* else emit the simplified arg into the result list */
		newargs = lappend(newargs, arg);
2579 2580 2581 2582 2583 2584
	}

	return newargs;
}

/*
2585
 * Subroutine for eval_const_expressions: process arguments of an AND clause
2586
 *
2587 2588 2589 2590
 * 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:
2591 2592 2593 2594 2595
 *		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
2596 2597
 * 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.
2598 2599 2600 2601 2602 2603
 *
 * 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 *
2604 2605 2606
simplify_and_arguments(List *args,
					   eval_const_expressions_context *context,
					   bool *haveNull, bool *forceFalse)
2607 2608
{
	List	   *newargs = NIL;
2609
	List	   *unprocessed_args;
2610

2611 2612 2613
	/* See comments in simplify_or_arguments */
	unprocessed_args = list_copy(args);
	while (unprocessed_args)
2614
	{
2615 2616 2617 2618 2619 2620 2621
		Node	   *arg = (Node *) linitial(unprocessed_args);

		unprocessed_args = list_delete_first(unprocessed_args);

		/* flatten nested ANDs as per above comment */
		if (and_clause(arg))
		{
2622
			List	   *subargs = list_copy(((BoolExpr *) arg)->args);
2623 2624 2625 2626 2627 2628

			/* overly tense code to avoid leaking unused list header */
			if (!unprocessed_args)
				unprocessed_args = subargs;
			else
			{
2629
				List	   *oldhdr = unprocessed_args;
2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640

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

		/*
2641 2642 2643 2644
		 * 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.
2645 2646 2647
		 */
		if (and_clause(arg))
		{
2648
			List	   *subargs = list_copy(((BoolExpr *) arg)->args);
2649

2650 2651 2652 2653 2654
			unprocessed_args = list_concat(subargs, unprocessed_args);
			continue;
		}

		/*
2655 2656
		 * OK, we have a const-simplified non-AND argument.  Process it per
		 * comments above.
2657
		 */
2658 2659
		if (IsA(arg, Const))
		{
Bruce Momjian's avatar
Bruce Momjian committed
2660
			Const	   *const_input = (Const *) arg;
2661 2662 2663 2664 2665 2666

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

2668 2669 2670 2671 2672 2673 2674 2675
				/*
				 * 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 */
2676
			continue;
2677
		}
2678 2679 2680

		/* else emit the simplified arg into the result list */
		newargs = lappend(newargs, arg);
2681 2682 2683 2684 2685
	}

	return newargs;
}

2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713
/*
 * 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))
2714
			return rightop;		/* true = foo */
2715 2716 2717 2718 2719 2720 2721
		else
			return make_notclause(rightop);		/* false = foo */
	}
	if (rightop && IsA(rightop, Const))
	{
		Assert(!((Const *) rightop)->constisnull);
		if (DatumGetBool(((Const *) rightop)->constvalue))
2722
			return leftop;		/* foo = true */
2723 2724 2725 2726 2727 2728
		else
			return make_notclause(leftop);		/* foo = false */
	}
	return NULL;
}

2729
/*
2730 2731
 * Subroutine for eval_const_expressions: try to simplify a function call
 * (which might originally have been an operator; we don't care)
2732
 *
2733
 * Inputs are the function OID, actual result type OID (which is needed for
2734
 * polymorphic functions) and typmod, and the pre-simplified argument list;
2735
 * also the context data for eval_const_expressions.
2736 2737
 *
 * Returns a simplified expression if successful, or NULL if cannot
2738
 * simplify the function call.
2739 2740
 */
static Expr *
2741 2742
simplify_function(Oid funcid, Oid result_type, int32 result_typmod,
				  List *args,
2743 2744
				  bool allow_inline,
				  eval_const_expressions_context *context)
2745 2746
{
	HeapTuple	func_tuple;
2747
	Expr	   *newexpr;
2748 2749

	/*
2750 2751 2752 2753 2754 2755
	 * 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.
2756
	 */
2757 2758 2759
	func_tuple = SearchSysCache(PROCOID,
								ObjectIdGetDatum(funcid),
								0, 0, 0);
2760
	if (!HeapTupleIsValid(func_tuple))
2761
		elog(ERROR, "cache lookup failed for function %u", funcid);
2762

2763
	newexpr = evaluate_function(funcid, result_type, result_typmod, args,
2764
								func_tuple, context);
2765 2766

	if (!newexpr && allow_inline)
2767
		newexpr = inline_function(funcid, result_type, args,
2768
								  func_tuple, context);
2769

2770 2771
	ReleaseSysCache(func_tuple);

2772 2773 2774 2775
	return newexpr;
}

/*
2776
 * evaluate_function: try to pre-evaluate a function call
2777 2778 2779
 *
 * 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
2780 2781
 * constant inputs (call it and return the result as a Const node).  In
 * estimation mode we are willing to pre-evaluate stable functions too.
2782 2783
 *
 * Returns a simplified expression if successful, or NULL if cannot
2784
 * simplify the function.
2785 2786
 */
static Expr *
2787
evaluate_function(Oid funcid, Oid result_type, int32 result_typmod, List *args,
2788 2789
				  HeapTuple func_tuple,
				  eval_const_expressions_context *context)
2790 2791 2792 2793
{
	Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
	bool		has_nonconst_input = false;
	bool		has_null_input = false;
2794
	ListCell   *arg;
2795
	FuncExpr   *newexpr;
2796

2797
	/*
2798
	 * Can't simplify if it returns a set.
2799
	 */
2800
	if (funcform->proretset)
2801
		return NULL;
2802

2803
	/*
2804 2805
	 * 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.
2806 2807 2808
	 *
	 * 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()
2809 2810 2811 2812
	 * 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.
2813
	 */
2814
	if (funcform->prorettype == RECORDOID)
2815 2816
		return NULL;

2817
	/*
2818
	 * Check for constant inputs and especially constant-NULL inputs.
2819
	 */
2820
	foreach(arg, args)
2821
	{
2822 2823 2824 2825
		if (IsA(lfirst(arg), Const))
			has_null_input |= ((Const *) lfirst(arg))->constisnull;
		else
			has_nonconst_input = true;
2826 2827 2828
	}

	/*
2829 2830 2831 2832
	 * 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.
2833
	 */
2834
	if (funcform->proisstrict && has_null_input)
2835
		return (Expr *) makeNullConst(result_type);
2836 2837

	/*
2838 2839 2840
	 * 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.)
2841
	 */
2842 2843 2844 2845
	if (has_nonconst_input)
		return NULL;

	/*
2846 2847 2848 2849 2850
	 * 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.
2851 2852
	 */
	if (funcform->provolatile == PROVOLATILE_IMMUTABLE)
2853
		 /* okay */ ;
2854
	else if (context->estimate && funcform->provolatile == PROVOLATILE_STABLE)
2855
		 /* okay */ ;
2856
	else
2857 2858
		return NULL;

2859 2860 2861
	/*
	 * OK, looks like we can simplify this operator/function.
	 *
2862
	 * Build a new FuncExpr node containing the already-simplified arguments.
2863
	 */
2864 2865
	newexpr = makeNode(FuncExpr);
	newexpr->funcid = funcid;
2866
	newexpr->funcresulttype = result_type;
2867
	newexpr->funcretset = false;
2868
	newexpr->funcformat = COERCE_DONTCARE;		/* doesn't matter */
2869
	newexpr->args = args;
2870

2871
	return evaluate_expr((Expr *) newexpr, result_type, result_typmod);
2872 2873
}

2874
/*
2875
 * inline_function: try to expand a function call inline
2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886
 *
 * 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
2887
 * functions (volatiles might deliver inconsistent answers) nor to be
Bruce Momjian's avatar
Bruce Momjian committed
2888
 * unreasonably expensive to evaluate.	The expensiveness check not only
2889 2890 2891 2892
 * 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.
 *
2893 2894 2895 2896
 * 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
2897
 * simplify the function.
2898 2899
 */
static Expr *
2900
inline_function(Oid funcid, Oid result_type, List *args,
2901 2902
				HeapTuple func_tuple,
				eval_const_expressions_context *context)
2903 2904
{
	Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
2905
	Oid		   *argtypes;
2906 2907 2908 2909 2910
	char	   *src;
	Datum		tmp;
	bool		isNull;
	MemoryContext oldcxt;
	MemoryContext mycxt;
2911
	ErrorContextCallback sqlerrcontext;
2912 2913 2914 2915 2916
	List	   *raw_parsetree_list;
	List	   *querytree_list;
	Query	   *querytree;
	Node	   *newexpr;
	int		   *usecounts;
2917
	ListCell   *arg;
2918 2919 2920
	int			i;

	/*
2921 2922
	 * Forget it if the function is not SQL-language or has other showstopper
	 * properties.	(The nargs check is just paranoia.)
2923 2924 2925 2926
	 */
	if (funcform->prolang != SQLlanguageId ||
		funcform->prosecdef ||
		funcform->proretset ||
2927
		funcform->pronargs != list_length(args))
2928 2929 2930
		return NULL;

	/* Check for recursive function, and give up trying to expand if so */
2931
	if (list_member_oid(context->active_fns, funcid))
2932 2933 2934 2935 2936 2937
		return NULL;

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

2938
	/*
2939 2940
	 * Setup error traceback support for ereport().  This is so that we can
	 * finger the function that bad information came from.
2941 2942
	 */
	sqlerrcontext.callback = sql_inline_error_callback;
2943
	sqlerrcontext.arg = func_tuple;
2944 2945 2946
	sqlerrcontext.previous = error_context_stack;
	error_context_stack = &sqlerrcontext;

2947
	/*
2948 2949
	 * Make a temporary memory context, so that we don't leak all the stuff
	 * that parsing might create.
2950 2951
	 */
	mycxt = AllocSetContextCreate(CurrentMemoryContext,
2952
								  "inline_function",
2953 2954 2955 2956 2957
								  ALLOCSET_DEFAULT_MINSIZE,
								  ALLOCSET_DEFAULT_INITSIZE,
								  ALLOCSET_DEFAULT_MAXSIZE);
	oldcxt = MemoryContextSwitchTo(mycxt);

2958 2959 2960 2961 2962 2963
	/* 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++)
	{
2964
		if (IsPolymorphicType(argtypes[i]))
2965 2966 2967 2968 2969
		{
			argtypes[i] = exprType((Node *) list_nth(args, i));
		}
	}

2970 2971 2972 2973 2974 2975
	/* Fetch and parse the function body */
	tmp = SysCacheGetAttr(PROCOID,
						  func_tuple,
						  Anum_pg_proc_prosrc,
						  &isNull);
	if (isNull)
2976
		elog(ERROR, "null prosrc for function %u", funcid);
2977 2978 2979
	src = DatumGetCString(DirectFunctionCall1(textout, tmp));

	/*
2980 2981 2982 2983
	 * 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.
2984
	 */
2985
	raw_parsetree_list = pg_parse_query(src);
2986
	if (list_length(raw_parsetree_list) != 1)
2987 2988
		goto fail;

2989
	querytree_list = parse_analyze(linitial(raw_parsetree_list), src,
2990
								   argtypes, funcform->pronargs);
2991

2992
	if (list_length(querytree_list) != 1)
2993 2994
		goto fail;

2995
	querytree = (Query *) linitial(querytree_list);
2996 2997 2998 2999 3000 3001

	/*
	 * The single command must be a simple "SELECT expression".
	 */
	if (!IsA(querytree, Query) ||
		querytree->commandType != CMD_SELECT ||
3002 3003
		querytree->utilityStmt ||
		querytree->intoClause ||
3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015
		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 ||
3016
		list_length(querytree->targetList) != 1)
3017 3018
		goto fail;

3019
	newexpr = (Node *) ((TargetEntry *) linitial(querytree->targetList))->expr;
3020

3021
	/*
3022
	 * Make sure the function (still) returns what it's declared to.  This will
3023 3024 3025
	 * 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
3026
	 * careful.
3027
	 */
3028 3029
	if (check_sql_fn_retval(funcid, result_type, querytree_list, NULL))
		goto fail;				/* reject whole-tuple-result cases */
3030

3031
	/*
3032 3033 3034 3035 3036 3037 3038
	 * 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).
3039 3040 3041 3042 3043 3044 3045 3046
	 */
	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
3047
			 contain_volatile_functions(newexpr))
3048 3049 3050 3051 3052 3053 3054
		goto fail;

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

	/*
3055 3056 3057 3058
	 * 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.
3059
	 */
3060
	usecounts = (int *) palloc0(funcform->pronargs * sizeof(int));
3061 3062 3063 3064 3065 3066 3067
	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
3068
		Node	   *param = lfirst(arg);
3069 3070 3071 3072 3073 3074 3075 3076 3077

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

			/*
3082 3083
			 * We define "expensive" as "contains any subplan or more than 10
			 * operators".  Note that the subplan search has to be done
3084 3085 3086 3087 3088
			 * explicitly, since cost_qual_eval() will barf on unplanned
			 * subselects.
			 */
			if (contain_subplans(param))
				goto fail;
3089
			cost_qual_eval(&eval_cost, list_make1(param), NULL);
3090 3091 3092
			if (eval_cost.startup + eval_cost.per_tuple >
				10 * cpu_operator_cost)
				goto fail;
Bruce Momjian's avatar
Bruce Momjian committed
3093

3094 3095 3096 3097 3098
			/*
			 * Check volatility last since this is more expensive than the
			 * above tests
			 */
			if (contain_volatile_functions(param))
3099 3100 3101 3102 3103 3104
				goto fail;
		}
		i++;
	}

	/*
3105 3106
	 * Whew --- we can make the substitution.  Copy the modified expression
	 * out of the temporary memory context, and clean up.
3107 3108 3109 3110 3111 3112 3113
	 */
	MemoryContextSwitchTo(oldcxt);

	newexpr = copyObject(newexpr);

	MemoryContextDelete(mycxt);

3114 3115 3116 3117 3118 3119
	/*
	 * Since check_sql_fn_retval allows binary-compatibility cases, the
	 * expression we now have might return some type that's only binary
	 * compatible with the original expression result type.  To avoid
	 * confusing matters, insert a RelabelType in such cases.
	 */
3120
	if (exprType(newexpr) != result_type)
3121
	{
3122
		Assert(IsBinaryCoercible(exprType(newexpr), result_type));
3123
		newexpr = (Node *) makeRelabelType((Expr *) newexpr,
3124
										   result_type,
3125 3126 3127 3128
										   -1,
										   COERCE_IMPLICIT_CAST);
	}

3129
	/*
3130 3131
	 * Recursively try to simplify the modified expression.  Here we must add
	 * the current function to the context list of active functions.
3132
	 */
3133 3134 3135
	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);
3136

3137 3138
	error_context_stack = sqlerrcontext.previous;

3139 3140 3141 3142 3143 3144
	return (Expr *) newexpr;

	/* Here if func is not inlinable: release temp memory and return NULL */
fail:
	MemoryContextSwitchTo(oldcxt);
	MemoryContextDelete(mycxt);
3145
	error_context_stack = sqlerrcontext.previous;
3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158

	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
3159
	context.nargs = nargs;
3160 3161 3162 3163 3164 3165 3166 3167
	context.args = args;
	context.usecounts = usecounts;

	return substitute_actual_parameters_mutator(expr, &context);
}

static Node *
substitute_actual_parameters_mutator(Node *node,
3168
							   substitute_actual_parameters_context *context)
3169 3170 3171 3172 3173 3174 3175
{
	if (node == NULL)
		return NULL;
	if (IsA(node, Param))
	{
		Param	   *param = (Param *) node;

3176 3177
		if (param->paramkind != PARAM_EXTERN)
			elog(ERROR, "unexpected paramkind: %d", (int) param->paramkind);
3178
		if (param->paramid <= 0 || param->paramid > context->nargs)
3179
			elog(ERROR, "invalid paramid: %d", param->paramid);
3180 3181 3182 3183 3184 3185

		/* 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) */
3186
		return list_nth(context->args, param->paramid - 1);
3187 3188 3189 3190 3191
	}
	return expression_tree_mutator(node, substitute_actual_parameters_mutator,
								   (void *) context);
}

3192 3193 3194 3195 3196 3197
/*
 * 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
3198
	HeapTuple	func_tuple = (HeapTuple) arg;
3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218
	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);
	}
3219 3220 3221 3222 3223

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

3224 3225 3226 3227 3228 3229 3230
/*
 * 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 *
3231
evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod)
3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256
{
	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.
	 *
3257 3258 3259 3260
	 * 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?
3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281
	 */
	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.
	 */
3282
	return (Expr *) makeConst(result_type, result_typmod, resultTypLen,
3283 3284 3285 3286
							  const_val, const_is_null,
							  resultTypByVal);
}

3287

3288
/*
3289 3290 3291 3292 3293 3294 3295 3296 3297
 * 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
3298 3299 3300 3301 3302
 * logic to consolidate the redundant "boilerplate" code.  There are
 * two versions: expression_tree_walker() and expression_tree_mutator().
 */

/*--------------------
3303 3304
 * expression_tree_walker() is designed to support routines that traverse
 * a tree in a read-only fashion (although it will also work for routines
3305 3306
 * that modify nodes in-place but never add/delete/replace nodes).
 * A walker routine should look like this:
3307 3308 3309 3310 3311
 *
 * bool my_walker (Node *node, my_struct *context)
 * {
 *		if (node == NULL)
 *			return false;
Bruce Momjian's avatar
Bruce Momjian committed
3312
 *		// check for nodes that special work is required for, eg:
3313 3314 3315 3316 3317 3318 3319 3320
 *		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
3321
 *		// for any node type not specially processed, do:
3322 3323 3324 3325
 *		return expression_tree_walker(node, my_walker, (void *) context);
 * }
 *
 * The "context" argument points to a struct that holds whatever context
3326 3327
 * information the walker routine needs --- it can be used to return data
 * gathered by the walker, too.  This argument is not touched by
3328 3329 3330 3331 3332 3333 3334
 * 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
3335 3336
 * 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
3337
 * iff no invocation of the walker returned "true".
3338 3339 3340 3341 3342 3343
 *
 * 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.
3344 3345 3346
 * Also, RangeTblRef, FromExpr, JoinExpr, and SetOperationStmt nodes are
 * handled, so that query jointrees and setOperation trees can be processed
 * without additional code.
3347
 *
3348 3349
 * expression_tree_walker will handle SubLink nodes by recursing normally
 * into the "testexpr" subtree (which is an expression belonging to the outer
3350 3351 3352 3353 3354 3355 3356 3357 3358
 * 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:
3359 3360 3361 3362
 *
 *		if (IsA(node, Query))
 *		{
 *			adjust context for subquery;
3363
 *			result = query_tree_walker((Query *) node, my_walker, context,
3364
 *									   0); // adjust flags as needed
3365 3366 3367
 *			restore context if needed;
 *			return result;
 *		}
3368
 *
3369 3370
 * query_tree_walker is a convenience routine (see below) that calls the
 * walker on all the expression subtrees of the given Query node.
3371
 *
3372
 * expression_tree_walker will handle SubPlan nodes by recursing normally
3373
 * into the "testexpr" and the "args" list (which are expressions belonging to
Bruce Momjian's avatar
Bruce Momjian committed
3374
 * the outer plan).  It will not touch the completed subplan, however.	Since
3375 3376 3377
 * 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.
3378 3379 3380 3381
 *--------------------
 */

bool
3382 3383 3384
expression_tree_walker(Node *node,
					   bool (*walker) (),
					   void *context)
3385
{
3386
	ListCell   *temp;
3387 3388

	/*
3389 3390
	 * The walker has already visited the current node, and so we need only
	 * recurse into any sub-nodes it has.
3391
	 *
3392 3393 3394
	 * 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.
3395 3396 3397
	 */
	if (node == NULL)
		return false;
3398 3399 3400 3401

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

3402 3403 3404
	switch (nodeTag(node))
	{
		case T_Var:
3405
		case T_Const:
3406
		case T_Param:
3407
		case T_CoerceToDomainValue:
3408
		case T_CaseTestExpr:
3409
		case T_SetToDefault:
3410
		case T_CurrentOfExpr:
3411
		case T_RangeTblRef:
3412 3413
		case T_OuterJoinInfo:
			/* primitive node types with no expression subnodes */
3414
			break;
3415
		case T_Aggref:
3416
			{
Bruce Momjian's avatar
Bruce Momjian committed
3417
				Aggref	   *expr = (Aggref *) node;
3418

3419
				/* recurse directly on List */
3420 3421 3422 3423 3424
				if (expression_tree_walker((Node *) expr->args,
										   walker, context))
					return true;
			}
			break;
3425 3426 3427
		case T_ArrayRef:
			{
				ArrayRef   *aref = (ArrayRef *) node;
3428

3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442
				/* 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;
3443
		case T_FuncExpr:
3444
			{
3445
				FuncExpr   *expr = (FuncExpr *) node;
3446

3447 3448 3449 3450 3451 3452 3453 3454
				if (expression_tree_walker((Node *) expr->args,
										   walker, context))
					return true;
			}
			break;
		case T_OpExpr:
			{
				OpExpr	   *expr = (OpExpr *) node;
3455

3456 3457
				if (expression_tree_walker((Node *) expr->args,
										   walker, context))
3458
					return true;
3459 3460 3461 3462 3463 3464 3465 3466
			}
			break;
		case T_DistinctExpr:
			{
				DistinctExpr *expr = (DistinctExpr *) node;

				if (expression_tree_walker((Node *) expr->args,
										   walker, context))
3467 3468 3469
					return true;
			}
			break;
3470 3471 3472 3473 3474 3475 3476 3477 3478
		case T_ScalarArrayOpExpr:
			{
				ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;

				if (expression_tree_walker((Node *) expr->args,
										   walker, context))
					return true;
			}
			break;
3479 3480 3481 3482 3483 3484 3485 3486
		case T_BoolExpr:
			{
				BoolExpr   *expr = (BoolExpr *) node;

				if (expression_tree_walker((Node *) expr->args,
										   walker, context))
					return true;
			}
3487
			break;
3488
		case T_SubLink:
3489
			{
3490
				SubLink    *sublink = (SubLink *) node;
3491

3492
				if (walker(sublink->testexpr, context))
3493
					return true;
Bruce Momjian's avatar
Bruce Momjian committed
3494

3495
				/*
3496 3497
				 * Also invoke the walker on the sublink's Query node, so it
				 * can recurse into the sub-query if it wants to.
3498 3499
				 */
				return walker(sublink->subselect, context);
3500 3501
			}
			break;
3502
		case T_SubPlan:
3503
			{
Bruce Momjian's avatar
Bruce Momjian committed
3504
				SubPlan    *subplan = (SubPlan *) node;
3505

3506
				/* recurse into the testexpr, but not into the Plan */
3507
				if (walker(subplan->testexpr, context))
3508 3509
					return true;
				/* also examine args list */
3510
				if (expression_tree_walker((Node *) subplan->args,
3511 3512 3513 3514 3515 3516
										   walker, context))
					return true;
			}
			break;
		case T_FieldSelect:
			return walker(((FieldSelect *) node)->arg, context);
3517 3518
		case T_FieldStore:
			{
Bruce Momjian's avatar
Bruce Momjian committed
3519
				FieldStore *fstore = (FieldStore *) node;
3520 3521 3522 3523 3524 3525 3526

				if (walker(fstore->arg, context))
					return true;
				if (walker(fstore->newvals, context))
					return true;
			}
			break;
3527 3528
		case T_RelabelType:
			return walker(((RelabelType *) node)->arg, context);
3529 3530
		case T_CoerceViaIO:
			return walker(((CoerceViaIO *) node)->arg, context);
3531 3532
		case T_ArrayCoerceExpr:
			return walker(((ArrayCoerceExpr *) node)->arg, context);
3533 3534
		case T_ConvertRowtypeExpr:
			return walker(((ConvertRowtypeExpr *) node)->arg, context);
3535 3536 3537 3538
		case T_CaseExpr:
			{
				CaseExpr   *caseexpr = (CaseExpr *) node;

3539 3540
				if (walker(caseexpr->arg, context))
					return true;
3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555
				/* 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;
3556 3557
		case T_ArrayExpr:
			return walker(((ArrayExpr *) node)->elements, context);
3558 3559
		case T_RowExpr:
			return walker(((RowExpr *) node)->args, context);
3560 3561 3562 3563 3564 3565 3566 3567 3568 3569
		case T_RowCompareExpr:
			{
				RowCompareExpr *rcexpr = (RowCompareExpr *) node;

				if (walker(rcexpr->largs, context))
					return true;
				if (walker(rcexpr->rargs, context))
					return true;
			}
			break;
3570 3571
		case T_CoalesceExpr:
			return walker(((CoalesceExpr *) node)->args, context);
3572 3573
		case T_MinMaxExpr:
			return walker(((MinMaxExpr *) node)->args, context);
3574 3575 3576 3577 3578 3579
		case T_XmlExpr:
			{
				XmlExpr *xexpr = (XmlExpr *) node;
				
				if (walker(xexpr->named_args, context))
					return true;
3580
				/* we assume walker doesn't care about arg_names */
3581 3582 3583 3584
				if (walker(xexpr->args, context))
					return true;
			}
			break;
3585 3586 3587 3588 3589 3590
		case T_NullIfExpr:
			return walker(((NullIfExpr *) node)->args, context);
		case T_NullTest:
			return walker(((NullTest *) node)->arg, context);
		case T_BooleanTest:
			return walker(((BooleanTest *) node)->arg, context);
3591 3592
		case T_CoerceToDomain:
			return walker(((CoerceToDomain *) node)->arg, context);
3593 3594
		case T_TargetEntry:
			return walker(((TargetEntry *) node)->expr, context);
3595 3596 3597
		case T_Query:
			/* Do nothing with a sub-Query, per discussion above */
			break;
3598 3599 3600 3601 3602 3603 3604
		case T_List:
			foreach(temp, (List *) node)
			{
				if (walker((Node *) lfirst(temp), context))
					return true;
			}
			break;
3605 3606
		case T_FromExpr:
			{
3607
				FromExpr   *from = (FromExpr *) node;
3608 3609 3610 3611 3612 3613 3614

				if (walker(from->fromlist, context))
					return true;
				if (walker(from->quals, context))
					return true;
			}
			break;
3615 3616
		case T_JoinExpr:
			{
3617
				JoinExpr   *join = (JoinExpr *) node;
3618 3619 3620 3621 3622 3623 3624

				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
3625

3626
				/*
3627
				 * alias clause, using list are deemed uninteresting.
3628 3629 3630
				 */
			}
			break;
3631 3632 3633 3634 3635 3636 3637 3638 3639 3640
		case T_SetOperationStmt:
			{
				SetOperationStmt *setop = (SetOperationStmt *) node;

				if (walker(setop->larg, context))
					return true;
				if (walker(setop->rarg, context))
					return true;
			}
			break;
3641 3642 3643 3644 3645 3646 3647 3648 3649
		case T_InClauseInfo:
			{
				InClauseInfo *ininfo = (InClauseInfo *) node;

				if (expression_tree_walker((Node *) ininfo->sub_targetlist,
										   walker, context))
					return true;
			}
			break;
3650 3651 3652 3653 3654 3655 3656 3657 3658
		case T_AppendRelInfo:
			{
				AppendRelInfo *appinfo = (AppendRelInfo *) node;

				if (expression_tree_walker((Node *) appinfo->translated_vars,
										   walker, context))
					return true;
			}
			break;
3659
		default:
3660 3661
			elog(ERROR, "unrecognized node type: %d",
				 (int) nodeTag(node));
3662 3663 3664 3665
			break;
	}
	return false;
}
3666

3667 3668 3669 3670 3671 3672 3673 3674
/*
 * 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.
3675
 *
3676 3677 3678 3679 3680
 * 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.)
3681 3682 3683 3684
 */
bool
query_tree_walker(Query *query,
				  bool (*walker) (),
3685
				  void *context,
3686
				  int flags)
3687 3688 3689 3690 3691
{
	Assert(query != NULL && IsA(query, Query));

	if (walker((Node *) query->targetList, context))
		return true;
3692 3693
	if (walker((Node *) query->returningList, context))
		return true;
3694
	if (walker((Node *) query->jointree, context))
3695
		return true;
3696 3697
	if (walker(query->setOperations, context))
		return true;
3698 3699
	if (walker(query->havingQual, context))
		return true;
3700 3701 3702 3703
	if (walker(query->limitOffset, context))
		return true;
	if (walker(query->limitCount, context))
		return true;
3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722
	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)
3723
	{
3724
		RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
3725

3726
		switch (rte->rtekind)
3727
		{
3728 3729 3730 3731 3732
			case RTE_RELATION:
			case RTE_SPECIAL:
				/* nothing to do */
				break;
			case RTE_SUBQUERY:
Bruce Momjian's avatar
Bruce Momjian committed
3733
				if (!(flags & QTW_IGNORE_RT_SUBQUERIES))
3734 3735 3736 3737
					if (walker(rte->subquery, context))
						return true;
				break;
			case RTE_JOIN:
Bruce Momjian's avatar
Bruce Momjian committed
3738
				if (!(flags & QTW_IGNORE_JOINALIASES))
3739 3740
					if (walker(rte->joinaliasvars, context))
						return true;
3741
				break;
3742 3743 3744 3745
			case RTE_FUNCTION:
				if (walker(rte->funcexpr, context))
					return true;
				break;
3746 3747 3748 3749
			case RTE_VALUES:
				if (walker(rte->values_lists, context))
					return true;
				break;
3750 3751
		}
	}
3752 3753 3754 3755
	return false;
}


3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767
/*--------------------
 * 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
3768
 *		// check for nodes that special work is required for, eg:
3769 3770 3771 3772 3773 3774 3775 3776
 *		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
3777
 *		// for any node type not specially processed, do:
3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799
 *		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.
 *
3800
 * expression_tree_mutator will handle SubLink nodes by recursing normally
3801
 * into the "testexpr" subtree (which is an expression belonging to the outer
3802 3803 3804 3805 3806 3807 3808 3809
 * 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).
 *
3810 3811
 * 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
3812 3813
 * 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
3814
 * can force appropriate behavior by recognizing SubPlan expression nodes
3815
 * and doing the right thing.
3816 3817 3818 3819
 *--------------------
 */

Node *
3820 3821 3822
expression_tree_mutator(Node *node,
						Node *(*mutator) (),
						void *context)
3823 3824
{
	/*
3825 3826
	 * The mutator has already decided not to modify the current node, but we
	 * must call the mutator for any sub-nodes.
3827 3828 3829
	 */

#define FLATCOPY(newnode, node, nodetype)  \
3830
	( (newnode) = (nodetype *) palloc(sizeof(nodetype)), \
3831 3832
	  memcpy((newnode), (node), sizeof(nodetype)) )

3833
#define CHECKFLATCOPY(newnode, node, nodetype)	\
3834
	( AssertMacro(IsA((node), nodetype)), \
3835
	  (newnode) = (nodetype *) palloc(sizeof(nodetype)), \
3836 3837 3838 3839 3840 3841 3842
	  memcpy((newnode), (node), sizeof(nodetype)) )

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

	if (node == NULL)
		return NULL;
3843 3844 3845 3846

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

3847 3848
	switch (nodeTag(node))
	{
3849 3850 3851 3852 3853
		/*
		 * Primitive node types with no expression subnodes.  Var and Const
		 * are frequent enough to deserve special cases, the others we just
		 * use copyObject for.
		 */
3854
		case T_Var:
3855 3856 3857 3858 3859 3860 3861 3862
			{
				Var	   *var = (Var *) node;
				Var	   *newnode;

				FLATCOPY(newnode, var, Var);
				return (Node *) newnode;
			}
			break;
3863
		case T_Const:
3864 3865 3866 3867 3868 3869 3870 3871 3872
			{
				Const	   *oldnode = (Const *) node;
				Const	   *newnode;

				FLATCOPY(newnode, oldnode, Const);
				/* XXX we don't bother with datumCopy; should we? */
				return (Node *) newnode;
			}
			break;
3873
		case T_Param:
3874
		case T_CoerceToDomainValue:
3875
		case T_CaseTestExpr:
3876
		case T_SetToDefault:
3877
		case T_CurrentOfExpr:
3878
		case T_RangeTblRef:
3879
		case T_OuterJoinInfo:
3880
			return (Node *) copyObject(node);
3881 3882
		case T_Aggref:
			{
3883 3884
				Aggref	   *aggref = (Aggref *) node;
				Aggref	   *newnode;
3885 3886

				FLATCOPY(newnode, aggref, Aggref);
3887
				MUTATE(newnode->args, aggref->args, List *);
3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901
				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,
3902
					   Expr *);
3903
				MUTATE(newnode->refassgnexpr, arrayref->refassgnexpr,
3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929
					   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
3930 3931
				DistinctExpr *expr = (DistinctExpr *) node;
				DistinctExpr *newnode;
3932 3933 3934 3935 3936 3937

				FLATCOPY(newnode, expr, DistinctExpr);
				MUTATE(newnode->args, expr->args, List *);
				return (Node *) newnode;
			}
			break;
3938 3939
		case T_ScalarArrayOpExpr:
			{
Bruce Momjian's avatar
Bruce Momjian committed
3940 3941
				ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
				ScalarArrayOpExpr *newnode;
3942 3943 3944 3945 3946 3947

				FLATCOPY(newnode, expr, ScalarArrayOpExpr);
				MUTATE(newnode->args, expr->args, List *);
				return (Node *) newnode;
			}
			break;
3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963
		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);
3964
				MUTATE(newnode->testexpr, sublink->testexpr, Node *);
Bruce Momjian's avatar
Bruce Momjian committed
3965

3966
				/*
3967 3968
				 * Also invoke the mutator on the sublink's Query node, so it
				 * can recurse into the sub-query if it wants to.
3969 3970
				 */
				MUTATE(newnode->subselect, sublink->subselect, Node *);
3971 3972 3973
				return (Node *) newnode;
			}
			break;
3974
		case T_SubPlan:
3975
			{
Bruce Momjian's avatar
Bruce Momjian committed
3976 3977
				SubPlan    *subplan = (SubPlan *) node;
				SubPlan    *newnode;
3978

3979
				FLATCOPY(newnode, subplan, SubPlan);
3980 3981
				/* transform testexpr */
				MUTATE(newnode->testexpr, subplan->testexpr, Node *);
3982
				/* transform args list (params to be passed to subplan) */
3983 3984
				MUTATE(newnode->args, subplan->args, List *);
				/* but not the sub-Plan itself, which is referenced as-is */
3985 3986 3987
				return (Node *) newnode;
			}
			break;
3988 3989 3990 3991 3992 3993
		case T_FieldSelect:
			{
				FieldSelect *fselect = (FieldSelect *) node;
				FieldSelect *newnode;

				FLATCOPY(newnode, fselect, FieldSelect);
3994
				MUTATE(newnode->arg, fselect->arg, Expr *);
3995 3996 3997
				return (Node *) newnode;
			}
			break;
3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009
		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;
4010 4011 4012 4013 4014 4015
		case T_RelabelType:
			{
				RelabelType *relabel = (RelabelType *) node;
				RelabelType *newnode;

				FLATCOPY(newnode, relabel, RelabelType);
4016
				MUTATE(newnode->arg, relabel->arg, Expr *);
4017 4018 4019
				return (Node *) newnode;
			}
			break;
4020 4021 4022 4023 4024 4025 4026 4027 4028 4029
		case T_CoerceViaIO:
			{
				CoerceViaIO *iocoerce = (CoerceViaIO *) node;
				CoerceViaIO *newnode;

				FLATCOPY(newnode, iocoerce, CoerceViaIO);
				MUTATE(newnode->arg, iocoerce->arg, Expr *);
				return (Node *) newnode;
			}
			break;
4030 4031 4032 4033 4034 4035 4036 4037 4038 4039
		case T_ArrayCoerceExpr:
			{
				ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
				ArrayCoerceExpr *newnode;

				FLATCOPY(newnode, acoerce, ArrayCoerceExpr);
				MUTATE(newnode->arg, acoerce->arg, Expr *);
				return (Node *) newnode;
			}
			break;
4040 4041 4042 4043 4044 4045 4046 4047 4048 4049
		case T_ConvertRowtypeExpr:
			{
				ConvertRowtypeExpr *convexpr = (ConvertRowtypeExpr *) node;
				ConvertRowtypeExpr *newnode;

				FLATCOPY(newnode, convexpr, ConvertRowtypeExpr);
				MUTATE(newnode->arg, convexpr->arg, Expr *);
				return (Node *) newnode;
			}
			break;
4050 4051 4052 4053 4054 4055
		case T_CaseExpr:
			{
				CaseExpr   *caseexpr = (CaseExpr *) node;
				CaseExpr   *newnode;

				FLATCOPY(newnode, caseexpr, CaseExpr);
4056
				MUTATE(newnode->arg, caseexpr->arg, Expr *);
4057
				MUTATE(newnode->args, caseexpr->args, List *);
4058
				MUTATE(newnode->defresult, caseexpr->defresult, Expr *);
4059 4060 4061 4062 4063 4064 4065 4066 4067
				return (Node *) newnode;
			}
			break;
		case T_CaseWhen:
			{
				CaseWhen   *casewhen = (CaseWhen *) node;
				CaseWhen   *newnode;

				FLATCOPY(newnode, casewhen, CaseWhen);
4068 4069
				MUTATE(newnode->expr, casewhen->expr, Expr *);
				MUTATE(newnode->result, casewhen->result, Expr *);
4070 4071 4072
				return (Node *) newnode;
			}
			break;
4073 4074
		case T_ArrayExpr:
			{
Bruce Momjian's avatar
Bruce Momjian committed
4075 4076
				ArrayExpr  *arrayexpr = (ArrayExpr *) node;
				ArrayExpr  *newnode;
4077 4078 4079 4080 4081 4082

				FLATCOPY(newnode, arrayexpr, ArrayExpr);
				MUTATE(newnode->elements, arrayexpr->elements, List *);
				return (Node *) newnode;
			}
			break;
4083 4084
		case T_RowExpr:
			{
Bruce Momjian's avatar
Bruce Momjian committed
4085 4086
				RowExpr    *rowexpr = (RowExpr *) node;
				RowExpr    *newnode;
4087 4088 4089 4090 4091 4092

				FLATCOPY(newnode, rowexpr, RowExpr);
				MUTATE(newnode->args, rowexpr->args, List *);
				return (Node *) newnode;
			}
			break;
4093 4094
		case T_RowCompareExpr:
			{
Bruce Momjian's avatar
Bruce Momjian committed
4095 4096
				RowCompareExpr *rcexpr = (RowCompareExpr *) node;
				RowCompareExpr *newnode;
4097 4098 4099 4100 4101 4102 4103

				FLATCOPY(newnode, rcexpr, RowCompareExpr);
				MUTATE(newnode->largs, rcexpr->largs, List *);
				MUTATE(newnode->rargs, rcexpr->rargs, List *);
				return (Node *) newnode;
			}
			break;
4104 4105 4106 4107 4108 4109 4110 4111 4112 4113
		case T_CoalesceExpr:
			{
				CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
				CoalesceExpr *newnode;

				FLATCOPY(newnode, coalesceexpr, CoalesceExpr);
				MUTATE(newnode->args, coalesceexpr->args, List *);
				return (Node *) newnode;
			}
			break;
4114 4115 4116 4117 4118 4119 4120 4121 4122 4123
		case T_MinMaxExpr:
			{
				MinMaxExpr *minmaxexpr = (MinMaxExpr *) node;
				MinMaxExpr *newnode;

				FLATCOPY(newnode, minmaxexpr, MinMaxExpr);
				MUTATE(newnode->args, minmaxexpr->args, List *);
				return (Node *) newnode;
			}
			break;
4124 4125 4126 4127 4128 4129 4130
		case T_XmlExpr:
			{
				XmlExpr *xexpr = (XmlExpr *) node;
				XmlExpr *newnode;

				FLATCOPY(newnode, xexpr, XmlExpr);
				MUTATE(newnode->named_args, xexpr->named_args, List *);
4131
				/* assume mutator does not care about arg_names */
4132 4133 4134 4135
				MUTATE(newnode->args, xexpr->args, List *);
				return (Node *) newnode;
			}
			break;
4136 4137
		case T_NullIfExpr:
			{
Bruce Momjian's avatar
Bruce Momjian committed
4138 4139
				NullIfExpr *expr = (NullIfExpr *) node;
				NullIfExpr *newnode;
4140 4141 4142 4143 4144 4145

				FLATCOPY(newnode, expr, NullIfExpr);
				MUTATE(newnode->args, expr->args, List *);
				return (Node *) newnode;
			}
			break;
4146 4147
		case T_NullTest:
			{
4148 4149
				NullTest   *ntest = (NullTest *) node;
				NullTest   *newnode;
4150 4151

				FLATCOPY(newnode, ntest, NullTest);
4152
				MUTATE(newnode->arg, ntest->arg, Expr *);
4153 4154 4155 4156 4157 4158 4159 4160 4161
				return (Node *) newnode;
			}
			break;
		case T_BooleanTest:
			{
				BooleanTest *btest = (BooleanTest *) node;
				BooleanTest *newnode;

				FLATCOPY(newnode, btest, BooleanTest);
4162
				MUTATE(newnode->arg, btest->arg, Expr *);
4163 4164 4165
				return (Node *) newnode;
			}
			break;
4166
		case T_CoerceToDomain:
4167
			{
4168 4169
				CoerceToDomain *ctest = (CoerceToDomain *) node;
				CoerceToDomain *newnode;
4170

4171
				FLATCOPY(newnode, ctest, CoerceToDomain);
4172
				MUTATE(newnode->arg, ctest->arg, Expr *);
4173 4174 4175
				return (Node *) newnode;
			}
			break;
4176
		case T_TargetEntry:
4177
			{
4178 4179
				TargetEntry *targetentry = (TargetEntry *) node;
				TargetEntry *newnode;
4180

4181 4182
				FLATCOPY(newnode, targetentry, TargetEntry);
				MUTATE(newnode->expr, targetentry->expr, Expr *);
4183 4184 4185
				return (Node *) newnode;
			}
			break;
4186 4187 4188
		case T_Query:
			/* Do nothing with a sub-Query, per discussion above */
			return node;
4189 4190
		case T_List:
			{
4191
				/*
4192 4193 4194
				 * 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!
4195
				 */
4196
				List	   *resultlist;
4197
				ListCell   *temp;
4198

4199
				resultlist = NIL;
4200 4201
				foreach(temp, (List *) node)
				{
4202 4203 4204
					resultlist = lappend(resultlist,
										 mutator((Node *) lfirst(temp),
												 context));
4205
				}
4206
				return (Node *) resultlist;
4207 4208
			}
			break;
4209 4210
		case T_FromExpr:
			{
4211 4212
				FromExpr   *from = (FromExpr *) node;
				FromExpr   *newnode;
4213 4214 4215 4216 4217 4218 4219

				FLATCOPY(newnode, from, FromExpr);
				MUTATE(newnode->fromlist, from->fromlist, List *);
				MUTATE(newnode->quals, from->quals, Node *);
				return (Node *) newnode;
			}
			break;
4220 4221
		case T_JoinExpr:
			{
4222 4223
				JoinExpr   *join = (JoinExpr *) node;
				JoinExpr   *newnode;
4224 4225 4226 4227 4228

				FLATCOPY(newnode, join, JoinExpr);
				MUTATE(newnode->larg, join->larg, Node *);
				MUTATE(newnode->rarg, join->rarg, Node *);
				MUTATE(newnode->quals, join->quals, Node *);
4229
				/* We do not mutate alias or using by default */
4230 4231 4232
				return (Node *) newnode;
			}
			break;
4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243
		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;
4244 4245 4246 4247 4248 4249 4250
		case T_InClauseInfo:
			{
				InClauseInfo *ininfo = (InClauseInfo *) node;
				InClauseInfo *newnode;

				FLATCOPY(newnode, ininfo, InClauseInfo);
				MUTATE(newnode->sub_targetlist, ininfo->sub_targetlist, List *);
4251
				/* Assume we need not make a copy of in_operators list */
4252 4253 4254
				return (Node *) newnode;
			}
			break;
4255 4256 4257 4258 4259 4260 4261 4262 4263 4264
		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;
4265
		default:
4266 4267
			elog(ERROR, "unrecognized node type: %d",
				 (int) nodeTag(node));
4268 4269 4270 4271 4272
			break;
	}
	/* can't get here, but keep compiler happy */
	return NULL;
}
4273 4274 4275 4276 4277 4278 4279 4280


/*
 * 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
4281
 * mutator intends to descend into subqueries.	It is also useful for
4282 4283
 * descending into subqueries within a mutator.
 *
4284
 * Some callers want to suppress mutating of certain items in the Query,
4285 4286 4287 4288
 * 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.)
4289 4290
 *
 * Normally the Query node itself is copied, but some callers want it to be
Bruce Momjian's avatar
Bruce Momjian committed
4291
 * modified in-place; they must pass QTW_DONT_COPY_QUERY in flags.	All
4292
 * modified substructure is safely copied in any case.
4293
 */
4294
Query *
4295 4296 4297
query_tree_mutator(Query *query,
				   Node *(*mutator) (),
				   void *context,
4298
				   int flags)
4299 4300 4301
{
	Assert(query != NULL && IsA(query, Query));

Bruce Momjian's avatar
Bruce Momjian committed
4302
	if (!(flags & QTW_DONT_COPY_QUERY))
4303
	{
Bruce Momjian's avatar
Bruce Momjian committed
4304
		Query	   *newquery;
4305 4306 4307 4308 4309

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

4310
	MUTATE(query->targetList, query->targetList, List *);
4311
	MUTATE(query->returningList, query->returningList, List *);
4312 4313 4314
	MUTATE(query->jointree, query->jointree, FromExpr *);
	MUTATE(query->setOperations, query->setOperations, Node *);
	MUTATE(query->havingQual, query->havingQual, Node *);
4315 4316
	MUTATE(query->limitOffset, query->limitOffset, Node *);
	MUTATE(query->limitCount, query->limitCount, Node *);
4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336
	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)
4337
	{
4338 4339
		RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
		RangeTblEntry *newrte;
4340

4341
		FLATCOPY(newrte, rte, RangeTblEntry);
4342
		switch (rte->rtekind)
4343
		{
4344 4345
			case RTE_RELATION:
			case RTE_SPECIAL:
4346
				/* we don't bother to copy eref, aliases, etc; OK? */
4347 4348
				break;
			case RTE_SUBQUERY:
Bruce Momjian's avatar
Bruce Momjian committed
4349
				if (!(flags & QTW_IGNORE_RT_SUBQUERIES))
4350 4351 4352 4353
				{
					CHECKFLATCOPY(newrte->subquery, rte->subquery, Query);
					MUTATE(newrte->subquery, newrte->subquery, Query *);
				}
4354 4355 4356 4357 4358
				else
				{
					/* else, copy RT subqueries as-is */
					newrte->subquery = copyObject(rte->subquery);
				}
4359 4360
				break;
			case RTE_JOIN:
Bruce Momjian's avatar
Bruce Momjian committed
4361
				if (!(flags & QTW_IGNORE_JOINALIASES))
4362
					MUTATE(newrte->joinaliasvars, rte->joinaliasvars, List *);
4363 4364 4365 4366 4367
				else
				{
					/* else, copy join aliases as-is */
					newrte->joinaliasvars = copyObject(rte->joinaliasvars);
				}
4368
				break;
4369 4370 4371
			case RTE_FUNCTION:
				MUTATE(newrte->funcexpr, rte->funcexpr, Node *);
				break;
4372 4373 4374
			case RTE_VALUES:
				MUTATE(newrte->values_lists, rte->values_lists, List *);
				break;
4375
		}
4376
		newrt = lappend(newrt, newrte);
4377
	}
4378
	return newrt;
4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424
}

/*
 * 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);
4425
}