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