PostgreSQL Source Code  git master
clauses.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * clauses.c
4  * routines to manipulate qualification clauses
5  *
6  * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  * src/backend/optimizer/util/clauses.c
12  *
13  * HISTORY
14  * AUTHOR DATE MAJOR EVENT
15  * Andrew Yu Nov 3, 1994 clause.c and clauses.c combined
16  *
17  *-------------------------------------------------------------------------
18  */
19 
20 #include "postgres.h"
21 
22 #include "access/htup_details.h"
23 #include "catalog/pg_aggregate.h"
24 #include "catalog/pg_class.h"
25 #include "catalog/pg_language.h"
26 #include "catalog/pg_operator.h"
27 #include "catalog/pg_proc.h"
28 #include "catalog/pg_type.h"
29 #include "executor/executor.h"
30 #include "executor/functions.h"
31 #include "funcapi.h"
32 #include "miscadmin.h"
33 #include "nodes/makefuncs.h"
34 #include "nodes/nodeFuncs.h"
35 #include "optimizer/clauses.h"
36 #include "optimizer/cost.h"
37 #include "optimizer/planmain.h"
38 #include "optimizer/prep.h"
39 #include "optimizer/var.h"
40 #include "parser/analyze.h"
41 #include "parser/parse_agg.h"
42 #include "parser/parse_coerce.h"
43 #include "parser/parse_func.h"
44 #include "rewrite/rewriteManip.h"
45 #include "tcop/tcopprot.h"
46 #include "utils/acl.h"
47 #include "utils/builtins.h"
48 #include "utils/datum.h"
49 #include "utils/fmgroids.h"
50 #include "utils/lsyscache.h"
51 #include "utils/memutils.h"
52 #include "utils/syscache.h"
53 #include "utils/typcache.h"
54 
55 
56 typedef struct
57 {
62 
63 typedef struct
64 {
69  bool estimate;
71 
72 typedef struct
73 {
74  int nargs;
76  int *usecounts;
78 
79 typedef struct
80 {
81  int nargs;
85 
86 typedef struct
87 {
88  char *proname;
89  char *prosrc;
91 
92 typedef struct
93 {
94  char max_hazard; /* worst proparallel hazard found so far */
95  char max_interesting; /* worst proparallel hazard of interest */
96  List *safe_param_ids; /* PARAM_EXEC Param IDs to treat as safe */
98 
99 static bool contain_agg_clause_walker(Node *node, void *context);
100 static bool get_agg_clause_costs_walker(Node *node,
102 static bool find_window_functions_walker(Node *node, WindowFuncLists *lists);
103 static bool contain_subplans_walker(Node *node, void *context);
104 static bool contain_mutable_functions_walker(Node *node, void *context);
105 static bool contain_volatile_functions_walker(Node *node, void *context);
106 static bool contain_volatile_functions_not_nextval_walker(Node *node, void *context);
107 static bool max_parallel_hazard_walker(Node *node,
108  max_parallel_hazard_context *context);
109 static bool contain_nonstrict_functions_walker(Node *node, void *context);
110 static bool contain_context_dependent_node(Node *clause);
111 static bool contain_context_dependent_node_walker(Node *node, int *flags);
112 static bool contain_leaked_vars_walker(Node *node, void *context);
113 static Relids find_nonnullable_rels_walker(Node *node, bool top_level);
114 static List *find_nonnullable_vars_walker(Node *node, bool top_level);
115 static bool is_strict_saop(ScalarArrayOpExpr *expr, bool falseOK);
120  bool *haveNull, bool *forceTrue);
123  bool *haveNull, bool *forceFalse);
124 static Node *simplify_boolean_equality(Oid opno, List *args);
125 static Expr *simplify_function(Oid funcid,
126  Oid result_type, int32 result_typmod,
127  Oid result_collid, Oid input_collid, List **args_p,
128  bool funcvariadic, bool process_args, bool allow_non_const,
130 static List *expand_function_arguments(List *args, Oid result_type,
131  HeapTuple func_tuple);
132 static List *reorder_function_arguments(List *args, HeapTuple func_tuple);
133 static List *add_function_defaults(List *args, HeapTuple func_tuple);
134 static List *fetch_function_defaults(HeapTuple func_tuple);
135 static void recheck_cast_function_args(List *args, Oid result_type,
136  HeapTuple func_tuple);
137 static Expr *evaluate_function(Oid funcid, Oid result_type, int32 result_typmod,
138  Oid result_collid, Oid input_collid, List *args,
139  bool funcvariadic,
140  HeapTuple func_tuple,
142 static Expr *inline_function(Oid funcid, Oid result_type, Oid result_collid,
143  Oid input_collid, List *args,
144  bool funcvariadic,
145  HeapTuple func_tuple,
147 static Node *substitute_actual_parameters(Node *expr, int nargs, List *args,
148  int *usecounts);
151 static void sql_inline_error_callback(void *arg);
152 static Expr *evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod,
153  Oid result_collation);
155  int nargs, List *args);
158 static bool tlist_matches_coltypelist(List *tlist, List *coltypelist);
159 
160 
161 /*****************************************************************************
162  * OPERATOR clause functions
163  *****************************************************************************/
164 
165 /*
166  * make_opclause
167  * Creates an operator clause given its operator info, left operand
168  * and right operand (pass NULL to create single-operand clause),
169  * and collation info.
170  */
171 Expr *
172 make_opclause(Oid opno, Oid opresulttype, bool opretset,
173  Expr *leftop, Expr *rightop,
174  Oid opcollid, Oid inputcollid)
175 {
176  OpExpr *expr = makeNode(OpExpr);
177 
178  expr->opno = opno;
179  expr->opfuncid = InvalidOid;
180  expr->opresulttype = opresulttype;
181  expr->opretset = opretset;
182  expr->opcollid = opcollid;
183  expr->inputcollid = inputcollid;
184  if (rightop)
185  expr->args = list_make2(leftop, rightop);
186  else
187  expr->args = list_make1(leftop);
188  expr->location = -1;
189  return (Expr *) expr;
190 }
191 
192 /*
193  * get_leftop
194  *
195  * Returns the left operand of a clause of the form (op expr expr)
196  * or (op expr)
197  */
198 Node *
199 get_leftop(const Expr *clause)
200 {
201  const OpExpr *expr = (const OpExpr *) clause;
202 
203  if (expr->args != NIL)
204  return linitial(expr->args);
205  else
206  return NULL;
207 }
208 
209 /*
210  * get_rightop
211  *
212  * Returns the right operand in a clause of the form (op expr expr).
213  * NB: result will be NULL if applied to a unary op clause.
214  */
215 Node *
216 get_rightop(const Expr *clause)
217 {
218  const OpExpr *expr = (const OpExpr *) clause;
219 
220  if (list_length(expr->args) >= 2)
221  return lsecond(expr->args);
222  else
223  return NULL;
224 }
225 
226 /*****************************************************************************
227  * NOT clause functions
228  *****************************************************************************/
229 
230 /*
231  * not_clause
232  *
233  * Returns t iff this is a 'not' clause: (NOT expr).
234  */
235 bool
236 not_clause(Node *clause)
237 {
238  return (clause != NULL &&
239  IsA(clause, BoolExpr) &&
240  ((BoolExpr *) clause)->boolop == NOT_EXPR);
241 }
242 
243 /*
244  * make_notclause
245  *
246  * Create a 'not' clause given the expression to be negated.
247  */
248 Expr *
249 make_notclause(Expr *notclause)
250 {
251  BoolExpr *expr = makeNode(BoolExpr);
252 
253  expr->boolop = NOT_EXPR;
254  expr->args = list_make1(notclause);
255  expr->location = -1;
256  return (Expr *) expr;
257 }
258 
259 /*
260  * get_notclausearg
261  *
262  * Retrieve the clause within a 'not' clause
263  */
264 Expr *
266 {
267  return linitial(((BoolExpr *) notclause)->args);
268 }
269 
270 /*****************************************************************************
271  * OR clause functions
272  *****************************************************************************/
273 
274 /*
275  * or_clause
276  *
277  * Returns t iff the clause is an 'or' clause: (OR { expr }).
278  */
279 bool
280 or_clause(Node *clause)
281 {
282  return (clause != NULL &&
283  IsA(clause, BoolExpr) &&
284  ((BoolExpr *) clause)->boolop == OR_EXPR);
285 }
286 
287 /*
288  * make_orclause
289  *
290  * Creates an 'or' clause given a list of its subclauses.
291  */
292 Expr *
293 make_orclause(List *orclauses)
294 {
295  BoolExpr *expr = makeNode(BoolExpr);
296 
297  expr->boolop = OR_EXPR;
298  expr->args = orclauses;
299  expr->location = -1;
300  return (Expr *) expr;
301 }
302 
303 /*****************************************************************************
304  * AND clause functions
305  *****************************************************************************/
306 
307 
308 /*
309  * and_clause
310  *
311  * Returns t iff its argument is an 'and' clause: (AND { expr }).
312  */
313 bool
314 and_clause(Node *clause)
315 {
316  return (clause != NULL &&
317  IsA(clause, BoolExpr) &&
318  ((BoolExpr *) clause)->boolop == AND_EXPR);
319 }
320 
321 /*
322  * make_andclause
323  *
324  * Creates an 'and' clause given a list of its subclauses.
325  */
326 Expr *
327 make_andclause(List *andclauses)
328 {
329  BoolExpr *expr = makeNode(BoolExpr);
330 
331  expr->boolop = AND_EXPR;
332  expr->args = andclauses;
333  expr->location = -1;
334  return (Expr *) expr;
335 }
336 
337 /*
338  * make_and_qual
339  *
340  * Variant of make_andclause for ANDing two qual conditions together.
341  * Qual conditions have the property that a NULL nodetree is interpreted
342  * as 'true'.
343  *
344  * NB: this makes no attempt to preserve AND/OR flatness; so it should not
345  * be used on a qual that has already been run through prepqual.c.
346  */
347 Node *
348 make_and_qual(Node *qual1, Node *qual2)
349 {
350  if (qual1 == NULL)
351  return qual2;
352  if (qual2 == NULL)
353  return qual1;
354  return (Node *) make_andclause(list_make2(qual1, qual2));
355 }
356 
357 /*
358  * The planner frequently prefers to represent qualification expressions
359  * as lists of boolean expressions with implicit AND semantics.
360  *
361  * These functions convert between an AND-semantics expression list and the
362  * ordinary representation of a boolean expression.
363  *
364  * Note that an empty list is considered equivalent to TRUE.
365  */
366 Expr *
368 {
369  if (andclauses == NIL)
370  return (Expr *) makeBoolConst(true, false);
371  else if (list_length(andclauses) == 1)
372  return (Expr *) linitial(andclauses);
373  else
374  return make_andclause(andclauses);
375 }
376 
377 List *
379 {
380  /*
381  * NB: because the parser sets the qual field to NULL in a query that has
382  * no WHERE clause, we must consider a NULL input clause as TRUE, even
383  * though one might more reasonably think it FALSE. Grumble. If this
384  * causes trouble, consider changing the parser's behavior.
385  */
386  if (clause == NULL)
387  return NIL; /* NULL -> NIL list == TRUE */
388  else if (and_clause((Node *) clause))
389  return ((BoolExpr *) clause)->args;
390  else if (IsA(clause, Const) &&
391  !((Const *) clause)->constisnull &&
392  DatumGetBool(((Const *) clause)->constvalue))
393  return NIL; /* constant TRUE input -> NIL list */
394  else
395  return list_make1(clause);
396 }
397 
398 
399 /*****************************************************************************
400  * Aggregate-function clause manipulation
401  *****************************************************************************/
402 
403 /*
404  * contain_agg_clause
405  * Recursively search for Aggref/GroupingFunc nodes within a clause.
406  *
407  * Returns true if any aggregate found.
408  *
409  * This does not descend into subqueries, and so should be used only after
410  * reduction of sublinks to subplans, or in contexts where it's known there
411  * are no subqueries. There mustn't be outer-aggregate references either.
412  *
413  * (If you want something like this but able to deal with subqueries,
414  * see rewriteManip.c's contain_aggs_of_level().)
415  */
416 bool
418 {
419  return contain_agg_clause_walker(clause, NULL);
420 }
421 
422 static bool
423 contain_agg_clause_walker(Node *node, void *context)
424 {
425  if (node == NULL)
426  return false;
427  if (IsA(node, Aggref))
428  {
429  Assert(((Aggref *) node)->agglevelsup == 0);
430  return true; /* abort the tree traversal and return true */
431  }
432  if (IsA(node, GroupingFunc))
433  {
434  Assert(((GroupingFunc *) node)->agglevelsup == 0);
435  return true; /* abort the tree traversal and return true */
436  }
437  Assert(!IsA(node, SubLink));
438  return expression_tree_walker(node, contain_agg_clause_walker, context);
439 }
440 
441 /*
442  * get_agg_clause_costs
443  * Recursively find the Aggref nodes in an expression tree, and
444  * accumulate cost information about them.
445  *
446  * 'aggsplit' tells us the expected partial-aggregation mode, which affects
447  * the cost estimates.
448  *
449  * NOTE that the counts/costs are ADDED to those already in *costs ... so
450  * the caller is responsible for zeroing the struct initially.
451  *
452  * We count the nodes, estimate their execution costs, and estimate the total
453  * space needed for their transition state values if all are evaluated in
454  * parallel (as would be done in a HashAgg plan). Also, we check whether
455  * partial aggregation is feasible. See AggClauseCosts for the exact set
456  * of statistics collected.
457  *
458  * In addition, we mark Aggref nodes with the correct aggtranstype, so
459  * that that doesn't need to be done repeatedly. (That makes this function's
460  * name a bit of a misnomer.)
461  *
462  * This does not descend into subqueries, and so should be used only after
463  * reduction of sublinks to subplans, or in contexts where it's known there
464  * are no subqueries. There mustn't be outer-aggregate references either.
465  */
466 void
468  AggClauseCosts *costs)
469 {
471 
472  context.root = root;
473  context.aggsplit = aggsplit;
474  context.costs = costs;
475  (void) get_agg_clause_costs_walker(clause, &context);
476 }
477 
478 static bool
480 {
481  if (node == NULL)
482  return false;
483  if (IsA(node, Aggref))
484  {
485  Aggref *aggref = (Aggref *) node;
486  AggClauseCosts *costs = context->costs;
487  HeapTuple aggTuple;
488  Form_pg_aggregate aggform;
489  Oid aggtransfn;
490  Oid aggfinalfn;
491  Oid aggcombinefn;
492  Oid aggserialfn;
493  Oid aggdeserialfn;
494  Oid aggtranstype;
495  int32 aggtransspace;
496  QualCost argcosts;
497 
498  Assert(aggref->agglevelsup == 0);
499 
500  /*
501  * Fetch info about aggregate from pg_aggregate. Note it's correct to
502  * ignore the moving-aggregate variant, since what we're concerned
503  * with here is aggregates not window functions.
504  */
505  aggTuple = SearchSysCache1(AGGFNOID,
506  ObjectIdGetDatum(aggref->aggfnoid));
507  if (!HeapTupleIsValid(aggTuple))
508  elog(ERROR, "cache lookup failed for aggregate %u",
509  aggref->aggfnoid);
510  aggform = (Form_pg_aggregate) GETSTRUCT(aggTuple);
511  aggtransfn = aggform->aggtransfn;
512  aggfinalfn = aggform->aggfinalfn;
513  aggcombinefn = aggform->aggcombinefn;
514  aggserialfn = aggform->aggserialfn;
515  aggdeserialfn = aggform->aggdeserialfn;
516  aggtranstype = aggform->aggtranstype;
517  aggtransspace = aggform->aggtransspace;
518  ReleaseSysCache(aggTuple);
519 
520  /*
521  * Resolve the possibly-polymorphic aggregate transition type, unless
522  * already done in a previous pass over the expression.
523  */
524  if (OidIsValid(aggref->aggtranstype))
525  aggtranstype = aggref->aggtranstype;
526  else
527  {
528  Oid inputTypes[FUNC_MAX_ARGS];
529  int numArguments;
530 
531  /* extract argument types (ignoring any ORDER BY expressions) */
532  numArguments = get_aggregate_argtypes(aggref, inputTypes);
533 
534  /* resolve actual type of transition state, if polymorphic */
535  aggtranstype = resolve_aggregate_transtype(aggref->aggfnoid,
536  aggtranstype,
537  inputTypes,
538  numArguments);
539  aggref->aggtranstype = aggtranstype;
540  }
541 
542  /*
543  * Count it, and check for cases requiring ordered input. Note that
544  * ordered-set aggs always have nonempty aggorder. Any ordered-input
545  * case also defeats partial aggregation.
546  */
547  costs->numAggs++;
548  if (aggref->aggorder != NIL || aggref->aggdistinct != NIL)
549  {
550  costs->numOrderedAggs++;
551  costs->hasNonPartial = true;
552  }
553 
554  /*
555  * Check whether partial aggregation is feasible, unless we already
556  * found out that we can't do it.
557  */
558  if (!costs->hasNonPartial)
559  {
560  /*
561  * If there is no combine function, then partial aggregation is
562  * not possible.
563  */
564  if (!OidIsValid(aggcombinefn))
565  costs->hasNonPartial = true;
566 
567  /*
568  * If we have any aggs with transtype INTERNAL then we must check
569  * whether they have serialization/deserialization functions; if
570  * not, we can't serialize partial-aggregation results.
571  */
572  else if (aggtranstype == INTERNALOID &&
573  (!OidIsValid(aggserialfn) || !OidIsValid(aggdeserialfn)))
574  costs->hasNonSerial = true;
575  }
576 
577  /*
578  * Add the appropriate component function execution costs to
579  * appropriate totals.
580  */
581  if (DO_AGGSPLIT_COMBINE(context->aggsplit))
582  {
583  /* charge for combining previously aggregated states */
584  costs->transCost.per_tuple += get_func_cost(aggcombinefn) * cpu_operator_cost;
585  }
586  else
587  costs->transCost.per_tuple += get_func_cost(aggtransfn) * cpu_operator_cost;
588  if (DO_AGGSPLIT_DESERIALIZE(context->aggsplit) &&
589  OidIsValid(aggdeserialfn))
590  costs->transCost.per_tuple += get_func_cost(aggdeserialfn) * cpu_operator_cost;
591  if (DO_AGGSPLIT_SERIALIZE(context->aggsplit) &&
592  OidIsValid(aggserialfn))
593  costs->finalCost += get_func_cost(aggserialfn) * cpu_operator_cost;
594  if (!DO_AGGSPLIT_SKIPFINAL(context->aggsplit) &&
595  OidIsValid(aggfinalfn))
596  costs->finalCost += get_func_cost(aggfinalfn) * cpu_operator_cost;
597 
598  /*
599  * These costs are incurred only by the initial aggregate node, so we
600  * mustn't include them again at upper levels.
601  */
602  if (!DO_AGGSPLIT_COMBINE(context->aggsplit))
603  {
604  /* add the input expressions' cost to per-input-row costs */
605  cost_qual_eval_node(&argcosts, (Node *) aggref->args, context->root);
606  costs->transCost.startup += argcosts.startup;
607  costs->transCost.per_tuple += argcosts.per_tuple;
608 
609  /*
610  * Add any filter's cost to per-input-row costs.
611  *
612  * XXX Ideally we should reduce input expression costs according
613  * to filter selectivity, but it's not clear it's worth the
614  * trouble.
615  */
616  if (aggref->aggfilter)
617  {
618  cost_qual_eval_node(&argcosts, (Node *) aggref->aggfilter,
619  context->root);
620  costs->transCost.startup += argcosts.startup;
621  costs->transCost.per_tuple += argcosts.per_tuple;
622  }
623  }
624 
625  /*
626  * If there are direct arguments, treat their evaluation cost like the
627  * cost of the finalfn.
628  */
629  if (aggref->aggdirectargs)
630  {
631  cost_qual_eval_node(&argcosts, (Node *) aggref->aggdirectargs,
632  context->root);
633  costs->transCost.startup += argcosts.startup;
634  costs->finalCost += argcosts.per_tuple;
635  }
636 
637  /*
638  * If the transition type is pass-by-value then it doesn't add
639  * anything to the required size of the hashtable. If it is
640  * pass-by-reference then we have to add the estimated size of the
641  * value itself, plus palloc overhead.
642  */
643  if (!get_typbyval(aggtranstype))
644  {
645  int32 avgwidth;
646 
647  /* Use average width if aggregate definition gave one */
648  if (aggtransspace > 0)
649  avgwidth = aggtransspace;
650  else if (aggtransfn == F_ARRAY_APPEND)
651  {
652  /*
653  * If the transition function is array_append(), it'll use an
654  * expanded array as transvalue, which will occupy at least
655  * ALLOCSET_SMALL_INITSIZE and possibly more. Use that as the
656  * estimate for lack of a better idea.
657  */
658  avgwidth = ALLOCSET_SMALL_INITSIZE;
659  }
660  else
661  {
662  /*
663  * If transition state is of same type as first aggregated
664  * input, assume it's the same typmod (same width) as well.
665  * This works for cases like MAX/MIN and is probably somewhat
666  * reasonable otherwise.
667  */
668  int32 aggtranstypmod = -1;
669 
670  if (aggref->args)
671  {
672  TargetEntry *tle = (TargetEntry *) linitial(aggref->args);
673 
674  if (aggtranstype == exprType((Node *) tle->expr))
675  aggtranstypmod = exprTypmod((Node *) tle->expr);
676  }
677 
678  avgwidth = get_typavgwidth(aggtranstype, aggtranstypmod);
679  }
680 
681  avgwidth = MAXALIGN(avgwidth);
682  costs->transitionSpace += avgwidth + 2 * sizeof(void *);
683  }
684  else if (aggtranstype == INTERNALOID)
685  {
686  /*
687  * INTERNAL transition type is a special case: although INTERNAL
688  * is pass-by-value, it's almost certainly being used as a pointer
689  * to some large data structure. The aggregate definition can
690  * provide an estimate of the size. If it doesn't, then we assume
691  * ALLOCSET_DEFAULT_INITSIZE, which is a good guess if the data is
692  * being kept in a private memory context, as is done by
693  * array_agg() for instance.
694  */
695  if (aggtransspace > 0)
696  costs->transitionSpace += aggtransspace;
697  else
699  }
700 
701  /*
702  * We assume that the parser checked that there are no aggregates (of
703  * this level anyway) in the aggregated arguments, direct arguments,
704  * or filter clause. Hence, we need not recurse into any of them.
705  */
706  return false;
707  }
708  Assert(!IsA(node, SubLink));
710  (void *) context);
711 }
712 
713 
714 /*****************************************************************************
715  * Window-function clause manipulation
716  *****************************************************************************/
717 
718 /*
719  * contain_window_function
720  * Recursively search for WindowFunc nodes within a clause.
721  *
722  * Since window functions don't have level fields, but are hard-wired to
723  * be associated with the current query level, this is just the same as
724  * rewriteManip.c's function.
725  */
726 bool
728 {
729  return contain_windowfuncs(clause);
730 }
731 
732 /*
733  * find_window_functions
734  * Locate all the WindowFunc nodes in an expression tree, and organize
735  * them by winref ID number.
736  *
737  * Caller must provide an upper bound on the winref IDs expected in the tree.
738  */
740 find_window_functions(Node *clause, Index maxWinRef)
741 {
742  WindowFuncLists *lists = palloc(sizeof(WindowFuncLists));
743 
744  lists->numWindowFuncs = 0;
745  lists->maxWinRef = maxWinRef;
746  lists->windowFuncs = (List **) palloc0((maxWinRef + 1) * sizeof(List *));
747  (void) find_window_functions_walker(clause, lists);
748  return lists;
749 }
750 
751 static bool
753 {
754  if (node == NULL)
755  return false;
756  if (IsA(node, WindowFunc))
757  {
758  WindowFunc *wfunc = (WindowFunc *) node;
759 
760  /* winref is unsigned, so one-sided test is OK */
761  if (wfunc->winref > lists->maxWinRef)
762  elog(ERROR, "WindowFunc contains out-of-range winref %u",
763  wfunc->winref);
764  /* eliminate duplicates, so that we avoid repeated computation */
765  if (!list_member(lists->windowFuncs[wfunc->winref], wfunc))
766  {
767  lists->windowFuncs[wfunc->winref] =
768  lappend(lists->windowFuncs[wfunc->winref], wfunc);
769  lists->numWindowFuncs++;
770  }
771 
772  /*
773  * We assume that the parser checked that there are no window
774  * functions in the arguments or filter clause. Hence, we need not
775  * recurse into them. (If either the parser or the planner screws up
776  * on this point, the executor will still catch it; see ExecInitExpr.)
777  */
778  return false;
779  }
780  Assert(!IsA(node, SubLink));
782  (void *) lists);
783 }
784 
785 
786 /*****************************************************************************
787  * Support for expressions returning sets
788  *****************************************************************************/
789 
790 /*
791  * expression_returns_set_rows
792  * Estimate the number of rows returned by a set-returning expression.
793  * The result is 1 if it's not a set-returning expression.
794  *
795  * We should only examine the top-level function or operator; it used to be
796  * appropriate to recurse, but not anymore. (Even if there are more SRFs in
797  * the function's inputs, their multipliers are accounted for separately.)
798  *
799  * Note: keep this in sync with expression_returns_set() in nodes/nodeFuncs.c.
800  */
801 double
803 {
804  if (clause == NULL)
805  return 1.0;
806  if (IsA(clause, FuncExpr))
807  {
808  FuncExpr *expr = (FuncExpr *) clause;
809 
810  if (expr->funcretset)
811  return clamp_row_est(get_func_rows(expr->funcid));
812  }
813  if (IsA(clause, OpExpr))
814  {
815  OpExpr *expr = (OpExpr *) clause;
816 
817  if (expr->opretset)
818  {
819  set_opfuncid(expr);
820  return clamp_row_est(get_func_rows(expr->opfuncid));
821  }
822  }
823  return 1.0;
824 }
825 
826 
827 /*****************************************************************************
828  * Subplan clause manipulation
829  *****************************************************************************/
830 
831 /*
832  * contain_subplans
833  * Recursively search for subplan nodes within a clause.
834  *
835  * If we see a SubLink node, we will return true. This is only possible if
836  * the expression tree hasn't yet been transformed by subselect.c. We do not
837  * know whether the node will produce a true subplan or just an initplan,
838  * but we make the conservative assumption that it will be a subplan.
839  *
840  * Returns true if any subplan found.
841  */
842 bool
844 {
845  return contain_subplans_walker(clause, NULL);
846 }
847 
848 static bool
849 contain_subplans_walker(Node *node, void *context)
850 {
851  if (node == NULL)
852  return false;
853  if (IsA(node, SubPlan) ||
854  IsA(node, AlternativeSubPlan) ||
855  IsA(node, SubLink))
856  return true; /* abort the tree traversal and return true */
857  return expression_tree_walker(node, contain_subplans_walker, context);
858 }
859 
860 
861 /*****************************************************************************
862  * Check clauses for mutable functions
863  *****************************************************************************/
864 
865 /*
866  * contain_mutable_functions
867  * Recursively search for mutable functions within a clause.
868  *
869  * Returns true if any mutable function (or operator implemented by a
870  * mutable function) is found. This test is needed so that we don't
871  * mistakenly think that something like "WHERE random() < 0.5" can be treated
872  * as a constant qualification.
873  *
874  * We will recursively look into Query nodes (i.e., SubLink sub-selects)
875  * but not into SubPlans. See comments for contain_volatile_functions().
876  */
877 bool
879 {
880  return contain_mutable_functions_walker(clause, NULL);
881 }
882 
883 static bool
884 contain_mutable_functions_checker(Oid func_id, void *context)
885 {
886  return (func_volatile(func_id) != PROVOLATILE_IMMUTABLE);
887 }
888 
889 static bool
891 {
892  if (node == NULL)
893  return false;
894  /* Check for mutable functions in node itself */
896  context))
897  return true;
898 
899  if (IsA(node, SQLValueFunction))
900  {
901  /* all variants of SQLValueFunction are stable */
902  return true;
903  }
904 
905  if (IsA(node, NextValueExpr))
906  {
907  /* NextValueExpr is volatile */
908  return true;
909  }
910 
911  /*
912  * It should be safe to treat MinMaxExpr as immutable, because it will
913  * depend on a non-cross-type btree comparison function, and those should
914  * always be immutable. Treating XmlExpr as immutable is more dubious,
915  * and treating CoerceToDomain as immutable is outright dangerous. But we
916  * have done so historically, and changing this would probably cause more
917  * problems than it would fix. In practice, if you have a non-immutable
918  * domain constraint you are in for pain anyhow.
919  */
920 
921  /* Recurse to check arguments */
922  if (IsA(node, Query))
923  {
924  /* Recurse into subselects */
925  return query_tree_walker((Query *) node,
927  context, 0);
928  }
930  context);
931 }
932 
933 
934 /*****************************************************************************
935  * Check clauses for volatile functions
936  *****************************************************************************/
937 
938 /*
939  * contain_volatile_functions
940  * Recursively search for volatile functions within a clause.
941  *
942  * Returns true if any volatile function (or operator implemented by a
943  * volatile function) is found. This test prevents, for example,
944  * invalid conversions of volatile expressions into indexscan quals.
945  *
946  * We will recursively look into Query nodes (i.e., SubLink sub-selects)
947  * but not into SubPlans. This is a bit odd, but intentional. If we are
948  * looking at a SubLink, we are probably deciding whether a query tree
949  * transformation is safe, and a contained sub-select should affect that;
950  * for example, duplicating a sub-select containing a volatile function
951  * would be bad. However, once we've got to the stage of having SubPlans,
952  * subsequent planning need not consider volatility within those, since
953  * the executor won't change its evaluation rules for a SubPlan based on
954  * volatility.
955  */
956 bool
958 {
959  return contain_volatile_functions_walker(clause, NULL);
960 }
961 
962 static bool
964 {
965  return (func_volatile(func_id) == PROVOLATILE_VOLATILE);
966 }
967 
968 static bool
970 {
971  if (node == NULL)
972  return false;
973  /* Check for volatile functions in node itself */
975  context))
976  return true;
977 
978  if (IsA(node, NextValueExpr))
979  {
980  /* NextValueExpr is volatile */
981  return true;
982  }
983 
984  /*
985  * See notes in contain_mutable_functions_walker about why we treat
986  * MinMaxExpr, XmlExpr, and CoerceToDomain as immutable, while
987  * SQLValueFunction is stable. Hence, none of them are of interest here.
988  */
989 
990  /* Recurse to check arguments */
991  if (IsA(node, Query))
992  {
993  /* Recurse into subselects */
994  return query_tree_walker((Query *) node,
996  context, 0);
997  }
999  context);
1000 }
1001 
1002 /*
1003  * Special purpose version of contain_volatile_functions() for use in COPY:
1004  * ignore nextval(), but treat all other functions normally.
1005  */
1006 bool
1008 {
1009  return contain_volatile_functions_not_nextval_walker(clause, NULL);
1010 }
1011 
1012 static bool
1014 {
1015  return (func_id != F_NEXTVAL_OID &&
1016  func_volatile(func_id) == PROVOLATILE_VOLATILE);
1017 }
1018 
1019 static bool
1021 {
1022  if (node == NULL)
1023  return false;
1024  /* Check for volatile functions in node itself */
1025  if (check_functions_in_node(node,
1027  context))
1028  return true;
1029 
1030  /*
1031  * See notes in contain_mutable_functions_walker about why we treat
1032  * MinMaxExpr, XmlExpr, and CoerceToDomain as immutable, while
1033  * SQLValueFunction is stable. Hence, none of them are of interest here.
1034  * Also, since we're intentionally ignoring nextval(), presumably we
1035  * should ignore NextValueExpr.
1036  */
1037 
1038  /* Recurse to check arguments */
1039  if (IsA(node, Query))
1040  {
1041  /* Recurse into subselects */
1042  return query_tree_walker((Query *) node,
1044  context, 0);
1045  }
1046  return expression_tree_walker(node,
1048  context);
1049 }
1050 
1051 
1052 /*****************************************************************************
1053  * Check queries for parallel unsafe and/or restricted constructs
1054  *****************************************************************************/
1055 
1056 /*
1057  * max_parallel_hazard
1058  * Find the worst parallel-hazard level in the given query
1059  *
1060  * Returns the worst function hazard property (the earliest in this list:
1061  * PROPARALLEL_UNSAFE, PROPARALLEL_RESTRICTED, PROPARALLEL_SAFE) that can
1062  * be found in the given parsetree. We use this to find out whether the query
1063  * can be parallelized at all. The caller will also save the result in
1064  * PlannerGlobal so as to short-circuit checks of portions of the querytree
1065  * later, in the common case where everything is SAFE.
1066  */
1067 char
1069 {
1071 
1072  context.max_hazard = PROPARALLEL_SAFE;
1074  context.safe_param_ids = NIL;
1075  (void) max_parallel_hazard_walker((Node *) parse, &context);
1076  return context.max_hazard;
1077 }
1078 
1079 /*
1080  * is_parallel_safe
1081  * Detect whether the given expr contains only parallel-safe functions
1082  *
1083  * root->glob->maxParallelHazard must previously have been set to the
1084  * result of max_parallel_hazard() on the whole query.
1085  */
1086 bool
1088 {
1090  PlannerInfo *proot;
1091  ListCell *l;
1092 
1093  /*
1094  * Even if the original querytree contained nothing unsafe, we need to
1095  * search the expression if we have generated any PARAM_EXEC Params while
1096  * planning, because those are parallel-restricted and there might be one
1097  * in this expression. But otherwise we don't need to look.
1098  */
1099  if (root->glob->maxParallelHazard == PROPARALLEL_SAFE &&
1100  root->glob->paramExecTypes == NIL)
1101  return true;
1102  /* Else use max_parallel_hazard's search logic, but stop on RESTRICTED */
1103  context.max_hazard = PROPARALLEL_SAFE;
1105  context.safe_param_ids = NIL;
1106 
1107  /*
1108  * The params that refer to the same or parent query level are considered
1109  * parallel-safe. The idea is that we compute such params at Gather or
1110  * Gather Merge node and pass their value to workers.
1111  */
1112  for (proot = root; proot != NULL; proot = proot->parent_root)
1113  {
1114  foreach(l, proot->init_plans)
1115  {
1116  SubPlan *initsubplan = (SubPlan *) lfirst(l);
1117  ListCell *l2;
1118 
1119  foreach(l2, initsubplan->setParam)
1120  context.safe_param_ids = lcons_int(lfirst_int(l2),
1121  context.safe_param_ids);
1122  }
1123  }
1124 
1125  return !max_parallel_hazard_walker(node, &context);
1126 }
1127 
1128 /* core logic for all parallel-hazard checks */
1129 static bool
1131 {
1132  switch (proparallel)
1133  {
1134  case PROPARALLEL_SAFE:
1135  /* nothing to see here, move along */
1136  break;
1138  /* increase max_hazard to RESTRICTED */
1139  Assert(context->max_hazard != PROPARALLEL_UNSAFE);
1140  context->max_hazard = proparallel;
1141  /* done if we are not expecting any unsafe functions */
1142  if (context->max_interesting == proparallel)
1143  return true;
1144  break;
1145  case PROPARALLEL_UNSAFE:
1146  context->max_hazard = proparallel;
1147  /* we're always done at the first unsafe construct */
1148  return true;
1149  default:
1150  elog(ERROR, "unrecognized proparallel value \"%c\"", proparallel);
1151  break;
1152  }
1153  return false;
1154 }
1155 
1156 /* check_functions_in_node callback */
1157 static bool
1158 max_parallel_hazard_checker(Oid func_id, void *context)
1159 {
1160  return max_parallel_hazard_test(func_parallel(func_id),
1161  (max_parallel_hazard_context *) context);
1162 }
1163 
1164 static bool
1166 {
1167  if (node == NULL)
1168  return false;
1169 
1170  /* Check for hazardous functions in node itself */
1172  context))
1173  return true;
1174 
1175  /*
1176  * It should be OK to treat MinMaxExpr as parallel-safe, since btree
1177  * opclass support functions are generally parallel-safe. XmlExpr is a
1178  * bit more dubious but we can probably get away with it. We err on the
1179  * side of caution by treating CoerceToDomain as parallel-restricted.
1180  * (Note: in principle that's wrong because a domain constraint could
1181  * contain a parallel-unsafe function; but useful constraints probably
1182  * never would have such, and assuming they do would cripple use of
1183  * parallel query in the presence of domain types.) SQLValueFunction
1184  * should be safe in all cases. NextValueExpr is parallel-unsafe.
1185  */
1186  if (IsA(node, CoerceToDomain))
1187  {
1189  return true;
1190  }
1191 
1192  if (IsA(node, NextValueExpr))
1193  {
1195  return true;
1196  }
1197 
1198  /*
1199  * As a notational convenience for callers, look through RestrictInfo.
1200  */
1201  else if (IsA(node, RestrictInfo))
1202  {
1203  RestrictInfo *rinfo = (RestrictInfo *) node;
1204 
1205  return max_parallel_hazard_walker((Node *) rinfo->clause, context);
1206  }
1207 
1208  /*
1209  * Really we should not see SubLink during a max_interesting == restricted
1210  * scan, but if we do, return true.
1211  */
1212  else if (IsA(node, SubLink))
1213  {
1215  return true;
1216  }
1217 
1218  /*
1219  * Only parallel-safe SubPlans can be sent to workers. Within the
1220  * testexpr of the SubPlan, Params representing the output columns of the
1221  * subplan can be treated as parallel-safe, so temporarily add their IDs
1222  * to the safe_param_ids list while examining the testexpr.
1223  */
1224  else if (IsA(node, SubPlan))
1225  {
1226  SubPlan *subplan = (SubPlan *) node;
1227  List *save_safe_param_ids;
1228 
1229  if (!subplan->parallel_safe &&
1231  return true;
1232  save_safe_param_ids = context->safe_param_ids;
1233  context->safe_param_ids = list_concat(list_copy(subplan->paramIds),
1234  context->safe_param_ids);
1235  if (max_parallel_hazard_walker(subplan->testexpr, context))
1236  return true; /* no need to restore safe_param_ids */
1237  context->safe_param_ids = save_safe_param_ids;
1238  /* we must also check args, but no special Param treatment there */
1239  if (max_parallel_hazard_walker((Node *) subplan->args, context))
1240  return true;
1241  /* don't want to recurse normally, so we're done */
1242  return false;
1243  }
1244 
1245  /*
1246  * We can't pass Params to workers at the moment either, so they are also
1247  * parallel-restricted, unless they are PARAM_EXTERN Params or are
1248  * PARAM_EXEC Params listed in safe_param_ids, meaning they could be
1249  * either generated within the worker or can be computed in master and
1250  * then their value can be passed to the worker.
1251  */
1252  else if (IsA(node, Param))
1253  {
1254  Param *param = (Param *) node;
1255 
1256  if (param->paramkind == PARAM_EXTERN)
1257  return false;
1258 
1259  if (param->paramkind != PARAM_EXEC ||
1260  !list_member_int(context->safe_param_ids, param->paramid))
1261  {
1263  return true;
1264  }
1265  return false; /* nothing to recurse to */
1266  }
1267 
1268  /*
1269  * When we're first invoked on a completely unplanned tree, we must
1270  * recurse into subqueries so to as to locate parallel-unsafe constructs
1271  * anywhere in the tree.
1272  */
1273  else if (IsA(node, Query))
1274  {
1275  Query *query = (Query *) node;
1276 
1277  /* SELECT FOR UPDATE/SHARE must be treated as unsafe */
1278  if (query->rowMarks != NULL)
1279  {
1280  context->max_hazard = PROPARALLEL_UNSAFE;
1281  return true;
1282  }
1283 
1284  /* Recurse into subselects */
1285  return query_tree_walker(query,
1287  context, 0);
1288  }
1289 
1290  /* Recurse to check arguments */
1291  return expression_tree_walker(node,
1293  context);
1294 }
1295 
1296 
1297 /*****************************************************************************
1298  * Check clauses for nonstrict functions
1299  *****************************************************************************/
1300 
1301 /*
1302  * contain_nonstrict_functions
1303  * Recursively search for nonstrict functions within a clause.
1304  *
1305  * Returns true if any nonstrict construct is found --- ie, anything that
1306  * could produce non-NULL output with a NULL input.
1307  *
1308  * The idea here is that the caller has verified that the expression contains
1309  * one or more Var or Param nodes (as appropriate for the caller's need), and
1310  * now wishes to prove that the expression result will be NULL if any of these
1311  * inputs is NULL. If we return false, then the proof succeeded.
1312  */
1313 bool
1315 {
1316  return contain_nonstrict_functions_walker(clause, NULL);
1317 }
1318 
1319 static bool
1321 {
1322  return !func_strict(func_id);
1323 }
1324 
1325 static bool
1327 {
1328  if (node == NULL)
1329  return false;
1330  if (IsA(node, Aggref))
1331  {
1332  /* an aggregate could return non-null with null input */
1333  return true;
1334  }
1335  if (IsA(node, GroupingFunc))
1336  {
1337  /*
1338  * A GroupingFunc doesn't evaluate its arguments, and therefore must
1339  * be treated as nonstrict.
1340  */
1341  return true;
1342  }
1343  if (IsA(node, WindowFunc))
1344  {
1345  /* a window function could return non-null with null input */
1346  return true;
1347  }
1348  if (IsA(node, ArrayRef))
1349  {
1350  /* array assignment is nonstrict, but subscripting is strict */
1351  if (((ArrayRef *) node)->refassgnexpr != NULL)
1352  return true;
1353  /* else fall through to check args */
1354  }
1355  if (IsA(node, DistinctExpr))
1356  {
1357  /* IS DISTINCT FROM is inherently non-strict */
1358  return true;
1359  }
1360  if (IsA(node, NullIfExpr))
1361  {
1362  /* NULLIF is inherently non-strict */
1363  return true;
1364  }
1365  if (IsA(node, BoolExpr))
1366  {
1367  BoolExpr *expr = (BoolExpr *) node;
1368 
1369  switch (expr->boolop)
1370  {
1371  case AND_EXPR:
1372  case OR_EXPR:
1373  /* AND, OR are inherently non-strict */
1374  return true;
1375  default:
1376  break;
1377  }
1378  }
1379  if (IsA(node, SubLink))
1380  {
1381  /* In some cases a sublink might be strict, but in general not */
1382  return true;
1383  }
1384  if (IsA(node, SubPlan))
1385  return true;
1386  if (IsA(node, AlternativeSubPlan))
1387  return true;
1388  if (IsA(node, FieldStore))
1389  return true;
1390  if (IsA(node, ArrayCoerceExpr))
1391  {
1392  /*
1393  * ArrayCoerceExpr is strict at the array level, regardless of what
1394  * the per-element expression is; so we should ignore elemexpr and
1395  * recurse only into the arg.
1396  */
1397  return expression_tree_walker((Node *) ((ArrayCoerceExpr *) node)->arg,
1399  context);
1400  }
1401  if (IsA(node, CaseExpr))
1402  return true;
1403  if (IsA(node, ArrayExpr))
1404  return true;
1405  if (IsA(node, RowExpr))
1406  return true;
1407  if (IsA(node, RowCompareExpr))
1408  return true;
1409  if (IsA(node, CoalesceExpr))
1410  return true;
1411  if (IsA(node, MinMaxExpr))
1412  return true;
1413  if (IsA(node, XmlExpr))
1414  return true;
1415  if (IsA(node, NullTest))
1416  return true;
1417  if (IsA(node, BooleanTest))
1418  return true;
1419 
1420  /* Check other function-containing nodes */
1422  context))
1423  return true;
1424 
1426  context);
1427 }
1428 
1429 /*****************************************************************************
1430  * Check clauses for context-dependent nodes
1431  *****************************************************************************/
1432 
1433 /*
1434  * contain_context_dependent_node
1435  * Recursively search for context-dependent nodes within a clause.
1436  *
1437  * CaseTestExpr nodes must appear directly within the corresponding CaseExpr,
1438  * not nested within another one, or they'll see the wrong test value. If one
1439  * appears "bare" in the arguments of a SQL function, then we can't inline the
1440  * SQL function for fear of creating such a situation.
1441  *
1442  * CoerceToDomainValue would have the same issue if domain CHECK expressions
1443  * could get inlined into larger expressions, but presently that's impossible.
1444  * Still, it might be allowed in future, or other node types with similar
1445  * issues might get invented. So give this function a generic name, and set
1446  * up the recursion state to allow multiple flag bits.
1447  */
1448 static bool
1450 {
1451  int flags = 0;
1452 
1453  return contain_context_dependent_node_walker(clause, &flags);
1454 }
1455 
1456 #define CCDN_IN_CASEEXPR 0x0001 /* CaseTestExpr okay here? */
1457 
1458 static bool
1460 {
1461  if (node == NULL)
1462  return false;
1463  if (IsA(node, CaseTestExpr))
1464  return !(*flags & CCDN_IN_CASEEXPR);
1465  if (IsA(node, CaseExpr))
1466  {
1467  CaseExpr *caseexpr = (CaseExpr *) node;
1468 
1469  /*
1470  * If this CASE doesn't have a test expression, then it doesn't create
1471  * a context in which CaseTestExprs should appear, so just fall
1472  * through and treat it as a generic expression node.
1473  */
1474  if (caseexpr->arg)
1475  {
1476  int save_flags = *flags;
1477  bool res;
1478 
1479  /*
1480  * Note: in principle, we could distinguish the various sub-parts
1481  * of a CASE construct and set the flag bit only for some of them,
1482  * since we are only expecting CaseTestExprs to appear in the
1483  * "expr" subtree of the CaseWhen nodes. But it doesn't really
1484  * seem worth any extra code. If there are any bare CaseTestExprs
1485  * elsewhere in the CASE, something's wrong already.
1486  */
1487  *flags |= CCDN_IN_CASEEXPR;
1488  res = expression_tree_walker(node,
1490  (void *) flags);
1491  *flags = save_flags;
1492  return res;
1493  }
1494  }
1496  (void *) flags);
1497 }
1498 
1499 /*****************************************************************************
1500  * Check clauses for Vars passed to non-leakproof functions
1501  *****************************************************************************/
1502 
1503 /*
1504  * contain_leaked_vars
1505  * Recursively scan a clause to discover whether it contains any Var
1506  * nodes (of the current query level) that are passed as arguments to
1507  * leaky functions.
1508  *
1509  * Returns true if the clause contains any non-leakproof functions that are
1510  * passed Var nodes of the current query level, and which might therefore leak
1511  * data. Such clauses must be applied after any lower-level security barrier
1512  * clauses.
1513  */
1514 bool
1516 {
1517  return contain_leaked_vars_walker(clause, NULL);
1518 }
1519 
1520 static bool
1521 contain_leaked_vars_checker(Oid func_id, void *context)
1522 {
1523  return !get_func_leakproof(func_id);
1524 }
1525 
1526 static bool
1527 contain_leaked_vars_walker(Node *node, void *context)
1528 {
1529  if (node == NULL)
1530  return false;
1531 
1532  switch (nodeTag(node))
1533  {
1534  case T_Var:
1535  case T_Const:
1536  case T_Param:
1537  case T_ArrayRef:
1538  case T_ArrayExpr:
1539  case T_FieldSelect:
1540  case T_FieldStore:
1541  case T_NamedArgExpr:
1542  case T_BoolExpr:
1543  case T_RelabelType:
1544  case T_CollateExpr:
1545  case T_CaseExpr:
1546  case T_CaseTestExpr:
1547  case T_RowExpr:
1548  case T_MinMaxExpr:
1549  case T_SQLValueFunction:
1550  case T_NullTest:
1551  case T_BooleanTest:
1552  case T_NextValueExpr:
1553  case T_List:
1554 
1555  /*
1556  * We know these node types don't contain function calls; but
1557  * something further down in the node tree might.
1558  */
1559  break;
1560 
1561  case T_FuncExpr:
1562  case T_OpExpr:
1563  case T_DistinctExpr:
1564  case T_NullIfExpr:
1565  case T_ScalarArrayOpExpr:
1566  case T_CoerceViaIO:
1567  case T_ArrayCoerceExpr:
1568 
1569  /*
1570  * If node contains a leaky function call, and there's any Var
1571  * underneath it, reject.
1572  */
1574  context) &&
1575  contain_var_clause(node))
1576  return true;
1577  break;
1578 
1579  case T_RowCompareExpr:
1580  {
1581  /*
1582  * It's worth special-casing this because a leaky comparison
1583  * function only compromises one pair of row elements, which
1584  * might not contain Vars while others do.
1585  */
1586  RowCompareExpr *rcexpr = (RowCompareExpr *) node;
1587  ListCell *opid;
1588  ListCell *larg;
1589  ListCell *rarg;
1590 
1591  forthree(opid, rcexpr->opnos,
1592  larg, rcexpr->largs,
1593  rarg, rcexpr->rargs)
1594  {
1595  Oid funcid = get_opcode(lfirst_oid(opid));
1596 
1597  if (!get_func_leakproof(funcid) &&
1598  (contain_var_clause((Node *) lfirst(larg)) ||
1599  contain_var_clause((Node *) lfirst(rarg))))
1600  return true;
1601  }
1602  }
1603  break;
1604 
1605  case T_CurrentOfExpr:
1606 
1607  /*
1608  * WHERE CURRENT OF doesn't contain leaky function calls.
1609  * Moreover, it is essential that this is considered non-leaky,
1610  * since the planner must always generate a TID scan when CURRENT
1611  * OF is present -- c.f. cost_tidscan.
1612  */
1613  return false;
1614 
1615  default:
1616 
1617  /*
1618  * If we don't recognize the node tag, assume it might be leaky.
1619  * This prevents an unexpected security hole if someone adds a new
1620  * node type that can call a function.
1621  */
1622  return true;
1623  }
1625  context);
1626 }
1627 
1628 /*
1629  * find_nonnullable_rels
1630  * Determine which base rels are forced nonnullable by given clause.
1631  *
1632  * Returns the set of all Relids that are referenced in the clause in such
1633  * a way that the clause cannot possibly return TRUE if any of these Relids
1634  * is an all-NULL row. (It is OK to err on the side of conservatism; hence
1635  * the analysis here is simplistic.)
1636  *
1637  * The semantics here are subtly different from contain_nonstrict_functions:
1638  * that function is concerned with NULL results from arbitrary expressions,
1639  * but here we assume that the input is a Boolean expression, and wish to
1640  * see if NULL inputs will provably cause a FALSE-or-NULL result. We expect
1641  * the expression to have been AND/OR flattened and converted to implicit-AND
1642  * format.
1643  *
1644  * Note: this function is largely duplicative of find_nonnullable_vars().
1645  * The reason not to simplify this function into a thin wrapper around
1646  * find_nonnullable_vars() is that the tested conditions really are different:
1647  * a clause like "t1.v1 IS NOT NULL OR t1.v2 IS NOT NULL" does not prove
1648  * that either v1 or v2 can't be NULL, but it does prove that the t1 row
1649  * as a whole can't be all-NULL.
1650  *
1651  * top_level is true while scanning top-level AND/OR structure; here, showing
1652  * the result is either FALSE or NULL is good enough. top_level is false when
1653  * we have descended below a NOT or a strict function: now we must be able to
1654  * prove that the subexpression goes to NULL.
1655  *
1656  * We don't use expression_tree_walker here because we don't want to descend
1657  * through very many kinds of nodes; only the ones we can be sure are strict.
1658  */
1659 Relids
1661 {
1662  return find_nonnullable_rels_walker(clause, true);
1663 }
1664 
1665 static Relids
1666 find_nonnullable_rels_walker(Node *node, bool top_level)
1667 {
1668  Relids result = NULL;
1669  ListCell *l;
1670 
1671  if (node == NULL)
1672  return NULL;
1673  if (IsA(node, Var))
1674  {
1675  Var *var = (Var *) node;
1676 
1677  if (var->varlevelsup == 0)
1678  result = bms_make_singleton(var->varno);
1679  }
1680  else if (IsA(node, List))
1681  {
1682  /*
1683  * At top level, we are examining an implicit-AND list: if any of the
1684  * arms produces FALSE-or-NULL then the result is FALSE-or-NULL. If
1685  * not at top level, we are examining the arguments of a strict
1686  * function: if any of them produce NULL then the result of the
1687  * function must be NULL. So in both cases, the set of nonnullable
1688  * rels is the union of those found in the arms, and we pass down the
1689  * top_level flag unmodified.
1690  */
1691  foreach(l, (List *) node)
1692  {
1693  result = bms_join(result,
1695  top_level));
1696  }
1697  }
1698  else if (IsA(node, FuncExpr))
1699  {
1700  FuncExpr *expr = (FuncExpr *) node;
1701 
1702  if (func_strict(expr->funcid))
1703  result = find_nonnullable_rels_walker((Node *) expr->args, false);
1704  }
1705  else if (IsA(node, OpExpr))
1706  {
1707  OpExpr *expr = (OpExpr *) node;
1708 
1709  set_opfuncid(expr);
1710  if (func_strict(expr->opfuncid))
1711  result = find_nonnullable_rels_walker((Node *) expr->args, false);
1712  }
1713  else if (IsA(node, ScalarArrayOpExpr))
1714  {
1715  ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1716 
1717  if (is_strict_saop(expr, true))
1718  result = find_nonnullable_rels_walker((Node *) expr->args, false);
1719  }
1720  else if (IsA(node, BoolExpr))
1721  {
1722  BoolExpr *expr = (BoolExpr *) node;
1723 
1724  switch (expr->boolop)
1725  {
1726  case AND_EXPR:
1727  /* At top level we can just recurse (to the List case) */
1728  if (top_level)
1729  {
1730  result = find_nonnullable_rels_walker((Node *) expr->args,
1731  top_level);
1732  break;
1733  }
1734 
1735  /*
1736  * Below top level, even if one arm produces NULL, the result
1737  * could be FALSE (hence not NULL). However, if *all* the
1738  * arms produce NULL then the result is NULL, so we can take
1739  * the intersection of the sets of nonnullable rels, just as
1740  * for OR. Fall through to share code.
1741  */
1742  /* FALL THRU */
1743  case OR_EXPR:
1744 
1745  /*
1746  * OR is strict if all of its arms are, so we can take the
1747  * intersection of the sets of nonnullable rels for each arm.
1748  * This works for both values of top_level.
1749  */
1750  foreach(l, expr->args)
1751  {
1752  Relids subresult;
1753 
1754  subresult = find_nonnullable_rels_walker(lfirst(l),
1755  top_level);
1756  if (result == NULL) /* first subresult? */
1757  result = subresult;
1758  else
1759  result = bms_int_members(result, subresult);
1760 
1761  /*
1762  * If the intersection is empty, we can stop looking. This
1763  * also justifies the test for first-subresult above.
1764  */
1765  if (bms_is_empty(result))
1766  break;
1767  }
1768  break;
1769  case NOT_EXPR:
1770  /* NOT will return null if its arg is null */
1771  result = find_nonnullable_rels_walker((Node *) expr->args,
1772  false);
1773  break;
1774  default:
1775  elog(ERROR, "unrecognized boolop: %d", (int) expr->boolop);
1776  break;
1777  }
1778  }
1779  else if (IsA(node, RelabelType))
1780  {
1781  RelabelType *expr = (RelabelType *) node;
1782 
1783  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1784  }
1785  else if (IsA(node, CoerceViaIO))
1786  {
1787  /* not clear this is useful, but it can't hurt */
1788  CoerceViaIO *expr = (CoerceViaIO *) node;
1789 
1790  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1791  }
1792  else if (IsA(node, ArrayCoerceExpr))
1793  {
1794  /* ArrayCoerceExpr is strict at the array level; ignore elemexpr */
1795  ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
1796 
1797  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1798  }
1799  else if (IsA(node, ConvertRowtypeExpr))
1800  {
1801  /* not clear this is useful, but it can't hurt */
1802  ConvertRowtypeExpr *expr = (ConvertRowtypeExpr *) node;
1803 
1804  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1805  }
1806  else if (IsA(node, CollateExpr))
1807  {
1808  CollateExpr *expr = (CollateExpr *) node;
1809 
1810  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1811  }
1812  else if (IsA(node, NullTest))
1813  {
1814  /* IS NOT NULL can be considered strict, but only at top level */
1815  NullTest *expr = (NullTest *) node;
1816 
1817  if (top_level && expr->nulltesttype == IS_NOT_NULL && !expr->argisrow)
1818  result = find_nonnullable_rels_walker((Node *) expr->arg, false);
1819  }
1820  else if (IsA(node, BooleanTest))
1821  {
1822  /* Boolean tests that reject NULL are strict at top level */
1823  BooleanTest *expr = (BooleanTest *) node;
1824 
1825  if (top_level &&
1826  (expr->booltesttype == IS_TRUE ||
1827  expr->booltesttype == IS_FALSE ||
1828  expr->booltesttype == IS_NOT_UNKNOWN))
1829  result = find_nonnullable_rels_walker((Node *) expr->arg, false);
1830  }
1831  else if (IsA(node, PlaceHolderVar))
1832  {
1833  PlaceHolderVar *phv = (PlaceHolderVar *) node;
1834 
1835  result = find_nonnullable_rels_walker((Node *) phv->phexpr, top_level);
1836  }
1837  return result;
1838 }
1839 
1840 /*
1841  * find_nonnullable_vars
1842  * Determine which Vars are forced nonnullable by given clause.
1843  *
1844  * Returns a list of all level-zero Vars that are referenced in the clause in
1845  * such a way that the clause cannot possibly return TRUE if any of these Vars
1846  * is NULL. (It is OK to err on the side of conservatism; hence the analysis
1847  * here is simplistic.)
1848  *
1849  * The semantics here are subtly different from contain_nonstrict_functions:
1850  * that function is concerned with NULL results from arbitrary expressions,
1851  * but here we assume that the input is a Boolean expression, and wish to
1852  * see if NULL inputs will provably cause a FALSE-or-NULL result. We expect
1853  * the expression to have been AND/OR flattened and converted to implicit-AND
1854  * format.
1855  *
1856  * The result is a palloc'd List, but we have not copied the member Var nodes.
1857  * Also, we don't bother trying to eliminate duplicate entries.
1858  *
1859  * top_level is true while scanning top-level AND/OR structure; here, showing
1860  * the result is either FALSE or NULL is good enough. top_level is false when
1861  * we have descended below a NOT or a strict function: now we must be able to
1862  * prove that the subexpression goes to NULL.
1863  *
1864  * We don't use expression_tree_walker here because we don't want to descend
1865  * through very many kinds of nodes; only the ones we can be sure are strict.
1866  */
1867 List *
1869 {
1870  return find_nonnullable_vars_walker(clause, true);
1871 }
1872 
1873 static List *
1874 find_nonnullable_vars_walker(Node *node, bool top_level)
1875 {
1876  List *result = NIL;
1877  ListCell *l;
1878 
1879  if (node == NULL)
1880  return NIL;
1881  if (IsA(node, Var))
1882  {
1883  Var *var = (Var *) node;
1884 
1885  if (var->varlevelsup == 0)
1886  result = list_make1(var);
1887  }
1888  else if (IsA(node, List))
1889  {
1890  /*
1891  * At top level, we are examining an implicit-AND list: if any of the
1892  * arms produces FALSE-or-NULL then the result is FALSE-or-NULL. If
1893  * not at top level, we are examining the arguments of a strict
1894  * function: if any of them produce NULL then the result of the
1895  * function must be NULL. So in both cases, the set of nonnullable
1896  * vars is the union of those found in the arms, and we pass down the
1897  * top_level flag unmodified.
1898  */
1899  foreach(l, (List *) node)
1900  {
1901  result = list_concat(result,
1903  top_level));
1904  }
1905  }
1906  else if (IsA(node, FuncExpr))
1907  {
1908  FuncExpr *expr = (FuncExpr *) node;
1909 
1910  if (func_strict(expr->funcid))
1911  result = find_nonnullable_vars_walker((Node *) expr->args, false);
1912  }
1913  else if (IsA(node, OpExpr))
1914  {
1915  OpExpr *expr = (OpExpr *) node;
1916 
1917  set_opfuncid(expr);
1918  if (func_strict(expr->opfuncid))
1919  result = find_nonnullable_vars_walker((Node *) expr->args, false);
1920  }
1921  else if (IsA(node, ScalarArrayOpExpr))
1922  {
1923  ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1924 
1925  if (is_strict_saop(expr, true))
1926  result = find_nonnullable_vars_walker((Node *) expr->args, false);
1927  }
1928  else if (IsA(node, BoolExpr))
1929  {
1930  BoolExpr *expr = (BoolExpr *) node;
1931 
1932  switch (expr->boolop)
1933  {
1934  case AND_EXPR:
1935  /* At top level we can just recurse (to the List case) */
1936  if (top_level)
1937  {
1938  result = find_nonnullable_vars_walker((Node *) expr->args,
1939  top_level);
1940  break;
1941  }
1942 
1943  /*
1944  * Below top level, even if one arm produces NULL, the result
1945  * could be FALSE (hence not NULL). However, if *all* the
1946  * arms produce NULL then the result is NULL, so we can take
1947  * the intersection of the sets of nonnullable vars, just as
1948  * for OR. Fall through to share code.
1949  */
1950  /* FALL THRU */
1951  case OR_EXPR:
1952 
1953  /*
1954  * OR is strict if all of its arms are, so we can take the
1955  * intersection of the sets of nonnullable vars for each arm.
1956  * This works for both values of top_level.
1957  */
1958  foreach(l, expr->args)
1959  {
1960  List *subresult;
1961 
1962  subresult = find_nonnullable_vars_walker(lfirst(l),
1963  top_level);
1964  if (result == NIL) /* first subresult? */
1965  result = subresult;
1966  else
1967  result = list_intersection(result, subresult);
1968 
1969  /*
1970  * If the intersection is empty, we can stop looking. This
1971  * also justifies the test for first-subresult above.
1972  */
1973  if (result == NIL)
1974  break;
1975  }
1976  break;
1977  case NOT_EXPR:
1978  /* NOT will return null if its arg is null */
1979  result = find_nonnullable_vars_walker((Node *) expr->args,
1980  false);
1981  break;
1982  default:
1983  elog(ERROR, "unrecognized boolop: %d", (int) expr->boolop);
1984  break;
1985  }
1986  }
1987  else if (IsA(node, RelabelType))
1988  {
1989  RelabelType *expr = (RelabelType *) node;
1990 
1991  result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1992  }
1993  else if (IsA(node, CoerceViaIO))
1994  {
1995  /* not clear this is useful, but it can't hurt */
1996  CoerceViaIO *expr = (CoerceViaIO *) node;
1997 
1998  result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1999  }
2000  else if (IsA(node, ArrayCoerceExpr))
2001  {
2002  /* ArrayCoerceExpr is strict at the array level; ignore elemexpr */
2003  ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
2004 
2005  result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
2006  }
2007  else if (IsA(node, ConvertRowtypeExpr))
2008  {
2009  /* not clear this is useful, but it can't hurt */
2010  ConvertRowtypeExpr *expr = (ConvertRowtypeExpr *) node;
2011 
2012  result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
2013  }
2014  else if (IsA(node, CollateExpr))
2015  {
2016  CollateExpr *expr = (CollateExpr *) node;
2017 
2018  result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
2019  }
2020  else if (IsA(node, NullTest))
2021  {
2022  /* IS NOT NULL can be considered strict, but only at top level */
2023  NullTest *expr = (NullTest *) node;
2024 
2025  if (top_level && expr->nulltesttype == IS_NOT_NULL && !expr->argisrow)
2026  result = find_nonnullable_vars_walker((Node *) expr->arg, false);
2027  }
2028  else if (IsA(node, BooleanTest))
2029  {
2030  /* Boolean tests that reject NULL are strict at top level */
2031  BooleanTest *expr = (BooleanTest *) node;
2032 
2033  if (top_level &&
2034  (expr->booltesttype == IS_TRUE ||
2035  expr->booltesttype == IS_FALSE ||
2036  expr->booltesttype == IS_NOT_UNKNOWN))
2037  result = find_nonnullable_vars_walker((Node *) expr->arg, false);
2038  }
2039  else if (IsA(node, PlaceHolderVar))
2040  {
2041  PlaceHolderVar *phv = (PlaceHolderVar *) node;
2042 
2043  result = find_nonnullable_vars_walker((Node *) phv->phexpr, top_level);
2044  }
2045  return result;
2046 }
2047 
2048 /*
2049  * find_forced_null_vars
2050  * Determine which Vars must be NULL for the given clause to return TRUE.
2051  *
2052  * This is the complement of find_nonnullable_vars: find the level-zero Vars
2053  * that must be NULL for the clause to return TRUE. (It is OK to err on the
2054  * side of conservatism; hence the analysis here is simplistic. In fact,
2055  * we only detect simple "var IS NULL" tests at the top level.)
2056  *
2057  * The result is a palloc'd List, but we have not copied the member Var nodes.
2058  * Also, we don't bother trying to eliminate duplicate entries.
2059  */
2060 List *
2062 {
2063  List *result = NIL;
2064  Var *var;
2065  ListCell *l;
2066 
2067  if (node == NULL)
2068  return NIL;
2069  /* Check single-clause cases using subroutine */
2070  var = find_forced_null_var(node);
2071  if (var)
2072  {
2073  result = list_make1(var);
2074  }
2075  /* Otherwise, handle AND-conditions */
2076  else if (IsA(node, List))
2077  {
2078  /*
2079  * At top level, we are examining an implicit-AND list: if any of the
2080  * arms produces FALSE-or-NULL then the result is FALSE-or-NULL.
2081  */
2082  foreach(l, (List *) node)
2083  {
2084  result = list_concat(result,
2086  }
2087  }
2088  else if (IsA(node, BoolExpr))
2089  {
2090  BoolExpr *expr = (BoolExpr *) node;
2091 
2092  /*
2093  * We don't bother considering the OR case, because it's fairly
2094  * unlikely anyone would write "v1 IS NULL OR v1 IS NULL". Likewise,
2095  * the NOT case isn't worth expending code on.
2096  */
2097  if (expr->boolop == AND_EXPR)
2098  {
2099  /* At top level we can just recurse (to the List case) */
2100  result = find_forced_null_vars((Node *) expr->args);
2101  }
2102  }
2103  return result;
2104 }
2105 
2106 /*
2107  * find_forced_null_var
2108  * Return the Var forced null by the given clause, or NULL if it's
2109  * not an IS NULL-type clause. For success, the clause must enforce
2110  * *only* nullness of the particular Var, not any other conditions.
2111  *
2112  * This is just the single-clause case of find_forced_null_vars(), without
2113  * any allowance for AND conditions. It's used by initsplan.c on individual
2114  * qual clauses. The reason for not just applying find_forced_null_vars()
2115  * is that if an AND of an IS NULL clause with something else were to somehow
2116  * survive AND/OR flattening, initsplan.c might get fooled into discarding
2117  * the whole clause when only the IS NULL part of it had been proved redundant.
2118  */
2119 Var *
2121 {
2122  if (node == NULL)
2123  return NULL;
2124  if (IsA(node, NullTest))
2125  {
2126  /* check for var IS NULL */
2127  NullTest *expr = (NullTest *) node;
2128 
2129  if (expr->nulltesttype == IS_NULL && !expr->argisrow)
2130  {
2131  Var *var = (Var *) expr->arg;
2132 
2133  if (var && IsA(var, Var) &&
2134  var->varlevelsup == 0)
2135  return var;
2136  }
2137  }
2138  else if (IsA(node, BooleanTest))
2139  {
2140  /* var IS UNKNOWN is equivalent to var IS NULL */
2141  BooleanTest *expr = (BooleanTest *) node;
2142 
2143  if (expr->booltesttype == IS_UNKNOWN)
2144  {
2145  Var *var = (Var *) expr->arg;
2146 
2147  if (var && IsA(var, Var) &&
2148  var->varlevelsup == 0)
2149  return var;
2150  }
2151  }
2152  return NULL;
2153 }
2154 
2155 /*
2156  * Can we treat a ScalarArrayOpExpr as strict?
2157  *
2158  * If "falseOK" is true, then a "false" result can be considered strict,
2159  * else we need to guarantee an actual NULL result for NULL input.
2160  *
2161  * "foo op ALL array" is strict if the op is strict *and* we can prove
2162  * that the array input isn't an empty array. We can check that
2163  * for the cases of an array constant and an ARRAY[] construct.
2164  *
2165  * "foo op ANY array" is strict in the falseOK sense if the op is strict.
2166  * If not falseOK, the test is the same as for "foo op ALL array".
2167  */
2168 static bool
2169 is_strict_saop(ScalarArrayOpExpr *expr, bool falseOK)
2170 {
2171  Node *rightop;
2172 
2173  /* The contained operator must be strict. */
2174  set_sa_opfuncid(expr);
2175  if (!func_strict(expr->opfuncid))
2176  return false;
2177  /* If ANY and falseOK, that's all we need to check. */
2178  if (expr->useOr && falseOK)
2179  return true;
2180  /* Else, we have to see if the array is provably non-empty. */
2181  Assert(list_length(expr->args) == 2);
2182  rightop = (Node *) lsecond(expr->args);
2183  if (rightop && IsA(rightop, Const))
2184  {
2185  Datum arraydatum = ((Const *) rightop)->constvalue;
2186  bool arrayisnull = ((Const *) rightop)->constisnull;
2187  ArrayType *arrayval;
2188  int nitems;
2189 
2190  if (arrayisnull)
2191  return false;
2192  arrayval = DatumGetArrayTypeP(arraydatum);
2193  nitems = ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
2194  if (nitems > 0)
2195  return true;
2196  }
2197  else if (rightop && IsA(rightop, ArrayExpr))
2198  {
2199  ArrayExpr *arrayexpr = (ArrayExpr *) rightop;
2200 
2201  if (arrayexpr->elements != NIL && !arrayexpr->multidims)
2202  return true;
2203  }
2204  return false;
2205 }
2206 
2207 
2208 /*****************************************************************************
2209  * Check for "pseudo-constant" clauses
2210  *****************************************************************************/
2211 
2212 /*
2213  * is_pseudo_constant_clause
2214  * Detect whether an expression is "pseudo constant", ie, it contains no
2215  * variables of the current query level and no uses of volatile functions.
2216  * Such an expr is not necessarily a true constant: it can still contain
2217  * Params and outer-level Vars, not to mention functions whose results
2218  * may vary from one statement to the next. However, the expr's value
2219  * will be constant over any one scan of the current query, so it can be
2220  * used as, eg, an indexscan key.
2221  *
2222  * CAUTION: this function omits to test for one very important class of
2223  * not-constant expressions, namely aggregates (Aggrefs). In current usage
2224  * this is only applied to WHERE clauses and so a check for Aggrefs would be
2225  * a waste of cycles; but be sure to also check contain_agg_clause() if you
2226  * want to know about pseudo-constness in other contexts. The same goes
2227  * for window functions (WindowFuncs).
2228  */
2229 bool
2231 {
2232  /*
2233  * We could implement this check in one recursive scan. But since the
2234  * check for volatile functions is both moderately expensive and unlikely
2235  * to fail, it seems better to look for Vars first and only check for
2236  * volatile functions if we find no Vars.
2237  */
2238  if (!contain_var_clause(clause) &&
2239  !contain_volatile_functions(clause))
2240  return true;
2241  return false;
2242 }
2243 
2244 /*
2245  * is_pseudo_constant_clause_relids
2246  * Same as above, except caller already has available the var membership
2247  * of the expression; this lets us avoid the contain_var_clause() scan.
2248  */
2249 bool
2251 {
2252  if (bms_is_empty(relids) &&
2253  !contain_volatile_functions(clause))
2254  return true;
2255  return false;
2256 }
2257 
2258 
2259 /*****************************************************************************
2260  * *
2261  * General clause-manipulating routines *
2262  * *
2263  *****************************************************************************/
2264 
2265 /*
2266  * NumRelids
2267  * (formerly clause_relids)
2268  *
2269  * Returns the number of different relations referenced in 'clause'.
2270  */
2271 int
2272 NumRelids(Node *clause)
2273 {
2274  Relids varnos = pull_varnos(clause);
2275  int result = bms_num_members(varnos);
2276 
2277  bms_free(varnos);
2278  return result;
2279 }
2280 
2281 /*
2282  * CommuteOpExpr: commute a binary operator clause
2283  *
2284  * XXX the clause is destructively modified!
2285  */
2286 void
2288 {
2289  Oid opoid;
2290  Node *temp;
2291 
2292  /* Sanity checks: caller is at fault if these fail */
2293  if (!is_opclause(clause) ||
2294  list_length(clause->args) != 2)
2295  elog(ERROR, "cannot commute non-binary-operator clause");
2296 
2297  opoid = get_commutator(clause->opno);
2298 
2299  if (!OidIsValid(opoid))
2300  elog(ERROR, "could not find commutator for operator %u",
2301  clause->opno);
2302 
2303  /*
2304  * modify the clause in-place!
2305  */
2306  clause->opno = opoid;
2307  clause->opfuncid = InvalidOid;
2308  /* opresulttype, opretset, opcollid, inputcollid need not change */
2309 
2310  temp = linitial(clause->args);
2311  linitial(clause->args) = lsecond(clause->args);
2312  lsecond(clause->args) = temp;
2313 }
2314 
2315 /*
2316  * CommuteRowCompareExpr: commute a RowCompareExpr clause
2317  *
2318  * XXX the clause is destructively modified!
2319  */
2320 void
2322 {
2323  List *newops;
2324  List *temp;
2325  ListCell *l;
2326 
2327  /* Sanity checks: caller is at fault if these fail */
2328  if (!IsA(clause, RowCompareExpr))
2329  elog(ERROR, "expected a RowCompareExpr");
2330 
2331  /* Build list of commuted operators */
2332  newops = NIL;
2333  foreach(l, clause->opnos)
2334  {
2335  Oid opoid = lfirst_oid(l);
2336 
2337  opoid = get_commutator(opoid);
2338  if (!OidIsValid(opoid))
2339  elog(ERROR, "could not find commutator for operator %u",
2340  lfirst_oid(l));
2341  newops = lappend_oid(newops, opoid);
2342  }
2343 
2344  /*
2345  * modify the clause in-place!
2346  */
2347  switch (clause->rctype)
2348  {
2349  case ROWCOMPARE_LT:
2350  clause->rctype = ROWCOMPARE_GT;
2351  break;
2352  case ROWCOMPARE_LE:
2353  clause->rctype = ROWCOMPARE_GE;
2354  break;
2355  case ROWCOMPARE_GE:
2356  clause->rctype = ROWCOMPARE_LE;
2357  break;
2358  case ROWCOMPARE_GT:
2359  clause->rctype = ROWCOMPARE_LT;
2360  break;
2361  default:
2362  elog(ERROR, "unexpected RowCompare type: %d",
2363  (int) clause->rctype);
2364  break;
2365  }
2366 
2367  clause->opnos = newops;
2368 
2369  /*
2370  * Note: we need not change the opfamilies list; we assume any btree
2371  * opfamily containing an operator will also contain its commutator.
2372  * Collations don't change either.
2373  */
2374 
2375  temp = clause->largs;
2376  clause->largs = clause->rargs;
2377  clause->rargs = temp;
2378 }
2379 
2380 /*
2381  * Helper for eval_const_expressions: check that datatype of an attribute
2382  * is still what it was when the expression was parsed. This is needed to
2383  * guard against improper simplification after ALTER COLUMN TYPE. (XXX we
2384  * may well need to make similar checks elsewhere?)
2385  *
2386  * rowtypeid may come from a whole-row Var, and therefore it can be a domain
2387  * over composite, but for this purpose we only care about checking the type
2388  * of a contained field.
2389  */
2390 static bool
2391 rowtype_field_matches(Oid rowtypeid, int fieldnum,
2392  Oid expectedtype, int32 expectedtypmod,
2393  Oid expectedcollation)
2394 {
2395  TupleDesc tupdesc;
2396  Form_pg_attribute attr;
2397 
2398  /* No issue for RECORD, since there is no way to ALTER such a type */
2399  if (rowtypeid == RECORDOID)
2400  return true;
2401  tupdesc = lookup_rowtype_tupdesc_domain(rowtypeid, -1, false);
2402  if (fieldnum <= 0 || fieldnum > tupdesc->natts)
2403  {
2404  ReleaseTupleDesc(tupdesc);
2405  return false;
2406  }
2407  attr = TupleDescAttr(tupdesc, fieldnum - 1);
2408  if (attr->attisdropped ||
2409  attr->atttypid != expectedtype ||
2410  attr->atttypmod != expectedtypmod ||
2411  attr->attcollation != expectedcollation)
2412  {
2413  ReleaseTupleDesc(tupdesc);
2414  return false;
2415  }
2416  ReleaseTupleDesc(tupdesc);
2417  return true;
2418 }
2419 
2420 
2421 /*--------------------
2422  * eval_const_expressions
2423  *
2424  * Reduce any recognizably constant subexpressions of the given
2425  * expression tree, for example "2 + 2" => "4". More interestingly,
2426  * we can reduce certain boolean expressions even when they contain
2427  * non-constant subexpressions: "x OR true" => "true" no matter what
2428  * the subexpression x is. (XXX We assume that no such subexpression
2429  * will have important side-effects, which is not necessarily a good
2430  * assumption in the presence of user-defined functions; do we need a
2431  * pg_proc flag that prevents discarding the execution of a function?)
2432  *
2433  * We do understand that certain functions may deliver non-constant
2434  * results even with constant inputs, "nextval()" being the classic
2435  * example. Functions that are not marked "immutable" in pg_proc
2436  * will not be pre-evaluated here, although we will reduce their
2437  * arguments as far as possible.
2438  *
2439  * Whenever a function is eliminated from the expression by means of
2440  * constant-expression evaluation or inlining, we add the function to
2441  * root->glob->invalItems. This ensures the plan is known to depend on
2442  * such functions, even though they aren't referenced anymore.
2443  *
2444  * We assume that the tree has already been type-checked and contains
2445  * only operators and functions that are reasonable to try to execute.
2446  *
2447  * NOTE: "root" can be passed as NULL if the caller never wants to do any
2448  * Param substitutions nor receive info about inlined functions.
2449  *
2450  * NOTE: the planner assumes that this will always flatten nested AND and
2451  * OR clauses into N-argument form. See comments in prepqual.c.
2452  *
2453  * NOTE: another critical effect is that any function calls that require
2454  * default arguments will be expanded, and named-argument calls will be
2455  * converted to positional notation. The executor won't handle either.
2456  *--------------------
2457  */
2458 Node *
2460 {
2462 
2463  if (root)
2464  context.boundParams = root->glob->boundParams; /* bound Params */
2465  else
2466  context.boundParams = NULL;
2467  context.root = root; /* for inlined-function dependencies */
2468  context.active_fns = NIL; /* nothing being recursively simplified */
2469  context.case_val = NULL; /* no CASE being examined */
2470  context.estimate = false; /* safe transformations only */
2471  return eval_const_expressions_mutator(node, &context);
2472 }
2473 
2474 /*--------------------
2475  * estimate_expression_value
2476  *
2477  * This function attempts to estimate the value of an expression for
2478  * planning purposes. It is in essence a more aggressive version of
2479  * eval_const_expressions(): we will perform constant reductions that are
2480  * not necessarily 100% safe, but are reasonable for estimation purposes.
2481  *
2482  * Currently the extra steps that are taken in this mode are:
2483  * 1. Substitute values for Params, where a bound Param value has been made
2484  * available by the caller of planner(), even if the Param isn't marked
2485  * constant. This effectively means that we plan using the first supplied
2486  * value of the Param.
2487  * 2. Fold stable, as well as immutable, functions to constants.
2488  * 3. Reduce PlaceHolderVar nodes to their contained expressions.
2489  *--------------------
2490  */
2491 Node *
2493 {
2495 
2496  context.boundParams = root->glob->boundParams; /* bound Params */
2497  /* we do not need to mark the plan as depending on inlined functions */
2498  context.root = NULL;
2499  context.active_fns = NIL; /* nothing being recursively simplified */
2500  context.case_val = NULL; /* no CASE being examined */
2501  context.estimate = true; /* unsafe transformations OK */
2502  return eval_const_expressions_mutator(node, &context);
2503 }
2504 
2505 static Node *
2508 {
2509  if (node == NULL)
2510  return NULL;
2511  switch (nodeTag(node))
2512  {
2513  case T_Param:
2514  {
2515  Param *param = (Param *) node;
2516 
2517  /* Look to see if we've been given a value for this Param */
2518  if (param->paramkind == PARAM_EXTERN &&
2519  context->boundParams != NULL &&
2520  param->paramid > 0 &&
2521  param->paramid <= context->boundParams->numParams)
2522  {
2523  ParamExternData *prm = &context->boundParams->params[param->paramid - 1];
2524 
2525  if (OidIsValid(prm->ptype))
2526  {
2527  /* OK to substitute parameter value? */
2528  if (context->estimate ||
2529  (prm->pflags & PARAM_FLAG_CONST))
2530  {
2531  /*
2532  * Return a Const representing the param value.
2533  * Must copy pass-by-ref datatypes, since the
2534  * Param might be in a memory context
2535  * shorter-lived than our output plan should be.
2536  */
2537  int16 typLen;
2538  bool typByVal;
2539  Datum pval;
2540 
2541  Assert(prm->ptype == param->paramtype);
2542  get_typlenbyval(param->paramtype,
2543  &typLen, &typByVal);
2544  if (prm->isnull || typByVal)
2545  pval = prm->value;
2546  else
2547  pval = datumCopy(prm->value, typByVal, typLen);
2548  return (Node *) makeConst(param->paramtype,
2549  param->paramtypmod,
2550  param->paramcollid,
2551  (int) typLen,
2552  pval,
2553  prm->isnull,
2554  typByVal);
2555  }
2556  }
2557  }
2558 
2559  /*
2560  * Not replaceable, so just copy the Param (no need to
2561  * recurse)
2562  */
2563  return (Node *) copyObject(param);
2564  }
2565  case T_WindowFunc:
2566  {
2567  WindowFunc *expr = (WindowFunc *) node;
2568  Oid funcid = expr->winfnoid;
2569  List *args;
2570  Expr *aggfilter;
2571  HeapTuple func_tuple;
2572  WindowFunc *newexpr;
2573 
2574  /*
2575  * We can't really simplify a WindowFunc node, but we mustn't
2576  * just fall through to the default processing, because we
2577  * have to apply expand_function_arguments to its argument
2578  * list. That takes care of inserting default arguments and
2579  * expanding named-argument notation.
2580  */
2581  func_tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
2582  if (!HeapTupleIsValid(func_tuple))
2583  elog(ERROR, "cache lookup failed for function %u", funcid);
2584 
2585  args = expand_function_arguments(expr->args, expr->wintype,
2586  func_tuple);
2587 
2588  ReleaseSysCache(func_tuple);
2589 
2590  /* Now, recursively simplify the args (which are a List) */
2591  args = (List *)
2594  (void *) context);
2595  /* ... and the filter expression, which isn't */
2596  aggfilter = (Expr *)
2598  context);
2599 
2600  /* And build the replacement WindowFunc node */
2601  newexpr = makeNode(WindowFunc);
2602  newexpr->winfnoid = expr->winfnoid;
2603  newexpr->wintype = expr->wintype;
2604  newexpr->wincollid = expr->wincollid;
2605  newexpr->inputcollid = expr->inputcollid;
2606  newexpr->args = args;
2607  newexpr->aggfilter = aggfilter;
2608  newexpr->winref = expr->winref;
2609  newexpr->winstar = expr->winstar;
2610  newexpr->winagg = expr->winagg;
2611  newexpr->location = expr->location;
2612 
2613  return (Node *) newexpr;
2614  }
2615  case T_FuncExpr:
2616  {
2617  FuncExpr *expr = (FuncExpr *) node;
2618  List *args = expr->args;
2619  Expr *simple;
2620  FuncExpr *newexpr;
2621 
2622  /*
2623  * Code for op/func reduction is pretty bulky, so split it out
2624  * as a separate function. Note: exprTypmod normally returns
2625  * -1 for a FuncExpr, but not when the node is recognizably a
2626  * length coercion; we want to preserve the typmod in the
2627  * eventual Const if so.
2628  */
2629  simple = simplify_function(expr->funcid,
2630  expr->funcresulttype,
2631  exprTypmod(node),
2632  expr->funccollid,
2633  expr->inputcollid,
2634  &args,
2635  expr->funcvariadic,
2636  true,
2637  true,
2638  context);
2639  if (simple) /* successfully simplified it */
2640  return (Node *) simple;
2641 
2642  /*
2643  * The expression cannot be simplified any further, so build
2644  * and return a replacement FuncExpr node using the
2645  * possibly-simplified arguments. Note that we have also
2646  * converted the argument list to positional notation.
2647  */
2648  newexpr = makeNode(FuncExpr);
2649  newexpr->funcid = expr->funcid;
2650  newexpr->funcresulttype = expr->funcresulttype;
2651  newexpr->funcretset = expr->funcretset;
2652  newexpr->funcvariadic = expr->funcvariadic;
2653  newexpr->funcformat = expr->funcformat;
2654  newexpr->funccollid = expr->funccollid;
2655  newexpr->inputcollid = expr->inputcollid;
2656  newexpr->args = args;
2657  newexpr->location = expr->location;
2658  return (Node *) newexpr;
2659  }
2660  case T_OpExpr:
2661  {
2662  OpExpr *expr = (OpExpr *) node;
2663  List *args = expr->args;
2664  Expr *simple;
2665  OpExpr *newexpr;
2666 
2667  /*
2668  * Need to get OID of underlying function. Okay to scribble
2669  * on input to this extent.
2670  */
2671  set_opfuncid(expr);
2672 
2673  /*
2674  * Code for op/func reduction is pretty bulky, so split it out
2675  * as a separate function.
2676  */
2677  simple = simplify_function(expr->opfuncid,
2678  expr->opresulttype, -1,
2679  expr->opcollid,
2680  expr->inputcollid,
2681  &args,
2682  false,
2683  true,
2684  true,
2685  context);
2686  if (simple) /* successfully simplified it */
2687  return (Node *) simple;
2688 
2689  /*
2690  * If the operator is boolean equality or inequality, we know
2691  * how to simplify cases involving one constant and one
2692  * non-constant argument.
2693  */
2694  if (expr->opno == BooleanEqualOperator ||
2695  expr->opno == BooleanNotEqualOperator)
2696  {
2697  simple = (Expr *) simplify_boolean_equality(expr->opno,
2698  args);
2699  if (simple) /* successfully simplified it */
2700  return (Node *) simple;
2701  }
2702 
2703  /*
2704  * The expression cannot be simplified any further, so build
2705  * and return a replacement OpExpr node using the
2706  * possibly-simplified arguments.
2707  */
2708  newexpr = makeNode(OpExpr);
2709  newexpr->opno = expr->opno;
2710  newexpr->opfuncid = expr->opfuncid;
2711  newexpr->opresulttype = expr->opresulttype;
2712  newexpr->opretset = expr->opretset;
2713  newexpr->opcollid = expr->opcollid;
2714  newexpr->inputcollid = expr->inputcollid;
2715  newexpr->args = args;
2716  newexpr->location = expr->location;
2717  return (Node *) newexpr;
2718  }
2719  case T_DistinctExpr:
2720  {
2721  DistinctExpr *expr = (DistinctExpr *) node;
2722  List *args;
2723  ListCell *arg;
2724  bool has_null_input = false;
2725  bool all_null_input = true;
2726  bool has_nonconst_input = false;
2727  Expr *simple;
2728  DistinctExpr *newexpr;
2729 
2730  /*
2731  * Reduce constants in the DistinctExpr's arguments. We know
2732  * args is either NIL or a List node, so we can call
2733  * expression_tree_mutator directly rather than recursing to
2734  * self.
2735  */
2736  args = (List *) expression_tree_mutator((Node *) expr->args,
2738  (void *) context);
2739 
2740  /*
2741  * We must do our own check for NULLs because DistinctExpr has
2742  * different results for NULL input than the underlying
2743  * operator does.
2744  */
2745  foreach(arg, args)
2746  {
2747  if (IsA(lfirst(arg), Const))
2748  {
2749  has_null_input |= ((Const *) lfirst(arg))->constisnull;
2750  all_null_input &= ((Const *) lfirst(arg))->constisnull;
2751  }
2752  else
2753  has_nonconst_input = true;
2754  }
2755 
2756  /* all constants? then can optimize this out */
2757  if (!has_nonconst_input)
2758  {
2759  /* all nulls? then not distinct */
2760  if (all_null_input)
2761  return makeBoolConst(false, false);
2762 
2763  /* one null? then distinct */
2764  if (has_null_input)
2765  return makeBoolConst(true, false);
2766 
2767  /* otherwise try to evaluate the '=' operator */
2768  /* (NOT okay to try to inline it, though!) */
2769 
2770  /*
2771  * Need to get OID of underlying function. Okay to
2772  * scribble on input to this extent.
2773  */
2774  set_opfuncid((OpExpr *) expr); /* rely on struct
2775  * equivalence */
2776 
2777  /*
2778  * Code for op/func reduction is pretty bulky, so split it
2779  * out as a separate function.
2780  */
2781  simple = simplify_function(expr->opfuncid,
2782  expr->opresulttype, -1,
2783  expr->opcollid,
2784  expr->inputcollid,
2785  &args,
2786  false,
2787  false,
2788  false,
2789  context);
2790  if (simple) /* successfully simplified it */
2791  {
2792  /*
2793  * Since the underlying operator is "=", must negate
2794  * its result
2795  */
2796  Const *csimple = castNode(Const, simple);
2797 
2798  csimple->constvalue =
2799  BoolGetDatum(!DatumGetBool(csimple->constvalue));
2800  return (Node *) csimple;
2801  }
2802  }
2803 
2804  /*
2805  * The expression cannot be simplified any further, so build
2806  * and return a replacement DistinctExpr node using the
2807  * possibly-simplified arguments.
2808  */
2809  newexpr = makeNode(DistinctExpr);
2810  newexpr->opno = expr->opno;
2811  newexpr->opfuncid = expr->opfuncid;
2812  newexpr->opresulttype = expr->opresulttype;
2813  newexpr->opretset = expr->opretset;
2814  newexpr->opcollid = expr->opcollid;
2815  newexpr->inputcollid = expr->inputcollid;
2816  newexpr->args = args;
2817  newexpr->location = expr->location;
2818  return (Node *) newexpr;
2819  }
2820  case T_BoolExpr:
2821  {
2822  BoolExpr *expr = (BoolExpr *) node;
2823 
2824  switch (expr->boolop)
2825  {
2826  case OR_EXPR:
2827  {
2828  List *newargs;
2829  bool haveNull = false;
2830  bool forceTrue = false;
2831 
2832  newargs = simplify_or_arguments(expr->args,
2833  context,
2834  &haveNull,
2835  &forceTrue);
2836  if (forceTrue)
2837  return makeBoolConst(true, false);
2838  if (haveNull)
2839  newargs = lappend(newargs,
2840  makeBoolConst(false, true));
2841  /* If all the inputs are FALSE, result is FALSE */
2842  if (newargs == NIL)
2843  return makeBoolConst(false, false);
2844 
2845  /*
2846  * If only one nonconst-or-NULL input, it's the
2847  * result
2848  */
2849  if (list_length(newargs) == 1)
2850  return (Node *) linitial(newargs);
2851  /* Else we still need an OR node */
2852  return (Node *) make_orclause(newargs);
2853  }
2854  case AND_EXPR:
2855  {
2856  List *newargs;
2857  bool haveNull = false;
2858  bool forceFalse = false;
2859 
2860  newargs = simplify_and_arguments(expr->args,
2861  context,
2862  &haveNull,
2863  &forceFalse);
2864  if (forceFalse)
2865  return makeBoolConst(false, false);
2866  if (haveNull)
2867  newargs = lappend(newargs,
2868  makeBoolConst(false, true));
2869  /* If all the inputs are TRUE, result is TRUE */
2870  if (newargs == NIL)
2871  return makeBoolConst(true, false);
2872 
2873  /*
2874  * If only one nonconst-or-NULL input, it's the
2875  * result
2876  */
2877  if (list_length(newargs) == 1)
2878  return (Node *) linitial(newargs);
2879  /* Else we still need an AND node */
2880  return (Node *) make_andclause(newargs);
2881  }
2882  case NOT_EXPR:
2883  {
2884  Node *arg;
2885 
2886  Assert(list_length(expr->args) == 1);
2888  context);
2889 
2890  /*
2891  * Use negate_clause() to see if we can simplify
2892  * away the NOT.
2893  */
2894  return negate_clause(arg);
2895  }
2896  default:
2897  elog(ERROR, "unrecognized boolop: %d",
2898  (int) expr->boolop);
2899  break;
2900  }
2901  break;
2902  }
2903  case T_SubPlan:
2904  case T_AlternativeSubPlan:
2905 
2906  /*
2907  * Return a SubPlan unchanged --- too late to do anything with it.
2908  *
2909  * XXX should we ereport() here instead? Probably this routine
2910  * should never be invoked after SubPlan creation.
2911  */
2912  return node;
2913  case T_RelabelType:
2914  {
2915  /*
2916  * If we can simplify the input to a constant, then we don't
2917  * need the RelabelType node anymore: just change the type
2918  * field of the Const node. Otherwise, must copy the
2919  * RelabelType node.
2920  */
2921  RelabelType *relabel = (RelabelType *) node;
2922  Node *arg;
2923 
2924  arg = eval_const_expressions_mutator((Node *) relabel->arg,
2925  context);
2926 
2927  /*
2928  * If we find stacked RelabelTypes (eg, from foo :: int ::
2929  * oid) we can discard all but the top one.
2930  */
2931  while (arg && IsA(arg, RelabelType))
2932  arg = (Node *) ((RelabelType *) arg)->arg;
2933 
2934  if (arg && IsA(arg, Const))
2935  {
2936  Const *con = (Const *) arg;
2937 
2938  con->consttype = relabel->resulttype;
2939  con->consttypmod = relabel->resulttypmod;
2940  con->constcollid = relabel->resultcollid;
2941  return (Node *) con;
2942  }
2943  else
2944  {
2945  RelabelType *newrelabel = makeNode(RelabelType);
2946 
2947  newrelabel->arg = (Expr *) arg;
2948  newrelabel->resulttype = relabel->resulttype;
2949  newrelabel->resulttypmod = relabel->resulttypmod;
2950  newrelabel->resultcollid = relabel->resultcollid;
2951  newrelabel->relabelformat = relabel->relabelformat;
2952  newrelabel->location = relabel->location;
2953  return (Node *) newrelabel;
2954  }
2955  }
2956  case T_CoerceViaIO:
2957  {
2958  CoerceViaIO *expr = (CoerceViaIO *) node;
2959  List *args;
2960  Oid outfunc;
2961  bool outtypisvarlena;
2962  Oid infunc;
2963  Oid intypioparam;
2964  Expr *simple;
2965  CoerceViaIO *newexpr;
2966 
2967  /* Make a List so we can use simplify_function */
2968  args = list_make1(expr->arg);
2969 
2970  /*
2971  * CoerceViaIO represents calling the source type's output
2972  * function then the result type's input function. So, try to
2973  * simplify it as though it were a stack of two such function
2974  * calls. First we need to know what the functions are.
2975  *
2976  * Note that the coercion functions are assumed not to care
2977  * about input collation, so we just pass InvalidOid for that.
2978  */
2979  getTypeOutputInfo(exprType((Node *) expr->arg),
2980  &outfunc, &outtypisvarlena);
2982  &infunc, &intypioparam);
2983 
2984  simple = simplify_function(outfunc,
2985  CSTRINGOID, -1,
2986  InvalidOid,
2987  InvalidOid,
2988  &args,
2989  false,
2990  true,
2991  true,
2992  context);
2993  if (simple) /* successfully simplified output fn */
2994  {
2995  /*
2996  * Input functions may want 1 to 3 arguments. We always
2997  * supply all three, trusting that nothing downstream will
2998  * complain.
2999  */
3000  args = list_make3(simple,
3001  makeConst(OIDOID,
3002  -1,
3003  InvalidOid,
3004  sizeof(Oid),
3005  ObjectIdGetDatum(intypioparam),
3006  false,
3007  true),
3009  -1,
3010  InvalidOid,
3011  sizeof(int32),
3012  Int32GetDatum(-1),
3013  false,
3014  true));
3015 
3016  simple = simplify_function(infunc,
3017  expr->resulttype, -1,
3018  expr->resultcollid,
3019  InvalidOid,
3020  &args,
3021  false,
3022  false,
3023  true,
3024  context);
3025  if (simple) /* successfully simplified input fn */
3026  return (Node *) simple;
3027  }
3028 
3029  /*
3030  * The expression cannot be simplified any further, so build
3031  * and return a replacement CoerceViaIO node using the
3032  * possibly-simplified argument.
3033  */
3034  newexpr = makeNode(CoerceViaIO);
3035  newexpr->arg = (Expr *) linitial(args);
3036  newexpr->resulttype = expr->resulttype;
3037  newexpr->resultcollid = expr->resultcollid;
3038  newexpr->coerceformat = expr->coerceformat;
3039  newexpr->location = expr->location;
3040  return (Node *) newexpr;
3041  }
3042  case T_ArrayCoerceExpr:
3043  {
3044  ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
3045  Expr *arg;
3046  Expr *elemexpr;
3047  ArrayCoerceExpr *newexpr;
3048 
3049  /*
3050  * Reduce constants in the ArrayCoerceExpr's argument and
3051  * per-element expressions, then build a new ArrayCoerceExpr.
3052  */
3053  arg = (Expr *) eval_const_expressions_mutator((Node *) expr->arg,
3054  context);
3055  elemexpr = (Expr *) eval_const_expressions_mutator((Node *) expr->elemexpr,
3056  context);
3057 
3058  newexpr = makeNode(ArrayCoerceExpr);
3059  newexpr->arg = arg;
3060  newexpr->elemexpr = elemexpr;
3061  newexpr->resulttype = expr->resulttype;
3062  newexpr->resulttypmod = expr->resulttypmod;
3063  newexpr->resultcollid = expr->resultcollid;
3064  newexpr->coerceformat = expr->coerceformat;
3065  newexpr->location = expr->location;
3066 
3067  /*
3068  * If constant argument and per-element expression is
3069  * immutable, we can simplify the whole thing to a constant.
3070  * Exception: although contain_mutable_functions considers
3071  * CoerceToDomain immutable for historical reasons, let's not
3072  * do so here; this ensures coercion to an array-over-domain
3073  * does not apply the domain's constraints until runtime.
3074  */
3075  if (arg && IsA(arg, Const) &&
3076  elemexpr && !IsA(elemexpr, CoerceToDomain) &&
3077  !contain_mutable_functions((Node *) elemexpr))
3078  return (Node *) evaluate_expr((Expr *) newexpr,
3079  newexpr->resulttype,
3080  newexpr->resulttypmod,
3081  newexpr->resultcollid);
3082 
3083  /* Else we must return the partially-simplified node */
3084  return (Node *) newexpr;
3085  }
3086  case T_CollateExpr:
3087  {
3088  /*
3089  * If we can simplify the input to a constant, then we don't
3090  * need the CollateExpr node at all: just change the
3091  * constcollid field of the Const node. Otherwise, replace
3092  * the CollateExpr with a RelabelType. (We do that so as to
3093  * improve uniformity of expression representation and thus
3094  * simplify comparison of expressions.)
3095  */
3096  CollateExpr *collate = (CollateExpr *) node;
3097  Node *arg;
3098 
3099  arg = eval_const_expressions_mutator((Node *) collate->arg,
3100  context);
3101 
3102  if (arg && IsA(arg, Const))
3103  {
3104  Const *con = (Const *) arg;
3105 
3106  con->constcollid = collate->collOid;
3107  return (Node *) con;
3108  }
3109  else if (collate->collOid == exprCollation(arg))
3110  {
3111  /* Don't need a RelabelType either... */
3112  return arg;
3113  }
3114  else
3115  {
3116  RelabelType *relabel = makeNode(RelabelType);
3117 
3118  relabel->resulttype = exprType(arg);
3119  relabel->resulttypmod = exprTypmod(arg);
3120  relabel->resultcollid = collate->collOid;
3122  relabel->location = collate->location;
3123 
3124  /* Don't create stacked RelabelTypes */
3125  while (arg && IsA(arg, RelabelType))
3126  arg = (Node *) ((RelabelType *) arg)->arg;
3127  relabel->arg = (Expr *) arg;
3128 
3129  return (Node *) relabel;
3130  }
3131  }
3132  case T_CaseExpr:
3133  {
3134  /*----------
3135  * CASE expressions can be simplified if there are constant
3136  * condition clauses:
3137  * FALSE (or NULL): drop the alternative
3138  * TRUE: drop all remaining alternatives
3139  * If the first non-FALSE alternative is a constant TRUE,
3140  * we can simplify the entire CASE to that alternative's
3141  * expression. If there are no non-FALSE alternatives,
3142  * we simplify the entire CASE to the default result (ELSE).
3143  *
3144  * If we have a simple-form CASE with constant test
3145  * expression, we substitute the constant value for contained
3146  * CaseTestExpr placeholder nodes, so that we have the
3147  * opportunity to reduce constant test conditions. For
3148  * example this allows
3149  * CASE 0 WHEN 0 THEN 1 ELSE 1/0 END
3150  * to reduce to 1 rather than drawing a divide-by-0 error.
3151  * Note that when the test expression is constant, we don't
3152  * have to include it in the resulting CASE; for example
3153  * CASE 0 WHEN x THEN y ELSE z END
3154  * is transformed by the parser to
3155  * CASE 0 WHEN CaseTestExpr = x THEN y ELSE z END
3156  * which we can simplify to
3157  * CASE WHEN 0 = x THEN y ELSE z END
3158  * It is not necessary for the executor to evaluate the "arg"
3159  * expression when executing the CASE, since any contained
3160  * CaseTestExprs that might have referred to it will have been
3161  * replaced by the constant.
3162  *----------
3163  */
3164  CaseExpr *caseexpr = (CaseExpr *) node;
3165  CaseExpr *newcase;
3166  Node *save_case_val;
3167  Node *newarg;
3168  List *newargs;
3169  bool const_true_cond;
3170  Node *defresult = NULL;
3171  ListCell *arg;
3172 
3173  /* Simplify the test expression, if any */
3174  newarg = eval_const_expressions_mutator((Node *) caseexpr->arg,
3175  context);
3176 
3177  /* Set up for contained CaseTestExpr nodes */
3178  save_case_val = context->case_val;
3179  if (newarg && IsA(newarg, Const))
3180  {
3181  context->case_val = newarg;
3182  newarg = NULL; /* not needed anymore, see above */
3183  }
3184  else
3185  context->case_val = NULL;
3186 
3187  /* Simplify the WHEN clauses */
3188  newargs = NIL;
3189  const_true_cond = false;
3190  foreach(arg, caseexpr->args)
3191  {
3192  CaseWhen *oldcasewhen = lfirst_node(CaseWhen, arg);
3193  Node *casecond;
3194  Node *caseresult;
3195 
3196  /* Simplify this alternative's test condition */
3197  casecond = eval_const_expressions_mutator((Node *) oldcasewhen->expr,
3198  context);
3199 
3200  /*
3201  * If the test condition is constant FALSE (or NULL), then
3202  * drop this WHEN clause completely, without processing
3203  * the result.
3204  */
3205  if (casecond && IsA(casecond, Const))
3206  {
3207  Const *const_input = (Const *) casecond;
3208 
3209  if (const_input->constisnull ||
3210  !DatumGetBool(const_input->constvalue))
3211  continue; /* drop alternative with FALSE cond */
3212  /* Else it's constant TRUE */
3213  const_true_cond = true;
3214  }
3215 
3216  /* Simplify this alternative's result value */
3217  caseresult = eval_const_expressions_mutator((Node *) oldcasewhen->result,
3218  context);
3219 
3220  /* If non-constant test condition, emit a new WHEN node */
3221  if (!const_true_cond)
3222  {
3223  CaseWhen *newcasewhen = makeNode(CaseWhen);
3224 
3225  newcasewhen->expr = (Expr *) casecond;
3226  newcasewhen->result = (Expr *) caseresult;
3227  newcasewhen->location = oldcasewhen->location;
3228  newargs = lappend(newargs, newcasewhen);
3229  continue;
3230  }
3231 
3232  /*
3233  * Found a TRUE condition, so none of the remaining
3234  * alternatives can be reached. We treat the result as
3235  * the default result.
3236  */
3237  defresult = caseresult;
3238  break;
3239  }
3240 
3241  /* Simplify the default result, unless we replaced it above */
3242  if (!const_true_cond)
3243  defresult = eval_const_expressions_mutator((Node *) caseexpr->defresult,
3244  context);
3245 
3246  context->case_val = save_case_val;
3247 
3248  /*
3249  * If no non-FALSE alternatives, CASE reduces to the default
3250  * result
3251  */
3252  if (newargs == NIL)
3253  return defresult;
3254  /* Otherwise we need a new CASE node */
3255  newcase = makeNode(CaseExpr);
3256  newcase->casetype = caseexpr->casetype;
3257  newcase->casecollid = caseexpr->casecollid;
3258  newcase->arg = (Expr *) newarg;
3259  newcase->args = newargs;
3260  newcase->defresult = (Expr *) defresult;
3261  newcase->location = caseexpr->location;
3262  return (Node *) newcase;
3263  }
3264  case T_CaseTestExpr:
3265  {
3266  /*
3267  * If we know a constant test value for the current CASE
3268  * construct, substitute it for the placeholder. Else just
3269  * return the placeholder as-is.
3270  */
3271  if (context->case_val)
3272  return copyObject(context->case_val);
3273  else
3274  return copyObject(node);
3275  }
3276  case T_ArrayExpr:
3277  {
3278  ArrayExpr *arrayexpr = (ArrayExpr *) node;
3279  ArrayExpr *newarray;
3280  bool all_const = true;
3281  List *newelems;
3282  ListCell *element;
3283 
3284  newelems = NIL;
3285  foreach(element, arrayexpr->elements)
3286  {
3287  Node *e;
3288 
3289  e = eval_const_expressions_mutator((Node *) lfirst(element),
3290  context);
3291  if (!IsA(e, Const))
3292  all_const = false;
3293  newelems = lappend(newelems, e);
3294  }
3295 
3296  newarray = makeNode(ArrayExpr);
3297  newarray->array_typeid = arrayexpr->array_typeid;
3298  newarray->array_collid = arrayexpr->array_collid;
3299  newarray->element_typeid = arrayexpr->element_typeid;
3300  newarray->elements = newelems;
3301  newarray->multidims = arrayexpr->multidims;
3302  newarray->location = arrayexpr->location;
3303 
3304  if (all_const)
3305  return (Node *) evaluate_expr((Expr *) newarray,
3306  newarray->array_typeid,
3307  exprTypmod(node),
3308  newarray->array_collid);
3309 
3310  return (Node *) newarray;
3311  }
3312  case T_CoalesceExpr:
3313  {
3314  CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
3315  CoalesceExpr *newcoalesce;
3316  List *newargs;
3317  ListCell *arg;
3318 
3319  newargs = NIL;
3320  foreach(arg, coalesceexpr->args)
3321  {
3322  Node *e;
3323 
3325  context);
3326 
3327  /*
3328  * We can remove null constants from the list. For a
3329  * non-null constant, if it has not been preceded by any
3330  * other non-null-constant expressions then it is the
3331  * result. Otherwise, it's the next argument, but we can
3332  * drop following arguments since they will never be
3333  * reached.
3334  */
3335  if (IsA(e, Const))
3336  {
3337  if (((Const *) e)->constisnull)
3338  continue; /* drop null constant */
3339  if (newargs == NIL)
3340  return e; /* first expr */
3341  newargs = lappend(newargs, e);
3342  break;
3343  }
3344  newargs = lappend(newargs, e);
3345  }
3346 
3347  /*
3348  * If all the arguments were constant null, the result is just
3349  * null
3350  */
3351  if (newargs == NIL)
3352  return (Node *) makeNullConst(coalesceexpr->coalescetype,
3353  -1,
3354  coalesceexpr->coalescecollid);
3355 
3356  newcoalesce = makeNode(CoalesceExpr);
3357  newcoalesce->coalescetype = coalesceexpr->coalescetype;
3358  newcoalesce->coalescecollid = coalesceexpr->coalescecollid;
3359  newcoalesce->args = newargs;
3360  newcoalesce->location = coalesceexpr->location;
3361  return (Node *) newcoalesce;
3362  }
3363  case T_SQLValueFunction:
3364  {
3365  /*
3366  * All variants of SQLValueFunction are stable, so if we are
3367  * estimating the expression's value, we should evaluate the
3368  * current function value. Otherwise just copy.
3369  */
3370  SQLValueFunction *svf = (SQLValueFunction *) node;
3371 
3372  if (context->estimate)
3373  return (Node *) evaluate_expr((Expr *) svf,
3374  svf->type,
3375  svf->typmod,
3376  InvalidOid);
3377  else
3378  return copyObject((Node *) svf);
3379  }
3380  case T_FieldSelect:
3381  {
3382  /*
3383  * We can optimize field selection from a whole-row Var into a
3384  * simple Var. (This case won't be generated directly by the
3385  * parser, because ParseComplexProjection short-circuits it.
3386  * But it can arise while simplifying functions.) Also, we
3387  * can optimize field selection from a RowExpr construct.
3388  *
3389  * However, replacing a whole-row Var in this way has a
3390  * pitfall: if we've already built the rel targetlist for the
3391  * source relation, then the whole-row Var is scheduled to be
3392  * produced by the relation scan, but the simple Var probably
3393  * isn't, which will lead to a failure in setrefs.c. This is
3394  * not a problem when handling simple single-level queries, in
3395  * which expression simplification always happens first. It
3396  * is a risk for lateral references from subqueries, though.
3397  * To avoid such failures, don't optimize uplevel references.
3398  *
3399  * We must also check that the declared type of the field is
3400  * still the same as when the FieldSelect was created --- this
3401  * can change if someone did ALTER COLUMN TYPE on the rowtype.
3402  */
3403  FieldSelect *fselect = (FieldSelect *) node;
3404  FieldSelect *newfselect;
3405  Node *arg;
3406 
3407  arg = eval_const_expressions_mutator((Node *) fselect->arg,
3408  context);
3409  if (arg && IsA(arg, Var) &&
3410  ((Var *) arg)->varattno == InvalidAttrNumber &&
3411  ((Var *) arg)->varlevelsup == 0)
3412  {
3413  if (rowtype_field_matches(((Var *) arg)->vartype,
3414  fselect->fieldnum,
3415  fselect->resulttype,
3416  fselect->resulttypmod,
3417  fselect->resultcollid))
3418  return (Node *) makeVar(((Var *) arg)->varno,
3419  fselect->fieldnum,
3420  fselect->resulttype,
3421  fselect->resulttypmod,
3422  fselect->resultcollid,
3423  ((Var *) arg)->varlevelsup);
3424  }
3425  if (arg && IsA(arg, RowExpr))
3426  {
3427  RowExpr *rowexpr = (RowExpr *) arg;
3428 
3429  if (fselect->fieldnum > 0 &&
3430  fselect->fieldnum <= list_length(rowexpr->args))
3431  {
3432  Node *fld = (Node *) list_nth(rowexpr->args,
3433  fselect->fieldnum - 1);
3434 
3435  if (rowtype_field_matches(rowexpr->row_typeid,
3436  fselect->fieldnum,
3437  fselect->resulttype,
3438  fselect->resulttypmod,
3439  fselect->resultcollid) &&
3440  fselect->resulttype == exprType(fld) &&
3441  fselect->resulttypmod == exprTypmod(fld) &&
3442  fselect->resultcollid == exprCollation(fld))
3443  return fld;
3444  }
3445  }
3446  newfselect = makeNode(FieldSelect);
3447  newfselect->arg = (Expr *) arg;
3448  newfselect->fieldnum = fselect->fieldnum;
3449  newfselect->resulttype = fselect->resulttype;
3450  newfselect->resulttypmod = fselect->resulttypmod;
3451  newfselect->resultcollid = fselect->resultcollid;
3452  return (Node *) newfselect;
3453  }
3454  case T_NullTest:
3455  {
3456  NullTest *ntest = (NullTest *) node;
3457  NullTest *newntest;
3458  Node *arg;
3459 
3460  arg = eval_const_expressions_mutator((Node *) ntest->arg,
3461  context);
3462  if (ntest->argisrow && arg && IsA(arg, RowExpr))
3463  {
3464  /*
3465  * We break ROW(...) IS [NOT] NULL into separate tests on
3466  * its component fields. This form is usually more
3467  * efficient to evaluate, as well as being more amenable
3468  * to optimization.
3469  */
3470  RowExpr *rarg = (RowExpr *) arg;
3471  List *newargs = NIL;
3472  ListCell *l;
3473 
3474  foreach(l, rarg->args)
3475  {
3476  Node *relem = (Node *) lfirst(l);
3477 
3478  /*
3479  * A constant field refutes the whole NullTest if it's
3480  * of the wrong nullness; else we can discard it.
3481  */
3482  if (relem && IsA(relem, Const))
3483  {
3484  Const *carg = (Const *) relem;
3485 
3486  if (carg->constisnull ?
3487  (ntest->nulltesttype == IS_NOT_NULL) :
3488  (ntest->nulltesttype == IS_NULL))
3489  return makeBoolConst(false, false);
3490  continue;
3491  }
3492 
3493  /*
3494  * Else, make a scalar (argisrow == false) NullTest
3495  * for this field. Scalar semantics are required
3496  * because IS [NOT] NULL doesn't recurse; see comments
3497  * in ExecEvalRowNullInt().
3498  */
3499  newntest = makeNode(NullTest);
3500  newntest->arg = (Expr *) relem;
3501  newntest->nulltesttype = ntest->nulltesttype;
3502  newntest->argisrow = false;
3503  newntest->location = ntest->location;
3504  newargs = lappend(newargs, newntest);
3505  }
3506  /* If all the inputs were constants, result is TRUE */
3507  if (newargs == NIL)
3508  return makeBoolConst(true, false);
3509  /* If only one nonconst input, it's the result */
3510  if (list_length(newargs) == 1)
3511  return (Node *) linitial(newargs);
3512  /* Else we need an AND node */
3513  return (Node *) make_andclause(newargs);
3514  }
3515  if (!ntest->argisrow && arg && IsA(arg, Const))
3516  {
3517  Const *carg = (Const *) arg;
3518  bool result;
3519 
3520  switch (ntest->nulltesttype)
3521  {
3522  case IS_NULL:
3523  result = carg->constisnull;
3524  break;
3525  case IS_NOT_NULL:
3526  result = !carg->constisnull;
3527  break;
3528  default:
3529  elog(ERROR, "unrecognized nulltesttype: %d",
3530  (int) ntest->nulltesttype);
3531  result = false; /* keep compiler quiet */
3532  break;
3533  }
3534 
3535  return makeBoolConst(result, false);
3536  }
3537 
3538  newntest = makeNode(NullTest);
3539  newntest->arg = (Expr *) arg;
3540  newntest->nulltesttype = ntest->nulltesttype;
3541  newntest->argisrow = ntest->argisrow;
3542  newntest->location = ntest->location;
3543  return (Node *) newntest;
3544  }
3545  case T_BooleanTest:
3546  {
3547  BooleanTest *btest = (BooleanTest *) node;
3548  BooleanTest *newbtest;
3549  Node *arg;
3550 
3551  arg = eval_const_expressions_mutator((Node *) btest->arg,
3552  context);
3553  if (arg && IsA(arg, Const))
3554  {
3555  Const *carg = (Const *) arg;
3556  bool result;
3557 
3558  switch (btest->booltesttype)
3559  {
3560  case IS_TRUE:
3561  result = (!carg->constisnull &&
3562  DatumGetBool(carg->constvalue));
3563  break;
3564  case IS_NOT_TRUE:
3565  result = (carg->constisnull ||
3566  !DatumGetBool(carg->constvalue));
3567  break;
3568  case IS_FALSE:
3569  result = (!carg->constisnull &&
3570  !DatumGetBool(carg->constvalue));
3571  break;
3572  case IS_NOT_FALSE:
3573  result = (carg->constisnull ||
3574  DatumGetBool(carg->constvalue));
3575  break;
3576  case IS_UNKNOWN:
3577  result = carg->constisnull;
3578  break;
3579  case IS_NOT_UNKNOWN:
3580  result = !carg->constisnull;
3581  break;
3582  default:
3583  elog(ERROR, "unrecognized booltesttype: %d",
3584  (int) btest->booltesttype);
3585  result = false; /* keep compiler quiet */
3586  break;
3587  }
3588 
3589  return makeBoolConst(result, false);
3590  }
3591 
3592  newbtest = makeNode(BooleanTest);
3593  newbtest->arg = (Expr *) arg;
3594  newbtest->booltesttype = btest->booltesttype;
3595  newbtest->location = btest->location;
3596  return (Node *) newbtest;
3597  }
3598  case T_PlaceHolderVar:
3599 
3600  /*
3601  * In estimation mode, just strip the PlaceHolderVar node
3602  * altogether; this amounts to estimating that the contained value
3603  * won't be forced to null by an outer join. In regular mode we
3604  * just use the default behavior (ie, simplify the expression but
3605  * leave the PlaceHolderVar node intact).
3606  */
3607  if (context->estimate)
3608  {
3609  PlaceHolderVar *phv = (PlaceHolderVar *) node;
3610 
3611  return eval_const_expressions_mutator((Node *) phv->phexpr,
3612  context);
3613  }
3614  break;
3615  default:
3616  break;
3617  }
3618 
3619  /*
3620  * For any node type not handled above, we recurse using
3621  * expression_tree_mutator, which will copy the node unchanged but try to
3622  * simplify its arguments (if any) using this routine. For example: we
3623  * cannot eliminate an ArrayRef node, but we might be able to simplify
3624  * constant expressions in its subscripts.
3625  */
3627  (void *) context);
3628 }
3629 
3630 /*
3631  * Subroutine for eval_const_expressions: process arguments of an OR clause
3632  *
3633  * This includes flattening of nested ORs as well as recursion to
3634  * eval_const_expressions to simplify the OR arguments.
3635  *
3636  * After simplification, OR arguments are handled as follows:
3637  * non constant: keep
3638  * FALSE: drop (does not affect result)
3639  * TRUE: force result to TRUE
3640  * NULL: keep only one
3641  * We must keep one NULL input because OR expressions evaluate to NULL when no
3642  * input is TRUE and at least one is NULL. We don't actually include the NULL
3643  * here, that's supposed to be done by the caller.
3644  *
3645  * The output arguments *haveNull and *forceTrue must be initialized false
3646  * by the caller. They will be set true if a NULL constant or TRUE constant,
3647  * respectively, is detected anywhere in the argument list.
3648  */
3649 static List *
3652  bool *haveNull, bool *forceTrue)
3653 {
3654  List *newargs = NIL;
3655  List *unprocessed_args;
3656 
3657  /*
3658  * We want to ensure that any OR immediately beneath another OR gets
3659  * flattened into a single OR-list, so as to simplify later reasoning.
3660  *
3661  * To avoid stack overflow from recursion of eval_const_expressions, we
3662  * resort to some tenseness here: we keep a list of not-yet-processed
3663  * inputs, and handle flattening of nested ORs by prepending to the to-do
3664  * list instead of recursing. Now that the parser generates N-argument
3665  * ORs from simple lists, this complexity is probably less necessary than
3666  * it once was, but we might as well keep the logic.
3667  */
3668  unprocessed_args = list_copy(args);
3669  while (unprocessed_args)
3670  {
3671  Node *arg = (Node *) linitial(unprocessed_args);
3672 
3673  unprocessed_args = list_delete_first(unprocessed_args);
3674 
3675  /* flatten nested ORs as per above comment */
3676  if (or_clause(arg))
3677  {
3678  List *subargs = list_copy(((BoolExpr *) arg)->args);
3679 
3680  /* overly tense code to avoid leaking unused list header */
3681  if (!unprocessed_args)
3682  unprocessed_args = subargs;
3683  else
3684  {
3685  List *oldhdr = unprocessed_args;
3686 
3687  unprocessed_args = list_concat(subargs, unprocessed_args);
3688  pfree(oldhdr);
3689  }
3690  continue;
3691  }
3692 
3693  /* If it's not an OR, simplify it */
3694  arg = eval_const_expressions_mutator(arg, context);
3695 
3696  /*
3697  * It is unlikely but not impossible for simplification of a non-OR
3698  * clause to produce an OR. Recheck, but don't be too tense about it
3699  * since it's not a mainstream case. In particular we don't worry
3700  * about const-simplifying the input twice.
3701  */
3702  if (or_clause(arg))
3703  {
3704  List *subargs = list_copy(((BoolExpr *) arg)->args);
3705 
3706  unprocessed_args = list_concat(subargs, unprocessed_args);
3707  continue;
3708  }
3709 
3710  /*
3711  * OK, we have a const-simplified non-OR argument. Process it per
3712  * comments above.
3713  */
3714  if (IsA(arg, Const))
3715  {
3716  Const *const_input = (Const *) arg;
3717 
3718  if (const_input->constisnull)
3719  *haveNull = true;
3720  else if (DatumGetBool(const_input->constvalue))
3721  {
3722  *forceTrue = true;
3723 
3724  /*
3725  * Once we detect a TRUE result we can just exit the loop
3726  * immediately. However, if we ever add a notion of
3727  * non-removable functions, we'd need to keep scanning.
3728  */
3729  return NIL;
3730  }
3731  /* otherwise, we can drop the constant-false input */
3732  continue;
3733  }
3734 
3735  /* else emit the simplified arg into the result list */
3736  newargs = lappend(newargs, arg);
3737  }
3738 
3739  return newargs;
3740 }
3741 
3742 /*
3743  * Subroutine for eval_const_expressions: process arguments of an AND clause
3744  *
3745  * This includes flattening of nested ANDs as well as recursion to
3746  * eval_const_expressions to simplify the AND arguments.
3747  *
3748  * After simplification, AND arguments are handled as follows:
3749  * non constant: keep
3750  * TRUE: drop (does not affect result)
3751  * FALSE: force result to FALSE
3752  * NULL: keep only one
3753  * We must keep one NULL input because AND expressions evaluate to NULL when
3754  * no input is FALSE and at least one is NULL. We don't actually include the
3755  * NULL here, that's supposed to be done by the caller.
3756  *
3757  * The output arguments *haveNull and *forceFalse must be initialized false
3758  * by the caller. They will be set true if a null constant or false constant,
3759  * respectively, is detected anywhere in the argument list.
3760  */
3761 static List *
3764  bool *haveNull, bool *forceFalse)
3765 {
3766  List *newargs = NIL;
3767  List *unprocessed_args;
3768 
3769  /* See comments in simplify_or_arguments */
3770  unprocessed_args = list_copy(args);
3771  while (unprocessed_args)
3772  {
3773  Node *arg = (Node *) linitial(unprocessed_args);
3774 
3775  unprocessed_args = list_delete_first(unprocessed_args);
3776 
3777  /* flatten nested ANDs as per above comment */
3778  if (and_clause(arg))
3779  {
3780  List *subargs = list_copy(((BoolExpr *) arg)->args);
3781 
3782  /* overly tense code to avoid leaking unused list header */
3783  if (!unprocessed_args)
3784  unprocessed_args = subargs;
3785  else
3786  {
3787  List *oldhdr = unprocessed_args;
3788 
3789  unprocessed_args = list_concat(subargs, unprocessed_args);
3790  pfree(oldhdr);
3791  }
3792  continue;
3793  }
3794 
3795  /* If it's not an AND, simplify it */
3796  arg = eval_const_expressions_mutator(arg, context);
3797 
3798  /*
3799  * It is unlikely but not impossible for simplification of a non-AND
3800  * clause to produce an AND. Recheck, but don't be too tense about it
3801  * since it's not a mainstream case. In particular we don't worry
3802  * about const-simplifying the input twice.
3803  */
3804  if (and_clause(arg))
3805  {
3806  List *subargs = list_copy(((BoolExpr *) arg)->args);
3807 
3808  unprocessed_args = list_concat(subargs, unprocessed_args);
3809  continue;
3810  }
3811 
3812  /*
3813  * OK, we have a const-simplified non-AND argument. Process it per
3814  * comments above.
3815  */
3816  if (IsA(arg, Const))
3817  {
3818  Const *const_input = (Const *) arg;
3819 
3820  if (const_input->constisnull)
3821  *haveNull = true;
3822  else if (!DatumGetBool(const_input->constvalue))
3823  {
3824  *forceFalse = true;
3825 
3826  /*
3827  * Once we detect a FALSE result we can just exit the loop
3828  * immediately. However, if we ever add a notion of
3829  * non-removable functions, we'd need to keep scanning.
3830  */
3831  return NIL;
3832  }
3833  /* otherwise, we can drop the constant-true input */
3834  continue;
3835  }
3836 
3837  /* else emit the simplified arg into the result list */
3838  newargs = lappend(newargs, arg);
3839  }
3840 
3841  return newargs;
3842 }
3843 
3844 /*
3845  * Subroutine for eval_const_expressions: try to simplify boolean equality
3846  * or inequality condition
3847  *
3848  * Inputs are the operator OID and the simplified arguments to the operator.
3849  * Returns a simplified expression if successful, or NULL if cannot
3850  * simplify the expression.
3851  *
3852  * The idea here is to reduce "x = true" to "x" and "x = false" to "NOT x",
3853  * or similarly "x <> true" to "NOT x" and "x <> false" to "x".
3854  * This is only marginally useful in itself, but doing it in constant folding
3855  * ensures that we will recognize these forms as being equivalent in, for
3856  * example, partial index matching.
3857  *
3858  * We come here only if simplify_function has failed; therefore we cannot
3859  * see two constant inputs, nor a constant-NULL input.
3860  */
3861 static Node *
3863 {
3864  Node *leftop;
3865  Node *rightop;
3866 
3867  Assert(list_length(args) == 2);
3868  leftop = linitial(args);
3869  rightop = lsecond(args);
3870  if (leftop && IsA(leftop, Const))
3871  {
3872  Assert(!((Const *) leftop)->constisnull);
3873  if (opno == BooleanEqualOperator)
3874  {
3875  if (DatumGetBool(((Const *) leftop)->constvalue))
3876  return rightop; /* true = foo */
3877  else
3878  return negate_clause(rightop); /* false = foo */
3879  }
3880  else
3881  {
3882  if (DatumGetBool(((Const *) leftop)->constvalue))
3883  return negate_clause(rightop); /* true <> foo */
3884  else
3885  return rightop; /* false <> foo */
3886  }
3887  }
3888  if (rightop && IsA(rightop, Const))
3889  {
3890  Assert(!((Const *) rightop)->constisnull);
3891  if (opno == BooleanEqualOperator)
3892  {
3893  if (DatumGetBool(((Const *) rightop)->constvalue))
3894  return leftop; /* foo = true */
3895  else
3896  return negate_clause(leftop); /* foo = false */
3897  }
3898  else
3899  {
3900  if (DatumGetBool(((Const *) rightop)->constvalue))
3901  return negate_clause(leftop); /* foo <> true */
3902  else
3903  return leftop; /* foo <> false */
3904  }
3905  }
3906  return NULL;
3907 }
3908 
3909 /*
3910  * Subroutine for eval_const_expressions: try to simplify a function call
3911  * (which might originally have been an operator; we don't care)
3912  *
3913  * Inputs are the function OID, actual result type OID (which is needed for
3914  * polymorphic functions), result typmod, result collation, the input
3915  * collation to use for the function, the original argument list (not
3916  * const-simplified yet, unless process_args is false), and some flags;
3917  * also the context data for eval_const_expressions.
3918  *
3919  * Returns a simplified expression if successful, or NULL if cannot
3920  * simplify the function call.
3921  *
3922  * This function is also responsible for converting named-notation argument
3923  * lists into positional notation and/or adding any needed default argument
3924  * expressions; which is a bit grotty, but it avoids extra fetches of the
3925  * function's pg_proc tuple. For this reason, the args list is
3926  * pass-by-reference. Conversion and const-simplification of the args list
3927  * will be done even if simplification of the function call itself is not
3928  * possible.
3929  */
3930 static Expr *
3931 simplify_function(Oid funcid, Oid result_type, int32 result_typmod,
3932  Oid result_collid, Oid input_collid, List **args_p,
3933  bool funcvariadic, bool process_args, bool allow_non_const,
3935 {
3936  List *args = *args_p;
3937  HeapTuple func_tuple;
3938  Form_pg_proc func_form;
3939  Expr *newexpr;
3940 
3941  /*
3942  * We have three strategies for simplification: execute the function to
3943  * deliver a constant result, use a transform function to generate a
3944  * substitute node tree, or expand in-line the body of the function
3945  * definition (which only works for simple SQL-language functions, but
3946  * that is a common case). Each case needs access to the function's
3947  * pg_proc tuple, so fetch it just once.
3948  *
3949  * Note: the allow_non_const flag suppresses both the second and third
3950  * strategies; so if !allow_non_const, simplify_function can only return a
3951  * Const or NULL. Argument-list rewriting happens anyway, though.
3952  */
3953  func_tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
3954  if (!HeapTupleIsValid(func_tuple))
3955  elog(ERROR, "cache lookup failed for function %u", funcid);
3956  func_form = (Form_pg_proc) GETSTRUCT(func_tuple);
3957 
3958  /*
3959  * Process the function arguments, unless the caller did it already.
3960  *
3961  * Here we must deal with named or defaulted arguments, and then
3962  * recursively apply eval_const_expressions to the whole argument list.
3963  */
3964  if (process_args)
3965  {
3966  args = expand_function_arguments(args, result_type, func_tuple);
3967  args = (List *) expression_tree_mutator((Node *) args,
3969  (void *) context);
3970  /* Argument processing done, give it back to the caller */
3971  *args_p = args;
3972  }
3973 
3974  /* Now attempt simplification of the function call proper. */
3975 
3976  newexpr = evaluate_function(funcid, result_type, result_typmod,
3977  result_collid, input_collid,
3978  args, funcvariadic,
3979  func_tuple, context);
3980 
3981  if (!newexpr && allow_non_const && OidIsValid(func_form->protransform))
3982  {
3983  /*
3984  * Build a dummy FuncExpr node containing the simplified arg list. We
3985  * use this approach to present a uniform interface to the transform
3986  * function regardless of how the function is actually being invoked.
3987  */
3988  FuncExpr fexpr;
3989 
3990  fexpr.xpr.type = T_FuncExpr;
3991  fexpr.funcid = funcid;
3992  fexpr.funcresulttype = result_type;
3993  fexpr.funcretset = func_form->proretset;
3994  fexpr.funcvariadic = funcvariadic;
3996  fexpr.funccollid = result_collid;
3997  fexpr.inputcollid = input_collid;
3998  fexpr.args = args;
3999  fexpr.location = -1;
4000 
4001  newexpr = (Expr *)
4002  DatumGetPointer(OidFunctionCall1(func_form->protransform,
4003  PointerGetDatum(&fexpr)));
4004  }
4005 
4006  if (!newexpr && allow_non_const)
4007  newexpr = inline_function(funcid, result_type, result_collid,
4008  input_collid, args, funcvariadic,
4009  func_tuple, context);
4010 
4011  ReleaseSysCache(func_tuple);
4012 
4013  return newexpr;
4014 }
4015 
4016 /*
4017  * expand_function_arguments: convert named-notation args to positional args
4018  * and/or insert default args, as needed
4019  *
4020  * If we need to change anything, the input argument list is copied, not
4021  * modified.
4022  *
4023  * Note: this gets applied to operator argument lists too, even though the
4024  * cases it handles should never occur there. This should be OK since it
4025  * will fall through very quickly if there's nothing to do.
4026  */
4027 static List *
4029 {
4030  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4031  bool has_named_args = false;
4032  ListCell *lc;
4033 
4034  /* Do we have any named arguments? */
4035  foreach(lc, args)
4036  {
4037  Node *arg = (Node *) lfirst(lc);
4038 
4039  if (IsA(arg, NamedArgExpr))
4040  {
4041  has_named_args = true;
4042  break;
4043  }
4044  }
4045 
4046  /* If so, we must apply reorder_function_arguments */
4047  if (has_named_args)
4048  {
4049  args = reorder_function_arguments(args, func_tuple);
4050  /* Recheck argument types and add casts if needed */
4051  recheck_cast_function_args(args, result_type, func_tuple);
4052  }
4053  else if (list_length(args) < funcform->pronargs)
4054  {
4055  /* No named args, but we seem to be short some defaults */
4056  args = add_function_defaults(args, func_tuple);
4057  /* Recheck argument types and add casts if needed */
4058  recheck_cast_function_args(args, result_type, func_tuple);
4059  }
4060 
4061  return args;
4062 }
4063 
4064 /*
4065  * reorder_function_arguments: convert named-notation args to positional args
4066  *
4067  * This function also inserts default argument values as needed, since it's
4068  * impossible to form a truly valid positional call without that.
4069  */
4070 static List *
4072 {
4073  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4074  int pronargs = funcform->pronargs;
4075  int nargsprovided = list_length(args);
4076  Node *argarray[FUNC_MAX_ARGS];
4077  ListCell *lc;
4078  int i;
4079 
4080  Assert(nargsprovided <= pronargs);
4081  if (pronargs > FUNC_MAX_ARGS)
4082  elog(ERROR, "too many function arguments");
4083  MemSet(argarray, 0, pronargs * sizeof(Node *));
4084 
4085  /* Deconstruct the argument list into an array indexed by argnumber */
4086  i = 0;
4087  foreach(lc, args)
4088  {
4089  Node *arg = (Node *) lfirst(lc);
4090 
4091  if (!IsA(arg, NamedArgExpr))
4092  {
4093  /* positional argument, assumed to precede all named args */
4094  Assert(argarray[i] == NULL);
4095  argarray[i++] = arg;
4096  }
4097  else
4098  {
4099  NamedArgExpr *na = (NamedArgExpr *) arg;
4100 
4101  Assert(argarray[na->argnumber] == NULL);
4102  argarray[na->argnumber] = (Node *) na->arg;
4103  }
4104  }
4105 
4106  /*
4107  * Fetch default expressions, if needed, and insert into array at proper
4108  * locations (they aren't necessarily consecutive or all used)
4109  */
4110  if (nargsprovided < pronargs)
4111  {
4112  List *defaults = fetch_function_defaults(func_tuple);
4113 
4114  i = pronargs - funcform->pronargdefaults;
4115  foreach(lc, defaults)
4116  {
4117  if (argarray[i] == NULL)
4118  argarray[i] = (Node *) lfirst(lc);
4119  i++;
4120  }
4121  }
4122 
4123  /* Now reconstruct the args list in proper order */
4124  args = NIL;
4125  for (i = 0; i < pronargs; i++)
4126  {
4127  Assert(argarray[i] != NULL);
4128  args = lappend(args, argarray[i]);
4129  }
4130 
4131  return args;
4132 }
4133 
4134 /*
4135  * add_function_defaults: add missing function arguments from its defaults
4136  *
4137  * This is used only when the argument list was positional to begin with,
4138  * and so we know we just need to add defaults at the end.
4139  */
4140 static List *
4142 {
4143  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4144  int nargsprovided = list_length(args);
4145  List *defaults;
4146  int ndelete;
4147 
4148  /* Get all the default expressions from the pg_proc tuple */
4149  defaults = fetch_function_defaults(func_tuple);
4150 
4151  /* Delete any unused defaults from the list */
4152  ndelete = nargsprovided + list_length(defaults) - funcform->pronargs;
4153  if (ndelete < 0)
4154  elog(ERROR, "not enough default arguments");
4155  while (ndelete-- > 0)
4156  defaults = list_delete_first(defaults);
4157 
4158  /* And form the combined argument list, not modifying the input list */
4159  return list_concat(list_copy(args), defaults);
4160 }
4161 
4162 /*
4163  * fetch_function_defaults: get function's default arguments as expression list
4164  */
4165 static List *
4167 {
4168  List *defaults;
4169  Datum proargdefaults;
4170  bool isnull;
4171  char *str;
4172 
4173  /* The error cases here shouldn't happen, but check anyway */
4174  proargdefaults = SysCacheGetAttr(PROCOID, func_tuple,
4176  &isnull);
4177  if (isnull)
4178  elog(ERROR, "not enough default arguments");
4179  str = TextDatumGetCString(proargdefaults);
4180  defaults = castNode(List, stringToNode(str));
4181  pfree(str);
4182  return defaults;
4183 }
4184 
4185 /*
4186  * recheck_cast_function_args: recheck function args and typecast as needed
4187  * after adding defaults.
4188  *
4189  * It is possible for some of the defaulted arguments to be polymorphic;
4190  * therefore we can't assume that the default expressions have the correct
4191  * data types already. We have to re-resolve polymorphics and do coercion
4192  * just like the parser did.
4193  *
4194  * This should be a no-op if there are no polymorphic arguments,
4195  * but we do it anyway to be sure.
4196  *
4197  * Note: if any casts are needed, the args list is modified in-place;
4198  * caller should have already copied the list structure.
4199  */
4200 static void
4202 {
4203  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4204  int nargs;
4205  Oid actual_arg_types[FUNC_MAX_ARGS];
4206  Oid declared_arg_types[FUNC_MAX_ARGS];
4207  Oid rettype;
4208  ListCell *lc;
4209 
4210  if (list_length(args) > FUNC_MAX_ARGS)
4211  elog(ERROR, "too many function arguments");
4212  nargs = 0;
4213  foreach(lc, args)
4214  {
4215  actual_arg_types[nargs++] = exprType((Node *) lfirst(lc));
4216  }
4217  Assert(nargs == funcform->pronargs);
4218  memcpy(declared_arg_types, funcform->proargtypes.values,
4219  funcform->pronargs * sizeof(Oid));
4220  rettype = enforce_generic_type_consistency(actual_arg_types,
4221  declared_arg_types,
4222  nargs,
4223  funcform->prorettype,
4224  false);
4225  /* let's just check we got the same answer as the parser did ... */
4226  if (rettype != result_type)
4227  elog(ERROR, "function's resolved result type changed during planning");
4228 
4229  /* perform any necessary typecasting of arguments */
4230  make_fn_arguments(NULL, args, actual_arg_types, declared_arg_types);
4231 }
4232 
4233 /*
4234  * evaluate_function: try to pre-evaluate a function call
4235  *
4236  * We can do this if the function is strict and has any constant-null inputs
4237  * (just return a null constant), or if the function is immutable and has all
4238  * constant inputs (call it and return the result as a Const node). In
4239  * estimation mode we are willing to pre-evaluate stable functions too.
4240  *
4241  * Returns a simplified expression if successful, or NULL if cannot
4242  * simplify the function.
4243  */
4244 static Expr *
4245 evaluate_function(Oid funcid, Oid result_type, int32 result_typmod,
4246  Oid result_collid, Oid input_collid, List *args,
4247  bool funcvariadic,
4248  HeapTuple func_tuple,
4250 {
4251  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4252  bool has_nonconst_input = false;
4253  bool has_null_input = false;
4254  ListCell *arg;
4255  FuncExpr *newexpr;
4256 
4257  /*
4258  * Can't simplify if it returns a set.
4259  */
4260  if (funcform->proretset)
4261  return NULL;
4262 
4263  /*
4264  * Can't simplify if it returns RECORD. The immediate problem is that it
4265  * will be needing an expected tupdesc which we can't supply here.
4266  *
4267  * In the case where it has OUT parameters, it could get by without an
4268  * expected tupdesc, but we still have issues: get_expr_result_type()
4269  * doesn't know how to extract type info from a RECORD constant, and in
4270  * the case of a NULL function result there doesn't seem to be any clean
4271  * way to fix that. In view of the likelihood of there being still other
4272  * gotchas, seems best to leave the function call unreduced.
4273  */
4274  if (funcform->prorettype == RECORDOID)
4275  return NULL;
4276 
4277  /*
4278  * Check for constant inputs and especially constant-NULL inputs.
4279  */
4280  foreach(arg, args)
4281  {
4282  if (IsA(lfirst(arg), Const))
4283  has_null_input |= ((Const *) lfirst(arg))->constisnull;
4284  else
4285  has_nonconst_input = true;
4286  }
4287 
4288  /*
4289  * If the function is strict and has a constant-NULL input, it will never
4290  * be called at all, so we can replace the call by a NULL constant, even
4291  * if there are other inputs that aren't constant, and even if the
4292  * function is not otherwise immutable.
4293  */
4294  if (funcform->proisstrict && has_null_input)
4295  return (Expr *) makeNullConst(result_type, result_typmod,
4296  result_collid);
4297 
4298  /*
4299  * Otherwise, can simplify only if all inputs are constants. (For a
4300  * non-strict function, constant NULL inputs are treated the same as
4301  * constant non-NULL inputs.)
4302  */
4303  if (has_nonconst_input)
4304  return NULL;
4305 
4306  /*
4307  * Ordinarily we are only allowed to simplify immutable functions. But for
4308  * purposes of estimation, we consider it okay to simplify functions that
4309  * are merely stable; the risk that the result might change from planning
4310  * time to execution time is worth taking in preference to not being able
4311  * to estimate the value at all.
4312  */
4313  if (funcform->provolatile == PROVOLATILE_IMMUTABLE)
4314  /* okay */ ;
4315  else if (context->estimate && funcform->provolatile == PROVOLATILE_STABLE)
4316  /* okay */ ;
4317  else
4318  return NULL;
4319 
4320  /*
4321  * OK, looks like we can simplify this operator/function.
4322  *
4323  * Build a new FuncExpr node containing the already-simplified arguments.
4324  */
4325  newexpr = makeNode(FuncExpr);
4326  newexpr->funcid = funcid;
4327  newexpr->funcresulttype = result_type;
4328  newexpr->funcretset = false;
4329  newexpr->funcvariadic = funcvariadic;
4330  newexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
4331  newexpr->funccollid = result_collid; /* doesn't matter */
4332  newexpr->inputcollid = input_collid;
4333  newexpr->args = args;
4334  newexpr->location = -1;
4335 
4336  return evaluate_expr((Expr *) newexpr, result_type, result_typmod,
4337  result_collid);
4338 }
4339 
4340 /*
4341  * inline_function: try to expand a function call inline
4342  *
4343  * If the function is a sufficiently simple SQL-language function
4344  * (just "SELECT expression"), then we can inline it and avoid the rather
4345  * high per-call overhead of SQL functions. Furthermore, this can expose
4346  * opportunities for constant-folding within the function expression.
4347  *
4348  * We have to beware of some special cases however. A directly or
4349  * indirectly recursive function would cause us to recurse forever,
4350  * so we keep track of which functions we are already expanding and
4351  * do not re-expand them. Also, if a parameter is used more than once
4352  * in the SQL-function body, we require it not to contain any volatile
4353  * functions (volatiles might deliver inconsistent answers) nor to be
4354  * unreasonably expensive to evaluate. The expensiveness check not only
4355  * prevents us from doing multiple evaluations of an expensive parameter
4356  * at runtime, but is a safety value to limit growth of an expression due
4357  * to repeated inlining.
4358  *
4359  * We must also beware of changing the volatility or strictness status of
4360  * functions by inlining them.
4361  *
4362  * Also, at the moment we can't inline functions returning RECORD. This
4363  * doesn't work in the general case because it discards information such
4364  * as OUT-parameter declarations.
4365  *
4366  * Also, context-dependent expression nodes in the argument list are trouble.
4367  *
4368  * Returns a simplified expression if successful, or NULL if cannot
4369  * simplify the function.
4370  */
4371 static Expr *
4372 inline_function(Oid funcid, Oid result_type, Oid result_collid,
4373  Oid input_collid, List *args,
4374  bool funcvariadic,
4375  HeapTuple func_tuple,
4377 {
4378  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4379  char *src;
4380  Datum tmp;
4381  bool isNull;
4382  bool modifyTargetList;
4383  MemoryContext oldcxt;
4384  MemoryContext mycxt;
4385  inline_error_callback_arg callback_arg;
4386  ErrorContextCallback sqlerrcontext;
4387  FuncExpr *fexpr;
4389  ParseState *pstate;
4390  List *raw_parsetree_list;
4391  Query *querytree;
4392  Node *newexpr;
4393  int *usecounts;
4394  ListCell *arg;
4395  int i;
4396 
4397  /*
4398  * Forget it if the function is not SQL-language or has other showstopper
4399  * properties. (The nargs check is just paranoia.)
4400  */
4401  if (funcform->prolang != SQLlanguageId ||
4402  funcform->prosecdef ||
4403  funcform->proretset ||
4404  funcform->prorettype == RECORDOID ||
4405  !heap_attisnull(func_tuple, Anum_pg_proc_proconfig) ||
4406  funcform->pronargs != list_length(args))
4407  return NULL;
4408 
4409  /* Check for recursive function, and give up trying to expand if so */
4410  if (list_member_oid(context->active_fns, funcid))
4411  return NULL;
4412 
4413  /* Check permission to call function (fail later, if not) */
4415  return NULL;
4416 
4417  /* Check whether a plugin wants to hook function entry/exit */
4418  if (FmgrHookIsNeeded(funcid))
4419  return NULL;
4420 
4421  /*
4422  * Make a temporary memory context, so that we don't leak all the stuff
4423  * that parsing might create.
4424  */
4426  "inline_function",
4428  oldcxt = MemoryContextSwitchTo(mycxt);
4429 
4430  /* Fetch the function body */
4431  tmp = SysCacheGetAttr(PROCOID,
4432  func_tuple,
4434  &isNull);
4435  if (isNull)
4436  elog(ERROR, "null prosrc for function %u", funcid);
4437  src = TextDatumGetCString(tmp);
4438 
4439  /*
4440  * Setup error traceback support for ereport(). This is so that we can
4441  * finger the function that bad information came from.
4442  */
4443  callback_arg.proname = NameStr(funcform->proname);
4444  callback_arg.prosrc = src;
4445 
4446  sqlerrcontext.callback = sql_inline_error_callback;
4447  sqlerrcontext.arg = (void *) &callback_arg;
4448  sqlerrcontext.previous = error_context_stack;
4449  error_context_stack = &sqlerrcontext;
4450 
4451  /*
4452  * Set up to handle parameters while parsing the function body. We need a
4453  * dummy FuncExpr node containing the already-simplified arguments to pass
4454  * to prepare_sql_fn_parse_info. (It is really only needed if there are
4455  * some polymorphic arguments, but for simplicity we always build it.)
4456  */
4457  fexpr = makeNode(FuncExpr);
4458  fexpr->funcid = funcid;
4459  fexpr->funcresulttype = result_type;
4460  fexpr->funcretset = false;
4461  fexpr->funcvariadic = funcvariadic;
4462  fexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
4463  fexpr->funccollid = result_collid; /* doesn't matter */
4464  fexpr->inputcollid = input_collid;
4465  fexpr->args = args;
4466  fexpr->location = -1;
4467 
4468  pinfo = prepare_sql_fn_parse_info(func_tuple,
4469  (Node *) fexpr,
4470  input_collid);
4471 
4472  /*
4473  * We just do parsing and parse analysis, not rewriting, because rewriting
4474  * will not affect table-free-SELECT-only queries, which is all that we
4475  * care about. Also, we can punt as soon as we detect more than one
4476  * command in the function body.
4477  */
4478  raw_parsetree_list = pg_parse_query(src);
4479  if (list_length(raw_parsetree_list) != 1)
4480  goto fail;
4481 
4482  pstate = make_parsestate(NULL);
4483  pstate->p_sourcetext = src;
4484  sql_fn_parser_setup(pstate, pinfo);
4485 
4486  querytree = transformTopLevelStmt(pstate, linitial(raw_parsetree_list));
4487 
4488  free_parsestate(pstate);
4489 
4490  /*
4491  * The single command must be a simple "SELECT expression".
4492  *
4493  * Note: if you change the tests involved in this, see also plpgsql's
4494  * exec_simple_check_plan(). That generally needs to have the same idea
4495  * of what's a "simple expression", so that inlining a function that
4496  * previously wasn't inlined won't change plpgsql's conclusion.
4497  */
4498  if (!IsA(querytree, Query) ||
4499  querytree->commandType != CMD_SELECT ||
4500  querytree->hasAggs ||
4501  querytree->hasWindowFuncs ||
4502  querytree->hasTargetSRFs ||
4503  querytree->hasSubLinks ||
4504  querytree->cteList ||
4505  querytree->rtable ||
4506  querytree->jointree->fromlist ||
4507  querytree->jointree->quals ||
4508  querytree->groupClause ||
4509  querytree->groupingSets ||
4510  querytree->havingQual ||
4511  querytree->windowClause ||
4512  querytree->distinctClause ||
4513  querytree->sortClause ||
4514  querytree->limitOffset ||
4515  querytree->limitCount ||
4516  querytree->setOperations ||
4517  list_length(querytree->targetList) != 1)
4518  goto fail;
4519 
4520  /*
4521  * Make sure the function (still) returns what it's declared to. This
4522  * will raise an error if wrong, but that's okay since the function would
4523  * fail at runtime anyway. Note that check_sql_fn_retval will also insert
4524  * a RelabelType if needed to make the tlist expression match the declared
4525  * type of the function.
4526  *
4527  * Note: we do not try this until we have verified that no rewriting was
4528  * needed; that's probably not important, but let's be careful.
4529  */
4530  if (check_sql_fn_retval(funcid, result_type, list_make1(querytree),
4531  &modifyTargetList, NULL))
4532  goto fail; /* reject whole-tuple-result cases */
4533 
4534  /* Now we can grab the tlist expression */
4535  newexpr = (Node *) ((TargetEntry *) linitial(querytree->targetList))->expr;
4536 
4537  /* Assert that check_sql_fn_retval did the right thing */
4538  Assert(exprType(newexpr) == result_type);
4539  /* It couldn't have made any dangerous tlist changes, either */
4540  Assert(!modifyTargetList);
4541 
4542  /*
4543  * Additional validity checks on the expression. It mustn't be more
4544  * volatile than the surrounding function (this is to avoid breaking hacks
4545  * that involve pretending a function is immutable when it really ain't).
4546  * If the surrounding function is declared strict, then the expression
4547  * must contain only strict constructs and must use all of the function
4548  * parameters (this is overkill, but an exact analysis is hard).
4549  */
4550  if (funcform->provolatile == PROVOLATILE_IMMUTABLE &&
4551  contain_mutable_functions(newexpr))
4552  goto fail;
4553  else if (funcform->provolatile == PROVOLATILE_STABLE &&
4554  contain_volatile_functions(newexpr))
4555  goto fail;
4556 
4557  if (funcform->proisstrict &&
4558  contain_nonstrict_functions(newexpr))
4559  goto fail;
4560 
4561  /*
4562  * If any parameter expression contains a context-dependent node, we can't
4563  * inline, for fear of putting such a node into the wrong context.
4564  */
4565  if (contain_context_dependent_node((Node *) args))
4566  goto fail;
4567 
4568  /*
4569  * We may be able to do it; there are still checks on parameter usage to
4570  * make, but those are most easily done in combination with the actual
4571  * substitution of the inputs. So start building expression with inputs
4572  * substituted.
4573  */
4574  usecounts = (int *) palloc0(funcform->pronargs * sizeof(int));
4575  newexpr = substitute_actual_parameters(newexpr, funcform->pronargs,
4576  args, usecounts);
4577 
4578  /* Now check for parameter usage */
4579  i = 0;
4580  foreach(arg, args)
4581  {
4582  Node *param = lfirst(arg);
4583 
4584  if (usecounts[i] == 0)
4585  {
4586  /* Param not used at all: uncool if func is strict */
4587  if (funcform->proisstrict)
4588  goto fail;
4589  }
4590  else if (usecounts[i] != 1)
4591  {
4592  /* Param used multiple times: uncool if expensive or volatile */
4593  QualCost eval_cost;
4594 
4595  /*
4596  * We define "expensive" as "contains any subplan or more than 10
4597  * operators". Note that the subplan search has to be done
4598  * explicitly, since cost_qual_eval() will barf on unplanned
4599  * subselects.
4600  */
4601  if (contain_subplans(param))
4602  goto fail;
4603  cost_qual_eval(&eval_cost, list_make1(param), NULL);
4604  if (eval_cost.startup + eval_cost.per_tuple >
4605  10 * cpu_operator_cost)
4606  goto fail;
4607 
4608  /*
4609  * Check volatility last since this is more expensive than the
4610  * above tests
4611  */
4612  if (contain_volatile_functions(param))
4613  goto fail;
4614  }
4615  i++;
4616  }
4617 
4618  /*
4619  * Whew --- we can make the substitution. Copy the modified expression
4620  * out of the temporary memory context, and clean up.
4621  */
4622  MemoryContextSwitchTo(oldcxt);
4623 
4624  newexpr = copyObject(newexpr);
4625 
4626  MemoryContextDelete(mycxt);
4627 
4628  /*
4629  * If the result is of a collatable type, force the result to expose the
4630  * correct collation. In most cases this does not matter, but it's
4631  * possible that the function result is used directly as a sort key or in
4632  * other places where we expect exprCollation() to tell the truth.
4633  */
4634  if (OidIsValid(result_collid))
4635  {
4636  Oid exprcoll = exprCollation(newexpr);
4637 
4638  if (OidIsValid(exprcoll) && exprcoll != result_collid)
4639  {
4640  CollateExpr *newnode = makeNode(CollateExpr);
4641 
4642  newnode->arg = (Expr *) newexpr;
4643  newnode->collOid = result_collid;
4644  newnode->location = -1;
4645 
4646  newexpr = (Node *) newnode;
4647  }
4648  }
4649 
4650  /*
4651  * Since there is now no trace of the function in the plan tree, we must
4652  * explicitly record the plan's dependency on the function.
4653  */
4654  if (context->root)
4655  record_plan_function_dependency(context->root, funcid);
4656 
4657  /*
4658  * Recursively try to simplify the modified expression. Here we must add
4659  * the current function to the context list of active functions.
4660  */
4661  context->active_fns = lcons_oid(funcid, context->active_fns);
4662  newexpr = eval_const_expressions_mutator(newexpr, context);
4663  context->active_fns = list_delete_first(context->active_fns);
4664 
4665  error_context_stack = sqlerrcontext.previous;
4666 
4667  return (Expr *) newexpr;
4668 
4669  /* Here if func is not inlinable: release temp memory and return NULL */
4670 fail:
4671  MemoryContextSwitchTo(oldcxt);
4672  MemoryContextDelete(mycxt);
4673  error_context_stack = sqlerrcontext.previous;
4674 
4675  return NULL;
4676 }
4677 
4678 /*
4679  * Replace Param nodes by appropriate actual parameters
4680  */
4681 static Node *
4683  int *usecounts)
4684 {
4686 
4687  context.nargs = nargs;
4688  context.args = args;
4689  context.usecounts = usecounts;
4690 
4691  return substitute_actual_parameters_mutator(expr, &context);
4692 }
4693 
4694 static Node *
4697 {
4698  if (node == NULL)
4699  return NULL;
4700  if (IsA(node, Param))
4701  {
4702  Param *param = (Param *) node;
4703 
4704  if (param->paramkind != PARAM_EXTERN)
4705  elog(ERROR, "unexpected paramkind: %d", (int) param->paramkind);
4706  if (param->paramid <= 0 || param->paramid > context->nargs)
4707  elog(ERROR, "invalid paramid: %d", param->paramid);
4708 
4709  /* Count usage of parameter */
4710  context->usecounts[param->paramid - 1]++;
4711 
4712  /* Select the appropriate actual arg and replace the Param with it */
4713  /* We don't need to copy at this time (it'll get done later) */
4714  return list_nth(context->args, param->paramid - 1);
4715  }
4717  (void *) context);
4718 }
4719 
4720 /*
4721  * error context callback to let us supply a call-stack traceback
4722  */
4723 static void
4725 {
4726  inline_error_callback_arg *callback_arg = (inline_error_callback_arg *) arg;
4727  int syntaxerrposition;
4728 
4729  /* If it's a syntax error, convert to internal syntax error report */
4730  syntaxerrposition = geterrposition();
4731  if (syntaxerrposition > 0)
4732  {
4733  errposition(0);
4734  internalerrposition(syntaxerrposition);
4735  internalerrquery(callback_arg->prosrc);
4736  }
4737 
4738  errcontext("SQL function \"%s\" during inlining", callback_arg->proname);
4739 }
4740 
4741 /*
4742  * evaluate_expr: pre-evaluate a constant expression
4743  *
4744  * We use the executor's routine ExecEvalExpr() to avoid duplication of
4745  * code and ensure we get the same result as the executor would get.
4746  */
4747 static Expr *
4748 evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod,
4749  Oid result_collation)
4750 {
4751  EState *estate;
4752  ExprState *exprstate;
4753  MemoryContext oldcontext;
4754  Datum const_val;
4755  bool const_is_null;
4756  int16 resultTypLen;
4757  bool resultTypByVal;
4758 
4759  /*
4760  * To use the executor, we need an EState.
4761  */
4762  estate = CreateExecutorState();
4763 
4764  /* We can use the estate's working context to avoid memory leaks. */
4765  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
4766 
4767  /* Make sure any opfuncids are filled in. */
4768  fix_opfuncids((Node *) expr);
4769 
4770  /*
4771  * Prepare expr for execution. (Note: we can't use ExecPrepareExpr
4772  * because it'd result in recursively invoking eval_const_expressions.)
4773  */
4774  exprstate = ExecInitExpr(expr, NULL);
4775 
4776  /*
4777  * And evaluate it.
4778  *
4779  * It is OK to use a default econtext because none of the ExecEvalExpr()
4780  * code used in this situation will use econtext. That might seem
4781  * fortuitous, but it's not so unreasonable --- a constant expression does
4782  * not depend on context, by definition, n'est ce pas?
4783  */
4784  const_val = ExecEvalExprSwitchContext(exprstate,
4785  GetPerTupleExprContext(estate),
4786  &const_is_null);
4787 
4788  /* Get info needed about result datatype */
4789  get_typlenbyval(result_type, &resultTypLen, &resultTypByVal);
4790 
4791  /* Get back to outer memory context */
4792  MemoryContextSwitchTo(oldcontext);
4793 
4794  /*
4795  * Must copy result out of sub-context used by expression eval.
4796  *
4797  * Also, if it's varlena, forcibly detoast it. This protects us against
4798  * storing TOAST pointers into plans that might outlive the referenced
4799  * data. (makeConst would handle detoasting anyway, but it's worth a few
4800  * extra lines here so that we can do the copy and detoast in one step.)
4801  */
4802  if (!const_is_null)
4803  {
4804  if (resultTypLen == -1)
4805  const_val = PointerGetDatum(PG_DETOAST_DATUM_COPY(const_val));
4806  else
4807  const_val = datumCopy(const_val, resultTypByVal, resultTypLen);
4808  }
4809 
4810  /* Release all the junk we just created */
4811  FreeExecutorState(estate);
4812 
4813  /*
4814  * Make the constant result node.
4815  */
4816  return (Expr *) makeConst(result_type, result_typmod, result_collation,
4817  resultTypLen,
4818  const_val, const_is_null,
4819  resultTypByVal);
4820 }
4821 
4822 
4823 /*
4824  * inline_set_returning_function
4825  * Attempt to "inline" a set-returning function in the FROM clause.
4826  *
4827  * "rte" is an RTE_FUNCTION rangetable entry. If it represents a call of a
4828  * set-returning SQL function that can safely be inlined, expand the function
4829  * and return the substitute Query structure. Otherwise, return NULL.
4830  *
4831  * This has a good deal of similarity to inline_function(), but that's
4832  * for the non-set-returning case, and there are enough differences to
4833  * justify separate functions.
4834  */
4835 Query *
4837 {
4838  RangeTblFunction *rtfunc;
4839  FuncExpr *fexpr;
4840  Oid func_oid;
4841  HeapTuple func_tuple;
4842  Form_pg_proc funcform;
4843  char *src;
4844  Datum tmp;
4845  bool isNull;
4846  bool modifyTargetList;
4847  MemoryContext oldcxt;
4848  MemoryContext mycxt;
4849  List *saveInvalItems;
4850  inline_error_callback_arg callback_arg;
4851  ErrorContextCallback sqlerrcontext;
4853  List *raw_parsetree_list;
4854  List *querytree_list;
4855  Query *querytree;
4856 
4857  Assert(rte->rtekind == RTE_FUNCTION);
4858 
4859  /*
4860  * It doesn't make a lot of sense for a SQL SRF to refer to itself in its
4861  * own FROM clause, since that must cause infinite recursion at runtime.
4862  * It will cause this code to recurse too, so check for stack overflow.
4863  * (There's no need to do more.)
4864  */
4866 
4867  /* Fail if the RTE has ORDINALITY - we don't implement that here. */
4868  if (rte->funcordinality)
4869  return NULL;
4870 
4871  /* Fail if RTE isn't a single, simple FuncExpr */
4872  if (list_length(rte->functions) != 1)
4873  return NULL;
4874  rtfunc = (RangeTblFunction *) linitial(rte->functions);
4875 
4876  if (!IsA(rtfunc->funcexpr, FuncExpr))
4877  return NULL;
4878  fexpr = (FuncExpr *) rtfunc->funcexpr;
4879 
4880  func_oid = fexpr->funcid;
4881 
4882  /*
4883  * The function must be declared to return a set, else inlining would
4884  * change the results if the contained SELECT didn't return exactly one
4885  * row.
4886  */
4887  if (!fexpr->funcretset)
4888  return NULL;
4889 
4890  /*
4891  * Refuse to inline if the arguments contain any volatile functions or
4892  * sub-selects. Volatile functions are rejected because inlining may
4893  * result in the arguments being evaluated multiple times, risking a
4894  * change in behavior. Sub-selects are rejected partly for implementation
4895  * reasons (pushing them down another level might change their behavior)
4896  * and partly because they're likely to be expensive and so multiple
4897  * evaluation would be bad.
4898  */
4899  if (contain_volatile_functions((Node *) fexpr->args) ||
4900  contain_subplans((Node *) fexpr->args))
4901  return NULL;
4902 
4903  /* Check permission to call function (fail later, if not) */
4904  if (pg_proc_aclcheck(func_oid, GetUserId(), ACL_EXECUTE) != ACLCHECK_OK)
4905  return NULL;
4906 
4907  /* Check whether a plugin wants to hook function entry/exit */
4908  if (FmgrHookIsNeeded(func_oid))
4909  return NULL;
4910 
4911  /*
4912  * OK, let's take a look at the function's pg_proc entry.
4913  */
4914  func_tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(func_oid));
4915  if (!HeapTupleIsValid(func_tuple))
4916  elog(ERROR, "cache lookup failed for function %u", func_oid);
4917  funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4918 
4919  /*
4920  * Forget it if the function is not SQL-language or has other showstopper
4921  * properties. In particular it mustn't be declared STRICT, since we
4922  * couldn't enforce that. It also mustn't be VOLATILE, because that is
4923  * supposed to cause it to be executed with its own snapshot, rather than
4924  * sharing the snapshot of the calling query. (Rechecking proretset is
4925  * just paranoia.)
4926  */
4927  if (funcform->prolang != SQLlanguageId ||
4928  funcform->proisstrict ||
4929  funcform->provolatile == PROVOLATILE_VOLATILE ||
4930  funcform->prosecdef ||
4931  !funcform->proretset ||
4932  !heap_attisnull(func_tuple, Anum_pg_proc_proconfig))
4933  {
4934  ReleaseSysCache(func_tuple);
4935  return NULL;
4936  }
4937 
4938  /*
4939  * Make a temporary memory context, so that we don't leak all the stuff
4940  * that parsing might create.
4941  */
4943  "inline_set_returning_function",
4945  oldcxt = MemoryContextSwitchTo(mycxt);
4946 
4947  /*
4948  * When we call eval_const_expressions below, it might try to add items to
4949  * root->glob->invalItems. Since it is running in the temp context, those
4950  * items will be in that context, and will need to be copied out if we're
4951  * successful. Temporarily reset the list so that we can keep those items
4952  * separate from the pre-existing list contents.
4953  */
4954  saveInvalItems = root->glob->invalItems;
4955  root->glob->invalItems = NIL;
4956 
4957  /* Fetch the function body */
4958  tmp = SysCacheGetAttr(PROCOID,
4959  func_tuple,
4961  &isNull);
4962  if (isNull)
4963  elog(ERROR, "null prosrc for function %u", func_oid);
4964  src = TextDatumGetCString(tmp);
4965 
4966  /*
4967  * Setup error traceback support for ereport(). This is so that we can
4968  * finger the function that bad information came from.
4969  */
4970  callback_arg.proname = NameStr(funcform->proname);
4971  callback_arg.prosrc = src;
4972 
4973  sqlerrcontext.callback = sql_inline_error_callback;
4974  sqlerrcontext.arg = (void *) &callback_arg;
4975  sqlerrcontext.previous = error_context_stack;
4976  error_context_stack = &sqlerrcontext;
4977 
4978  /*
4979  * Run eval_const_expressions on the function call. This is necessary to
4980  * ensure that named-argument notation is converted to positional notation
4981  * and any default arguments are inserted. It's a bit of overkill for the
4982  * arguments, since they'll get processed again later, but no harm will be
4983  * done.
4984  */
4985  fexpr = (FuncExpr *) eval_const_expressions(root, (Node *) fexpr);
4986 
4987  /* It should still be a call of the same function, but let's check */
4988  if (!IsA(fexpr, FuncExpr) ||
4989  fexpr->funcid != func_oid)
4990  goto fail;
4991 
4992  /* Arg list length should now match the function */
4993  if (list_length(fexpr->args) != funcform->pronargs)
4994  goto fail;
4995 
4996  /*
4997  * Set up to handle parameters while parsing the function body. We can
4998  * use the FuncExpr just created as the input for
4999  * prepare_sql_fn_parse_info.
5000  */
5001  pinfo = prepare_sql_fn_parse_info(func_tuple,
5002  (Node *) fexpr,
5003  fexpr->inputcollid);
5004 
5005  /*
5006  * Parse, analyze, and rewrite (unlike inline_function(), we can't skip
5007  * rewriting here). We can fail as soon as we find more than one query,
5008  * though.
5009  */
5010  raw_parsetree_list = pg_parse_query(src);
5011  if (list_length(raw_parsetree_list) != 1)
5012  goto fail;
5013 
5014  querytree_list = pg_analyze_and_rewrite_params(linitial(raw_parsetree_list),
5015  src,
5017  pinfo, NULL);
5018  if (list_length(querytree_list) != 1)
5019  goto fail;
5020  querytree = linitial(querytree_list);
5021 
5022  /*
5023  * The single command must be a plain SELECT.
5024  */
5025  if (!IsA(querytree, Query) ||
5026  querytree->commandType != CMD_SELECT)
5027  goto fail;
5028 
5029  /*
5030  * Make sure the function (still) returns what it's declared to. This
5031  * will raise an error if wrong, but that's okay since the function would
5032  * fail at runtime anyway. Note that check_sql_fn_retval will also insert
5033  * RelabelType(s) and/or NULL columns if needed to make the tlist
5034  * expression(s) match the declared type of the function.
5035  *
5036  * If the function returns a composite type, don't inline unless the check
5037  * shows it's returning a whole tuple result; otherwise what it's
5038  * returning is a single composite column which is not what we need. (Like
5039  * check_sql_fn_retval, we deliberately exclude domains over composite
5040  * here.)
5041  */
5042  if (!check_sql_fn_retval(func_oid, fexpr->funcresulttype,
5043  querytree_list,
5044  &modifyTargetList, NULL) &&
5045  (get_typtype(fexpr->funcresulttype) == TYPTYPE_COMPOSITE ||
5046  fexpr->funcresulttype == RECORDOID))
5047  goto fail; /* reject not-whole-tuple-result cases */
5048 
5049  /*
5050  * If we had to modify the tlist to make it match, and the statement is
5051  * one in which changing the tlist contents could change semantics, we
5052  * have to punt and not inline.
5053  */
5054  if (modifyTargetList)
5055  goto fail;
5056 
5057  /*
5058  * If it returns RECORD, we have to check against the column type list
5059  * provided in the RTE; check_sql_fn_retval can't do that. (If no match,
5060  * we just fail to inline, rather than complaining; see notes for
5061  * tlist_matches_coltypelist.) We don't have to do this for functions
5062  * with declared OUT parameters, even though their funcresulttype is
5063  * RECORDOID, so check get_func_result_type too.
5064  */
5065  if (fexpr->funcresulttype == RECORDOID &&
5066  get_func_result_type(func_oid, NULL, NULL) == TYPEFUNC_RECORD &&
5068  rtfunc->funccoltypes))
5069  goto fail;
5070 
5071  /*
5072  * Looks good --- substitute parameters into the query.
5073  */
5074  querytree = substitute_actual_srf_parameters(querytree,
5075  funcform->pronargs,
5076  fexpr->args);
5077 
5078  /*
5079  * Copy the modified query out of the temporary memory context, and clean
5080  * up.
5081  */
5082  MemoryContextSwitchTo(oldcxt);
5083 
5084  querytree = copyObject(querytree);
5085 
5086  /* copy up any new invalItems, too */
5087  root->glob->invalItems = list_concat(saveInvalItems,
5088  copyObject(root->glob->invalItems));
5089 
5090  MemoryContextDelete(mycxt);
5091  error_context_stack = sqlerrcontext.previous;
5092  ReleaseSysCache(func_tuple);
5093 
5094  /*
5095  * We don't have to fix collations here because the upper query is already
5096  * parsed, ie, the collations in the RTE are what count.
5097  */
5098 
5099  /*
5100  * Since there is now no trace of the function in the plan tree, we must
5101  * explicitly record the plan's dependency on the function.
5102  */
5103  record_plan_function_dependency(root, func_oid);
5104 
5105  return querytree;
5106 
5107  /* Here if func is not inlinable: release temp memory and return NULL */
5108 fail:
5109  MemoryContextSwitchTo(oldcxt);
5110  root->glob->invalItems = saveInvalItems;
5111  MemoryContextDelete(mycxt);
5112  error_context_stack = sqlerrcontext.previous;
5113  ReleaseSysCache(func_tuple);
5114 
5115  return NULL;
5116 }
5117 
5118 /*
5119  * Replace Param nodes by appropriate actual parameters
5120  *
5121  * This is just enough different from substitute_actual_parameters()
5122  * that it needs its own code.
5123  */
5124 static Query *
5126 {
5128 
5129  context.nargs = nargs;
5130  context.args = args;
5131  context.sublevels_up = 1;
5132 
5133  return query_tree_mutator(expr,
5135  &context,
5136  0);
5137 }
5138 
5139 static Node *
5142 {
5143  Node *result;
5144 
5145  if (node == NULL)
5146  return NULL;
5147  if (IsA(node, Query))
5148  {
5149  context->sublevels_up++;
5150  result = (Node *) query_tree_mutator((Query *) node,
5152  (void *) context,
5153  0);
5154  context->sublevels_up--;
5155  return result;
5156  }
5157  if (IsA(node, Param))
5158  {
5159  Param *param = (Param *) node;
5160 
5161  if (param->paramkind == PARAM_EXTERN)
5162  {
5163  if (param->paramid <= 0 || param->paramid > context->nargs)
5164  elog(ERROR, "invalid paramid: %d", param->paramid);
5165 
5166  /*
5167  * Since the parameter is being inserted into a subquery, we must
5168  * adjust levels.
5169  */
5170  result = copyObject(list_nth(context->args, param->paramid - 1));
5171  IncrementVarSublevelsUp(result, context->sublevels_up, 0);
5172  return result;
5173  }
5174  }
5175  return expression_tree_mutator(node,
5177  (void *) context);
5178 }
5179 
5180 /*
5181  * Check whether a SELECT targetlist emits the specified column types,
5182  * to see if it's safe to inline a function returning record.
5183  *
5184  * We insist on exact match here. The executor allows binary-coercible
5185  * cases too, but we don't have a way to preserve the correct column types
5186  * in the correct places if we inline the function in such a case.
5187  *
5188  * Note that we only check type OIDs not typmods; this agrees with what the
5189  * executor would do at runtime, and attributing a specific typmod to a
5190  * function result is largely wishful thinking anyway.
5191  */
5192 static bool
5193 tlist_matches_coltypelist(List *tlist, List *coltypelist)
5194 {
5195  ListCell *tlistitem;
5196  ListCell *clistitem;
5197 
5198  clistitem = list_head(coltypelist);
5199  foreach(tlistitem, tlist)
5200  {
5201  TargetEntry *tle = (TargetEntry *) lfirst(tlistitem);
5202  Oid coltype;
5203 
5204  if (tle->resjunk)
5205  continue; /* ignore junk columns */
5206 
5207  if (clistitem == NULL)
5208  return false; /* too many tlist items */
5209 
5210  coltype = lfirst_oid(clistitem);
5211  clistitem = lnext(clistitem);
5212 
5213  if (exprType((Node *) tle->expr) != coltype)
5214  return false; /* column type mismatch */
5215  }
5216 
5217  if (clistitem != NULL)
5218  return false; /* too few tlist items */
5219 
5220  return true;
5221 }
Datum constvalue
Definition: primnodes.h:196
#define list_make2(x1, x2)
Definition: pg_list.h:140
#define list_make3(x1, x2, x3)
Definition: pg_list.h:141
Expr * get_notclausearg(Expr *notclause)
Definition: clauses.c:265
List * aggdistinct
Definition: primnodes.h:303
signed short int16
Definition: c.h:283
char maxParallelHazard
Definition: relation.h:133
Node * limitOffset
Definition: parsenodes.h:158
Oid funcresulttype
Definition: primnodes.h:450
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:3534
bool multidims
Definition: primnodes.h:960
ParamExternData params[FLEXIBLE_ARRAY_MEMBER]
Definition: params.h:76
Node * make_and_qual(Node *qual1, Node *qual2)
Definition: clauses.c:348
#define NIL
Definition: pg_list.h:69
Datum value
Definition: params.h:56
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2245
bool get_func_leakproof(Oid funcid)
Definition: lsyscache.c:1622
Datum boolop(PG_FUNCTION_ARGS)
Definition: _int_bool.c:420
bool contain_leaked_vars(Node *clause)
Definition: clauses.c:1515
void * stringToNode(char *str)
Definition: read.c:38
List * args
Definition: primnodes.h:990
AggClauseCosts * costs
Definition: clauses.c:60
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
static Expr * simplify_function(Oid funcid, Oid result_type, int32 result_typmod, Oid result_collid, Oid input_collid, List **args_p, bool funcvariadic, bool process_args, bool allow_non_const, eval_const_expressions_context *context)
Definition: clauses.c:3931
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
bool is_pseudo_constant_clause_relids(Node *clause, Relids relids)
Definition: clauses.c:2250
bool contain_volatile_functions_not_nextval(Node *clause)
Definition: clauses.c:1007
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:291
Node * negate_clause(Node *node)
Definition: prepqual.c:73
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1313
Index varlevelsup
Definition: primnodes.h:173
Node * expression_tree_mutator(Node *node, Node *(*mutator)(), void *context)
Definition: nodeFuncs.c:2409
#define PG_DETOAST_DATUM_COPY(datum)
Definition: fmgr.h:207
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2646
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
static Expr * evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod, Oid result_collation)
Definition: clauses.c:4748
#define PROVOLATILE_IMMUTABLE
Definition: pg_proc.h:5537
List * sortClause
Definition: parsenodes.h:156
void IncrementVarSublevelsUp(Node *node, int delta_sublevels_up, int min_sublevels_up)
Definition: rewriteManip.c:773
List * args
Definition: primnodes.h:359
List * args
Definition: primnodes.h:457
static bool contain_mutable_functions_walker(Node *node, void *context)
Definition: clauses.c:890
Oid wincollid
Definition: primnodes.h:357
List * lcons_int(int datum, List *list)
Definition: list.c:277
FromExpr * jointree
Definition: parsenodes.h:136
Node * estimate_expression_value(PlannerInfo *root, Node *node)
Definition: clauses.c:2492
Oid GetUserId(void)
Definition: miscinit.c:284
Index maxWinRef
Definition: clauses.h:26
Oid resulttype
Definition: primnodes.h:744
double expression_returns_set_rows(Node *clause)
Definition: clauses.c:802
#define castNode(_type_, nodeptr)
Definition: nodes.h:579
#define TYPTYPE_COMPOSITE
Definition: pg_type.h:721
#define OIDOID
Definition: pg_type.h:328
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:276
static bool contain_volatile_functions_not_nextval_walker(Node *node, void *context)
Definition: clauses.c:1020
float4 get_func_rows(Oid funcid)
Definition: lsyscache.c:1660
#define PointerGetDatum(X)
Definition: postgres.h:562
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:90
Oid funccollid
Definition: primnodes.h:455
#define forthree(cell1, list1, cell2, list2, cell3, list3)
Definition: pg_list.h:203
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1582
void sql_fn_parser_setup(struct ParseState *pstate, SQLFunctionParseInfoPtr pinfo)
Definition: functions.c:273
Oid resulttype
Definition: primnodes.h:815
RowCompareType rctype
Definition: primnodes.h:1038
void get_agg_clause_costs(PlannerInfo *root, Node *clause, AggSplit aggsplit, AggClauseCosts *costs)
Definition: clauses.c:467
bool hasAggs
Definition: parsenodes.h:123
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
int numWindowFuncs
Definition: clauses.h:25
WindowFuncLists * find_window_functions(Node *clause, Index maxWinRef)
Definition: clauses.c:740
Oid casecollid
Definition: primnodes.h:911
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define Anum_pg_proc_prosrc
Definition: pg_proc.h:115
Expr * arg
Definition: primnodes.h:794
#define INT4OID
Definition: pg_type.h:316
List * groupingSets
Definition: parsenodes.h:148
ParamKind paramkind
Definition: primnodes.h:244
List * list_copy(const List *oldlist)
Definition: list.c:1160
Definition: nodes.h:510
static bool contain_agg_clause_walker(Node *node, void *context)
Definition: clauses.c:423
Query * inline_set_returning_function(PlannerInfo *root, RangeTblEntry *rte)
Definition: clauses.c:4836
bool check_sql_fn_retval(Oid func_id, Oid rettype, List *queryTreeList, bool *modifyTargetList, JunkFilter **junkFilter)
Definition: functions.c:1532
List * args
Definition: primnodes.h:301
char get_typtype(Oid typid)
Definition: lsyscache.c:2379
void CommuteOpExpr(OpExpr *clause)
Definition: clauses.c:2287
#define MemSet(start, val, len)
Definition: c.h:853
Oid array_typeid
Definition: primnodes.h:956
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2459
Expr * arg
Definition: primnodes.h:742
List * list_concat(List *list1, List *list2)
Definition: list.c:321
static bool contain_mutable_functions_checker(Oid func_id, void *context)
Definition: clauses.c:884
#define PROPARALLEL_RESTRICTED
Definition: pg_proc.h:5547
List * paramIds
Definition: primnodes.h:687
bool funcretset
Definition: primnodes.h:451
bool hasNonSerial
Definition: relation.h:61
static bool contain_nonstrict_functions_walker(Node *node, void *context)
Definition: clauses.c:1326
Expr * make_opclause(Oid opno, Oid opresulttype, bool opretset, Expr *leftop, Expr *rightop, Oid opcollid, Oid inputcollid)
Definition: clauses.c:172
List * lcons_oid(Oid datum, List *list)
Definition: list.c:295
List * fromlist
Definition: primnodes.h:1478
bool contain_var_clause(Node *node)
Definition: var.c:331
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:957
void make_fn_arguments(ParseState *pstate, List *fargs, Oid *actual_arg_types, Oid *declared_arg_types)
Definition: parse_func.c:1711
bool hasNonPartial
Definition: relation.h:60
bool funcordinality
Definition: parsenodes.h:1006
QualCost transCost
Definition: relation.h:62
float4 get_func_cost(Oid funcid)
Definition: lsyscache.c:1641
Oid casetype
Definition: primnodes.h:910
unsigned int Oid
Definition: postgres_ext.h:31
List * rowMarks
Definition: parsenodes.h:161
Index winref
Definition: primnodes.h:361
Definition: primnodes.h:163
Const * makeConst(Oid consttype, int32 consttypmod, Oid constcollid, int constlen, Datum constvalue, bool constisnull, bool constbyval)
Definition: makefuncs.c:298
void(* callback)(void *arg)
Definition: elog.h:239
List * lappend_oid(List *list, Oid datum)
Definition: list.c:164
struct ErrorContextCallback * previous
Definition: elog.h:238
#define OidIsValid(objectId)
Definition: c.h:576
#define FmgrHookIsNeeded(fn_oid)
Definition: fmgr.h:730
#define BooleanEqualOperator
Definition: pg_operator.h:114
#define DO_AGGSPLIT_COMBINE(as)
Definition: nodes.h:769
int natts
Definition: tupdesc.h:79
Node * quals
Definition: primnodes.h:1479
#define lsecond(l)
Definition: pg_list.h:116
int location
Definition: primnodes.h:564
Cost startup
Definition: relation.h:45
int location
Definition: primnodes.h:926
#define Anum_pg_proc_proconfig
Definition: pg_proc.h:117
TupleDesc lookup_rowtype_tupdesc_domain(Oid type_id, int32 typmod, bool noError)
Definition: typcache.c:1674
static bool get_agg_clause_costs_walker(Node *node, get_agg_clause_costs_context *context)
Definition: clauses.c:479
signed int int32
Definition: c.h:284
char max_parallel_hazard(Query *parse)
Definition: clauses.c:1068
List * windowClause
Definition: parsenodes.h:152
List * targetList
Definition: parsenodes.h:138
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:336
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
List * find_forced_null_vars(Node *node)
Definition: clauses.c:2061
ErrorContextCallback * error_context_stack
Definition: elog.c:88
Expr * make_ands_explicit(List *andclauses)
Definition: clauses.c:367
#define FUNC_MAX_ARGS
bool check_functions_in_node(Node *node, check_function_callback checker, void *context)
Definition: nodeFuncs.c:1651
#define list_make1(x1)
Definition: pg_list.h:139
static Node * substitute_actual_srf_parameters_mutator(Node *node, substitute_actual_srf_parameters_context *context)
Definition: clauses.c:5140
bool get_typbyval(Oid typid)
Definition: lsyscache.c:1972
bool contain_subplans(Node *clause)
Definition: clauses.c:843
Oid consttype
Definition: primnodes.h:192
void FreeExecutorState(EState *estate)
Definition: execUtils.c:185
#define GetPerTupleExprContext(estate)
Definition: executor.h:467
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition: clauses.c:1087
CoercionForm funcformat
Definition: primnodes.h:454
static void recheck_cast_function_args(List *args, Oid result_type, HeapTuple func_tuple)
Definition: clauses.c:4201
Cost per_tuple
Definition: relation.h:46
static bool contain_volatile_functions_walker(Node *node, void *context)
Definition: clauses.c:969
#define DO_AGGSPLIT_SERIALIZE(as)
Definition: nodes.h:771
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2506
Oid opresulttype
Definition: primnodes.h:498
void pfree(void *pointer)
Definition: mcxt.c:949
MemoryContext es_query_cxt
Definition: execnodes.h:471
ParamListInfo boundParams
Definition: clauses.c:65
bool resjunk
Definition: primnodes.h:1382
#define linitial(l)
Definition: pg_list.h:111
List * rtable
Definition: parsenodes.h:135
List * make_ands_implicit(Expr *clause)
Definition: clauses.c:378
List * distinctClause
Definition: parsenodes.h:154
Oid funcid
Definition: primnodes.h:449
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define CCDN_IN_CASEEXPR
Definition: clauses.c:1456
List * paramExecTypes
Definition: relation.h:117
Expr * phexpr
Definition: relation.h:1940
bool list_member(const List *list, const void *datum)
Definition: list.c:444
static bool rowtype_field_matches(Oid rowtypeid, int fieldnum, Oid expectedtype, int32 expectedtypmod, Oid expectedcollation)
Definition: clauses.c:2391
static Node * substitute_actual_parameters_mutator(Node *node, substitute_actual_parameters_context *context)
Definition: clauses.c:4695
#define is_opclause(clause)
Definition: clauses.h:20
Oid paramcollid
Definition: primnodes.h:248
#define lfirst_int(lc)
Definition: pg_list.h:107
#define SQLlanguageId
Definition: pg_language.h:80
#define PROVOLATILE_STABLE
Definition: pg_proc.h:5538
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3508
List * args
Definition: primnodes.h:1054
Node * get_leftop(const Expr *clause)
Definition: clauses.c:199
#define ARR_DIMS(a)
Definition: array.h:279
Bitmapset * bms_join(Bitmapset *a, Bitmapset *b)
Definition: bitmapset.c:838
List * pg_parse_query(const char *query_string)
Definition: postgres.c:607
Oid enforce_generic_type_consistency(Oid *actual_arg_types, Oid *declared_arg_types, int nargs, Oid rettype, bool allow_poly)
BoolExprType boolop
Definition: primnodes.h:562
Node * makeBoolConst(bool value, bool isnull)
Definition: makefuncs.c:356
Expr * arg
Definition: primnodes.h:1187
static bool max_parallel_hazard_test(char proparallel, max_parallel_hazard_context *context)
Definition: clauses.c:1130
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:623
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:165
Oid constcollid
Definition: primnodes.h:194
Oid resultcollid
Definition: primnodes.h:747
#define lfirst_node(type, lc)
Definition: pg_list.h:109
int bms_num_members(const Bitmapset *a)
Definition: bitmapset.c:605
bool list_member_int(const List *list, int datum)
Definition: list.c:485
bool and_clause(Node *clause)
Definition: clauses.c:314
void(* ParserSetupHook)(struct ParseState *pstate, void *arg)
Definition: params.h:66
Node * limitCount
Definition: parsenodes.h:159
Relids find_nonnullable_rels(Node *clause)
Definition: clauses.c:1660