clauses.c 89.2 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * clauses.c
4
 *	  routines to manipulate qualification clauses
5
 *
Bruce Momjian's avatar
Bruce Momjian committed
6
 * Portions Copyright (c) 1996-2003, 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.170 2004/05/10 22:44:45 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_language.h"
23 24 25
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "executor/executor.h"
26
#include "miscadmin.h"
27 28
#include "nodes/makefuncs.h"
#include "optimizer/clauses.h"
29
#include "optimizer/cost.h"
30
#include "optimizer/planmain.h"
31
#include "optimizer/var.h"
32
#include "parser/analyze.h"
33
#include "parser/parse_clause.h"
34
#include "parser/parse_expr.h"
35 36 37
#include "tcop/tcopprot.h"
#include "utils/acl.h"
#include "utils/builtins.h"
38
#include "utils/datum.h"
Bruce Momjian's avatar
Bruce Momjian committed
39
#include "utils/lsyscache.h"
40
#include "utils/memutils.h"
41
#include "utils/syscache.h"
42

43

44 45 46 47 48
typedef struct
{
	int			nargs;
	List	   *args;
	int		   *usecounts;
49
} substitute_actual_parameters_context;
50

51
static bool contain_agg_clause_walker(Node *node, void *context);
52
static bool contain_distinct_agg_clause_walker(Node *node, void *context);
53
static bool count_agg_clause_walker(Node *node, int *count);
54
static bool expression_returns_set_walker(Node *node, void *context);
55
static bool contain_subplans_walker(Node *node, void *context);
56 57
static bool contain_mutable_functions_walker(Node *node, void *context);
static bool contain_volatile_functions_walker(Node *node, void *context);
58
static bool contain_nonstrict_functions_walker(Node *node, void *context);
59
static bool set_coercionform_dontcare_walker(Node *node, void *context);
60
static Node *eval_const_expressions_mutator(Node *node, List *active_fns);
61 62 63 64
static List *simplify_or_arguments(List *args,
								   bool *haveNull, bool *forceTrue);
static List *simplify_and_arguments(List *args,
									bool *haveNull, bool *forceFalse);
65
static Expr *simplify_function(Oid funcid, Oid result_type, List *args,
Bruce Momjian's avatar
Bruce Momjian committed
66
				  bool allow_inline, List *active_fns);
67
static Expr *evaluate_function(Oid funcid, Oid result_type, List *args,
Bruce Momjian's avatar
Bruce Momjian committed
68
				  HeapTuple func_tuple);
69
static Expr *inline_function(Oid funcid, Oid result_type, List *args,
Bruce Momjian's avatar
Bruce Momjian committed
70
				HeapTuple func_tuple, List *active_fns);
71
static Node *substitute_actual_parameters(Node *expr, int nargs, List *args,
Bruce Momjian's avatar
Bruce Momjian committed
72
							 int *usecounts);
73
static Node *substitute_actual_parameters_mutator(Node *node,
74
						  substitute_actual_parameters_context *context);
75
static void sql_inline_error_callback(void *arg);
76
static Expr *evaluate_expr(Expr *expr, Oid result_type);
77

78 79

/*****************************************************************************
80
 *		OPERATOR clause functions
81 82
 *****************************************************************************/

83
/*
84
 * make_opclause
85 86
 *	  Creates an operator clause given its operator info, left operand,
 *	  and right operand (pass NULL to create single-operand clause).
87
 */
88
Expr *
89 90
make_opclause(Oid opno, Oid opresulttype, bool opretset,
			  Expr *leftop, Expr *rightop)
91
{
92
	OpExpr	   *expr = makeNode(OpExpr);
93

94 95 96 97
	expr->opno = opno;
	expr->opfuncid = InvalidOid;
	expr->opresulttype = opresulttype;
	expr->opretset = opretset;
98
	if (rightop)
99
		expr->args = makeList2(leftop, rightop);
100
	else
101
		expr->args = makeList1(leftop);
102
	return (Expr *) expr;
103 104
}

105
/*
106
 * get_leftop
107
 *
108
 * Returns the left operand of a clause of the form (op expr expr)
109
 *		or (op expr)
110
 */
111
Node *
112
get_leftop(Expr *clause)
113
{
Bruce Momjian's avatar
Bruce Momjian committed
114
	OpExpr	   *expr = (OpExpr *) clause;
115

116
	if (expr->args != NIL)
117
		return lfirst(expr->args);
118 119
	else
		return NULL;
120 121
}

122
/*
123
 * get_rightop
124
 *
125
 * Returns the right operand in a clause of the form (op expr expr).
126
 * NB: result will be NULL if applied to a unary op clause.
127
 */
128
Node *
129
get_rightop(Expr *clause)
130
{
Bruce Momjian's avatar
Bruce Momjian committed
131
	OpExpr	   *expr = (OpExpr *) clause;
132

133
	if (expr->args != NIL && lnext(expr->args) != NIL)
134
		return lfirst(lnext(expr->args));
135 136
	else
		return NULL;
137 138 139
}

/*****************************************************************************
140
 *		NOT clause functions
141 142
 *****************************************************************************/

143
/*
144
 * not_clause
145
 *
146
 * Returns t iff this is a 'not' clause: (NOT expr).
147 148
 */
bool
149
not_clause(Node *clause)
150
{
151
	return (clause != NULL &&
152 153
			IsA(clause, BoolExpr) &&
			((BoolExpr *) clause)->boolop == NOT_EXPR);
154 155
}

156
/*
157
 * make_notclause
158
 *
159
 * Create a 'not' clause given the expression to be negated.
160
 */
161
Expr *
162
make_notclause(Expr *notclause)
163
{
164
	BoolExpr   *expr = makeNode(BoolExpr);
165

166 167 168
	expr->boolop = NOT_EXPR;
	expr->args = makeList1(notclause);
	return (Expr *) expr;
169 170
}

171
/*
172
 * get_notclausearg
173
 *
174
 * Retrieve the clause within a 'not' clause
175
 */
176 177
Expr *
get_notclausearg(Expr *notclause)
178
{
179
	return lfirst(((BoolExpr *) notclause)->args);
180 181
}

182 183 184 185
/*****************************************************************************
 *		OR clause functions
 *****************************************************************************/

186
/*
187
 * or_clause
188
 *
189
 * Returns t iff the clause is an 'or' clause: (OR { expr }).
190
 */
191 192
bool
or_clause(Node *clause)
193
{
194 195 196
	return (clause != NULL &&
			IsA(clause, BoolExpr) &&
			((BoolExpr *) clause)->boolop == OR_EXPR);
197 198
}

199
/*
200
 * make_orclause
201
 *
202
 * Creates an 'or' clause given a list of its subclauses.
203
 */
204
Expr *
205
make_orclause(List *orclauses)
206
{
207 208 209 210 211
	BoolExpr   *expr = makeNode(BoolExpr);

	expr->boolop = OR_EXPR;
	expr->args = orclauses;
	return (Expr *) expr;
212 213 214
}

/*****************************************************************************
215
 *		AND clause functions
216 217 218
 *****************************************************************************/


219
/*
220
 * and_clause
221
 *
222 223 224
 * Returns t iff its argument is an 'and' clause: (AND { expr }).
 */
bool
225
and_clause(Node *clause)
226
{
227
	return (clause != NULL &&
228 229
			IsA(clause, BoolExpr) &&
			((BoolExpr *) clause)->boolop == AND_EXPR);
230
}
231 232

/*
233
 * make_andclause
234
 *
235
 * Creates an 'and' clause given a list of its subclauses.
236
 */
237
Expr *
238
make_andclause(List *andclauses)
239
{
240
	BoolExpr   *expr = makeNode(BoolExpr);
241

242
	expr->boolop = AND_EXPR;
243
	expr->args = andclauses;
244
	return (Expr *) expr;
245 246
}

247 248 249 250 251 252
/*
 * 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'.
253 254 255
 *
 * 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.
256 257 258 259 260 261 262 263 264 265 266
 */
Node *
make_and_qual(Node *qual1, Node *qual2)
{
	if (qual1 == NULL)
		return qual2;
	if (qual2 == NULL)
		return qual1;
	return (Node *) make_andclause(makeList2(qual1, qual2));
}

267
/*
268 269
 * Sometimes (such as in the input of ExecQual), we use lists of expression
 * nodes with implicit AND semantics.
270 271 272 273 274
 *
 * 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.
275 276 277 278 279
 */
Expr *
make_ands_explicit(List *andclauses)
{
	if (andclauses == NIL)
280
		return (Expr *) makeBoolConst(true, false);
281
	else if (lnext(andclauses) == NIL)
282 283 284 285
		return (Expr *) lfirst(andclauses);
	else
		return make_andclause(andclauses);
}
286

287 288 289
List *
make_ands_implicit(Expr *clause)
{
290 291 292
	/*
	 * 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,
293 294
	 * even though one might more reasonably think it FALSE.  Grumble. If
	 * this causes trouble, consider changing the parser's behavior.
295
	 */
296
	if (clause == NULL)
297
		return NIL;				/* NULL -> NIL list == TRUE */
298
	else if (and_clause((Node *) clause))
299
		return ((BoolExpr *) clause)->args;
300
	else if (IsA(clause, Const) &&
301
			 !((Const *) clause)->constisnull &&
302
			 DatumGetBool(((Const *) clause)->constvalue))
303
		return NIL;				/* constant TRUE input -> NIL list */
304
	else
305
		return makeList1(clause);
306 307
}

308

309
/*****************************************************************************
310
 *		Aggregate-function clause manipulation
311 312
 *****************************************************************************/

313 314 315 316 317
/*
 * contain_agg_clause
 *	  Recursively search for Aggref nodes within a clause.
 *
 *	  Returns true if any aggregate found.
318 319 320 321 322 323 324
 *
 * 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().)
325 326 327 328 329 330 331 332 333 334 335 336 337
 */
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))
338 339
	{
		Assert(((Aggref *) node)->agglevelsup == 0);
340 341
		return true;			/* abort the tree traversal and return
								 * true */
342 343
	}
	Assert(!IsA(node, SubLink));
344 345 346
	return expression_tree_walker(node, contain_agg_clause_walker, context);
}

347 348 349 350 351
/*
 * contain_distinct_agg_clause
 *	  Recursively search for DISTINCT Aggref nodes within a clause.
 *
 *	  Returns true if any DISTINCT aggregate found.
352 353 354 355
 *
 * 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.
356 357 358 359 360 361 362 363 364 365 366 367 368 369
 */
bool
contain_distinct_agg_clause(Node *clause)
{
	return contain_distinct_agg_clause_walker(clause, NULL);
}

static bool
contain_distinct_agg_clause_walker(Node *node, void *context)
{
	if (node == NULL)
		return false;
	if (IsA(node, Aggref))
	{
370
		Assert(((Aggref *) node)->agglevelsup == 0);
371 372 373 374
		if (((Aggref *) node)->aggdistinct)
			return true;		/* abort the tree traversal and return
								 * true */
	}
375
	Assert(!IsA(node, SubLink));
376 377 378
	return expression_tree_walker(node, contain_distinct_agg_clause_walker, context);
}

379
/*
380 381
 * count_agg_clause
 *	  Recursively count the Aggref nodes in an expression tree.
382 383
 *
 *	  Note: this also checks for nested aggregates, which are an error.
384 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
int
count_agg_clause(Node *clause)
391
{
392
	int			result = 0;
393

394
	count_agg_clause_walker(clause, &result);
395 396 397 398
	return result;
}

static bool
399
count_agg_clause_walker(Node *node, int *count)
400 401 402 403 404
{
	if (node == NULL)
		return false;
	if (IsA(node, Aggref))
	{
405
		Assert(((Aggref *) node)->agglevelsup == 0);
406
		(*count)++;
407

408 409 410
		/*
		 * Complain if the aggregate's argument contains any aggregates;
		 * nested agg functions are semantically nonsensical.
411
		 */
412
		if (contain_agg_clause((Node *) ((Aggref *) node)->target))
413 414
			ereport(ERROR,
					(errcode(ERRCODE_GROUPING_ERROR),
Bruce Momjian's avatar
Bruce Momjian committed
415
				  errmsg("aggregate function calls may not be nested")));
416

417 418 419 420
		/*
		 * Having checked that, we need not recurse into the argument.
		 */
		return false;
421
	}
422
	Assert(!IsA(node, SubLink));
423 424
	return expression_tree_walker(node, count_agg_clause_walker,
								  (void *) count);
425 426
}

427

428
/*****************************************************************************
429
 *		Support for expressions returning sets
430 431 432
 *****************************************************************************/

/*
433
 * expression_returns_set
434
 *	  Test whether an expression returns a set result.
435
 *
436 437 438
 * 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.
439 440
 */
bool
441
expression_returns_set(Node *clause)
442
{
443
	return expression_returns_set_walker(clause, NULL);
444 445 446
}

static bool
447
expression_returns_set_walker(Node *node, void *context)
448 449 450
{
	if (node == NULL)
		return false;
451
	if (IsA(node, FuncExpr))
452
	{
453
		FuncExpr   *expr = (FuncExpr *) node;
454

455 456 457 458 459 460
		if (expr->funcretset)
			return true;
		/* else fall through to check args */
	}
	if (IsA(node, OpExpr))
	{
Bruce Momjian's avatar
Bruce Momjian committed
461
		OpExpr	   *expr = (OpExpr *) node;
462 463 464 465 466 467 468

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

	/* Avoid recursion for some cases that can't return a set */
469 470
	if (IsA(node, Aggref))
		return false;
471 472
	if (IsA(node, DistinctExpr))
		return false;
473 474
	if (IsA(node, ScalarArrayOpExpr))
		return false;
475 476
	if (IsA(node, BoolExpr))
		return false;
477 478
	if (IsA(node, SubLink))
		return false;
479
	if (IsA(node, SubPlan))
480
		return false;
481 482
	if (IsA(node, ArrayExpr))
		return false;
483 484
	if (IsA(node, RowExpr))
		return false;
485 486 487 488
	if (IsA(node, CoalesceExpr))
		return false;
	if (IsA(node, NullIfExpr))
		return false;
489

490 491
	return expression_tree_walker(node, expression_returns_set_walker,
								  context);
492 493
}

494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
/*****************************************************************************
 *		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;
520
	if (IsA(node, SubPlan) ||
521
		IsA(node, SubLink))
522 523
		return true;			/* abort the tree traversal and return
								 * true */
524 525 526
	return expression_tree_walker(node, contain_subplans_walker, context);
}

527

528
/*****************************************************************************
529
 *		Check clauses for mutable functions
530 531
 *****************************************************************************/

532
/*
533 534
 * contain_mutable_functions
 *	  Recursively search for mutable functions within a clause.
535
 *
536 537
 * Returns true if any mutable function (or operator implemented by a
 * mutable function) is found.	This test is needed so that we don't
538 539 540
 * mistakenly think that something like "WHERE random() < 0.5" can be treated
 * as a constant qualification.
 *
541
 * XXX we do not examine sub-selects to see if they contain uses of
542
 * mutable functions.  It's not real clear if that is correct or not...
543 544
 */
bool
545
contain_mutable_functions(Node *clause)
546
{
547
	return contain_mutable_functions_walker(clause, NULL);
548 549 550
}

static bool
551
contain_mutable_functions_walker(Node *node, void *context)
552 553 554
{
	if (node == NULL)
		return false;
555
	if (IsA(node, FuncExpr))
556
	{
557
		FuncExpr   *expr = (FuncExpr *) node;
558

559 560 561 562 563 564
		if (func_volatile(expr->funcid) != PROVOLATILE_IMMUTABLE)
			return true;
		/* else fall through to check args */
	}
	if (IsA(node, OpExpr))
	{
Bruce Momjian's avatar
Bruce Momjian committed
565
		OpExpr	   *expr = (OpExpr *) node;
566 567 568 569 570 571 572

		if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE)
			return true;
		/* else fall through to check args */
	}
	if (IsA(node, DistinctExpr))
	{
Bruce Momjian's avatar
Bruce Momjian committed
573
		DistinctExpr *expr = (DistinctExpr *) node;
574 575 576 577

		if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE)
			return true;
		/* else fall through to check args */
578
	}
579 580
	if (IsA(node, ScalarArrayOpExpr))
	{
Bruce Momjian's avatar
Bruce Momjian committed
581
		ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
582 583 584 585 586

		if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE)
			return true;
		/* else fall through to check args */
	}
587 588
	if (IsA(node, NullIfExpr))
	{
Bruce Momjian's avatar
Bruce Momjian committed
589
		NullIfExpr *expr = (NullIfExpr *) node;
590 591 592 593 594

		if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE)
			return true;
		/* else fall through to check args */
	}
595 596
	if (IsA(node, SubLink))
	{
Bruce Momjian's avatar
Bruce Momjian committed
597
		SubLink    *sublink = (SubLink *) node;
598 599 600 601
		List	   *opid;

		foreach(opid, sublink->operOids)
		{
602
			if (op_volatile(lfirsto(opid)) != PROVOLATILE_IMMUTABLE)
603 604 605 606
				return true;
		}
		/* else fall through to check args */
	}
607 608 609 610 611 612 613 614 615 616 617 618 619 620
	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
621
 * volatile function) is found. This test prevents invalid conversions
622 623
 * of volatile expressions into indexscan quals.
 *
624
 * XXX we do not examine sub-selects to see if they contain uses of
Bruce Momjian's avatar
Bruce Momjian committed
625
 * volatile functions.	It's not real clear if that is correct or not...
626 627 628 629 630 631 632 633 634 635 636 637
 */
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;
638
	if (IsA(node, FuncExpr))
639
	{
640
		FuncExpr   *expr = (FuncExpr *) node;
641

642 643 644 645 646 647
		if (func_volatile(expr->funcid) == PROVOLATILE_VOLATILE)
			return true;
		/* else fall through to check args */
	}
	if (IsA(node, OpExpr))
	{
Bruce Momjian's avatar
Bruce Momjian committed
648
		OpExpr	   *expr = (OpExpr *) node;
649 650 651 652 653 654 655

		if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE)
			return true;
		/* else fall through to check args */
	}
	if (IsA(node, DistinctExpr))
	{
Bruce Momjian's avatar
Bruce Momjian committed
656
		DistinctExpr *expr = (DistinctExpr *) node;
657 658 659 660

		if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE)
			return true;
		/* else fall through to check args */
661
	}
662 663
	if (IsA(node, ScalarArrayOpExpr))
	{
Bruce Momjian's avatar
Bruce Momjian committed
664
		ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
665 666 667 668 669

		if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE)
			return true;
		/* else fall through to check args */
	}
670 671
	if (IsA(node, NullIfExpr))
	{
Bruce Momjian's avatar
Bruce Momjian committed
672
		NullIfExpr *expr = (NullIfExpr *) node;
673 674 675 676 677

		if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE)
			return true;
		/* else fall through to check args */
	}
678 679
	if (IsA(node, SubLink))
	{
Bruce Momjian's avatar
Bruce Momjian committed
680
		SubLink    *sublink = (SubLink *) node;
681 682 683 684
		List	   *opid;

		foreach(opid, sublink->operOids)
		{
685
			if (op_volatile(lfirsto(opid)) == PROVOLATILE_VOLATILE)
686 687 688 689
				return true;
		}
		/* else fall through to check args */
	}
690
	return expression_tree_walker(node, contain_volatile_functions_walker,
691 692 693 694
								  context);
}


695 696 697 698 699 700 701 702 703 704 705
/*****************************************************************************
 *		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.
 *
706 707 708 709
 * 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
 * inputs is NULL.  If we return false, then the proof succeeded.
710 711 712 713 714 715 716 717 718 719 720 721
 */
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;
722 723 724 725 726
	if (IsA(node, Aggref))
	{
		/* an aggregate could return non-null with null input */
		return true;
	}
727 728 729 730 731 732 733 734 735 736
	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
737
		OpExpr	   *expr = (OpExpr *) node;
738 739 740 741 742 743 744 745 746 747

		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;
	}
748 749 750 751 752
	if (IsA(node, ScalarArrayOpExpr))
	{
		/* inherently non-strict, consider null scalar and empty array */
		return true;
	}
753
	if (IsA(node, BoolExpr))
754
	{
755
		BoolExpr   *expr = (BoolExpr *) node;
756

757
		switch (expr->boolop)
758 759
		{
			case AND_EXPR:
760 761
			case OR_EXPR:
				/* AND, OR are inherently non-strict */
762 763 764 765 766
				return true;
			default:
				break;
		}
	}
767 768 769 770 771 772 773
	if (IsA(node, SubLink))
	{
		/* In some cases a sublink might be strict, but in general not */
		return true;
	}
	if (IsA(node, SubPlan))
		return true;
774 775
	if (IsA(node, CaseExpr))
		return true;
776 777
	if (IsA(node, CaseWhen))
		return true;
778
	/* NB: ArrayExpr might someday be nonstrict */
779 780
	if (IsA(node, RowExpr))
		return true;
781 782 783 784
	if (IsA(node, CoalesceExpr))
		return true;
	if (IsA(node, NullIfExpr))
		return true;
785 786 787 788 789 790 791 792 793
	if (IsA(node, NullTest))
		return true;
	if (IsA(node, BooleanTest))
		return true;
	return expression_tree_walker(node, contain_nonstrict_functions_walker,
								  context);
}


794 795 796
/*****************************************************************************
 *		Check for "pseudo-constant" clauses
 *****************************************************************************/
797 798

/*
799 800
 * is_pseudo_constant_clause
 *	  Detect whether a clause is "constant", ie, it contains no variables
801
 *	  of the current query level and no uses of volatile functions.
802
 *	  Such a clause is not necessarily a true constant: it can still contain
803
 *	  Params and outer-level Vars, not to mention functions whose results
Bruce Momjian's avatar
Bruce Momjian committed
804
 *	  may vary from one statement to the next.	However, the clause's value
805 806 807
 *	  will be constant over any one scan of the current query, so it can be
 *	  used as an indexscan key or (if a top-level qual) can be pushed up to
 *	  become a gating qual.
808 809 810 811 812 813
 */
bool
is_pseudo_constant_clause(Node *clause)
{
	/*
	 * We could implement this check in one recursive scan.  But since the
814
	 * check for volatile functions is both moderately expensive and
815
	 * unlikely to fail, it seems better to look for Vars first and only
816
	 * check for volatile functions if we find no Vars.
817 818
	 */
	if (!contain_var_clause(clause) &&
819
		!contain_volatile_functions(clause))
820 821 822 823
		return true;
	return false;
}

824 825 826 827 828 829 830 831 832 833 834 835 836 837
/*
 * is_pseudo_constant_clause_relids
 *	  Same as above, except caller already has available the var membership
 *	  of the clause; this lets us avoid the contain_var_clause() scan.
 */
bool
is_pseudo_constant_clause_relids(Node *clause, Relids relids)
{
	if (bms_is_empty(relids) &&
		!contain_volatile_functions(clause))
		return true;
	return false;
}

838
/*
839
 * pull_constant_clauses
840 841
 *		Scan through a list of qualifications and separate "constant" quals
 *		from those that are not.
842
 *
843 844
 * Returns a list of the pseudo-constant clauses in constantQual and the
 * remaining quals as the return value.
845 846
 */
List *
847
pull_constant_clauses(List *quals, List **constantQual)
848
{
849 850
	FastList	constqual,
				restqual;
851
	List	   *q;
852

853 854 855
	FastListInit(&constqual);
	FastListInit(&restqual);

856 857
	foreach(q, quals)
	{
858
		Node	   *qual = (Node *) lfirst(q);
859

860
		if (is_pseudo_constant_clause(qual))
861
			FastAppend(&constqual, qual);
862
		else
863
			FastAppend(&restqual, qual);
864
	}
865 866
	*constantQual = FastListValue(&constqual);
	return FastListValue(&restqual);
867 868 869
}


870 871 872 873 874 875 876 877 878 879
/*****************************************************************************
 *		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
880
 * not the same as the set of output columns.
881 882 883 884
 */
bool
has_distinct_on_clause(Query *query)
{
885
	List	   *targetList;
886 887 888 889

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

891
	/*
892 893
	 * If the DISTINCT list contains all the nonjunk targetlist items, and
	 * nothing else (ie, no junk tlist items), then it's a simple
894 895
	 * 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
896 897 898 899
	 * 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.
900 901 902
	 *
	 * This code assumes that the DISTINCT list is valid, ie, all its entries
	 * match some entry of the tlist.
903 904 905 906 907
	 */
	foreach(targetList, query->targetList)
	{
		TargetEntry *tle = (TargetEntry *) lfirst(targetList);

908
		if (tle->resdom->ressortgroupref == 0)
909 910 911
		{
			if (tle->resdom->resjunk)
				continue;		/* we can ignore unsorted junk cols */
912
			return true;		/* definitely not in DISTINCT list */
913
		}
914
		if (targetIsInSortList(tle, query->distinctClause))
915
		{
916 917 918 919 920 921 922 923 924
			if (tle->resdom->resjunk)
				return true;	/* junk TLE in DISTINCT means DISTINCT ON */
			/* else this TLE is okay, keep looking */
		}
		else
		{
			/* This TLE is not in DISTINCT list */
			if (!tle->resdom->resjunk)
				return true;	/* non-junk, non-DISTINCT, so DISTINCT ON */
925
			if (targetIsInSortList(tle, query->sortClause))
926 927
				return true;	/* sorted, non-distinct junk */
			/* unsorted junk is okay, keep looking */
928 929 930 931 932 933
		}
	}
	/* It's a simple DISTINCT */
	return false;
}

934 935 936 937 938 939 940 941 942 943 944 945 946 947 948
/*
 * 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);
}

949

950 951 952 953 954 955
/*****************************************************************************
 *																			 *
 *		General clause-manipulating routines								 *
 *																			 *
 *****************************************************************************/

956
/*
957 958
 * NumRelids
 *		(formerly clause_relids)
959
 *
960 961 962
 * Returns the number of different relations referenced in 'clause'.
 */
int
963
NumRelids(Node *clause)
964
{
965 966
	Relids		varnos = pull_varnos(clause);
	int			result = bms_num_members(varnos);
967

968
	bms_free(varnos);
969
	return result;
970 971
}

972
/*
973
 * CommuteClause: commute a binary operator clause
974 975
 *
 * XXX the clause is destructively modified!
976
 */
977
void
978
CommuteClause(OpExpr *clause)
979
{
980
	Oid			opoid;
981
	Node	   *temp;
982

983
	/* Sanity checks: caller is at fault if these fail */
984
	if (!is_opclause(clause) ||
985
		length(clause->args) != 2)
986
		elog(ERROR, "cannot commute non-binary-operator clause");
987

988
	opoid = get_commutator(clause->opno);
989

990
	if (!OidIsValid(opoid))
991
		elog(ERROR, "could not find commutator for operator %u",
992
			 clause->opno);
993

994
	/*
995
	 * modify the clause in-place!
996
	 */
997 998 999 1000
	clause->opno = opoid;
	clause->opfuncid = InvalidOid;
	/* opresulttype and opretset are assumed not to change */

1001 1002 1003
	temp = lfirst(clause->args);
	lfirst(clause->args) = lsecond(clause->args);
	lsecond(clause->args) = temp;
1004
}
1005

1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
/*
 * 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;
	if (IsA(node, RelabelType))
		((RelabelType *) node)->relabelformat = COERCE_DONTCARE;
1033 1034
	if (IsA(node, RowExpr))
		((RowExpr *) node)->row_format = COERCE_DONTCARE;
1035 1036 1037 1038 1039 1040
	if (IsA(node, CoerceToDomain))
		((CoerceToDomain *) node)->coercionformat = COERCE_DONTCARE;
	return expression_tree_walker(node, set_coercionform_dontcare_walker,
								  context);
}

1041

1042 1043 1044 1045 1046 1047 1048
/*--------------------
 * 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
1049
 * the subexpression x is.	(XXX We assume that no such subexpression
1050 1051 1052 1053 1054 1055
 * 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
1056
 * example.  Functions that are not marked "immutable" in pg_proc
1057
 * will not be pre-evaluated here, although we will reduce their
1058
 * arguments as far as possible.
1059 1060 1061 1062 1063 1064 1065 1066
 *
 * We assume that the tree has already been type-checked and contains
 * only operators and functions that are reasonable to try to execute.
 *--------------------
 */
Node *
eval_const_expressions(Node *node)
{
1067 1068 1069 1070 1071
	/*
	 * The context for the mutator is a list of SQL functions being
	 * recursively simplified, so we start with an empty list.
	 */
	return eval_const_expressions_mutator(node, NIL);
1072 1073 1074
}

static Node *
1075
eval_const_expressions_mutator(Node *node, List *active_fns)
1076 1077 1078
{
	if (node == NULL)
		return NULL;
1079
	if (IsA(node, FuncExpr))
1080
	{
1081
		FuncExpr   *expr = (FuncExpr *) node;
1082
		List	   *args;
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
		Expr	   *simple;
		FuncExpr   *newexpr;

		/*
		 * Reduce constants in the FuncExpr'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.
		 */
		args = (List *) expression_tree_mutator((Node *) expr->args,
										  eval_const_expressions_mutator,
												(void *) active_fns);
Bruce Momjian's avatar
Bruce Momjian committed
1094

1095
		/*
Bruce Momjian's avatar
Bruce Momjian committed
1096 1097
		 * Code for op/func reduction is pretty bulky, so split it out as
		 * a separate function.
1098
		 */
1099 1100
		simple = simplify_function(expr->funcid, expr->funcresulttype, args,
								   true, active_fns);
1101 1102
		if (simple)				/* successfully simplified it */
			return (Node *) simple;
Bruce Momjian's avatar
Bruce Momjian committed
1103

1104 1105
		/*
		 * The expression cannot be simplified any further, so build and
Bruce Momjian's avatar
Bruce Momjian committed
1106 1107
		 * return a replacement FuncExpr node using the
		 * possibly-simplified arguments.
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
		 */
		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;
1123 1124

		/*
1125 1126 1127 1128 1129 1130 1131
		 * 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.
		 */
		args = (List *) expression_tree_mutator((Node *) expr->args,
										  eval_const_expressions_mutator,
												(void *) active_fns);
Bruce Momjian's avatar
Bruce Momjian committed
1132

1133
		/*
Bruce Momjian's avatar
Bruce Momjian committed
1134
		 * Need to get OID of underlying function.	Okay to scribble on
1135 1136 1137
		 * input to this extent.
		 */
		set_opfuncid(expr);
Bruce Momjian's avatar
Bruce Momjian committed
1138

1139
		/*
Bruce Momjian's avatar
Bruce Momjian committed
1140 1141
		 * Code for op/func reduction is pretty bulky, so split it out as
		 * a separate function.
1142
		 */
1143 1144
		simple = simplify_function(expr->opfuncid, expr->opresulttype, args,
								   true, active_fns);
1145 1146
		if (simple)				/* successfully simplified it */
			return (Node *) simple;
Bruce Momjian's avatar
Bruce Momjian committed
1147

1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
		/*
		 * 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;
		List	   *arg;
		bool		has_null_input = false;
		bool		all_null_input = true;
		bool		has_nonconst_input = false;
		Expr	   *simple;
		DistinctExpr *newexpr;

		/*
Bruce Momjian's avatar
Bruce Momjian committed
1173 1174
		 * Reduce constants in the DistinctExpr's arguments.  We know args
		 * is either NIL or a List node, so we can call
1175
		 * expression_tree_mutator directly rather than recursing to self.
1176 1177
		 */
		args = (List *) expression_tree_mutator((Node *) expr->args,
Bruce Momjian's avatar
Bruce Momjian committed
1178
										  eval_const_expressions_mutator,
1179
												(void *) active_fns);
1180

1181
		/*
Bruce Momjian's avatar
Bruce Momjian committed
1182 1183 1184
		 * We must do our own check for NULLs because DistinctExpr has
		 * different results for NULL input than the underlying operator
		 * does.
1185 1186
		 */
		foreach(arg, args)
1187
		{
1188 1189 1190 1191 1192 1193 1194 1195
			if (IsA(lfirst(arg), Const))
			{
				has_null_input |= ((Const *) lfirst(arg))->constisnull;
				all_null_input &= ((Const *) lfirst(arg))->constisnull;
			}
			else
				has_nonconst_input = true;
		}
1196

1197 1198 1199 1200 1201
		/* all constants? then can optimize this out */
		if (!has_nonconst_input)
		{
			/* all nulls? then not distinct */
			if (all_null_input)
1202
				return makeBoolConst(false, false);
1203

1204 1205
			/* one null? then distinct */
			if (has_null_input)
1206
				return makeBoolConst(true, false);
1207

1208 1209
			/* otherwise try to evaluate the '=' operator */
			/* (NOT okay to try to inline it, though!) */
1210

1211
			/*
Bruce Momjian's avatar
Bruce Momjian committed
1212 1213
			 * Need to get OID of underlying function.	Okay to scribble
			 * on input to this extent.
1214
			 */
Bruce Momjian's avatar
Bruce Momjian committed
1215 1216 1217
			set_opfuncid((OpExpr *) expr);		/* rely on struct
												 * equivalence */

1218 1219 1220 1221
			/*
			 * Code for op/func reduction is pretty bulky, so split it out
			 * as a separate function.
			 */
1222 1223
			simple = simplify_function(expr->opfuncid, expr->opresulttype,
									   args, false, active_fns);
1224
			if (simple)			/* successfully simplified it */
1225 1226 1227 1228 1229
			{
				/*
				 * Since the underlying operator is "=", must negate its
				 * result
				 */
Bruce Momjian's avatar
Bruce Momjian committed
1230
				Const	   *csimple = (Const *) simple;
1231 1232 1233 1234 1235 1236

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

1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
		/*
		 * 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;
		List	   *args;

		/*
		 * Reduce constants in the BoolExpr'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.
		 */
		args = (List *) expression_tree_mutator((Node *) expr->args,
										  eval_const_expressions_mutator,
												(void *) active_fns);

		switch (expr->boolop)
		{
1268
			case OR_EXPR:
1269
				{
1270
					List	   *newargs;
1271 1272 1273
					bool		haveNull = false;
					bool		forceTrue = false;

1274 1275
					newargs = simplify_or_arguments(args,
													&haveNull, &forceTrue);
1276
					if (forceTrue)
1277
						return makeBoolConst(true, false);
1278
					if (haveNull)
1279
						newargs = lappend(newargs, makeBoolConst(false, true));
1280
					/* If all the inputs are FALSE, result is FALSE */
1281
					if (newargs == NIL)
1282
						return makeBoolConst(false, false);
1283
					/* If only one nonconst-or-NULL input, it's the result */
1284 1285
					if (lnext(newargs) == NIL)
						return (Node *) lfirst(newargs);
1286
					/* Else we still need an OR node */
1287
					return (Node *) make_orclause(newargs);
1288 1289 1290
				}
			case AND_EXPR:
				{
1291
					List	   *newargs;
1292 1293 1294
					bool		haveNull = false;
					bool		forceFalse = false;

1295 1296
					newargs = simplify_and_arguments(args,
													 &haveNull, &forceFalse);
1297
					if (forceFalse)
1298
						return makeBoolConst(false, false);
1299
					if (haveNull)
1300
						newargs = lappend(newargs, makeBoolConst(false, true));
1301
					/* If all the inputs are TRUE, result is TRUE */
1302
					if (newargs == NIL)
1303
						return makeBoolConst(true, false);
1304
					/* If only one nonconst-or-NULL input, it's the result */
1305 1306
					if (lnext(newargs) == NIL)
						return (Node *) lfirst(newargs);
1307
					/* Else we still need an AND node */
1308
					return (Node *) make_andclause(newargs);
1309 1310 1311
				}
			case NOT_EXPR:
				Assert(length(args) == 1);
1312 1313
				if (IsA(lfirst(args), Const))
				{
1314 1315
					Const *const_input = (Const *) lfirst(args);

1316 1317
					/* NOT NULL => NULL */
					if (const_input->constisnull)
1318
						return makeBoolConst(false, true);
1319
					/* otherwise pretty easy */
1320
					return makeBoolConst(!DatumGetBool(const_input->constvalue),
1321 1322
										 false);
				}
1323 1324 1325 1326 1327
				else if (not_clause((Node *) lfirst(args)))
				{
					/* Cancel NOT/NOT */
					return (Node *) get_notclausearg((Expr *) lfirst(args));
				}
1328
				/* Else we still need a NOT node */
1329
				return (Node *) make_notclause((Expr *) lfirst(args));
1330
			default:
1331
				elog(ERROR, "unrecognized boolop: %d",
1332
					 (int) expr->boolop);
1333 1334
				break;
		}
1335
	}
1336
	if (IsA(node, SubPlan))
1337
	{
1338
		/*
Bruce Momjian's avatar
Bruce Momjian committed
1339
		 * Return a SubPlan unchanged --- too late to do anything with it.
1340
		 *
1341
		 * XXX should we ereport() here instead?  Probably this routine
1342
		 * should never be invoked after SubPlan creation.
1343
		 */
1344
		return node;
1345
	}
1346 1347 1348 1349
	if (IsA(node, RelabelType))
	{
		/*
		 * If we can simplify the input to a constant, then we don't need
1350
		 * the RelabelType node anymore: just change the type field of the
1351
		 * Const node.	Otherwise, must copy the RelabelType node.
1352 1353 1354 1355
		 */
		RelabelType *relabel = (RelabelType *) node;
		Node	   *arg;

1356 1357
		arg = eval_const_expressions_mutator((Node *) relabel->arg,
											 active_fns);
1358 1359

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

1366 1367
		if (arg && IsA(arg, Const))
		{
1368
			Const	   *con = (Const *) arg;
1369 1370

			con->consttype = relabel->resulttype;
1371

1372 1373 1374
			/*
			 * relabel's resulttypmod is discarded, which is OK for now;
			 * if the type actually needs a runtime length coercion then
1375 1376
			 * there should be a function call to do it just above this
			 * node.
1377
			 */
1378 1379 1380 1381 1382 1383
			return (Node *) con;
		}
		else
		{
			RelabelType *newrelabel = makeNode(RelabelType);

1384
			newrelabel->arg = (Expr *) arg;
1385 1386 1387 1388 1389
			newrelabel->resulttype = relabel->resulttype;
			newrelabel->resulttypmod = relabel->resulttypmod;
			return (Node *) newrelabel;
		}
	}
1390 1391
	if (IsA(node, CaseExpr))
	{
1392
		/*----------
1393
		 * CASE expressions can be simplified if there are constant
1394 1395 1396 1397 1398 1399 1400
		 * 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).
1401 1402 1403 1404 1405 1406 1407 1408
		 *
		 * If we have a simple-form CASE with constant test expression and
		 * one or more constant comparison expressions, we could run the
		 * implied comparisons and potentially reduce those arms to constants.
		 * This is not yet implemented, however.  At present, the
		 * CaseTestExpr placeholder will always act as a non-constant node
		 * and prevent the comparison boolean expressions from being reduced
		 * to Const nodes.
1409
		 *----------
1410 1411 1412
		 */
		CaseExpr   *caseexpr = (CaseExpr *) node;
		CaseExpr   *newcase;
1413
		Node	   *newarg;
1414
		FastList	newargs;
1415 1416 1417 1418
		Node	   *defresult;
		Const	   *const_input;
		List	   *arg;

1419 1420 1421 1422 1423
		/* Simplify the test expression, if any */
		newarg = eval_const_expressions_mutator((Node *) caseexpr->arg,
												active_fns);

		/* Simplify the WHEN clauses */
1424
		FastListInit(&newargs);
1425 1426 1427 1428
		foreach(arg, caseexpr->args)
		{
			/* Simplify this alternative's condition and result */
			CaseWhen   *casewhen = (CaseWhen *)
1429 1430
			expression_tree_mutator((Node *) lfirst(arg),
									eval_const_expressions_mutator,
1431
									(void *) active_fns);
1432

1433 1434
			Assert(IsA(casewhen, CaseWhen));
			if (casewhen->expr == NULL ||
1435
				!IsA(casewhen->expr, Const))
1436
			{
1437
				FastAppend(&newargs, casewhen);
1438 1439 1440 1441
				continue;
			}
			const_input = (Const *) casewhen->expr;
			if (const_input->constisnull ||
1442
				!DatumGetBool(const_input->constvalue))
1443
				continue;		/* drop alternative with FALSE condition */
1444

1445
			/*
1446
			 * Found a TRUE condition.	If it's the first (un-dropped)
1447 1448
			 * alternative, the CASE reduces to just this alternative.
			 */
1449
			if (FastListValue(&newargs) == NIL)
1450
				return (Node *) casewhen->result;
1451

1452 1453 1454
			/*
			 * Otherwise, add it to the list, and drop all the rest.
			 */
1455
			FastAppend(&newargs, casewhen);
1456 1457 1458 1459
			break;
		}

		/* Simplify the default result */
1460
		defresult = eval_const_expressions_mutator((Node *) caseexpr->defresult,
1461
												   active_fns);
1462 1463 1464 1465 1466

		/*
		 * If no non-FALSE alternatives, CASE reduces to the default
		 * result
		 */
1467
		if (FastListValue(&newargs) == NIL)
1468 1469 1470 1471
			return defresult;
		/* Otherwise we need a new CASE node */
		newcase = makeNode(CaseExpr);
		newcase->casetype = caseexpr->casetype;
1472
		newcase->arg = (Expr *) newarg;
1473
		newcase->args = FastListValue(&newargs);
1474
		newcase->defresult = (Expr *) defresult;
1475 1476
		return (Node *) newcase;
	}
1477 1478
	if (IsA(node, ArrayExpr))
	{
Bruce Momjian's avatar
Bruce Momjian committed
1479 1480 1481
		ArrayExpr  *arrayexpr = (ArrayExpr *) node;
		ArrayExpr  *newarray;
		bool		all_const = true;
1482
		FastList	newelems;
Bruce Momjian's avatar
Bruce Momjian committed
1483
		List	   *element;
1484

1485
		FastListInit(&newelems);
1486 1487
		foreach(element, arrayexpr->elements)
		{
Bruce Momjian's avatar
Bruce Momjian committed
1488
			Node	   *e;
1489 1490 1491 1492 1493

			e = eval_const_expressions_mutator((Node *) lfirst(element),
											   active_fns);
			if (!IsA(e, Const))
				all_const = false;
1494
			FastAppend(&newelems, e);
1495 1496 1497 1498 1499
		}

		newarray = makeNode(ArrayExpr);
		newarray->array_typeid = arrayexpr->array_typeid;
		newarray->element_typeid = arrayexpr->element_typeid;
1500
		newarray->elements = FastListValue(&newelems);
1501
		newarray->multidims = arrayexpr->multidims;
1502 1503 1504 1505 1506 1507 1508

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

		return (Node *) newarray;
	}
1509 1510 1511 1512
	if (IsA(node, CoalesceExpr))
	{
		CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
		CoalesceExpr *newcoalesce;
1513
		FastList	newargs;
Bruce Momjian's avatar
Bruce Momjian committed
1514
		List	   *arg;
1515

1516
		FastListInit(&newargs);
1517 1518
		foreach(arg, coalesceexpr->args)
		{
Bruce Momjian's avatar
Bruce Momjian committed
1519
			Node	   *e;
1520 1521 1522

			e = eval_const_expressions_mutator((Node *) lfirst(arg),
											   active_fns);
Bruce Momjian's avatar
Bruce Momjian committed
1523 1524 1525 1526 1527

			/*
			 * 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.
1528 1529 1530 1531 1532
			 */
			if (IsA(e, Const))
			{
				if (((Const *) e)->constisnull)
					continue;	/* drop null constant */
1533
				if (FastListValue(&newargs) == NIL)
1534 1535
					return e;	/* first expr */
			}
1536
			FastAppend(&newargs, e);
1537 1538 1539 1540
		}

		newcoalesce = makeNode(CoalesceExpr);
		newcoalesce->coalescetype = coalesceexpr->coalescetype;
1541
		newcoalesce->args = FastListValue(&newargs);
1542 1543
		return (Node *) newcoalesce;
	}
1544 1545 1546 1547
	if (IsA(node, FieldSelect))
	{
		/*
		 * We can optimize field selection from a whole-row Var into a
Bruce Momjian's avatar
Bruce Momjian committed
1548 1549
		 * simple Var.	(This case won't be generated directly by the
		 * parser, because ParseComplexProjection short-circuits it. But
1550 1551
		 * it can arise while simplifying functions.)  Also, we can
		 * optimize field selection from a RowExpr construct.
1552 1553
		 */
		FieldSelect *fselect = (FieldSelect *) node;
1554 1555
		FieldSelect *newfselect;
		Node	   *arg;
1556

1557 1558 1559 1560
		arg = eval_const_expressions_mutator((Node *) fselect->arg,
											 active_fns);
		if (arg && IsA(arg, Var) &&
			((Var *) arg)->varattno == InvalidAttrNumber)
1561
		{
1562
			return (Node *) makeVar(((Var *) arg)->varno,
1563 1564 1565
									fselect->fieldnum,
									fselect->resulttype,
									fselect->resulttypmod,
1566
									((Var *) arg)->varlevelsup);
1567
		}
1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581
		if (arg && IsA(arg, RowExpr))
		{
			RowExpr	*rowexpr = (RowExpr *) arg;

			if (fselect->fieldnum > 0 &&
				fselect->fieldnum <= length(rowexpr->args))
				return (Node *) nth(fselect->fieldnum - 1, rowexpr->args);
		}
		newfselect = makeNode(FieldSelect);
		newfselect->arg = (Expr *) arg;
		newfselect->fieldnum = fselect->fieldnum;
		newfselect->resulttype = fselect->resulttype;
		newfselect->resulttypmod = fselect->resulttypmod;
		return (Node *) newfselect;
1582
	}
1583

1584 1585
	/*
	 * For any node type not handled above, we recurse using
1586 1587 1588 1589
	 * 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.
1590 1591
	 */
	return expression_tree_mutator(node, eval_const_expressions_mutator,
1592
								   (void *) active_fns);
1593 1594
}

1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716
/*
 * Subroutine for eval_const_expressions: scan the arguments of an OR clause
 *
 * OR arguments are handled as follows:
 *		non constant: keep
 *		FALSE: drop (does not affect result)
 *		TRUE: force result to TRUE
 *		NULL: keep only one
 * We must keep one NULL input because ExecEvalOr returns NULL when no input
 * is TRUE and at least one is NULL.
 *
 * This is split out as a subroutine so that we can recurse to fold sub-ORs
 * into the upper OR clause, thereby preserving AND/OR flatness.
 *
 * 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 *
simplify_or_arguments(List *args, bool *haveNull, bool *forceTrue)
{
	List	   *newargs = NIL;
	List	   *larg;

	foreach(larg, args)
	{
		Node   *arg = (Node *) lfirst(larg);

		if (IsA(arg, Const))
		{
			Const  *const_input = (Const *) arg;

			if (const_input->constisnull)
				*haveNull = true;
			else if (DatumGetBool(const_input->constvalue))
			{
				*forceTrue = true;
				/*
				 * 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 */
		}
		else if (or_clause(arg))
		{
			newargs = nconc(newargs,
							simplify_or_arguments(((BoolExpr *) arg)->args,
												  haveNull, forceTrue));
		}
		else
		{
			newargs = lappend(newargs, arg);
		}
	}

	return newargs;
}

/*
 * Subroutine for eval_const_expressions: scan the arguments of an AND clause
 *
 * AND arguments are handled as follows:
 *		non constant: keep
 *		TRUE: drop (does not affect result)
 *		FALSE: force result to FALSE
 *		NULL: keep only one
 * We must keep one NULL input because ExecEvalAnd returns NULL when no input
 * is FALSE and at least one is NULL.
 *
 * This is split out as a subroutine so that we can recurse to fold sub-ANDs
 * into the upper AND clause, thereby preserving AND/OR flatness.
 *
 * 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 *
simplify_and_arguments(List *args, bool *haveNull, bool *forceFalse)
{
	List	   *newargs = NIL;
	List	   *larg;

	foreach(larg, args)
	{
		Node   *arg = (Node *) lfirst(larg);

		if (IsA(arg, Const))
		{
			Const  *const_input = (Const *) arg;

			if (const_input->constisnull)
				*haveNull = true;
			else if (!DatumGetBool(const_input->constvalue))
			{
				*forceFalse = true;
				/*
				 * 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 */
		}
		else if (and_clause(arg))
		{
			newargs = nconc(newargs,
							simplify_and_arguments(((BoolExpr *) arg)->args,
												   haveNull, forceFalse));
		}
		else
		{
			newargs = lappend(newargs, arg);
		}
	}

	return newargs;
}

1717
/*
1718 1719
 * Subroutine for eval_const_expressions: try to simplify a function call
 * (which might originally have been an operator; we don't care)
1720
 *
1721 1722
 * Inputs are the function OID, actual result type OID (which is needed for
 * polymorphic functions), and the pre-simplified argument list;
1723
 * also a list of already-active inline function expansions.
1724 1725
 *
 * Returns a simplified expression if successful, or NULL if cannot
1726
 * simplify the function call.
1727 1728
 */
static Expr *
1729 1730
simplify_function(Oid funcid, Oid result_type, List *args,
				  bool allow_inline, List *active_fns)
1731 1732
{
	HeapTuple	func_tuple;
1733
	Expr	   *newexpr;
1734 1735

	/*
Bruce Momjian's avatar
Bruce Momjian committed
1736 1737 1738 1739 1740 1741
	 * 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.
1742
	 */
1743 1744 1745
	func_tuple = SearchSysCache(PROCOID,
								ObjectIdGetDatum(funcid),
								0, 0, 0);
1746
	if (!HeapTupleIsValid(func_tuple))
1747
		elog(ERROR, "cache lookup failed for function %u", funcid);
1748

1749
	newexpr = evaluate_function(funcid, result_type, args, func_tuple);
1750 1751

	if (!newexpr && allow_inline)
1752 1753
		newexpr = inline_function(funcid, result_type, args,
								  func_tuple, active_fns);
1754

1755 1756
	ReleaseSysCache(func_tuple);

1757 1758 1759 1760
	return newexpr;
}

/*
1761
 * evaluate_function: try to pre-evaluate a function call
1762 1763 1764 1765 1766 1767
 *
 * 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
 * constant inputs (call it and return the result as a Const node).
 *
 * Returns a simplified expression if successful, or NULL if cannot
1768
 * simplify the function.
1769 1770
 */
static Expr *
1771 1772
evaluate_function(Oid funcid, Oid result_type, List *args,
				  HeapTuple func_tuple)
1773 1774 1775 1776 1777
{
	Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
	bool		has_nonconst_input = false;
	bool		has_null_input = false;
	List	   *arg;
1778
	FuncExpr   *newexpr;
1779

1780
	/*
1781
	 * Can't simplify if it returns a set.
1782
	 */
1783
	if (funcform->proretset)
1784
		return NULL;
1785

1786
	/*
1787
	 * Check for constant inputs and especially constant-NULL inputs.
1788
	 */
1789
	foreach(arg, args)
1790
	{
1791 1792 1793 1794
		if (IsA(lfirst(arg), Const))
			has_null_input |= ((Const *) lfirst(arg))->constisnull;
		else
			has_nonconst_input = true;
1795 1796 1797
	}

	/*
1798 1799
	 * 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
Bruce Momjian's avatar
Bruce Momjian committed
1800 1801
	 * constant, even if there are other inputs that aren't constant, and
	 * even if the function is not otherwise immutable.
1802
	 */
1803
	if (funcform->proisstrict && has_null_input)
1804
		return (Expr *) makeNullConst(result_type);
1805 1806

	/*
Bruce Momjian's avatar
Bruce Momjian committed
1807 1808
	 * Otherwise, can simplify only if the function is immutable and all
	 * inputs are constants. (For a non-strict function, constant NULL
1809 1810 1811 1812
	 * inputs are treated the same as constant non-NULL inputs.)
	 */
	if (funcform->provolatile != PROVOLATILE_IMMUTABLE ||
		has_nonconst_input)
1813 1814
		return NULL;

1815 1816 1817
	/*
	 * OK, looks like we can simplify this operator/function.
	 *
1818
	 * Build a new FuncExpr node containing the already-simplified arguments.
1819
	 */
1820 1821
	newexpr = makeNode(FuncExpr);
	newexpr->funcid = funcid;
1822
	newexpr->funcresulttype = result_type;
1823
	newexpr->funcretset = false;
1824
	newexpr->funcformat = COERCE_DONTCARE;		/* doesn't matter */
1825
	newexpr->args = args;
1826

1827
	return evaluate_expr((Expr *) newexpr, result_type);
1828 1829
}

1830
/*
1831
 * inline_function: try to expand a function call inline
1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842
 *
 * 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
1843
 * functions (volatiles might deliver inconsistent answers) nor to be
Bruce Momjian's avatar
Bruce Momjian committed
1844
 * unreasonably expensive to evaluate.	The expensiveness check not only
1845 1846 1847 1848
 * 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.
 *
1849 1850 1851 1852
 * 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
1853
 * simplify the function.
1854 1855
 */
static Expr *
1856 1857
inline_function(Oid funcid, Oid result_type, List *args,
				HeapTuple func_tuple, List *active_fns)
1858 1859
{
	Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
1860 1861
	bool		polymorphic = false;
	Oid			argtypes[FUNC_MAX_ARGS];
1862 1863 1864 1865 1866
	char	   *src;
	Datum		tmp;
	bool		isNull;
	MemoryContext oldcxt;
	MemoryContext mycxt;
1867
	ErrorContextCallback sqlerrcontext;
1868 1869 1870 1871 1872 1873 1874 1875 1876 1877
	List	   *raw_parsetree_list;
	List	   *querytree_list;
	Query	   *querytree;
	Node	   *newexpr;
	int		   *usecounts;
	List	   *arg;
	int			i;

	/*
	 * Forget it if the function is not SQL-language or has other
Bruce Momjian's avatar
Bruce Momjian committed
1878
	 * showstopper properties.	(The nargs check is just paranoia.)
1879 1880 1881 1882 1883 1884 1885 1886
	 */
	if (funcform->prolang != SQLlanguageId ||
		funcform->prosecdef ||
		funcform->proretset ||
		funcform->pronargs != length(args))
		return NULL;

	/* Check for recursive function, and give up trying to expand if so */
1887
	if (oidMember(funcid, active_fns))
1888 1889 1890 1891 1892 1893
		return NULL;

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

1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905
	/* Check for polymorphic arguments, and substitute actual arg types */
	memcpy(argtypes, funcform->proargtypes, FUNC_MAX_ARGS * sizeof(Oid));
	for (i = 0; i < funcform->pronargs; i++)
	{
		if (argtypes[i] == ANYARRAYOID ||
			argtypes[i] == ANYELEMENTOID)
		{
			polymorphic = true;
			argtypes[i] = exprType((Node *) nth(i, args));
		}
	}

1906 1907 1908 1909
	if (funcform->prorettype == ANYARRAYOID ||
		funcform->prorettype == ANYELEMENTOID)
		polymorphic = true;

1910
	/*
Bruce Momjian's avatar
Bruce Momjian committed
1911 1912
	 * Setup error traceback support for ereport().  This is so that we
	 * can finger the function that bad information came from.
1913 1914
	 */
	sqlerrcontext.callback = sql_inline_error_callback;
1915
	sqlerrcontext.arg = func_tuple;
1916 1917 1918
	sqlerrcontext.previous = error_context_stack;
	error_context_stack = &sqlerrcontext;

1919 1920 1921 1922 1923
	/*
	 * Make a temporary memory context, so that we don't leak all the
	 * stuff that parsing might create.
	 */
	mycxt = AllocSetContextCreate(CurrentMemoryContext,
1924
								  "inline_function",
1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935
								  ALLOCSET_DEFAULT_MINSIZE,
								  ALLOCSET_DEFAULT_INITSIZE,
								  ALLOCSET_DEFAULT_MAXSIZE);
	oldcxt = MemoryContextSwitchTo(mycxt);

	/* Fetch and parse the function body */
	tmp = SysCacheGetAttr(PROCOID,
						  func_tuple,
						  Anum_pg_proc_prosrc,
						  &isNull);
	if (isNull)
1936
		elog(ERROR, "null prosrc for function %u", funcid);
1937 1938 1939 1940
	src = DatumGetCString(DirectFunctionCall1(textout, tmp));

	/*
	 * We just do parsing and parse analysis, not rewriting, because
Bruce Momjian's avatar
Bruce Momjian committed
1941 1942 1943
	 * 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.
1944
	 */
1945
	raw_parsetree_list = pg_parse_query(src);
1946 1947 1948
	if (length(raw_parsetree_list) != 1)
		goto fail;

1949
	querytree_list = parse_analyze(lfirst(raw_parsetree_list),
1950
								   argtypes, funcform->pronargs);
1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978

	if (length(querytree_list) != 1)
		goto fail;

	querytree = (Query *) lfirst(querytree_list);

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

1979
	newexpr = (Node *) ((TargetEntry *) lfirst(querytree->targetList))->expr;
1980

1981 1982 1983 1984 1985
	/*
	 * If the function has any arguments declared as polymorphic types,
	 * then it wasn't type-checked at definition time; must do so now.
	 * (This will raise an error if wrong, but that's okay since the
	 * function would fail at runtime anyway.  Note we do not try this
Bruce Momjian's avatar
Bruce Momjian committed
1986 1987
	 * until we have verified that no rewriting was needed; that's
	 * probably not important, but let's be careful.)
1988 1989
	 */
	if (polymorphic)
1990 1991
		(void) check_sql_fn_retval(result_type, get_typtype(result_type),
								   querytree_list);
1992

1993 1994 1995 1996 1997
	/*
	 * 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
Bruce Momjian's avatar
Bruce Momjian committed
1998 1999 2000
	 * 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).
2001 2002 2003 2004 2005 2006 2007 2008
	 */
	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
2009
			 contain_volatile_functions(newexpr))
2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029
		goto fail;

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

	/*
	 * 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.
	 */
	usecounts = (int *) palloc0((funcform->pronargs + 1) * sizeof(int));
	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
2030
		Node	   *param = lfirst(arg);
2031 2032 2033 2034 2035 2036 2037 2038 2039

		if (usecounts[i] == 0)
		{
			/* Param not used at all: uncool if func is strict */
			if (funcform->proisstrict)
				goto fail;
		}
		else if (usecounts[i] != 1)
		{
2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054
			/* Param used multiple times: uncool if expensive or volatile */
			QualCost	eval_cost;

			/*
			 * We define "expensive" as "contains any subplan or more than
			 * 10 operators".  Note that the subplan search has to be done
			 * explicitly, since cost_qual_eval() will barf on unplanned
			 * subselects.
			 */
			if (contain_subplans(param))
				goto fail;
			cost_qual_eval(&eval_cost, makeList1(param));
			if (eval_cost.startup + eval_cost.per_tuple >
				10 * cpu_operator_cost)
				goto fail;
Bruce Momjian's avatar
Bruce Momjian committed
2055

2056 2057 2058 2059 2060
			/*
			 * Check volatility last since this is more expensive than the
			 * above tests
			 */
			if (contain_volatile_functions(param))
2061 2062 2063 2064 2065 2066
				goto fail;
		}
		i++;
	}

	/*
Bruce Momjian's avatar
Bruce Momjian committed
2067 2068
	 * Whew --- we can make the substitution.  Copy the modified
	 * expression out of the temporary memory context, and clean up.
2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080
	 */
	MemoryContextSwitchTo(oldcxt);

	newexpr = copyObject(newexpr);

	MemoryContextDelete(mycxt);

	/*
	 * Recursively try to simplify the modified expression.  Here we must
	 * add the current function to the context list of active functions.
	 */
	newexpr = eval_const_expressions_mutator(newexpr,
2081
											 lconso(funcid, active_fns));
2082

2083 2084
	error_context_stack = sqlerrcontext.previous;

2085 2086 2087 2088 2089 2090
	return (Expr *) newexpr;

	/* Here if func is not inlinable: release temp memory and return NULL */
fail:
	MemoryContextSwitchTo(oldcxt);
	MemoryContextDelete(mycxt);
2091
	error_context_stack = sqlerrcontext.previous;
2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104

	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
2105
	context.nargs = nargs;
2106 2107 2108 2109 2110 2111 2112 2113
	context.args = args;
	context.usecounts = usecounts;

	return substitute_actual_parameters_mutator(expr, &context);
}

static Node *
substitute_actual_parameters_mutator(Node *node,
2114
						   substitute_actual_parameters_context *context)
2115 2116 2117 2118 2119 2120 2121 2122
{
	if (node == NULL)
		return NULL;
	if (IsA(node, Param))
	{
		Param	   *param = (Param *) node;

		if (param->paramkind != PARAM_NUM)
2123
			elog(ERROR, "unexpected paramkind: %d", param->paramkind);
2124
		if (param->paramid <= 0 || param->paramid > context->nargs)
2125
			elog(ERROR, "invalid paramid: %d", param->paramid);
2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137

		/* 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) */
		return nth(param->paramid - 1, context->args);
	}
	return expression_tree_mutator(node, substitute_actual_parameters_mutator,
								   (void *) context);
}

2138 2139 2140 2141 2142 2143
/*
 * error context callback to let us supply a call-stack traceback
 */
static void
sql_inline_error_callback(void *arg)
{
2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164
	HeapTuple func_tuple = (HeapTuple) arg;
	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);
	}
2165 2166 2167 2168 2169

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

2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202
/*
 * evaluate_expr: pre-evaluate a constant expression
 *
 * We use the executor's routine ExecEvalExpr() to avoid duplication of
 * code and ensure we get the same result as the executor would get.
 */
static Expr *
evaluate_expr(Expr *expr, Oid result_type)
{
	EState	   *estate;
	ExprState  *exprstate;
	MemoryContext oldcontext;
	Datum		const_val;
	bool		const_is_null;
	int16		resultTypLen;
	bool		resultTypByVal;

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

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

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

	/*
	 * And evaluate it.
	 *
Bruce Momjian's avatar
Bruce Momjian committed
2203 2204 2205 2206
	 * 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?
2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232
	 */
	const_val = ExecEvalExprSwitchContext(exprstate,
										  GetPerTupleExprContext(estate),
										  &const_is_null, NULL);

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

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

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

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

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

2233

2234
/*
2235 2236 2237 2238 2239 2240 2241 2242 2243
 * 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
2244 2245 2246 2247 2248
 * logic to consolidate the redundant "boilerplate" code.  There are
 * two versions: expression_tree_walker() and expression_tree_mutator().
 */

/*--------------------
2249 2250
 * expression_tree_walker() is designed to support routines that traverse
 * a tree in a read-only fashion (although it will also work for routines
2251 2252
 * that modify nodes in-place but never add/delete/replace nodes).
 * A walker routine should look like this:
2253 2254 2255 2256 2257
 *
 * bool my_walker (Node *node, my_struct *context)
 * {
 *		if (node == NULL)
 *			return false;
Bruce Momjian's avatar
Bruce Momjian committed
2258
 *		// check for nodes that special work is required for, eg:
2259 2260 2261 2262 2263 2264 2265 2266
 *		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
2267
 *		// for any node type not specially processed, do:
2268 2269 2270 2271
 *		return expression_tree_walker(node, my_walker, (void *) context);
 * }
 *
 * The "context" argument points to a struct that holds whatever context
2272 2273
 * information the walker routine needs --- it can be used to return data
 * gathered by the walker, too.  This argument is not touched by
2274 2275 2276 2277 2278 2279 2280
 * 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
2281 2282
 * 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
2283
 * iff no invocation of the walker returned "true".
2284 2285 2286 2287 2288 2289 2290
 *
 * The node types handled by expression_tree_walker include all those
 * normally found in target lists and qualifier clauses during the planning
 * stage.  In particular, it handles List nodes since a cnf-ified qual clause
 * will have List structure at the top level, and it handles TargetEntry nodes
 * so that a scan of a target list can be handled without additional code.
 * (But only the "expr" part of a TargetEntry is examined, unless the walker
2291
 * chooses to process TargetEntry nodes specially.)  Also, RangeTblRef,
2292 2293
 * FromExpr, JoinExpr, and SetOperationStmt nodes are handled, so that query
 * jointrees and setOperation trees can be processed without additional code.
2294
 *
2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305
 * expression_tree_walker will handle SubLink nodes by recursing normally into
 * the "lefthand" arguments (which are expressions belonging to the outer
 * plan).  It will also call the walker on the sub-Query node; however, when
 * expression_tree_walker itself is called on a Query node, it does nothing
 * and returns "false".  The net effect is that unless the walker does
 * something special at a Query node, sub-selects will not be visited during
 * an expression tree walk. This is exactly the behavior wanted in many cases
 * --- and for those walkers that do want to recurse into sub-selects, special
 * behavior is typically needed anyway at the entry to a sub-select (such as
 * incrementing a depth counter). A walker that wants to examine sub-selects
 * should include code along the lines of:
2306 2307 2308 2309
 *
 *		if (IsA(node, Query))
 *		{
 *			adjust context for subquery;
2310
 *			result = query_tree_walker((Query *) node, my_walker, context,
2311
 *									   0); // adjust flags as needed
2312 2313 2314
 *			restore context if needed;
 *			return result;
 *		}
2315
 *
2316 2317
 * query_tree_walker is a convenience routine (see below) that calls the
 * walker on all the expression subtrees of the given Query node.
2318
 *
2319
 * expression_tree_walker will handle SubPlan nodes by recursing normally
2320
 * into the "exprs" and "args" lists (which are expressions belonging to
Bruce Momjian's avatar
Bruce Momjian committed
2321
 * the outer plan).  It will not touch the completed subplan, however.	Since
2322 2323 2324
 * 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.
2325 2326 2327 2328
 *--------------------
 */

bool
2329 2330 2331
expression_tree_walker(Node *node,
					   bool (*walker) (),
					   void *context)
2332 2333 2334 2335
{
	List	   *temp;

	/*
2336 2337
	 * The walker has already visited the current node, and so we need
	 * only recurse into any sub-nodes it has.
2338
	 *
2339 2340
	 * 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
2341 2342 2343 2344
	 * bothering to call the walker.
	 */
	if (node == NULL)
		return false;
2345 2346 2347 2348

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

2349 2350 2351
	switch (nodeTag(node))
	{
		case T_Var:
2352
		case T_Const:
2353
		case T_Param:
2354
		case T_CoerceToDomainValue:
2355
		case T_CaseTestExpr:
2356
		case T_SetToDefault:
2357
		case T_RangeTblRef:
2358 2359
			/* primitive node types with no subnodes */
			break;
2360 2361 2362 2363 2364
		case T_Aggref:
			return walker(((Aggref *) node)->target, context);
		case T_ArrayRef:
			{
				ArrayRef   *aref = (ArrayRef *) node;
2365

2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379
				/* 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;
2380
		case T_FuncExpr:
2381
			{
2382
				FuncExpr   *expr = (FuncExpr *) node;
2383

2384 2385 2386 2387 2388 2389 2390 2391
				if (expression_tree_walker((Node *) expr->args,
										   walker, context))
					return true;
			}
			break;
		case T_OpExpr:
			{
				OpExpr	   *expr = (OpExpr *) node;
2392

2393 2394
				if (expression_tree_walker((Node *) expr->args,
										   walker, context))
2395
					return true;
2396 2397 2398 2399 2400 2401 2402 2403
			}
			break;
		case T_DistinctExpr:
			{
				DistinctExpr *expr = (DistinctExpr *) node;

				if (expression_tree_walker((Node *) expr->args,
										   walker, context))
2404 2405 2406
					return true;
			}
			break;
2407 2408 2409 2410 2411 2412 2413 2414 2415
		case T_ScalarArrayOpExpr:
			{
				ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;

				if (expression_tree_walker((Node *) expr->args,
										   walker, context))
					return true;
			}
			break;
2416 2417 2418 2419 2420 2421 2422 2423
		case T_BoolExpr:
			{
				BoolExpr   *expr = (BoolExpr *) node;

				if (expression_tree_walker((Node *) expr->args,
										   walker, context))
					return true;
			}
2424
			break;
2425
		case T_SubLink:
2426
			{
2427
				SubLink    *sublink = (SubLink *) node;
2428

2429 2430 2431
				if (expression_tree_walker((Node *) sublink->lefthand,
										   walker, context))
					return true;
Bruce Momjian's avatar
Bruce Momjian committed
2432

2433
				/*
2434 2435
				 * Also invoke the walker on the sublink's Query node, so
				 * it can recurse into the sub-query if it wants to.
2436 2437
				 */
				return walker(sublink->subselect, context);
2438 2439
			}
			break;
2440
		case T_SubPlan:
2441
			{
Bruce Momjian's avatar
Bruce Momjian committed
2442
				SubPlan    *subplan = (SubPlan *) node;
2443

2444 2445
				/* recurse into the exprs list, but not into the Plan */
				if (expression_tree_walker((Node *) subplan->exprs,
2446
										   walker, context))
2447 2448
					return true;
				/* also examine args list */
2449
				if (expression_tree_walker((Node *) subplan->args,
2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461
										   walker, context))
					return true;
			}
			break;
		case T_FieldSelect:
			return walker(((FieldSelect *) node)->arg, context);
		case T_RelabelType:
			return walker(((RelabelType *) node)->arg, context);
		case T_CaseExpr:
			{
				CaseExpr   *caseexpr = (CaseExpr *) node;

2462 2463
				if (walker(caseexpr->arg, context))
					return true;
2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478
				/* 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;
2479 2480
		case T_ArrayExpr:
			return walker(((ArrayExpr *) node)->elements, context);
2481 2482
		case T_RowExpr:
			return walker(((RowExpr *) node)->args, context);
2483 2484 2485 2486
		case T_CoalesceExpr:
			return walker(((CoalesceExpr *) node)->args, context);
		case T_NullIfExpr:
			return walker(((NullIfExpr *) node)->args, context);
2487 2488 2489 2490
		case T_NullTest:
			return walker(((NullTest *) node)->arg, context);
		case T_BooleanTest:
			return walker(((BooleanTest *) node)->arg, context);
2491 2492
		case T_CoerceToDomain:
			return walker(((CoerceToDomain *) node)->arg, context);
2493 2494
		case T_TargetEntry:
			return walker(((TargetEntry *) node)->expr, context);
2495 2496 2497
		case T_Query:
			/* Do nothing with a sub-Query, per discussion above */
			break;
2498 2499 2500 2501 2502 2503 2504
		case T_List:
			foreach(temp, (List *) node)
			{
				if (walker((Node *) lfirst(temp), context))
					return true;
			}
			break;
2505 2506
		case T_FromExpr:
			{
2507
				FromExpr   *from = (FromExpr *) node;
2508 2509 2510 2511 2512 2513 2514

				if (walker(from->fromlist, context))
					return true;
				if (walker(from->quals, context))
					return true;
			}
			break;
2515 2516
		case T_JoinExpr:
			{
2517
				JoinExpr   *join = (JoinExpr *) node;
2518 2519 2520 2521 2522 2523 2524

				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
2525

2526
				/*
2527
				 * alias clause, using list are deemed uninteresting.
2528 2529 2530
				 */
			}
			break;
2531 2532 2533 2534 2535 2536 2537 2538 2539 2540
		case T_SetOperationStmt:
			{
				SetOperationStmt *setop = (SetOperationStmt *) node;

				if (walker(setop->larg, context))
					return true;
				if (walker(setop->rarg, context))
					return true;
			}
			break;
2541 2542 2543 2544 2545 2546 2547 2548 2549
		case T_InClauseInfo:
			{
				InClauseInfo *ininfo = (InClauseInfo *) node;

				if (expression_tree_walker((Node *) ininfo->sub_targetlist,
										   walker, context))
					return true;
			}
			break;
2550
		default:
2551 2552
			elog(ERROR, "unrecognized node type: %d",
				 (int) nodeTag(node));
2553 2554 2555 2556
			break;
	}
	return false;
}
2557

2558 2559 2560 2561 2562 2563 2564 2565
/*
 * 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.
2566
 *
2567 2568 2569 2570 2571
 * 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.)
2572 2573 2574 2575
 */
bool
query_tree_walker(Query *query,
				  bool (*walker) (),
2576
				  void *context,
2577
				  int flags)
2578
{
2579 2580
	List	   *rt;

2581 2582 2583 2584
	Assert(query != NULL && IsA(query, Query));

	if (walker((Node *) query->targetList, context))
		return true;
2585
	if (walker((Node *) query->jointree, context))
2586
		return true;
2587 2588
	if (walker(query->setOperations, context))
		return true;
2589 2590
	if (walker(query->havingQual, context))
		return true;
2591 2592 2593 2594
	if (walker(query->limitOffset, context))
		return true;
	if (walker(query->limitCount, context))
		return true;
2595 2596
	if (walker(query->in_info_list, context))
		return true;
2597
	foreach(rt, query->rtable)
2598
	{
2599
		RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2600

2601
		switch (rte->rtekind)
2602
		{
2603 2604 2605 2606 2607
			case RTE_RELATION:
			case RTE_SPECIAL:
				/* nothing to do */
				break;
			case RTE_SUBQUERY:
Bruce Momjian's avatar
Bruce Momjian committed
2608
				if (!(flags & QTW_IGNORE_RT_SUBQUERIES))
2609 2610 2611 2612
					if (walker(rte->subquery, context))
						return true;
				break;
			case RTE_JOIN:
Bruce Momjian's avatar
Bruce Momjian committed
2613
				if (!(flags & QTW_IGNORE_JOINALIASES))
2614 2615
					if (walker(rte->joinaliasvars, context))
						return true;
2616
				break;
2617 2618 2619 2620
			case RTE_FUNCTION:
				if (walker(rte->funcexpr, context))
					return true;
				break;
2621 2622
		}
	}
2623 2624 2625 2626
	return false;
}


2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638
/*--------------------
 * 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
2639
 *		// check for nodes that special work is required for, eg:
2640 2641 2642 2643 2644 2645 2646 2647
 *		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
2648
 *		// for any node type not specially processed, do:
2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670
 *		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.
 *
2671 2672 2673 2674 2675 2676 2677 2678 2679 2680
 * expression_tree_mutator will handle SubLink nodes by recursing normally
 * into the "lefthand" arguments (which are expressions belonging to the outer
 * 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).
 *
2681
 * expression_tree_mutator will handle a SubPlan node by recursing into
2682
 * the "exprs" and "args" lists (which belong to the outer plan), but it
2683 2684
 * 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
2685
 * can force appropriate behavior by recognizing SubPlan expression nodes
2686
 * and doing the right thing.
2687 2688 2689 2690
 *--------------------
 */

Node *
2691 2692 2693
expression_tree_mutator(Node *node,
						Node *(*mutator) (),
						void *context)
2694 2695
{
	/*
2696 2697
	 * The mutator has already decided not to modify the current node, but
	 * we must call the mutator for any sub-nodes.
2698 2699 2700 2701 2702 2703
	 */

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

2704
#define CHECKFLATCOPY(newnode, node, nodetype)	\
2705 2706 2707 2708 2709 2710 2711 2712 2713
	( AssertMacro(IsA((node), nodetype)), \
	  (newnode) = makeNode(nodetype), \
	  memcpy((newnode), (node), sizeof(nodetype)) )

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

	if (node == NULL)
		return NULL;
2714 2715 2716 2717

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

2718 2719 2720
	switch (nodeTag(node))
	{
		case T_Var:
2721
		case T_Const:
2722
		case T_Param:
2723
		case T_CoerceToDomainValue:
2724
		case T_CaseTestExpr:
2725
		case T_SetToDefault:
2726
		case T_RangeTblRef:
2727 2728
			/* primitive node types with no subnodes */
			return (Node *) copyObject(node);
2729 2730
		case T_Aggref:
			{
2731 2732
				Aggref	   *aggref = (Aggref *) node;
				Aggref	   *newnode;
2733 2734

				FLATCOPY(newnode, aggref, Aggref);
2735
				MUTATE(newnode->target, aggref->target, Expr *);
2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749
				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,
2750
					   Expr *);
2751
				MUTATE(newnode->refassgnexpr, arrayref->refassgnexpr,
2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777
					   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
2778 2779
				DistinctExpr *expr = (DistinctExpr *) node;
				DistinctExpr *newnode;
2780 2781 2782 2783 2784 2785

				FLATCOPY(newnode, expr, DistinctExpr);
				MUTATE(newnode->args, expr->args, List *);
				return (Node *) newnode;
			}
			break;
2786 2787
		case T_ScalarArrayOpExpr:
			{
Bruce Momjian's avatar
Bruce Momjian committed
2788 2789
				ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
				ScalarArrayOpExpr *newnode;
2790 2791 2792 2793 2794 2795

				FLATCOPY(newnode, expr, ScalarArrayOpExpr);
				MUTATE(newnode->args, expr->args, List *);
				return (Node *) newnode;
			}
			break;
2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812
		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);
				MUTATE(newnode->lefthand, sublink->lefthand, List *);
Bruce Momjian's avatar
Bruce Momjian committed
2813

2814 2815 2816 2817 2818
				/*
				 * Also invoke the mutator on the sublink's Query node, so
				 * it can recurse into the sub-query if it wants to.
				 */
				MUTATE(newnode->subselect, sublink->subselect, Node *);
2819 2820 2821
				return (Node *) newnode;
			}
			break;
2822
		case T_SubPlan:
2823
			{
Bruce Momjian's avatar
Bruce Momjian committed
2824 2825
				SubPlan    *subplan = (SubPlan *) node;
				SubPlan    *newnode;
2826

2827
				FLATCOPY(newnode, subplan, SubPlan);
2828 2829
				/* transform exprs list */
				MUTATE(newnode->exprs, subplan->exprs, List *);
2830
				/* transform args list (params to be passed to subplan) */
2831 2832
				MUTATE(newnode->args, subplan->args, List *);
				/* but not the sub-Plan itself, which is referenced as-is */
2833 2834 2835
				return (Node *) newnode;
			}
			break;
2836 2837 2838 2839 2840 2841
		case T_FieldSelect:
			{
				FieldSelect *fselect = (FieldSelect *) node;
				FieldSelect *newnode;

				FLATCOPY(newnode, fselect, FieldSelect);
2842
				MUTATE(newnode->arg, fselect->arg, Expr *);
2843 2844 2845
				return (Node *) newnode;
			}
			break;
2846 2847 2848 2849 2850 2851
		case T_RelabelType:
			{
				RelabelType *relabel = (RelabelType *) node;
				RelabelType *newnode;

				FLATCOPY(newnode, relabel, RelabelType);
2852
				MUTATE(newnode->arg, relabel->arg, Expr *);
2853 2854 2855
				return (Node *) newnode;
			}
			break;
2856 2857 2858 2859 2860 2861
		case T_CaseExpr:
			{
				CaseExpr   *caseexpr = (CaseExpr *) node;
				CaseExpr   *newnode;

				FLATCOPY(newnode, caseexpr, CaseExpr);
2862
				MUTATE(newnode->arg, caseexpr->arg, Expr *);
2863
				MUTATE(newnode->args, caseexpr->args, List *);
2864
				MUTATE(newnode->defresult, caseexpr->defresult, Expr *);
2865 2866 2867 2868 2869 2870 2871 2872 2873
				return (Node *) newnode;
			}
			break;
		case T_CaseWhen:
			{
				CaseWhen   *casewhen = (CaseWhen *) node;
				CaseWhen   *newnode;

				FLATCOPY(newnode, casewhen, CaseWhen);
2874 2875
				MUTATE(newnode->expr, casewhen->expr, Expr *);
				MUTATE(newnode->result, casewhen->result, Expr *);
2876 2877 2878
				return (Node *) newnode;
			}
			break;
2879 2880
		case T_ArrayExpr:
			{
Bruce Momjian's avatar
Bruce Momjian committed
2881 2882
				ArrayExpr  *arrayexpr = (ArrayExpr *) node;
				ArrayExpr  *newnode;
2883 2884 2885 2886 2887 2888

				FLATCOPY(newnode, arrayexpr, ArrayExpr);
				MUTATE(newnode->elements, arrayexpr->elements, List *);
				return (Node *) newnode;
			}
			break;
2889 2890 2891 2892 2893 2894 2895 2896 2897 2898
		case T_RowExpr:
			{
				RowExpr	   *rowexpr = (RowExpr *) node;
				RowExpr	   *newnode;

				FLATCOPY(newnode, rowexpr, RowExpr);
				MUTATE(newnode->args, rowexpr->args, List *);
				return (Node *) newnode;
			}
			break;
2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910
		case T_CoalesceExpr:
			{
				CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
				CoalesceExpr *newnode;

				FLATCOPY(newnode, coalesceexpr, CoalesceExpr);
				MUTATE(newnode->args, coalesceexpr->args, List *);
				return (Node *) newnode;
			}
			break;
		case T_NullIfExpr:
			{
Bruce Momjian's avatar
Bruce Momjian committed
2911 2912
				NullIfExpr *expr = (NullIfExpr *) node;
				NullIfExpr *newnode;
2913 2914 2915 2916 2917 2918

				FLATCOPY(newnode, expr, NullIfExpr);
				MUTATE(newnode->args, expr->args, List *);
				return (Node *) newnode;
			}
			break;
2919 2920
		case T_NullTest:
			{
2921 2922
				NullTest   *ntest = (NullTest *) node;
				NullTest   *newnode;
2923 2924

				FLATCOPY(newnode, ntest, NullTest);
2925
				MUTATE(newnode->arg, ntest->arg, Expr *);
2926 2927 2928 2929 2930 2931 2932 2933 2934
				return (Node *) newnode;
			}
			break;
		case T_BooleanTest:
			{
				BooleanTest *btest = (BooleanTest *) node;
				BooleanTest *newnode;

				FLATCOPY(newnode, btest, BooleanTest);
2935
				MUTATE(newnode->arg, btest->arg, Expr *);
2936 2937 2938
				return (Node *) newnode;
			}
			break;
2939
		case T_CoerceToDomain:
2940
			{
2941 2942
				CoerceToDomain *ctest = (CoerceToDomain *) node;
				CoerceToDomain *newnode;
2943

2944
				FLATCOPY(newnode, ctest, CoerceToDomain);
2945
				MUTATE(newnode->arg, ctest->arg, Expr *);
2946 2947 2948
				return (Node *) newnode;
			}
			break;
2949
		case T_TargetEntry:
2950
			{
2951
				/*
2952 2953
				 * We mutate the expression, but not the resdom, by
				 * default.
2954
				 */
2955 2956
				TargetEntry *targetentry = (TargetEntry *) node;
				TargetEntry *newnode;
2957

2958 2959
				FLATCOPY(newnode, targetentry, TargetEntry);
				MUTATE(newnode->expr, targetentry->expr, Expr *);
2960 2961 2962
				return (Node *) newnode;
			}
			break;
2963 2964 2965
		case T_Query:
			/* Do nothing with a sub-Query, per discussion above */
			return node;
2966 2967
		case T_List:
			{
2968 2969 2970 2971 2972
				/*
				 * 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!
2973
				 */
2974
				FastList	resultlist;
2975 2976
				List	   *temp;

2977
				FastListInit(&resultlist);
2978 2979
				foreach(temp, (List *) node)
				{
2980 2981
					FastAppend(&resultlist,
							   mutator((Node *) lfirst(temp), context));
2982
				}
2983
				return (Node *) FastListValue(&resultlist);
2984 2985
			}
			break;
2986 2987
		case T_FromExpr:
			{
2988 2989
				FromExpr   *from = (FromExpr *) node;
				FromExpr   *newnode;
2990 2991 2992 2993 2994 2995 2996

				FLATCOPY(newnode, from, FromExpr);
				MUTATE(newnode->fromlist, from->fromlist, List *);
				MUTATE(newnode->quals, from->quals, Node *);
				return (Node *) newnode;
			}
			break;
2997 2998
		case T_JoinExpr:
			{
2999 3000
				JoinExpr   *join = (JoinExpr *) node;
				JoinExpr   *newnode;
3001 3002 3003 3004 3005

				FLATCOPY(newnode, join, JoinExpr);
				MUTATE(newnode->larg, join->larg, Node *);
				MUTATE(newnode->rarg, join->rarg, Node *);
				MUTATE(newnode->quals, join->quals, Node *);
3006
				/* We do not mutate alias or using by default */
3007 3008 3009
				return (Node *) newnode;
			}
			break;
3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020
		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;
3021 3022 3023 3024 3025 3026 3027 3028 3029 3030
		case T_InClauseInfo:
			{
				InClauseInfo *ininfo = (InClauseInfo *) node;
				InClauseInfo *newnode;

				FLATCOPY(newnode, ininfo, InClauseInfo);
				MUTATE(newnode->sub_targetlist, ininfo->sub_targetlist, List *);
				return (Node *) newnode;
			}
			break;
3031
		default:
3032 3033
			elog(ERROR, "unrecognized node type: %d",
				 (int) nodeTag(node));
3034 3035 3036 3037 3038
			break;
	}
	/* can't get here, but keep compiler happy */
	return NULL;
}
3039 3040 3041 3042 3043 3044 3045 3046


/*
 * 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
3047
 * mutator intends to descend into subqueries.	It is also useful for
3048 3049
 * descending into subqueries within a mutator.
 *
3050
 * Some callers want to suppress mutating of certain items in the Query,
3051 3052 3053 3054
 * 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.)
3055 3056
 *
 * Normally the Query node itself is copied, but some callers want it to be
Bruce Momjian's avatar
Bruce Momjian committed
3057
 * modified in-place; they must pass QTW_DONT_COPY_QUERY in flags.	All
3058
 * modified substructure is safely copied in any case.
3059
 */
3060
Query *
3061 3062 3063
query_tree_mutator(Query *query,
				   Node *(*mutator) (),
				   void *context,
3064
				   int flags)
3065
{
3066
	FastList	newrt;
3067 3068
	List	   *rt;

3069 3070
	Assert(query != NULL && IsA(query, Query));

Bruce Momjian's avatar
Bruce Momjian committed
3071
	if (!(flags & QTW_DONT_COPY_QUERY))
3072
	{
Bruce Momjian's avatar
Bruce Momjian committed
3073
		Query	   *newquery;
3074 3075 3076 3077 3078

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

3079 3080 3081 3082
	MUTATE(query->targetList, query->targetList, List *);
	MUTATE(query->jointree, query->jointree, FromExpr *);
	MUTATE(query->setOperations, query->setOperations, Node *);
	MUTATE(query->havingQual, query->havingQual, Node *);
3083 3084
	MUTATE(query->limitOffset, query->limitOffset, Node *);
	MUTATE(query->limitCount, query->limitCount, Node *);
3085
	MUTATE(query->in_info_list, query->in_info_list, List *);
3086
	FastListInit(&newrt);
3087
	foreach(rt, query->rtable)
3088
	{
3089 3090
		RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
		RangeTblEntry *newrte;
3091

3092
		FLATCOPY(newrte, rte, RangeTblEntry);
3093
		switch (rte->rtekind)
3094
		{
3095 3096
			case RTE_RELATION:
			case RTE_SPECIAL:
3097
				/* we don't bother to copy eref, aliases, etc; OK? */
3098 3099
				break;
			case RTE_SUBQUERY:
Bruce Momjian's avatar
Bruce Momjian committed
3100
				if (!(flags & QTW_IGNORE_RT_SUBQUERIES))
3101 3102 3103 3104 3105 3106
				{
					CHECKFLATCOPY(newrte->subquery, rte->subquery, Query);
					MUTATE(newrte->subquery, newrte->subquery, Query *);
				}
				break;
			case RTE_JOIN:
Bruce Momjian's avatar
Bruce Momjian committed
3107
				if (!(flags & QTW_IGNORE_JOINALIASES))
3108 3109 3110
				{
					MUTATE(newrte->joinaliasvars, rte->joinaliasvars, List *);
				}
3111
				break;
3112 3113 3114
			case RTE_FUNCTION:
				MUTATE(newrte->funcexpr, rte->funcexpr, Node *);
				break;
3115
		}
3116
		FastAppend(&newrt, newrte);
3117
	}
3118
	query->rtable = FastListValue(&newrt);
3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165
	return query;
}

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