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