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