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