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