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