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