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