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