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