PostgreSQL Source Code  git master
clauses.c File Reference
#include "postgres.h"
#include "access/htup_details.h"
#include "catalog/pg_aggregate.h"
#include "catalog/pg_class.h"
#include "catalog/pg_language.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "executor/executor.h"
#include "executor/functions.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "nodes/subscripting.h"
#include "nodes/supportnodes.h"
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
#include "optimizer/optimizer.h"
#include "optimizer/plancat.h"
#include "optimizer/planmain.h"
#include "parser/analyze.h"
#include "parser/parse_agg.h"
#include "parser/parse_coerce.h"
#include "parser/parse_func.h"
#include "rewrite/rewriteManip.h"
#include "tcop/tcopprot.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/datum.h"
#include "utils/fmgroids.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
Include dependency graph for clauses.c:

Go to the source code of this file.

Data Structures

struct  eval_const_expressions_context
 
struct  substitute_actual_parameters_context
 
struct  substitute_actual_srf_parameters_context
 
struct  inline_error_callback_arg
 
struct  max_parallel_hazard_context
 

Macros

#define CCDN_CASETESTEXPR_OK   0x0001 /* CaseTestExpr okay here? */
 
#define ece_generic_processing(node)
 
#define ece_all_arguments_const(node)   (!expression_tree_walker((Node *) (node), contain_non_const_walker, NULL))
 
#define ece_evaluate_expr(node)
 

Functions

static bool contain_agg_clause_walker (Node *node, void *context)
 
static bool find_window_functions_walker (Node *node, WindowFuncLists *lists)
 
static bool contain_subplans_walker (Node *node, void *context)
 
static bool contain_mutable_functions_walker (Node *node, void *context)
 
static bool contain_volatile_functions_walker (Node *node, void *context)
 
static bool contain_volatile_functions_not_nextval_walker (Node *node, void *context)
 
static bool max_parallel_hazard_walker (Node *node, max_parallel_hazard_context *context)
 
static bool contain_nonstrict_functions_walker (Node *node, void *context)
 
static bool contain_exec_param_walker (Node *node, List *param_ids)
 
static bool contain_context_dependent_node (Node *clause)
 
static bool contain_context_dependent_node_walker (Node *node, int *flags)
 
static bool contain_leaked_vars_walker (Node *node, void *context)
 
static Relids find_nonnullable_rels_walker (Node *node, bool top_level)
 
static Listfind_nonnullable_vars_walker (Node *node, bool top_level)
 
static bool is_strict_saop (ScalarArrayOpExpr *expr, bool falseOK)
 
static Nodeeval_const_expressions_mutator (Node *node, eval_const_expressions_context *context)
 
static bool contain_non_const_walker (Node *node, void *context)
 
static bool ece_function_is_safe (Oid funcid, eval_const_expressions_context *context)
 
static Listsimplify_or_arguments (List *args, eval_const_expressions_context *context, bool *haveNull, bool *forceTrue)
 
static Listsimplify_and_arguments (List *args, eval_const_expressions_context *context, bool *haveNull, bool *forceFalse)
 
static Nodesimplify_boolean_equality (Oid opno, List *args)
 
static Exprsimplify_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)
 
static Listreorder_function_arguments (List *args, HeapTuple func_tuple)
 
static Listadd_function_defaults (List *args, HeapTuple func_tuple)
 
static Listfetch_function_defaults (HeapTuple func_tuple)
 
static void recheck_cast_function_args (List *args, Oid result_type, HeapTuple func_tuple)
 
static Exprevaluate_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)
 
static Exprinline_function (Oid funcid, Oid result_type, Oid result_collid, Oid input_collid, List *args, bool funcvariadic, HeapTuple func_tuple, eval_const_expressions_context *context)
 
static Nodesubstitute_actual_parameters (Node *expr, int nargs, List *args, int *usecounts)
 
static Nodesubstitute_actual_parameters_mutator (Node *node, substitute_actual_parameters_context *context)
 
static void sql_inline_error_callback (void *arg)
 
static Querysubstitute_actual_srf_parameters (Query *expr, int nargs, List *args)
 
static Nodesubstitute_actual_srf_parameters_mutator (Node *node, substitute_actual_srf_parameters_context *context)
 
bool contain_agg_clause (Node *clause)
 
bool contain_window_function (Node *clause)
 
WindowFuncListsfind_window_functions (Node *clause, Index maxWinRef)
 
double expression_returns_set_rows (PlannerInfo *root, Node *clause)
 
bool contain_subplans (Node *clause)
 
bool contain_mutable_functions (Node *clause)
 
static bool contain_mutable_functions_checker (Oid func_id, void *context)
 
bool contain_volatile_functions (Node *clause)
 
static bool contain_volatile_functions_checker (Oid func_id, void *context)
 
bool contain_volatile_functions_not_nextval (Node *clause)
 
static bool contain_volatile_functions_not_nextval_checker (Oid func_id, void *context)
 
char max_parallel_hazard (Query *parse)
 
bool is_parallel_safe (PlannerInfo *root, Node *node)
 
static bool max_parallel_hazard_test (char proparallel, max_parallel_hazard_context *context)
 
static bool max_parallel_hazard_checker (Oid func_id, void *context)
 
bool contain_nonstrict_functions (Node *clause)
 
static bool contain_nonstrict_functions_checker (Oid func_id, void *context)
 
bool contain_exec_param (Node *clause, List *param_ids)
 
bool contain_leaked_vars (Node *clause)
 
static bool contain_leaked_vars_checker (Oid func_id, void *context)
 
Relids find_nonnullable_rels (Node *clause)
 
Listfind_nonnullable_vars (Node *clause)
 
Listfind_forced_null_vars (Node *node)
 
Varfind_forced_null_var (Node *node)
 
bool is_pseudo_constant_clause (Node *clause)
 
bool is_pseudo_constant_clause_relids (Node *clause, Relids relids)
 
int NumRelids (PlannerInfo *root, Node *clause)
 
void CommuteOpExpr (OpExpr *clause)
 
static bool rowtype_field_matches (Oid rowtypeid, int fieldnum, Oid expectedtype, int32 expectedtypmod, Oid expectedcollation)
 
Nodeeval_const_expressions (PlannerInfo *root, Node *node)
 
Nodeestimate_expression_value (PlannerInfo *root, Node *node)
 
Listexpand_function_arguments (List *args, Oid result_type, HeapTuple func_tuple)
 
Exprevaluate_expr (Expr *expr, Oid result_type, int32 result_typmod, Oid result_collation)
 
Queryinline_set_returning_function (PlannerInfo *root, RangeTblEntry *rte)
 

Macro Definition Documentation

◆ CCDN_CASETESTEXPR_OK

#define CCDN_CASETESTEXPR_OK   0x0001 /* CaseTestExpr okay here? */

Definition at line 1000 of file clauses.c.

Referenced by contain_context_dependent_node_walker().

◆ ece_all_arguments_const

#define ece_all_arguments_const (   node)    (!expression_tree_walker((Node *) (node), contain_non_const_walker, NULL))

Definition at line 2086 of file clauses.c.

Referenced by eval_const_expressions_mutator().

◆ ece_evaluate_expr

#define ece_evaluate_expr (   node)
Value:
((Node *) evaluate_expr((Expr *) (node), \
exprType((Node *) (node)), \
exprTypmod((Node *) (node)), \
exprCollation((Node *) (node))))
Expr * evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod, Oid result_collation)
Definition: clauses.c:4497
Definition: nodes.h:533
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41

Definition at line 2090 of file clauses.c.

Referenced by eval_const_expressions_mutator().

◆ ece_generic_processing

#define ece_generic_processing (   node)
Value:
(void *) context)
Node * expression_tree_mutator(Node *node, Node *(*mutator)(), void *context)
Definition: nodeFuncs.c:2579
Definition: nodes.h:533
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2100

Definition at line 2077 of file clauses.c.

Referenced by eval_const_expressions_mutator().

Function Documentation

◆ add_function_defaults()

static List * add_function_defaults ( List args,
HeapTuple  func_tuple 
)
static

Definition at line 3868 of file clauses.c.

References elog, ERROR, fetch_function_defaults(), GETSTRUCT, list_concat_copy(), list_copy_tail(), and list_length().

Referenced by expand_function_arguments().

3869 {
3870  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
3871  int nargsprovided = list_length(args);
3872  List *defaults;
3873  int ndelete;
3874 
3875  /* Get all the default expressions from the pg_proc tuple */
3876  defaults = fetch_function_defaults(func_tuple);
3877 
3878  /* Delete any unused defaults from the list */
3879  ndelete = nargsprovided + list_length(defaults) - funcform->pronargs;
3880  if (ndelete < 0)
3881  elog(ERROR, "not enough default arguments");
3882  if (ndelete > 0)
3883  defaults = list_copy_tail(defaults, ndelete);
3884 
3885  /* And form the combined argument list, not modifying the input list */
3886  return list_concat_copy(args, defaults);
3887 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
List * list_copy_tail(const List *oldlist, int nskip)
Definition: list.c:1437
#define ERROR
Definition: elog.h:45
List * list_concat_copy(const List *list1, const List *list2)
Definition: list.c:567
static List * fetch_function_defaults(HeapTuple func_tuple)
Definition: clauses.c:3893
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:133
static int list_length(const List *l)
Definition: pg_list.h:149
#define elog(elevel,...)
Definition: elog.h:227
Definition: pg_list.h:50

◆ CommuteOpExpr()

void CommuteOpExpr ( OpExpr clause)

Definition at line 1915 of file clauses.c.

References OpExpr::args, elog, ERROR, get_commutator(), InvalidOid, is_opclause(), linitial, list_length(), lsecond, OidIsValid, OpExpr::opfuncid, and OpExpr::opno.

Referenced by get_switched_clauses().

1916 {
1917  Oid opoid;
1918  Node *temp;
1919 
1920  /* Sanity checks: caller is at fault if these fail */
1921  if (!is_opclause(clause) ||
1922  list_length(clause->args) != 2)
1923  elog(ERROR, "cannot commute non-binary-operator clause");
1924 
1925  opoid = get_commutator(clause->opno);
1926 
1927  if (!OidIsValid(opoid))
1928  elog(ERROR, "could not find commutator for operator %u",
1929  clause->opno);
1930 
1931  /*
1932  * modify the clause in-place!
1933  */
1934  clause->opno = opoid;
1935  clause->opfuncid = InvalidOid;
1936  /* opresulttype, opretset, opcollid, inputcollid need not change */
1937 
1938  temp = linitial(clause->args);
1939  linitial(clause->args) = lsecond(clause->args);
1940  lsecond(clause->args) = temp;
1941 }
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1480
Definition: nodes.h:533
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
#define lsecond(l)
Definition: pg_list.h:179
#define linitial(l)
Definition: pg_list.h:174
#define ERROR
Definition: elog.h:45
Oid opfuncid
Definition: primnodes.h:538
#define InvalidOid
Definition: postgres_ext.h:36
static int list_length(const List *l)
Definition: pg_list.h:149
#define elog(elevel,...)
Definition: elog.h:227
Oid opno
Definition: primnodes.h:537
static bool is_opclause(const void *clause)
Definition: nodeFuncs.h:66
List * args
Definition: primnodes.h:543

◆ contain_agg_clause()

bool contain_agg_clause ( Node clause)

Definition at line 170 of file clauses.c.

References contain_agg_clause_walker().

Referenced by get_eclass_for_sort_expr(), and subquery_planner().

171 {
172  return contain_agg_clause_walker(clause, NULL);
173 }
static bool contain_agg_clause_walker(Node *node, void *context)
Definition: clauses.c:176

◆ contain_agg_clause_walker()

static bool contain_agg_clause_walker ( Node node,
void *  context 
)
static

Definition at line 176 of file clauses.c.

References Assert, expression_tree_walker(), and IsA.

Referenced by contain_agg_clause().

177 {
178  if (node == NULL)
179  return false;
180  if (IsA(node, Aggref))
181  {
182  Assert(((Aggref *) node)->agglevelsup == 0);
183  return true; /* abort the tree traversal and return true */
184  }
185  if (IsA(node, GroupingFunc))
186  {
187  Assert(((GroupingFunc *) node)->agglevelsup == 0);
188  return true; /* abort the tree traversal and return true */
189  }
190  Assert(!IsA(node, SubLink));
191  return expression_tree_walker(node, contain_agg_clause_walker, context);
192 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:584
static bool contain_agg_clause_walker(Node *node, void *context)
Definition: clauses.c:176
#define Assert(condition)
Definition: c.h:804
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1885

◆ contain_context_dependent_node()

static bool contain_context_dependent_node ( Node clause)
static

Definition at line 993 of file clauses.c.

References contain_context_dependent_node_walker().

Referenced by inline_function().

994 {
995  int flags = 0;
996 
997  return contain_context_dependent_node_walker(clause, &flags);
998 }
static bool contain_context_dependent_node_walker(Node *node, int *flags)
Definition: clauses.c:1003

◆ contain_context_dependent_node_walker()

static bool contain_context_dependent_node_walker ( Node node,
int *  flags 
)
static

Definition at line 1003 of file clauses.c.

References ArrayCoerceExpr::arg, CaseExpr::arg, CCDN_CASETESTEXPR_OK, ArrayCoerceExpr::elemexpr, expression_tree_walker(), and IsA.

Referenced by contain_context_dependent_node().

1004 {
1005  if (node == NULL)
1006  return false;
1007  if (IsA(node, CaseTestExpr))
1008  return !(*flags & CCDN_CASETESTEXPR_OK);
1009  else if (IsA(node, CaseExpr))
1010  {
1011  CaseExpr *caseexpr = (CaseExpr *) node;
1012 
1013  /*
1014  * If this CASE doesn't have a test expression, then it doesn't create
1015  * a context in which CaseTestExprs should appear, so just fall
1016  * through and treat it as a generic expression node.
1017  */
1018  if (caseexpr->arg)
1019  {
1020  int save_flags = *flags;
1021  bool res;
1022 
1023  /*
1024  * Note: in principle, we could distinguish the various sub-parts
1025  * of a CASE construct and set the flag bit only for some of them,
1026  * since we are only expecting CaseTestExprs to appear in the
1027  * "expr" subtree of the CaseWhen nodes. But it doesn't really
1028  * seem worth any extra code. If there are any bare CaseTestExprs
1029  * elsewhere in the CASE, something's wrong already.
1030  */
1031  *flags |= CCDN_CASETESTEXPR_OK;
1032  res = expression_tree_walker(node,
1034  (void *) flags);
1035  *flags = save_flags;
1036  return res;
1037  }
1038  }
1039  else if (IsA(node, ArrayCoerceExpr))
1040  {
1041  ArrayCoerceExpr *ac = (ArrayCoerceExpr *) node;
1042  int save_flags;
1043  bool res;
1044 
1045  /* Check the array expression */
1046  if (contain_context_dependent_node_walker((Node *) ac->arg, flags))
1047  return true;
1048 
1049  /* Check the elemexpr, which is allowed to contain CaseTestExpr */
1050  save_flags = *flags;
1051  *flags |= CCDN_CASETESTEXPR_OK;
1053  flags);
1054  *flags = save_flags;
1055  return res;
1056  }
1058  (void *) flags);
1059 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:584
Definition: nodes.h:533
#define CCDN_CASETESTEXPR_OK
Definition: clauses.c:1000
Expr * elemexpr
Definition: primnodes.h:883
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1885
Expr * arg
Definition: primnodes.h:956
static bool contain_context_dependent_node_walker(Node *node, int *flags)
Definition: clauses.c:1003

◆ contain_exec_param()

bool contain_exec_param ( Node clause,
List param_ids 
)

Definition at line 951 of file clauses.c.

References contain_exec_param_walker().

Referenced by test_opexpr_is_hashable().

952 {
953  return contain_exec_param_walker(clause, param_ids);
954 }
static bool contain_exec_param_walker(Node *node, List *param_ids)
Definition: clauses.c:957

◆ contain_exec_param_walker()

static bool contain_exec_param_walker ( Node node,
List param_ids 
)
static

Definition at line 957 of file clauses.c.

References expression_tree_walker(), IsA, list_member_int(), PARAM_EXEC, Param::paramid, and Param::paramkind.

Referenced by contain_exec_param().

958 {
959  if (node == NULL)
960  return false;
961  if (IsA(node, Param))
962  {
963  Param *p = (Param *) node;
964 
965  if (p->paramkind == PARAM_EXEC &&
966  list_member_int(param_ids, p->paramid))
967  return true;
968  }
969  return expression_tree_walker(node, contain_exec_param_walker, param_ids);
970 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:584
ParamKind paramkind
Definition: primnodes.h:262
bool list_member_int(const List *list, int datum)
Definition: list.c:669
int paramid
Definition: primnodes.h:263
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1885
static bool contain_exec_param_walker(Node *node, List *param_ids)
Definition: clauses.c:957

◆ contain_leaked_vars()

bool contain_leaked_vars ( Node clause)

Definition at line 1077 of file clauses.c.

References contain_leaked_vars_walker().

Referenced by make_restrictinfo_internal(), and qual_is_pushdown_safe().

1078 {
1079  return contain_leaked_vars_walker(clause, NULL);
1080 }
static bool contain_leaked_vars_walker(Node *node, void *context)
Definition: clauses.c:1089

◆ contain_leaked_vars_checker()

static bool contain_leaked_vars_checker ( Oid  func_id,
void *  context 
)
static

Definition at line 1083 of file clauses.c.

References get_func_leakproof().

Referenced by contain_leaked_vars_walker().

1084 {
1085  return !get_func_leakproof(func_id);
1086 }
bool get_func_leakproof(Oid funcid)
Definition: lsyscache.c:1808

◆ contain_leaked_vars_walker()

static bool contain_leaked_vars_walker ( Node node,
void *  context 
)
static

Definition at line 1089 of file clauses.c.

References MinMaxExpr::args, check_functions_in_node(), TypeCacheEntry::cmp_proc, contain_leaked_vars_checker(), contain_var_clause(), expression_tree_walker(), SubscriptRoutines::fetch_leakproof, forthree, get_func_leakproof(), get_opcode(), getSubscriptingRoutines(), RowCompareExpr::largs, lfirst, lfirst_oid, lookup_type_cache(), MinMaxExpr::minmaxtype, nodeTag, OidIsValid, RowCompareExpr::opnos, RowCompareExpr::rargs, SubscriptingRef::refassgnexpr, SubscriptingRef::refcontainertype, SubscriptRoutines::store_leakproof, T_ArrayCoerceExpr, T_ArrayExpr, T_BooleanTest, T_BoolExpr, T_CaseExpr, T_CaseTestExpr, T_CoerceViaIO, T_CollateExpr, T_Const, T_CurrentOfExpr, T_DistinctExpr, T_FieldSelect, T_FieldStore, T_FuncExpr, T_List, T_MinMaxExpr, T_NamedArgExpr, T_NextValueExpr, T_NullIfExpr, T_NullTest, T_OpExpr, T_Param, T_RelabelType, T_RowCompareExpr, T_RowExpr, T_ScalarArrayOpExpr, T_SQLValueFunction, T_SubscriptingRef, T_Var, and TYPECACHE_CMP_PROC.

Referenced by contain_leaked_vars().

1090 {
1091  if (node == NULL)
1092  return false;
1093 
1094  switch (nodeTag(node))
1095  {
1096  case T_Var:
1097  case T_Const:
1098  case T_Param:
1099  case T_ArrayExpr:
1100  case T_FieldSelect:
1101  case T_FieldStore:
1102  case T_NamedArgExpr:
1103  case T_BoolExpr:
1104  case T_RelabelType:
1105  case T_CollateExpr:
1106  case T_CaseExpr:
1107  case T_CaseTestExpr:
1108  case T_RowExpr:
1109  case T_SQLValueFunction:
1110  case T_NullTest:
1111  case T_BooleanTest:
1112  case T_NextValueExpr:
1113  case T_List:
1114 
1115  /*
1116  * We know these node types don't contain function calls; but
1117  * something further down in the node tree might.
1118  */
1119  break;
1120 
1121  case T_FuncExpr:
1122  case T_OpExpr:
1123  case T_DistinctExpr:
1124  case T_NullIfExpr:
1125  case T_ScalarArrayOpExpr:
1126  case T_CoerceViaIO:
1127  case T_ArrayCoerceExpr:
1128 
1129  /*
1130  * If node contains a leaky function call, and there's any Var
1131  * underneath it, reject.
1132  */
1134  context) &&
1135  contain_var_clause(node))
1136  return true;
1137  break;
1138 
1139  case T_SubscriptingRef:
1140  {
1141  SubscriptingRef *sbsref = (SubscriptingRef *) node;
1142  const SubscriptRoutines *sbsroutines;
1143 
1144  /* Consult the subscripting support method info */
1145  sbsroutines = getSubscriptingRoutines(sbsref->refcontainertype,
1146  NULL);
1147  if (!sbsroutines ||
1148  !(sbsref->refassgnexpr != NULL ?
1149  sbsroutines->store_leakproof :
1150  sbsroutines->fetch_leakproof))
1151  {
1152  /* Node is leaky, so reject if it contains Vars */
1153  if (contain_var_clause(node))
1154  return true;
1155  }
1156  }
1157  break;
1158 
1159  case T_RowCompareExpr:
1160  {
1161  /*
1162  * It's worth special-casing this because a leaky comparison
1163  * function only compromises one pair of row elements, which
1164  * might not contain Vars while others do.
1165  */
1166  RowCompareExpr *rcexpr = (RowCompareExpr *) node;
1167  ListCell *opid;
1168  ListCell *larg;
1169  ListCell *rarg;
1170 
1171  forthree(opid, rcexpr->opnos,
1172  larg, rcexpr->largs,
1173  rarg, rcexpr->rargs)
1174  {
1175  Oid funcid = get_opcode(lfirst_oid(opid));
1176 
1177  if (!get_func_leakproof(funcid) &&
1178  (contain_var_clause((Node *) lfirst(larg)) ||
1179  contain_var_clause((Node *) lfirst(rarg))))
1180  return true;
1181  }
1182  }
1183  break;
1184 
1185  case T_MinMaxExpr:
1186  {
1187  /*
1188  * MinMaxExpr is leakproof if the comparison function it calls
1189  * is leakproof.
1190  */
1191  MinMaxExpr *minmaxexpr = (MinMaxExpr *) node;
1192  TypeCacheEntry *typentry;
1193  bool leakproof;
1194 
1195  /* Look up the btree comparison function for the datatype */
1196  typentry = lookup_type_cache(minmaxexpr->minmaxtype,
1198  if (OidIsValid(typentry->cmp_proc))
1199  leakproof = get_func_leakproof(typentry->cmp_proc);
1200  else
1201  {
1202  /*
1203  * The executor will throw an error, but here we just
1204  * treat the missing function as leaky.
1205  */
1206  leakproof = false;
1207  }
1208 
1209  if (!leakproof &&
1210  contain_var_clause((Node *) minmaxexpr->args))
1211  return true;
1212  }
1213  break;
1214 
1215  case T_CurrentOfExpr:
1216 
1217  /*
1218  * WHERE CURRENT OF doesn't contain leaky function calls.
1219  * Moreover, it is essential that this is considered non-leaky,
1220  * since the planner must always generate a TID scan when CURRENT
1221  * OF is present -- cf. cost_tidscan.
1222  */
1223  return false;
1224 
1225  default:
1226 
1227  /*
1228  * If we don't recognize the node tag, assume it might be leaky.
1229  * This prevents an unexpected security hole if someone adds a new
1230  * node type that can call a function.
1231  */
1232  return true;
1233  }
1235  context);
1236 }
Oid minmaxtype
Definition: primnodes.h:1126
bool get_func_leakproof(Oid funcid)
Definition: lsyscache.c:1808
List * args
Definition: primnodes.h:1130
#define forthree(cell1, list1, cell2, list2, cell3, list3)
Definition: pg_list.h:491
Definition: nodes.h:533
bool contain_var_clause(Node *node)
Definition: var.c:358
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
const struct SubscriptRoutines * getSubscriptingRoutines(Oid typid, Oid *typelemp)
Definition: lsyscache.c:3077
bool check_functions_in_node(Node *node, check_function_callback checker, void *context)
Definition: nodeFuncs.c:1702
Definition: nodes.h:301
Definition: nodes.h:156
Definition: nodes.h:155
TypeCacheEntry * lookup_type_cache(Oid type_id, int flags)
Definition: typcache.c:338
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1256
#define TYPECACHE_CMP_PROC
Definition: typcache.h:139
#define lfirst(lc)
Definition: pg_list.h:169
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1885
#define nodeTag(nodeptr)
Definition: nodes.h:538
Expr * refassgnexpr
Definition: primnodes.h:446
static bool contain_leaked_vars_checker(Oid func_id, void *context)
Definition: clauses.c:1083
Oid refcontainertype
Definition: primnodes.h:434
static bool contain_leaked_vars_walker(Node *node, void *context)
Definition: clauses.c:1089
#define lfirst_oid(lc)
Definition: pg_list.h:171
Definition: nodes.h:157

◆ contain_mutable_functions()

◆ contain_mutable_functions_checker()

static bool contain_mutable_functions_checker ( Oid  func_id,
void *  context 
)
static

Definition at line 364 of file clauses.c.

References func_volatile().

Referenced by contain_mutable_functions_walker().

365 {
366  return (func_volatile(func_id) != PROVOLATILE_IMMUTABLE);
367 }
char func_volatile(Oid funcid)
Definition: lsyscache.c:1751

◆ contain_mutable_functions_walker()

static bool contain_mutable_functions_walker ( Node node,
void *  context 
)
static

Definition at line 370 of file clauses.c.

References check_functions_in_node(), contain_mutable_functions_checker(), expression_tree_walker(), IsA, and query_tree_walker().

Referenced by contain_mutable_functions().

371 {
372  if (node == NULL)
373  return false;
374  /* Check for mutable functions in node itself */
376  context))
377  return true;
378 
379  if (IsA(node, SQLValueFunction))
380  {
381  /* all variants of SQLValueFunction are stable */
382  return true;
383  }
384 
385  if (IsA(node, NextValueExpr))
386  {
387  /* NextValueExpr is volatile */
388  return true;
389  }
390 
391  /*
392  * It should be safe to treat MinMaxExpr as immutable, because it will
393  * depend on a non-cross-type btree comparison function, and those should
394  * always be immutable. Treating XmlExpr as immutable is more dubious,
395  * and treating CoerceToDomain as immutable is outright dangerous. But we
396  * have done so historically, and changing this would probably cause more
397  * problems than it would fix. In practice, if you have a non-immutable
398  * domain constraint you are in for pain anyhow.
399  */
400 
401  /* Recurse to check arguments */
402  if (IsA(node, Query))
403  {
404  /* Recurse into subselects */
405  return query_tree_walker((Query *) node,
407  context, 0);
408  }
410  context);
411 }
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2336
#define IsA(nodeptr, _type_)
Definition: nodes.h:584
static bool contain_mutable_functions_walker(Node *node, void *context)
Definition: clauses.c:370
static bool contain_mutable_functions_checker(Oid func_id, void *context)
Definition: clauses.c:364
bool check_functions_in_node(Node *node, check_function_callback checker, void *context)
Definition: nodeFuncs.c:1702
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1885

◆ contain_non_const_walker()

static bool contain_non_const_walker ( Node node,
void *  context 
)
static

Definition at line 3325 of file clauses.c.

References expression_tree_walker(), and IsA.

3326 {
3327  if (node == NULL)
3328  return false;
3329  if (IsA(node, Const))
3330  return false;
3331  if (IsA(node, List))
3332  return expression_tree_walker(node, contain_non_const_walker, context);
3333  /* Otherwise, abort the tree traversal and return true */
3334  return true;
3335 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:584
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1885
Definition: pg_list.h:50
static bool contain_non_const_walker(Node *node, void *context)
Definition: clauses.c:3325

◆ contain_nonstrict_functions()

bool contain_nonstrict_functions ( Node clause)

Definition at line 807 of file clauses.c.

References contain_nonstrict_functions_walker().

Referenced by inline_function(), process_equivalence(), and pullup_replace_vars_callback().

808 {
809  return contain_nonstrict_functions_walker(clause, NULL);
810 }
static bool contain_nonstrict_functions_walker(Node *node, void *context)
Definition: clauses.c:819

◆ contain_nonstrict_functions_checker()

static bool contain_nonstrict_functions_checker ( Oid  func_id,
void *  context 
)
static

Definition at line 813 of file clauses.c.

References func_strict().

Referenced by contain_nonstrict_functions_walker().

814 {
815  return !func_strict(func_id);
816 }
bool func_strict(Oid funcid)
Definition: lsyscache.c:1732

◆ contain_nonstrict_functions_walker()

static bool contain_nonstrict_functions_walker ( Node node,
void *  context 
)
static

Definition at line 819 of file clauses.c.

References AND_EXPR, arg, BoolExpr::boolop, check_functions_in_node(), contain_nonstrict_functions_checker(), expression_tree_walker(), SubscriptRoutines::fetch_strict, getSubscriptingRoutines(), IsA, OR_EXPR, SubscriptingRef::refassgnexpr, and SubscriptingRef::refcontainertype.

Referenced by contain_nonstrict_functions().

820 {
821  if (node == NULL)
822  return false;
823  if (IsA(node, Aggref))
824  {
825  /* an aggregate could return non-null with null input */
826  return true;
827  }
828  if (IsA(node, GroupingFunc))
829  {
830  /*
831  * A GroupingFunc doesn't evaluate its arguments, and therefore must
832  * be treated as nonstrict.
833  */
834  return true;
835  }
836  if (IsA(node, WindowFunc))
837  {
838  /* a window function could return non-null with null input */
839  return true;
840  }
841  if (IsA(node, SubscriptingRef))
842  {
843  SubscriptingRef *sbsref = (SubscriptingRef *) node;
844  const SubscriptRoutines *sbsroutines;
845 
846  /* Subscripting assignment is always presumed nonstrict */
847  if (sbsref->refassgnexpr != NULL)
848  return true;
849  /* Otherwise we must look up the subscripting support methods */
850  sbsroutines = getSubscriptingRoutines(sbsref->refcontainertype, NULL);
851  if (!(sbsroutines && sbsroutines->fetch_strict))
852  return true;
853  /* else fall through to check args */
854  }
855  if (IsA(node, DistinctExpr))
856  {
857  /* IS DISTINCT FROM is inherently non-strict */
858  return true;
859  }
860  if (IsA(node, NullIfExpr))
861  {
862  /* NULLIF is inherently non-strict */
863  return true;
864  }
865  if (IsA(node, BoolExpr))
866  {
867  BoolExpr *expr = (BoolExpr *) node;
868 
869  switch (expr->boolop)
870  {
871  case AND_EXPR:
872  case OR_EXPR:
873  /* AND, OR are inherently non-strict */
874  return true;
875  default:
876  break;
877  }
878  }
879  if (IsA(node, SubLink))
880  {
881  /* In some cases a sublink might be strict, but in general not */
882  return true;
883  }
884  if (IsA(node, SubPlan))
885  return true;
886  if (IsA(node, AlternativeSubPlan))
887  return true;
888  if (IsA(node, FieldStore))
889  return true;
890  if (IsA(node, CoerceViaIO))
891  {
892  /*
893  * CoerceViaIO is strict regardless of whether the I/O functions are,
894  * so just go look at its argument; asking check_functions_in_node is
895  * useless expense and could deliver the wrong answer.
896  */
898  context);
899  }
900  if (IsA(node, ArrayCoerceExpr))
901  {
902  /*
903  * ArrayCoerceExpr is strict at the array level, regardless of what
904  * the per-element expression is; so we should ignore elemexpr and
905  * recurse only into the arg.
906  */
908  context);
909  }
910  if (IsA(node, CaseExpr))
911  return true;
912  if (IsA(node, ArrayExpr))
913  return true;
914  if (IsA(node, RowExpr))
915  return true;
916  if (IsA(node, RowCompareExpr))
917  return true;
918  if (IsA(node, CoalesceExpr))
919  return true;
920  if (IsA(node, MinMaxExpr))
921  return true;
922  if (IsA(node, XmlExpr))
923  return true;
924  if (IsA(node, NullTest))
925  return true;
926  if (IsA(node, BooleanTest))
927  return true;
928 
929  /* Check other function-containing nodes */
931  context))
932  return true;
933 
935  context);
936 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:584
Definition: nodes.h:533
static bool contain_nonstrict_functions_walker(Node *node, void *context)
Definition: clauses.c:819
const struct SubscriptRoutines * getSubscriptingRoutines(Oid typid, Oid *typelemp)
Definition: lsyscache.c:3077
bool check_functions_in_node(Node *node, check_function_callback checker, void *context)
Definition: nodeFuncs.c:1702
BoolExprType boolop
Definition: primnodes.h:603
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1885
Expr * refassgnexpr
Definition: primnodes.h:446
void * arg
Oid refcontainertype
Definition: primnodes.h:434
static bool contain_nonstrict_functions_checker(Oid func_id, void *context)
Definition: clauses.c:813

◆ contain_subplans()

bool contain_subplans ( Node clause)

Definition at line 323 of file clauses.c.

References contain_subplans_walker().

Referenced by convert_EXISTS_to_ANY(), ExecInitValuesScan(), inline_function(), inline_set_returning_function(), qual_is_pushdown_safe(), and subquery_planner().

324 {
325  return contain_subplans_walker(clause, NULL);
326 }
static bool contain_subplans_walker(Node *node, void *context)
Definition: clauses.c:329

◆ contain_subplans_walker()

static bool contain_subplans_walker ( Node node,
void *  context 
)
static

Definition at line 329 of file clauses.c.

References expression_tree_walker(), and IsA.

Referenced by contain_subplans().

330 {
331  if (node == NULL)
332  return false;
333  if (IsA(node, SubPlan) ||
334  IsA(node, AlternativeSubPlan) ||
335  IsA(node, SubLink))
336  return true; /* abort the tree traversal and return true */
337  return expression_tree_walker(node, contain_subplans_walker, context);
338 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:584
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1885
static bool contain_subplans_walker(Node *node, void *context)
Definition: clauses.c:329

◆ contain_volatile_functions()

◆ contain_volatile_functions_checker()

static bool contain_volatile_functions_checker ( Oid  func_id,
void *  context 
)
static

Definition at line 443 of file clauses.c.

References func_volatile().

Referenced by contain_volatile_functions_walker().

444 {
445  return (func_volatile(func_id) == PROVOLATILE_VOLATILE);
446 }
char func_volatile(Oid funcid)
Definition: lsyscache.c:1751

◆ contain_volatile_functions_not_nextval()

bool contain_volatile_functions_not_nextval ( Node clause)

Definition at line 487 of file clauses.c.

References contain_volatile_functions_not_nextval_walker().

Referenced by BeginCopyFrom().

488 {
490 }
static bool contain_volatile_functions_not_nextval_walker(Node *node, void *context)
Definition: clauses.c:500

◆ contain_volatile_functions_not_nextval_checker()

static bool contain_volatile_functions_not_nextval_checker ( Oid  func_id,
void *  context 
)
static

Definition at line 493 of file clauses.c.

References func_volatile().

Referenced by contain_volatile_functions_not_nextval_walker().

494 {
495  return (func_id != F_NEXTVAL &&
496  func_volatile(func_id) == PROVOLATILE_VOLATILE);
497 }
char func_volatile(Oid funcid)
Definition: lsyscache.c:1751

◆ contain_volatile_functions_not_nextval_walker()

static bool contain_volatile_functions_not_nextval_walker ( Node node,
void *  context 
)
static

Definition at line 500 of file clauses.c.

References check_functions_in_node(), contain_volatile_functions_not_nextval_checker(), expression_tree_walker(), IsA, and query_tree_walker().

Referenced by contain_volatile_functions_not_nextval().

501 {
502  if (node == NULL)
503  return false;
504  /* Check for volatile functions in node itself */
505  if (check_functions_in_node(node,
507  context))
508  return true;
509 
510  /*
511  * See notes in contain_mutable_functions_walker about why we treat
512  * MinMaxExpr, XmlExpr, and CoerceToDomain as immutable, while
513  * SQLValueFunction is stable. Hence, none of them are of interest here.
514  * Also, since we're intentionally ignoring nextval(), presumably we
515  * should ignore NextValueExpr.
516  */
517 
518  /* Recurse to check arguments */
519  if (IsA(node, Query))
520  {
521  /* Recurse into subselects */
522  return query_tree_walker((Query *) node,
524  context, 0);
525  }
526  return expression_tree_walker(node,
528  context);
529 }
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2336
#define IsA(nodeptr, _type_)
Definition: nodes.h:584
static bool contain_volatile_functions_not_nextval_walker(Node *node, void *context)
Definition: clauses.c:500
bool check_functions_in_node(Node *node, check_function_callback checker, void *context)
Definition: nodeFuncs.c:1702
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1885
static bool contain_volatile_functions_not_nextval_checker(Oid func_id, void *context)
Definition: clauses.c:493

◆ contain_volatile_functions_walker()

static bool contain_volatile_functions_walker ( Node node,
void *  context 
)
static

Definition at line 449 of file clauses.c.

References check_functions_in_node(), contain_volatile_functions_checker(), expression_tree_walker(), IsA, and query_tree_walker().

Referenced by contain_volatile_functions().

450 {
451  if (node == NULL)
452  return false;
453  /* Check for volatile functions in node itself */
455  context))
456  return true;
457 
458  if (IsA(node, NextValueExpr))
459  {
460  /* NextValueExpr is volatile */
461  return true;
462  }
463 
464  /*
465  * See notes in contain_mutable_functions_walker about why we treat
466  * MinMaxExpr, XmlExpr, and CoerceToDomain as immutable, while
467  * SQLValueFunction is stable. Hence, none of them are of interest here.
468  */
469 
470  /* Recurse to check arguments */
471  if (IsA(node, Query))
472  {
473  /* Recurse into subselects */
474  return query_tree_walker((Query *) node,
476  context, 0);
477  }
479  context);
480 }
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2336
#define IsA(nodeptr, _type_)
Definition: nodes.h:584
bool check_functions_in_node(Node *node, check_function_callback checker, void *context)
Definition: nodeFuncs.c:1702
static bool contain_volatile_functions_walker(Node *node, void *context)
Definition: clauses.c:449
static bool contain_volatile_functions_checker(Oid func_id, void *context)
Definition: clauses.c:443
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1885

◆ contain_window_function()

bool contain_window_function ( Node clause)

Definition at line 207 of file clauses.c.

References contain_windowfuncs().

Referenced by get_eclass_for_sort_expr(), and qual_is_pushdown_safe().

208 {
209  return contain_windowfuncs(clause);
210 }
bool contain_windowfuncs(Node *node)
Definition: rewriteManip.c:197

◆ ece_function_is_safe()

static bool ece_function_is_safe ( Oid  funcid,
eval_const_expressions_context context 
)
static

Definition at line 3341 of file clauses.c.

References eval_const_expressions_context::estimate, and func_volatile().

Referenced by eval_const_expressions_mutator().

3342 {
3343  char provolatile = func_volatile(funcid);
3344 
3345  /*
3346  * Ordinarily we are only allowed to simplify immutable functions. But for
3347  * purposes of estimation, we consider it okay to simplify functions that
3348  * are merely stable; the risk that the result might change from planning
3349  * time to execution time is worth taking in preference to not being able
3350  * to estimate the value at all.
3351  */
3352  if (provolatile == PROVOLATILE_IMMUTABLE)
3353  return true;
3354  if (context->estimate && provolatile == PROVOLATILE_STABLE)
3355  return true;
3356  return false;
3357 }
char func_volatile(Oid funcid)
Definition: lsyscache.c:1751

◆ estimate_expression_value()

Node* estimate_expression_value ( PlannerInfo root,
Node node 
)

Definition at line 2055 of file clauses.c.

References eval_const_expressions_context::active_fns, eval_const_expressions_context::boundParams, PlannerGlobal::boundParams, eval_const_expressions_context::case_val, eval_const_expressions_context::estimate, eval_const_expressions_mutator(), PlannerInfo::glob, NIL, and eval_const_expressions_context::root.

Referenced by array_unnest_support(), bernoulli_samplescangetsamplesize(), clause_selectivity_ext(), generate_series_int4_support(), generate_series_int8_support(), get_restriction_variable(), gincost_opexpr(), gincost_scalararrayopexpr(), preprocess_limit(), scalararraysel(), system_rows_samplescangetsamplesize(), system_samplescangetsamplesize(), and system_time_samplescangetsamplesize().

2056 {
2058 
2059  context.boundParams = root->glob->boundParams; /* bound Params */
2060  /* we do not need to mark the plan as depending on inlined functions */
2061  context.root = NULL;
2062  context.active_fns = NIL; /* nothing being recursively simplified */
2063  context.case_val = NULL; /* no CASE being examined */
2064  context.estimate = true; /* unsafe transformations OK */
2065  return eval_const_expressions_mutator(node, &context);
2066 }
#define NIL
Definition: pg_list.h:65
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2100
ParamListInfo boundParams
Definition: clauses.c:59
PlannerGlobal * glob
Definition: pathnodes.h:175
ParamListInfo boundParams
Definition: pathnodes.h:105

◆ eval_const_expressions()

Node* eval_const_expressions ( PlannerInfo root,
Node node 
)

Definition at line 2022 of file clauses.c.

References eval_const_expressions_context::active_fns, eval_const_expressions_context::boundParams, PlannerGlobal::boundParams, eval_const_expressions_context::case_val, eval_const_expressions_context::estimate, eval_const_expressions_mutator(), PlannerInfo::glob, NIL, and eval_const_expressions_context::root.

Referenced by apply_child_basequals(), ATExecAttachPartition(), ConstraintImpliedByRelConstraint(), convert_EXISTS_to_ANY(), DoCopy(), expression_planner(), expression_planner_with_deps(), get_proposed_default_constraint(), get_relation_constraints(), preprocess_expression(), preprocess_function_rtes(), process_implied_equality(), RelationBuildPartitionKey(), RelationGetIndexExpressions(), RelationGetIndexPredicate(), and simplify_EXISTS_query().

2023 {
2025 
2026  if (root)
2027  context.boundParams = root->glob->boundParams; /* bound Params */
2028  else
2029  context.boundParams = NULL;
2030  context.root = root; /* for inlined-function dependencies */
2031  context.active_fns = NIL; /* nothing being recursively simplified */
2032  context.case_val = NULL; /* no CASE being examined */
2033  context.estimate = false; /* safe transformations only */
2034  return eval_const_expressions_mutator(node, &context);
2035 }
#define NIL
Definition: pg_list.h:65
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2100
ParamListInfo boundParams
Definition: clauses.c:59
PlannerGlobal * glob
Definition: pathnodes.h:175
ParamListInfo boundParams
Definition: pathnodes.h:105

◆ eval_const_expressions_mutator()

static Node * eval_const_expressions_mutator ( Node node,
eval_const_expressions_context context 
)
static

Definition at line 2100 of file clauses.c.

References WindowFunc::aggfilter, AND_EXPR, applyRelabelType(), arg, FieldSelect::arg, RelabelType::arg, CoerceViaIO::arg, ArrayCoerceExpr::arg, ConvertRowtypeExpr::arg, CollateExpr::arg, CaseExpr::arg, NullTest::arg, BooleanTest::arg, CoerceToDomain::arg, NullTest::argisrow, generate_unaccent_rules::args, WindowFunc::args, FuncExpr::args, OpExpr::args, BoolExpr::args, CaseExpr::args, RowExpr::args, CoalesceExpr::args, Assert, BoolGetDatum, BoolExpr::boolop, BooleanTest::booltesttype, eval_const_expressions_context::boundParams, eval_const_expressions_context::case_val, CaseExpr::casecollid, CaseExpr::casetype, castNode, CoalesceExpr::coalescecollid, CoalesceExpr::coalescetype, COERCE_IMPLICIT_CAST, CoerceViaIO::coerceformat, CoerceToDomain::coercionformat, CollateExpr::collOid, Const::constisnull, Const::consttype, Const::constvalue, contain_mutable_functions(), ConvertRowtypeExpr::convertformat, copyObject, datumCopy(), DatumGetBool, CaseExpr::defresult, DomainHasConstraints(), ece_all_arguments_const, ece_evaluate_expr, ece_function_is_safe(), ece_generic_processing, ArrayCoerceExpr::elemexpr, elog, ERROR, eval_const_expressions_context::estimate, evaluate_expr(), expand_function_arguments(), CaseWhen::expr, exprCollation(), expression_tree_mutator(), exprType(), exprTypmod(), FieldSelect::fieldnum, FuncExpr::funccollid, FuncExpr::funcformat, FuncExpr::funcid, FuncExpr::funcresulttype, FuncExpr::funcretset, FuncExpr::funcvariadic, get_typlenbyval(), getTypeInputInfo(), getTypeOutputInfo(), HeapTupleIsValid, WindowFunc::inputcollid, FuncExpr::inputcollid, OpExpr::inputcollid, Int32GetDatum, InvalidAttrNumber, InvalidOid, IS_FALSE, IS_NOT_FALSE, IS_NOT_NULL, IS_NOT_TRUE, IS_NOT_UNKNOWN, IS_NULL, IS_TRUE, IS_UNKNOWN, IsA, ParamExternData::isnull, lappend(), lfirst, lfirst_node, linitial, list_length(), list_make1, list_make3, list_nth(), WindowFunc::location, FuncExpr::location, OpExpr::location, RelabelType::location, CoerceViaIO::location, ConvertRowtypeExpr::location, CollateExpr::location, CaseExpr::location, CaseWhen::location, CoalesceExpr::location, NullTest::location, BooleanTest::location, CoerceToDomain::location, make_andclause(), make_orclause(), makeBoolConst(), makeConst(), makeNode, makeNullConst(), makeVar(), negate_clause(), NIL, nodeTag, NOT_EXPR, NullTest::nulltesttype, ParamListInfoData::numParams, ObjectIdGetDatum, OidIsValid, OpExpr::opcollid, OpExpr::opfuncid, ScalarArrayOpExpr::opfuncid, OpExpr::opno, OpExpr::opresulttype, OpExpr::opretset, OR_EXPR, PARAM_EXTERN, PARAM_FLAG_CONST, Param::paramcollid, ParamListInfoData::paramFetch, Param::paramid, Param::paramkind, ParamListInfoData::params, Param::paramtype, Param::paramtypmod, ParamExternData::pflags, PlaceHolderVar::phexpr, PROCOID, ParamExternData::ptype, record_plan_type_dependency(), RelabelType::relabelformat, ReleaseSysCache(), CaseWhen::result, FieldSelect::resultcollid, RelabelType::resultcollid, CoerceViaIO::resultcollid, CoerceToDomain::resultcollid, FieldSelect::resulttype, RelabelType::resulttype, CoerceViaIO::resulttype, ConvertRowtypeExpr::resulttype, CoerceToDomain::resulttype, FieldSelect::resulttypmod, RelabelType::resulttypmod, CoerceToDomain::resulttypmod, eval_const_expressions_context::root, RowExpr::row_typeid, rowtype_field_matches(), SearchSysCache1(), set_opfuncid(), set_sa_opfuncid(), simplify_and_arguments(), simplify_boolean_equality(), simplify_function(), simplify_or_arguments(), T_AlternativeSubPlan, T_ArrayCoerceExpr, T_ArrayExpr, T_BooleanTest, T_BoolExpr, T_CaseExpr, T_CaseTestExpr, T_CoalesceExpr, T_CoerceToDomain, T_CoerceViaIO, T_CollateExpr, T_ConvertRowtypeExpr, T_DistinctExpr, T_FieldSelect, T_FuncExpr, T_MinMaxExpr, T_NullTest, T_OpExpr, T_Param, T_PlaceHolderVar, T_RelabelType, T_RowExpr, T_ScalarArrayOpExpr, T_SQLValueFunction, T_SubPlan, T_SubscriptingRef, T_WindowFunc, Expr::type, ParamExternData::value, WindowFunc::winagg, WindowFunc::wincollid, WindowFunc::winfnoid, WindowFunc::winref, WindowFunc::winstar, and WindowFunc::wintype.

Referenced by estimate_expression_value(), eval_const_expressions(), inline_function(), simplify_and_arguments(), simplify_function(), and simplify_or_arguments().

2102 {
2103  if (node == NULL)
2104  return NULL;
2105  switch (nodeTag(node))
2106  {
2107  case T_Param:
2108  {
2109  Param *param = (Param *) node;
2110  ParamListInfo paramLI = context->boundParams;
2111 
2112  /* Look to see if we've been given a value for this Param */
2113  if (param->paramkind == PARAM_EXTERN &&
2114  paramLI != NULL &&
2115  param->paramid > 0 &&
2116  param->paramid <= paramLI->numParams)
2117  {
2118  ParamExternData *prm;
2119  ParamExternData prmdata;
2120 
2121  /*
2122  * Give hook a chance in case parameter is dynamic. Tell
2123  * it that this fetch is speculative, so it should avoid
2124  * erroring out if parameter is unavailable.
2125  */
2126  if (paramLI->paramFetch != NULL)
2127  prm = paramLI->paramFetch(paramLI, param->paramid,
2128  true, &prmdata);
2129  else
2130  prm = &paramLI->params[param->paramid - 1];
2131 
2132  /*
2133  * We don't just check OidIsValid, but insist that the
2134  * fetched type match the Param, just in case the hook did
2135  * something unexpected. No need to throw an error here
2136  * though; leave that for runtime.
2137  */
2138  if (OidIsValid(prm->ptype) &&
2139  prm->ptype == param->paramtype)
2140  {
2141  /* OK to substitute parameter value? */
2142  if (context->estimate ||
2143  (prm->pflags & PARAM_FLAG_CONST))
2144  {
2145  /*
2146  * Return a Const representing the param value.
2147  * Must copy pass-by-ref datatypes, since the
2148  * Param might be in a memory context
2149  * shorter-lived than our output plan should be.
2150  */
2151  int16 typLen;
2152  bool typByVal;
2153  Datum pval;
2154 
2155  get_typlenbyval(param->paramtype,
2156  &typLen, &typByVal);
2157  if (prm->isnull || typByVal)
2158  pval = prm->value;
2159  else
2160  pval = datumCopy(prm->value, typByVal, typLen);
2161  return (Node *) makeConst(param->paramtype,
2162  param->paramtypmod,
2163  param->paramcollid,
2164  (int) typLen,
2165  pval,
2166  prm->isnull,
2167  typByVal);
2168  }
2169  }
2170  }
2171 
2172  /*
2173  * Not replaceable, so just copy the Param (no need to
2174  * recurse)
2175  */
2176  return (Node *) copyObject(param);
2177  }
2178  case T_WindowFunc:
2179  {
2180  WindowFunc *expr = (WindowFunc *) node;
2181  Oid funcid = expr->winfnoid;
2182  List *args;
2183  Expr *aggfilter;
2184  HeapTuple func_tuple;
2185  WindowFunc *newexpr;
2186 
2187  /*
2188  * We can't really simplify a WindowFunc node, but we mustn't
2189  * just fall through to the default processing, because we
2190  * have to apply expand_function_arguments to its argument
2191  * list. That takes care of inserting default arguments and
2192  * expanding named-argument notation.
2193  */
2194  func_tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
2195  if (!HeapTupleIsValid(func_tuple))
2196  elog(ERROR, "cache lookup failed for function %u", funcid);
2197 
2198  args = expand_function_arguments(expr->args, expr->wintype,
2199  func_tuple);
2200 
2201  ReleaseSysCache(func_tuple);
2202 
2203  /* Now, recursively simplify the args (which are a List) */
2204  args = (List *)
2207  (void *) context);
2208  /* ... and the filter expression, which isn't */
2209  aggfilter = (Expr *)
2211  context);
2212 
2213  /* And build the replacement WindowFunc node */
2214  newexpr = makeNode(WindowFunc);
2215  newexpr->winfnoid = expr->winfnoid;
2216  newexpr->wintype = expr->wintype;
2217  newexpr->wincollid = expr->wincollid;
2218  newexpr->inputcollid = expr->inputcollid;
2219  newexpr->args = args;
2220  newexpr->aggfilter = aggfilter;
2221  newexpr->winref = expr->winref;
2222  newexpr->winstar = expr->winstar;
2223  newexpr->winagg = expr->winagg;
2224  newexpr->location = expr->location;
2225 
2226  return (Node *) newexpr;
2227  }
2228  case T_FuncExpr:
2229  {
2230  FuncExpr *expr = (FuncExpr *) node;
2231  List *args = expr->args;
2232  Expr *simple;
2233  FuncExpr *newexpr;
2234 
2235  /*
2236  * Code for op/func reduction is pretty bulky, so split it out
2237  * as a separate function. Note: exprTypmod normally returns
2238  * -1 for a FuncExpr, but not when the node is recognizably a
2239  * length coercion; we want to preserve the typmod in the
2240  * eventual Const if so.
2241  */
2242  simple = simplify_function(expr->funcid,
2243  expr->funcresulttype,
2244  exprTypmod(node),
2245  expr->funccollid,
2246  expr->inputcollid,
2247  &args,
2248  expr->funcvariadic,
2249  true,
2250  true,
2251  context);
2252  if (simple) /* successfully simplified it */
2253  return (Node *) simple;
2254 
2255  /*
2256  * The expression cannot be simplified any further, so build
2257  * and return a replacement FuncExpr node using the
2258  * possibly-simplified arguments. Note that we have also
2259  * converted the argument list to positional notation.
2260  */
2261  newexpr = makeNode(FuncExpr);
2262  newexpr->funcid = expr->funcid;
2263  newexpr->funcresulttype = expr->funcresulttype;
2264  newexpr->funcretset = expr->funcretset;
2265  newexpr->funcvariadic = expr->funcvariadic;
2266  newexpr->funcformat = expr->funcformat;
2267  newexpr->funccollid = expr->funccollid;
2268  newexpr->inputcollid = expr->inputcollid;
2269  newexpr->args = args;
2270  newexpr->location = expr->location;
2271  return (Node *) newexpr;
2272  }
2273  case T_OpExpr:
2274  {
2275  OpExpr *expr = (OpExpr *) node;
2276  List *args = expr->args;
2277  Expr *simple;
2278  OpExpr *newexpr;
2279 
2280  /*
2281  * Need to get OID of underlying function. Okay to scribble
2282  * on input to this extent.
2283  */
2284  set_opfuncid(expr);
2285 
2286  /*
2287  * Code for op/func reduction is pretty bulky, so split it out
2288  * as a separate function.
2289  */
2290  simple = simplify_function(expr->opfuncid,
2291  expr->opresulttype, -1,
2292  expr->opcollid,
2293  expr->inputcollid,
2294  &args,
2295  false,
2296  true,
2297  true,
2298  context);
2299  if (simple) /* successfully simplified it */
2300  return (Node *) simple;
2301 
2302  /*
2303  * If the operator is boolean equality or inequality, we know
2304  * how to simplify cases involving one constant and one
2305  * non-constant argument.
2306  */
2307  if (expr->opno == BooleanEqualOperator ||
2308  expr->opno == BooleanNotEqualOperator)
2309  {
2310  simple = (Expr *) simplify_boolean_equality(expr->opno,
2311  args);
2312  if (simple) /* successfully simplified it */
2313  return (Node *) simple;
2314  }
2315 
2316  /*
2317  * The expression cannot be simplified any further, so build
2318  * and return a replacement OpExpr node using the
2319  * possibly-simplified arguments.
2320  */
2321  newexpr = makeNode(OpExpr);
2322  newexpr->opno = expr->opno;
2323  newexpr->opfuncid = expr->opfuncid;
2324  newexpr->opresulttype = expr->opresulttype;
2325  newexpr->opretset = expr->opretset;
2326  newexpr->opcollid = expr->opcollid;
2327  newexpr->inputcollid = expr->inputcollid;
2328  newexpr->args = args;
2329  newexpr->location = expr->location;
2330  return (Node *) newexpr;
2331  }
2332  case T_DistinctExpr:
2333  {
2334  DistinctExpr *expr = (DistinctExpr *) node;
2335  List *args;
2336  ListCell *arg;
2337  bool has_null_input = false;
2338  bool all_null_input = true;
2339  bool has_nonconst_input = false;
2340  Expr *simple;
2341  DistinctExpr *newexpr;
2342 
2343  /*
2344  * Reduce constants in the DistinctExpr's arguments. We know
2345  * args is either NIL or a List node, so we can call
2346  * expression_tree_mutator directly rather than recursing to
2347  * self.
2348  */
2349  args = (List *) expression_tree_mutator((Node *) expr->args,
2351  (void *) context);
2352 
2353  /*
2354  * We must do our own check for NULLs because DistinctExpr has
2355  * different results for NULL input than the underlying
2356  * operator does.
2357  */
2358  foreach(arg, args)
2359  {
2360  if (IsA(lfirst(arg), Const))
2361  {
2362  has_null_input |= ((Const *) lfirst(arg))->constisnull;
2363  all_null_input &= ((Const *) lfirst(arg))->constisnull;
2364  }
2365  else
2366  has_nonconst_input = true;
2367  }
2368 
2369  /* all constants? then can optimize this out */
2370  if (!has_nonconst_input)
2371  {
2372  /* all nulls? then not distinct */
2373  if (all_null_input)
2374  return makeBoolConst(false, false);
2375 
2376  /* one null? then distinct */
2377  if (has_null_input)
2378  return makeBoolConst(true, false);
2379 
2380  /* otherwise try to evaluate the '=' operator */
2381  /* (NOT okay to try to inline it, though!) */
2382 
2383  /*
2384  * Need to get OID of underlying function. Okay to
2385  * scribble on input to this extent.
2386  */
2387  set_opfuncid((OpExpr *) expr); /* rely on struct
2388  * equivalence */
2389 
2390  /*
2391  * Code for op/func reduction is pretty bulky, so split it
2392  * out as a separate function.
2393  */
2394  simple = simplify_function(expr->opfuncid,
2395  expr->opresulttype, -1,
2396  expr->opcollid,
2397  expr->inputcollid,
2398  &args,
2399  false,
2400  false,
2401  false,
2402  context);
2403  if (simple) /* successfully simplified it */
2404  {
2405  /*
2406  * Since the underlying operator is "=", must negate
2407  * its result
2408  */
2409  Const *csimple = castNode(Const, simple);
2410 
2411  csimple->constvalue =
2412  BoolGetDatum(!DatumGetBool(csimple->constvalue));
2413  return (Node *) csimple;
2414  }
2415  }
2416 
2417  /*
2418  * The expression cannot be simplified any further, so build
2419  * and return a replacement DistinctExpr node using the
2420  * possibly-simplified arguments.
2421  */
2422  newexpr = makeNode(DistinctExpr);
2423  newexpr->opno = expr->opno;
2424  newexpr->opfuncid = expr->opfuncid;
2425  newexpr->opresulttype = expr->opresulttype;
2426  newexpr->opretset = expr->opretset;
2427  newexpr->opcollid = expr->opcollid;
2428  newexpr->inputcollid = expr->inputcollid;
2429  newexpr->args = args;
2430  newexpr->location = expr->location;
2431  return (Node *) newexpr;
2432  }
2433  case T_ScalarArrayOpExpr:
2434  {
2435  ScalarArrayOpExpr *saop;
2436 
2437  /* Copy the node and const-simplify its arguments */
2438  saop = (ScalarArrayOpExpr *) ece_generic_processing(node);
2439 
2440  /* Make sure we know underlying function */
2441  set_sa_opfuncid(saop);
2442 
2443  /*
2444  * If all arguments are Consts, and it's a safe function, we
2445  * can fold to a constant
2446  */
2447  if (ece_all_arguments_const(saop) &&
2448  ece_function_is_safe(saop->opfuncid, context))
2449  return ece_evaluate_expr(saop);
2450  return (Node *) saop;
2451  }
2452  case T_BoolExpr:
2453  {
2454  BoolExpr *expr = (BoolExpr *) node;
2455 
2456  switch (expr->boolop)
2457  {
2458  case OR_EXPR:
2459  {
2460  List *newargs;
2461  bool haveNull = false;
2462  bool forceTrue = false;
2463 
2464  newargs = simplify_or_arguments(expr->args,
2465  context,
2466  &haveNull,
2467  &forceTrue);
2468  if (forceTrue)
2469  return makeBoolConst(true, false);
2470  if (haveNull)
2471  newargs = lappend(newargs,
2472  makeBoolConst(false, true));
2473  /* If all the inputs are FALSE, result is FALSE */
2474  if (newargs == NIL)
2475  return makeBoolConst(false, false);
2476 
2477  /*
2478  * If only one nonconst-or-NULL input, it's the
2479  * result
2480  */
2481  if (list_length(newargs) == 1)
2482  return (Node *) linitial(newargs);
2483  /* Else we still need an OR node */
2484  return (Node *) make_orclause(newargs);
2485  }
2486  case AND_EXPR:
2487  {
2488  List *newargs;
2489  bool haveNull = false;
2490  bool forceFalse = false;
2491 
2492  newargs = simplify_and_arguments(expr->args,
2493  context,
2494  &haveNull,
2495  &forceFalse);
2496  if (forceFalse)
2497  return makeBoolConst(false, false);
2498  if (haveNull)
2499  newargs = lappend(newargs,
2500  makeBoolConst(false, true));
2501  /* If all the inputs are TRUE, result is TRUE */
2502  if (newargs == NIL)
2503  return makeBoolConst(true, false);
2504 
2505  /*
2506  * If only one nonconst-or-NULL input, it's the
2507  * result
2508  */
2509  if (list_length(newargs) == 1)
2510  return (Node *) linitial(newargs);
2511  /* Else we still need an AND node */
2512  return (Node *) make_andclause(newargs);
2513  }
2514  case NOT_EXPR:
2515  {
2516  Node *arg;
2517 
2518  Assert(list_length(expr->args) == 1);
2520  context);
2521 
2522  /*
2523  * Use negate_clause() to see if we can simplify
2524  * away the NOT.
2525  */
2526  return negate_clause(arg);
2527  }
2528  default:
2529  elog(ERROR, "unrecognized boolop: %d",
2530  (int) expr->boolop);
2531  break;
2532  }
2533  break;
2534  }
2535  case T_SubPlan:
2536  case T_AlternativeSubPlan:
2537 
2538  /*
2539  * Return a SubPlan unchanged --- too late to do anything with it.
2540  *
2541  * XXX should we ereport() here instead? Probably this routine
2542  * should never be invoked after SubPlan creation.
2543  */
2544  return node;
2545  case T_RelabelType:
2546  {
2547  RelabelType *relabel = (RelabelType *) node;
2548  Node *arg;
2549 
2550  /* Simplify the input ... */
2551  arg = eval_const_expressions_mutator((Node *) relabel->arg,
2552  context);
2553  /* ... and attach a new RelabelType node, if needed */
2554  return applyRelabelType(arg,
2555  relabel->resulttype,
2556  relabel->resulttypmod,
2557  relabel->resultcollid,
2558  relabel->relabelformat,
2559  relabel->location,
2560  true);
2561  }
2562  case T_CoerceViaIO:
2563  {
2564  CoerceViaIO *expr = (CoerceViaIO *) node;
2565  List *args;
2566  Oid outfunc;
2567  bool outtypisvarlena;
2568  Oid infunc;
2569  Oid intypioparam;
2570  Expr *simple;
2571  CoerceViaIO *newexpr;
2572 
2573  /* Make a List so we can use simplify_function */
2574  args = list_make1(expr->arg);
2575 
2576  /*
2577  * CoerceViaIO represents calling the source type's output
2578  * function then the result type's input function. So, try to
2579  * simplify it as though it were a stack of two such function
2580  * calls. First we need to know what the functions are.
2581  *
2582  * Note that the coercion functions are assumed not to care
2583  * about input collation, so we just pass InvalidOid for that.
2584  */
2585  getTypeOutputInfo(exprType((Node *) expr->arg),
2586  &outfunc, &outtypisvarlena);
2588  &infunc, &intypioparam);
2589 
2590  simple = simplify_function(outfunc,
2591  CSTRINGOID, -1,
2592  InvalidOid,
2593  InvalidOid,
2594  &args,
2595  false,
2596  true,
2597  true,
2598  context);
2599  if (simple) /* successfully simplified output fn */
2600  {
2601  /*
2602  * Input functions may want 1 to 3 arguments. We always
2603  * supply all three, trusting that nothing downstream will
2604  * complain.
2605  */
2606  args = list_make3(simple,
2607  makeConst(OIDOID,
2608  -1,
2609  InvalidOid,
2610  sizeof(Oid),
2611  ObjectIdGetDatum(intypioparam),
2612  false,
2613  true),
2614  makeConst(INT4OID,
2615  -1,
2616  InvalidOid,
2617  sizeof(int32),
2618  Int32GetDatum(-1),
2619  false,
2620  true));
2621 
2622  simple = simplify_function(infunc,
2623  expr->resulttype, -1,
2624  expr->resultcollid,
2625  InvalidOid,
2626  &args,
2627  false,
2628  false,
2629  true,
2630  context);
2631  if (simple) /* successfully simplified input fn */
2632  return (Node *) simple;
2633  }
2634 
2635  /*
2636  * The expression cannot be simplified any further, so build
2637  * and return a replacement CoerceViaIO node using the
2638  * possibly-simplified argument.
2639  */
2640  newexpr = makeNode(CoerceViaIO);
2641  newexpr->arg = (Expr *) linitial(args);
2642  newexpr->resulttype = expr->resulttype;
2643  newexpr->resultcollid = expr->resultcollid;
2644  newexpr->coerceformat = expr->coerceformat;
2645  newexpr->location = expr->location;
2646  return (Node *) newexpr;
2647  }
2648  case T_ArrayCoerceExpr:
2649  {
2651  Node *save_case_val;
2652 
2653  /*
2654  * Copy the node and const-simplify its arguments. We can't
2655  * use ece_generic_processing() here because we need to mess
2656  * with case_val only while processing the elemexpr.
2657  */
2658  memcpy(ac, node, sizeof(ArrayCoerceExpr));
2659  ac->arg = (Expr *)
2661  context);
2662 
2663  /*
2664  * Set up for the CaseTestExpr node contained in the elemexpr.
2665  * We must prevent it from absorbing any outer CASE value.
2666  */
2667  save_case_val = context->case_val;
2668  context->case_val = NULL;
2669 
2670  ac->elemexpr = (Expr *)
2672  context);
2673 
2674  context->case_val = save_case_val;
2675 
2676  /*
2677  * If constant argument and the per-element expression is
2678  * immutable, we can simplify the whole thing to a constant.
2679  * Exception: although contain_mutable_functions considers
2680  * CoerceToDomain immutable for historical reasons, let's not
2681  * do so here; this ensures coercion to an array-over-domain
2682  * does not apply the domain's constraints until runtime.
2683  */
2684  if (ac->arg && IsA(ac->arg, Const) &&
2685  ac->elemexpr && !IsA(ac->elemexpr, CoerceToDomain) &&
2687  return ece_evaluate_expr(ac);
2688 
2689  return (Node *) ac;
2690  }
2691  case T_CollateExpr:
2692  {
2693  /*
2694  * We replace CollateExpr with RelabelType, so as to improve
2695  * uniformity of expression representation and thus simplify
2696  * comparison of expressions. Hence this looks very nearly
2697  * the same as the RelabelType case, and we can apply the same
2698  * optimizations to avoid unnecessary RelabelTypes.
2699  */
2700  CollateExpr *collate = (CollateExpr *) node;
2701  Node *arg;
2702 
2703  /* Simplify the input ... */
2704  arg = eval_const_expressions_mutator((Node *) collate->arg,
2705  context);
2706  /* ... and attach a new RelabelType node, if needed */
2707  return applyRelabelType(arg,
2708  exprType(arg),
2709  exprTypmod(arg),
2710  collate->collOid,
2712  collate->location,
2713  true);
2714  }
2715  case T_CaseExpr:
2716  {
2717  /*----------
2718  * CASE expressions can be simplified if there are constant
2719  * condition clauses:
2720  * FALSE (or NULL): drop the alternative
2721  * TRUE: drop all remaining alternatives
2722  * If the first non-FALSE alternative is a constant TRUE,
2723  * we can simplify the entire CASE to that alternative's
2724  * expression. If there are no non-FALSE alternatives,
2725  * we simplify the entire CASE to the default result (ELSE).
2726  *
2727  * If we have a simple-form CASE with constant test
2728  * expression, we substitute the constant value for contained
2729  * CaseTestExpr placeholder nodes, so that we have the
2730  * opportunity to reduce constant test conditions. For
2731  * example this allows
2732  * CASE 0 WHEN 0 THEN 1 ELSE 1/0 END
2733  * to reduce to 1 rather than drawing a divide-by-0 error.
2734  * Note that when the test expression is constant, we don't
2735  * have to include it in the resulting CASE; for example
2736  * CASE 0 WHEN x THEN y ELSE z END
2737  * is transformed by the parser to
2738  * CASE 0 WHEN CaseTestExpr = x THEN y ELSE z END
2739  * which we can simplify to
2740  * CASE WHEN 0 = x THEN y ELSE z END
2741  * It is not necessary for the executor to evaluate the "arg"
2742  * expression when executing the CASE, since any contained
2743  * CaseTestExprs that might have referred to it will have been
2744  * replaced by the constant.
2745  *----------
2746  */
2747  CaseExpr *caseexpr = (CaseExpr *) node;
2748  CaseExpr *newcase;
2749  Node *save_case_val;
2750  Node *newarg;
2751  List *newargs;
2752  bool const_true_cond;
2753  Node *defresult = NULL;
2754  ListCell *arg;
2755 
2756  /* Simplify the test expression, if any */
2757  newarg = eval_const_expressions_mutator((Node *) caseexpr->arg,
2758  context);
2759 
2760  /* Set up for contained CaseTestExpr nodes */
2761  save_case_val = context->case_val;
2762  if (newarg && IsA(newarg, Const))
2763  {
2764  context->case_val = newarg;
2765  newarg = NULL; /* not needed anymore, see above */
2766  }
2767  else
2768  context->case_val = NULL;
2769 
2770  /* Simplify the WHEN clauses */
2771  newargs = NIL;
2772  const_true_cond = false;
2773  foreach(arg, caseexpr->args)
2774  {
2775  CaseWhen *oldcasewhen = lfirst_node(CaseWhen, arg);
2776  Node *casecond;
2777  Node *caseresult;
2778 
2779  /* Simplify this alternative's test condition */
2780  casecond = eval_const_expressions_mutator((Node *) oldcasewhen->expr,
2781  context);
2782 
2783  /*
2784  * If the test condition is constant FALSE (or NULL), then
2785  * drop this WHEN clause completely, without processing
2786  * the result.
2787  */
2788  if (casecond && IsA(casecond, Const))
2789  {
2790  Const *const_input = (Const *) casecond;
2791 
2792  if (const_input->constisnull ||
2793  !DatumGetBool(const_input->constvalue))
2794  continue; /* drop alternative with FALSE cond */
2795  /* Else it's constant TRUE */
2796  const_true_cond = true;
2797  }
2798 
2799  /* Simplify this alternative's result value */
2800  caseresult = eval_const_expressions_mutator((Node *) oldcasewhen->result,
2801  context);
2802 
2803  /* If non-constant test condition, emit a new WHEN node */
2804  if (!const_true_cond)
2805  {
2806  CaseWhen *newcasewhen = makeNode(CaseWhen);
2807 
2808  newcasewhen->expr = (Expr *) casecond;
2809  newcasewhen->result = (Expr *) caseresult;
2810  newcasewhen->location = oldcasewhen->location;
2811  newargs = lappend(newargs, newcasewhen);
2812  continue;
2813  }
2814 
2815  /*
2816  * Found a TRUE condition, so none of the remaining
2817  * alternatives can be reached. We treat the result as
2818  * the default result.
2819  */
2820  defresult = caseresult;
2821  break;
2822  }
2823 
2824  /* Simplify the default result, unless we replaced it above */
2825  if (!const_true_cond)
2826  defresult = eval_const_expressions_mutator((Node *) caseexpr->defresult,
2827  context);
2828 
2829  context->case_val = save_case_val;
2830 
2831  /*
2832  * If no non-FALSE alternatives, CASE reduces to the default
2833  * result
2834  */
2835  if (newargs == NIL)
2836  return defresult;
2837  /* Otherwise we need a new CASE node */
2838  newcase = makeNode(CaseExpr);
2839  newcase->casetype = caseexpr->casetype;
2840  newcase->casecollid = caseexpr->casecollid;
2841  newcase->arg = (Expr *) newarg;
2842  newcase->args = newargs;
2843  newcase->defresult = (Expr *) defresult;
2844  newcase->location = caseexpr->location;
2845  return (Node *) newcase;
2846  }
2847  case T_CaseTestExpr:
2848  {
2849  /*
2850  * If we know a constant test value for the current CASE
2851  * construct, substitute it for the placeholder. Else just
2852  * return the placeholder as-is.
2853  */
2854  if (context->case_val)
2855  return copyObject(context->case_val);
2856  else
2857  return copyObject(node);
2858  }
2859  case T_SubscriptingRef:
2860  case T_ArrayExpr:
2861  case T_RowExpr:
2862  case T_MinMaxExpr:
2863  {
2864  /*
2865  * Generic handling for node types whose own processing is
2866  * known to be immutable, and for which we need no smarts
2867  * beyond "simplify if all inputs are constants".
2868  *
2869  * Treating SubscriptingRef this way assumes that subscripting
2870  * fetch and assignment are both immutable. This constrains
2871  * type-specific subscripting implementations; maybe we should
2872  * relax it someday.
2873  *
2874  * Treating MinMaxExpr this way amounts to assuming that the
2875  * btree comparison function it calls is immutable; see the
2876  * reasoning in contain_mutable_functions_walker.
2877  */
2878 
2879  /* Copy the node and const-simplify its arguments */
2880  node = ece_generic_processing(node);
2881  /* If all arguments are Consts, we can fold to a constant */
2882  if (ece_all_arguments_const(node))
2883  return ece_evaluate_expr(node);
2884  return node;
2885  }
2886  case T_CoalesceExpr:
2887  {
2888  CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
2889  CoalesceExpr *newcoalesce;
2890  List *newargs;
2891  ListCell *arg;
2892 
2893  newargs = NIL;
2894  foreach(arg, coalesceexpr->args)
2895  {
2896  Node *e;
2897 
2899  context);
2900 
2901  /*
2902  * We can remove null constants from the list. For a
2903  * non-null constant, if it has not been preceded by any
2904  * other non-null-constant expressions then it is the
2905  * result. Otherwise, it's the next argument, but we can
2906  * drop following arguments since they will never be
2907  * reached.
2908  */
2909  if (IsA(e, Const))
2910  {
2911  if (((Const *) e)->constisnull)
2912  continue; /* drop null constant */
2913  if (newargs == NIL)
2914  return e; /* first expr */
2915  newargs = lappend(newargs, e);
2916  break;
2917  }
2918  newargs = lappend(newargs, e);
2919  }
2920 
2921  /*
2922  * If all the arguments were constant null, the result is just
2923  * null
2924  */
2925  if (newargs == NIL)
2926  return (Node *) makeNullConst(coalesceexpr->coalescetype,
2927  -1,
2928  coalesceexpr->coalescecollid);
2929 
2930  newcoalesce = makeNode(CoalesceExpr);
2931  newcoalesce->coalescetype = coalesceexpr->coalescetype;
2932  newcoalesce->coalescecollid = coalesceexpr->coalescecollid;
2933  newcoalesce->args = newargs;
2934  newcoalesce->location = coalesceexpr->location;
2935  return (Node *) newcoalesce;
2936  }
2937  case T_SQLValueFunction:
2938  {
2939  /*
2940  * All variants of SQLValueFunction are stable, so if we are
2941  * estimating the expression's value, we should evaluate the
2942  * current function value. Otherwise just copy.
2943  */
2944  SQLValueFunction *svf = (SQLValueFunction *) node;
2945 
2946  if (context->estimate)
2947  return (Node *) evaluate_expr((Expr *) svf,
2948  svf->type,
2949  svf->typmod,
2950  InvalidOid);
2951  else
2952  return copyObject((Node *) svf);
2953  }
2954  case T_FieldSelect:
2955  {
2956  /*
2957  * We can optimize field selection from a whole-row Var into a
2958  * simple Var. (This case won't be generated directly by the
2959  * parser, because ParseComplexProjection short-circuits it.
2960  * But it can arise while simplifying functions.) Also, we
2961  * can optimize field selection from a RowExpr construct, or
2962  * of course from a constant.
2963  *
2964  * However, replacing a whole-row Var in this way has a
2965  * pitfall: if we've already built the rel targetlist for the
2966  * source relation, then the whole-row Var is scheduled to be
2967  * produced by the relation scan, but the simple Var probably
2968  * isn't, which will lead to a failure in setrefs.c. This is
2969  * not a problem when handling simple single-level queries, in
2970  * which expression simplification always happens first. It
2971  * is a risk for lateral references from subqueries, though.
2972  * To avoid such failures, don't optimize uplevel references.
2973  *
2974  * We must also check that the declared type of the field is
2975  * still the same as when the FieldSelect was created --- this
2976  * can change if someone did ALTER COLUMN TYPE on the rowtype.
2977  * If it isn't, we skip the optimization; the case will
2978  * probably fail at runtime, but that's not our problem here.
2979  */
2980  FieldSelect *fselect = (FieldSelect *) node;
2981  FieldSelect *newfselect;
2982  Node *arg;
2983 
2984  arg = eval_const_expressions_mutator((Node *) fselect->arg,
2985  context);
2986  if (arg && IsA(arg, Var) &&
2987  ((Var *) arg)->varattno == InvalidAttrNumber &&
2988  ((Var *) arg)->varlevelsup == 0)
2989  {
2990  if (rowtype_field_matches(((Var *) arg)->vartype,
2991  fselect->fieldnum,
2992  fselect->resulttype,
2993  fselect->resulttypmod,
2994  fselect->resultcollid))
2995  return (Node *) makeVar(((Var *) arg)->varno,
2996  fselect->fieldnum,
2997  fselect->resulttype,
2998  fselect->resulttypmod,
2999  fselect->resultcollid,
3000  ((Var *) arg)->varlevelsup);
3001  }
3002  if (arg && IsA(arg, RowExpr))
3003  {
3004  RowExpr *rowexpr = (RowExpr *) arg;
3005 
3006  if (fselect->fieldnum > 0 &&
3007  fselect->fieldnum <= list_length(rowexpr->args))
3008  {
3009  Node *fld = (Node *) list_nth(rowexpr->args,
3010  fselect->fieldnum - 1);
3011 
3012  if (rowtype_field_matches(rowexpr->row_typeid,
3013  fselect->fieldnum,
3014  fselect->resulttype,
3015  fselect->resulttypmod,
3016  fselect->resultcollid) &&
3017  fselect->resulttype == exprType(fld) &&
3018  fselect->resulttypmod == exprTypmod(fld) &&
3019  fselect->resultcollid == exprCollation(fld))
3020  return fld;
3021  }
3022  }
3023  newfselect = makeNode(FieldSelect);
3024  newfselect->arg = (Expr *) arg;
3025  newfselect->fieldnum = fselect->fieldnum;
3026  newfselect->resulttype = fselect->resulttype;
3027  newfselect->resulttypmod = fselect->resulttypmod;
3028  newfselect->resultcollid = fselect->resultcollid;
3029  if (arg && IsA(arg, Const))
3030  {
3031  Const *con = (Const *) arg;
3032 
3034  newfselect->fieldnum,
3035  newfselect->resulttype,
3036  newfselect->resulttypmod,
3037  newfselect->resultcollid))
3038  return ece_evaluate_expr(newfselect);
3039  }
3040  return (Node *) newfselect;
3041  }
3042  case T_NullTest:
3043  {
3044  NullTest *ntest = (NullTest *) node;
3045  NullTest *newntest;
3046  Node *arg;
3047 
3048  arg = eval_const_expressions_mutator((Node *) ntest->arg,
3049  context);
3050  if (ntest->argisrow && arg && IsA(arg, RowExpr))
3051  {
3052  /*
3053  * We break ROW(...) IS [NOT] NULL into separate tests on
3054  * its component fields. This form is usually more
3055  * efficient to evaluate, as well as being more amenable
3056  * to optimization.
3057  */
3058  RowExpr *rarg = (RowExpr *) arg;
3059  List *newargs = NIL;
3060  ListCell *l;
3061 
3062  foreach(l, rarg->args)
3063  {
3064  Node *relem = (Node *) lfirst(l);
3065 
3066  /*
3067  * A constant field refutes the whole NullTest if it's
3068  * of the wrong nullness; else we can discard it.
3069  */
3070  if (relem && IsA(relem, Const))
3071  {
3072  Const *carg = (Const *) relem;
3073 
3074  if (carg->constisnull ?
3075  (ntest->nulltesttype == IS_NOT_NULL) :
3076  (ntest->nulltesttype == IS_NULL))
3077  return makeBoolConst(false, false);
3078  continue;
3079  }
3080 
3081  /*
3082  * Else, make a scalar (argisrow == false) NullTest
3083  * for this field. Scalar semantics are required
3084  * because IS [NOT] NULL doesn't recurse; see comments
3085  * in ExecEvalRowNullInt().
3086  */
3087  newntest = makeNode(NullTest);
3088  newntest->arg = (Expr *) relem;
3089  newntest->nulltesttype = ntest->nulltesttype;
3090  newntest->argisrow = false;
3091  newntest->location = ntest->location;
3092  newargs = lappend(newargs, newntest);
3093  }
3094  /* If all the inputs were constants, result is TRUE */
3095  if (newargs == NIL)
3096  return makeBoolConst(true, false);
3097  /* If only one nonconst input, it's the result */
3098  if (list_length(newargs) == 1)
3099  return (Node *) linitial(newargs);
3100  /* Else we need an AND node */
3101  return (Node *) make_andclause(newargs);
3102  }
3103  if (!ntest->argisrow && arg && IsA(arg, Const))
3104  {
3105  Const *carg = (Const *) arg;
3106  bool result;
3107 
3108  switch (ntest->nulltesttype)
3109  {
3110  case IS_NULL:
3111  result = carg->constisnull;
3112  break;
3113  case IS_NOT_NULL:
3114  result = !carg->constisnull;
3115  break;
3116  default:
3117  elog(ERROR, "unrecognized nulltesttype: %d",
3118  (int) ntest->nulltesttype);
3119  result = false; /* keep compiler quiet */
3120  break;
3121  }
3122 
3123  return makeBoolConst(result, false);
3124  }
3125 
3126  newntest = makeNode(NullTest);
3127  newntest->arg = (Expr *) arg;
3128  newntest->nulltesttype = ntest->nulltesttype;
3129  newntest->argisrow = ntest->argisrow;
3130  newntest->location = ntest->location;
3131  return (Node *) newntest;
3132  }
3133  case T_BooleanTest:
3134  {
3135  /*
3136  * This case could be folded into the generic handling used
3137  * for ArrayExpr etc. But because the simplification logic is
3138  * so trivial, applying evaluate_expr() to perform it would be
3139  * a heavy overhead. BooleanTest is probably common enough to
3140  * justify keeping this bespoke implementation.
3141  */
3142  BooleanTest *btest = (BooleanTest *) node;
3143  BooleanTest *newbtest;
3144  Node *arg;
3145 
3146  arg = eval_const_expressions_mutator((Node *) btest->arg,
3147  context);
3148  if (arg && IsA(arg, Const))
3149  {
3150  Const *carg = (Const *) arg;
3151  bool result;
3152 
3153  switch (btest->booltesttype)
3154  {
3155  case IS_TRUE:
3156  result = (!carg->constisnull &&
3157  DatumGetBool(carg->constvalue));
3158  break;
3159  case IS_NOT_TRUE:
3160  result = (carg->constisnull ||
3161  !DatumGetBool(carg->constvalue));
3162  break;
3163  case IS_FALSE:
3164  result = (!carg->constisnull &&
3165  !DatumGetBool(carg->constvalue));
3166  break;
3167  case IS_NOT_FALSE:
3168  result = (carg->constisnull ||
3169  DatumGetBool(carg->constvalue));
3170  break;
3171  case IS_UNKNOWN:
3172  result = carg->constisnull;
3173  break;
3174  case IS_NOT_UNKNOWN:
3175  result = !carg->constisnull;
3176  break;
3177  default:
3178  elog(ERROR, "unrecognized booltesttype: %d",
3179  (int) btest->booltesttype);
3180  result = false; /* keep compiler quiet */
3181  break;
3182  }
3183 
3184  return makeBoolConst(result, false);
3185  }
3186 
3187  newbtest = makeNode(BooleanTest);
3188  newbtest->arg = (Expr *) arg;
3189  newbtest->booltesttype = btest->booltesttype;
3190  newbtest->location = btest->location;
3191  return (Node *) newbtest;
3192  }
3193  case T_CoerceToDomain:
3194  {
3195  /*
3196  * If the domain currently has no constraints, we replace the
3197  * CoerceToDomain node with a simple RelabelType, which is
3198  * both far faster to execute and more amenable to later
3199  * optimization. We must then mark the plan as needing to be
3200  * rebuilt if the domain's constraints change.
3201  *
3202  * Also, in estimation mode, always replace CoerceToDomain
3203  * nodes, effectively assuming that the coercion will succeed.
3204  */
3205  CoerceToDomain *cdomain = (CoerceToDomain *) node;
3206  CoerceToDomain *newcdomain;
3207  Node *arg;
3208 
3209  arg = eval_const_expressions_mutator((Node *) cdomain->arg,
3210  context);
3211  if (context->estimate ||
3212  !DomainHasConstraints(cdomain->resulttype))
3213  {
3214  /* Record dependency, if this isn't estimation mode */
3215  if (context->root && !context->estimate)
3216  record_plan_type_dependency(context->root,
3217  cdomain->resulttype);
3218 
3219  /* Generate RelabelType to substitute for CoerceToDomain */
3220  return applyRelabelType(arg,
3221  cdomain->resulttype,
3222  cdomain->resulttypmod,
3223  cdomain->resultcollid,
3224  cdomain->coercionformat,
3225  cdomain->location,
3226  true);
3227  }
3228 
3229  newcdomain = makeNode(CoerceToDomain);
3230  newcdomain->arg = (Expr *) arg;
3231  newcdomain->resulttype = cdomain->resulttype;
3232  newcdomain->resulttypmod = cdomain->resulttypmod;
3233  newcdomain->resultcollid = cdomain->resultcollid;
3234  newcdomain->coercionformat = cdomain->coercionformat;
3235  newcdomain->location = cdomain->location;
3236  return (Node *) newcdomain;
3237  }
3238  case T_PlaceHolderVar:
3239 
3240  /*
3241  * In estimation mode, just strip the PlaceHolderVar node
3242  * altogether; this amounts to estimating that the contained value
3243  * won't be forced to null by an outer join. In regular mode we
3244  * just use the default behavior (ie, simplify the expression but
3245  * leave the PlaceHolderVar node intact).
3246  */
3247  if (context->estimate)
3248  {
3249  PlaceHolderVar *phv = (PlaceHolderVar *) node;
3250 
3251  return eval_const_expressions_mutator((Node *) phv->phexpr,
3252  context);
3253  }
3254  break;
3255  case T_ConvertRowtypeExpr:
3256  {
3258  Node *arg;
3259  ConvertRowtypeExpr *newcre;
3260 
3261  arg = eval_const_expressions_mutator((Node *) cre->arg,
3262  context);
3263 
3264  newcre = makeNode(ConvertRowtypeExpr);
3265  newcre->resulttype = cre->resulttype;
3266  newcre->convertformat = cre->convertformat;
3267  newcre->location = cre->location;
3268 
3269  /*
3270  * In case of a nested ConvertRowtypeExpr, we can convert the
3271  * leaf row directly to the topmost row format without any
3272  * intermediate conversions. (This works because
3273  * ConvertRowtypeExpr is used only for child->parent
3274  * conversion in inheritance trees, which works by exact match
3275  * of column name, and a column absent in an intermediate
3276  * result can't be present in the final result.)
3277  *
3278  * No need to check more than one level deep, because the
3279  * above recursion will have flattened anything else.
3280  */
3281  if (arg != NULL && IsA(arg, ConvertRowtypeExpr))
3282  {
3283  ConvertRowtypeExpr *argcre = (ConvertRowtypeExpr *) arg;
3284 
3285  arg = (Node *) argcre->arg;
3286 
3287  /*
3288  * Make sure an outer implicit conversion can't hide an
3289  * inner explicit one.
3290  */
3291  if (newcre->convertformat == COERCE_IMPLICIT_CAST)
3292  newcre->convertformat = argcre->convertformat;
3293  }
3294 
3295  newcre->arg = (Expr *) arg;
3296 
3297  if (arg != NULL && IsA(arg, Const))
3298  return ece_evaluate_expr((Node *) newcre);
3299  return (Node *) newcre;
3300  }
3301  default:
3302  break;
3303  }
3304 
3305  /*
3306  * For any node type not handled above, copy the node unchanged but
3307  * const-simplify its subexpressions. This is the correct thing for node
3308  * types whose behavior might change between planning and execution, such
3309  * as CurrentOfExpr. It's also a safe default for new node types not
3310  * known to this routine.
3311  */
3312  return ece_generic_processing(node);
3313 }
Datum constvalue
Definition: primnodes.h:214
#define list_make3(x1, x2, x3)
Definition: pg_list.h:210
Expr * evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod, Oid result_collation)
Definition: clauses.c:4497
signed short int16
Definition: c.h:428
Oid funcresulttype
Definition: primnodes.h:491
ParamExternData params[FLEXIBLE_ARRAY_MEMBER]
Definition: params.h:125
#define NIL
Definition: pg_list.h:65
Datum value
Definition: params.h:92
#define ece_generic_processing(node)
Definition: clauses.c:2077
List * args
Definition: primnodes.h:1046
#define IsA(nodeptr, _type_)
Definition: nodes.h:584
static Expr * simplify_function(Oid funcid, Oid result_type, int32 result_typmod, Oid result_collid, Oid input_collid, List **args_p, bool funcvariadic, bool process_args, bool allow_non_const, eval_const_expressions_context *context)
Definition: clauses.c:3648
Node * negate_clause(Node *node)
Definition: prepqual.c:74
Node * expression_tree_mutator(Node *node, Node *(*mutator)(), void *context)
Definition: nodeFuncs.c:2579
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2854
List * expand_function_arguments(List *args, Oid result_type, HeapTuple func_tuple)
Definition: clauses.c:3755
List * args
Definition: primnodes.h:385
List * args
Definition: primnodes.h:498
Oid wincollid
Definition: primnodes.h:383
int32 resulttypmod
Definition: primnodes.h:1285
Oid resulttype
Definition: primnodes.h:788
#define castNode(_type_, nodeptr)
Definition: nodes.h:602
Node * applyRelabelType(Node *arg, Oid rtype, int32 rtypmod, Oid rcollid, CoercionForm rformat, int rlocation, bool overwrite_ok)
Definition: nodeFuncs.c:582
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:267
Oid funccollid
Definition: primnodes.h:496
Oid resulttype
Definition: primnodes.h:859
Oid casecollid
Definition: primnodes.h:955
Expr * arg
Definition: primnodes.h:838
ParamKind paramkind
Definition: primnodes.h:262
Definition: nodes.h:533
CoercionForm coercionformat
Definition: primnodes.h:1287
Expr * arg
Definition: primnodes.h:786
bool funcretset
Definition: primnodes.h:492
Oid casetype
Definition: primnodes.h:954
unsigned int Oid
Definition: postgres_ext.h:31
Expr * make_orclause(List *orclauses)
Definition: makefuncs.c:652
Index winref
Definition: primnodes.h:387
Definition: primnodes.h:181
Const * makeConst(Oid consttype, int32 consttypmod, Oid constcollid, int constlen, Datum constvalue, bool constisnull, bool constbyval)
Definition: makefuncs.c:299
#define OidIsValid(objectId)
Definition: c.h:710
#define ece_all_arguments_const(node)
Definition: clauses.c:2086
int location
Definition: primnodes.h:970
signed int int32
Definition: c.h:429
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:337
bool DomainHasConstraints(Oid type_id)
Definition: typcache.c:1391
#define list_make1(x1)
Definition: pg_list.h:206
Oid consttype
Definition: primnodes.h:210
CoercionForm funcformat
Definition: primnodes.h:495
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2100
Oid opresulttype
Definition: primnodes.h:539
ParamFetchHook paramFetch
Definition: params.h:112
ParamListInfo boundParams
Definition: clauses.c:59
#define linitial(l)
Definition: pg_list.h:174
Oid funcid
Definition: primnodes.h:490
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:45
static bool rowtype_field_matches(Oid rowtypeid, int fieldnum, Oid expectedtype, int32 expectedtypmod, Oid expectedcollation)
Definition: clauses.c:1954
Oid paramcollid
Definition: primnodes.h:266
static void * list_nth(const List *list, int n)
Definition: pg_list.h:278
List * args
Definition: primnodes.h:1110
BoolExprType boolop
Definition: primnodes.h:603
Node * makeBoolConst(bool value, bool isnull)
Definition: makefuncs.c:357
Expr * arg
Definition: primnodes.h:1243
Oid resultcollid
Definition: primnodes.h:791
#define lfirst_node(type, lc)
Definition: pg_list.h:172
struct Const Const
Expr * make_andclause(List *andclauses)
Definition: makefuncs.c:636
int location
Definition: primnodes.h:544
Expr * arg
Definition: primnodes.h:1266
#define DatumGetBool(X)
Definition: postgres.h:393
Oid winfnoid
Definition: primnodes.h:381
Expr * arg
Definition: primnodes.h:858
Expr * elemexpr
Definition: primnodes.h:883
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2821
Oid opcollid
Definition: primnodes.h:541
Var * makeVar(Index varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:66
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:131
List * lappend(List *list, void *datum)
Definition: list.c:336
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
List * args
Definition: primnodes.h:957
BoolTestType booltesttype
Definition: primnodes.h:1267
uintptr_t Datum
Definition: postgres.h:367
CoercionForm convertformat
Definition: primnodes.h:910
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
Oid resultcollid
Definition: primnodes.h:861
Oid opfuncid
Definition: primnodes.h:538
Oid resulttype
Definition: primnodes.h:839
NullTestType nulltesttype
Definition: primnodes.h:1244
#define BoolGetDatum(X)
Definition: postgres.h:402
Oid resultcollid
Definition: primnodes.h:841
#define InvalidOid
Definition: postgres_ext.h:36
int32 paramtypmod
Definition: primnodes.h:265
#define makeNode(_type_)
Definition: nodes.h:581
static Node * simplify_boolean_equality(Oid opno, List *args)
Definition: clauses.c:3579
int location
Definition: primnodes.h:863
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
int location
Definition: primnodes.h:390
Oid inputcollid
Definition: primnodes.h:497
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
Expr * aggfilter
Definition: primnodes.h:386
int paramid
Definition: primnodes.h:263
uint16 pflags
Definition: params.h:94
int location
Definition: primnodes.h:1246
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
static List * simplify_and_arguments(List *args, eval_const_expressions_context *context, bool *haveNull, bool *forceFalse)
Definition: clauses.c:3485
Oid row_typeid
Definition: primnodes.h:1047
static int list_length(const List *l)
Definition: pg_list.h:149
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:759
Expr * arg
Definition: primnodes.h:924
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2198
int location
Definition: primnodes.h:959
Oid inputcollid
Definition: primnodes.h:542
static bool ece_function_is_safe(Oid funcid, eval_const_expressions_context *context)
Definition: clauses.c:3341
Oid inputcollid
Definition: primnodes.h:384
List * args
Definition: primnodes.h:604
#define InvalidAttrNumber
Definition: attnum.h:23
#define nodeTag(nodeptr)
Definition: nodes.h:538
Oid wintype
Definition: primnodes.h:382
CoercionForm coerceformat
Definition: primnodes.h:862
static List * simplify_or_arguments(List *args, eval_const_expressions_context *context, bool *haveNull, bool *forceTrue)
Definition: clauses.c:3379
#define Int32GetDatum(X)
Definition: postgres.h:479
e
Definition: preproc-init.c:82
void set_opfuncid(OpExpr *opexpr)
Definition: nodeFuncs.c:1664
bool winagg
Definition: primnodes.h:389
#define elog(elevel,...)
Definition: elog.h:227
Oid coalescetype
Definition: primnodes.h:1108
void * arg
NodeTag type
Definition: primnodes.h:138
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:358
bool argisrow
Definition: primnodes.h:1245
int32 resulttypmod
Definition: primnodes.h:840
Expr * arg
Definition: primnodes.h:956
int location
Definition: primnodes.h:499
Oid opno
Definition: primnodes.h:537
Expr * result
Definition: primnodes.h:969
#define copyObject(obj)
Definition: nodes.h:649
List * args
Definition: primnodes.h:543
CoercionForm relabelformat
Definition: primnodes.h:842
Expr * defresult
Definition: primnodes.h:958
Expr * expr
Definition: primnodes.h:968
int location
Definition: primnodes.h:926
Definition: pg_list.h:50
bool isnull
Definition: params.h:93
void set_sa_opfuncid(ScalarArrayOpExpr *opexpr)
Definition: nodeFuncs.c:1675
Oid paramtype
Definition: primnodes.h:264
int location
Definition: primnodes.h:843
bool constisnull
Definition: primnodes.h:215
Oid coalescecollid
Definition: primnodes.h:1109
bool funcvariadic
Definition: primnodes.h:493
#define PARAM_FLAG_CONST
Definition: params.h:88
bool opretset
Definition: primnodes.h:540
int32 resulttypmod
Definition: primnodes.h:790
bool winstar
Definition: primnodes.h:388
void record_plan_type_dependency(PlannerInfo *root, Oid typid)
Definition: setrefs.c:2945
Definition: nodes.h:157
AttrNumber fieldnum
Definition: primnodes.h:787
#define ece_evaluate_expr(node)
Definition: clauses.c:2090

◆ evaluate_expr()

Expr* evaluate_expr ( Expr expr,
Oid  result_type,
int32  result_typmod,
Oid  result_collation 
)

Definition at line 4497 of file clauses.c.

References CreateExecutorState(), datumCopy(), EState::es_query_cxt, ExecEvalExprSwitchContext(), ExecInitExpr(), fix_opfuncids(), FreeExecutorState(), get_typlenbyval(), GetPerTupleExprContext, makeConst(), MemoryContextSwitchTo(), PG_DETOAST_DATUM_COPY, and PointerGetDatum.

Referenced by eval_const_expressions_mutator(), evaluate_function(), and transformPartitionBoundValue().

4499 {
4500  EState *estate;
4501  ExprState *exprstate;
4502  MemoryContext oldcontext;
4503  Datum const_val;
4504  bool const_is_null;
4505  int16 resultTypLen;
4506  bool resultTypByVal;
4507 
4508  /*
4509  * To use the executor, we need an EState.
4510  */
4511  estate = CreateExecutorState();
4512 
4513  /* We can use the estate's working context to avoid memory leaks. */
4514  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
4515 
4516  /* Make sure any opfuncids are filled in. */
4517  fix_opfuncids((Node *) expr);
4518 
4519  /*
4520  * Prepare expr for execution. (Note: we can't use ExecPrepareExpr
4521  * because it'd result in recursively invoking eval_const_expressions.)
4522  */
4523  exprstate = ExecInitExpr(expr, NULL);
4524 
4525  /*
4526  * And evaluate it.
4527  *
4528  * It is OK to use a default econtext because none of the ExecEvalExpr()
4529  * code used in this situation will use econtext. That might seem
4530  * fortuitous, but it's not so unreasonable --- a constant expression does
4531  * not depend on context, by definition, n'est ce pas?
4532  */
4533  const_val = ExecEvalExprSwitchContext(exprstate,
4534  GetPerTupleExprContext(estate),
4535  &const_is_null);
4536 
4537  /* Get info needed about result datatype */
4538  get_typlenbyval(result_type, &resultTypLen, &resultTypByVal);
4539 
4540  /* Get back to outer memory context */
4541  MemoryContextSwitchTo(oldcontext);
4542 
4543  /*
4544  * Must copy result out of sub-context used by expression eval.
4545  *
4546  * Also, if it's varlena, forcibly detoast it. This protects us against
4547  * storing TOAST pointers into plans that might outlive the referenced
4548  * data. (makeConst would handle detoasting anyway, but it's worth a few
4549  * extra lines here so that we can do the copy and detoast in one step.)
4550  */
4551  if (!const_is_null)
4552  {
4553  if (resultTypLen == -1)
4554  const_val = PointerGetDatum(PG_DETOAST_DATUM_COPY(const_val));
4555  else
4556  const_val = datumCopy(const_val, resultTypByVal, resultTypLen);
4557  }
4558 
4559  /* Release all the junk we just created */
4560  FreeExecutorState(estate);
4561 
4562  /*
4563  * Make the constant result node.
4564  */
4565  return (Expr *) makeConst(result_type, result_typmod, result_collation,
4566  resultTypLen,
4567  const_val, const_is_null,
4568  resultTypByVal);
4569 }
signed short int16
Definition: c.h:428
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:307
#define PG_DETOAST_DATUM_COPY(datum)
Definition: fmgr.h:242
#define PointerGetDatum(X)
Definition: postgres.h:556
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1633
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Definition: nodes.h:533
Const * makeConst(Oid consttype, int32 consttypmod, Oid constcollid, int constlen, Datum constvalue, bool constisnull, bool constbyval)
Definition: makefuncs.c:299
void FreeExecutorState(EState *estate)
Definition: execUtils.c:186
#define GetPerTupleExprContext(estate)
Definition: executor.h:509
MemoryContext es_query_cxt
Definition: execnodes.h:572
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:131
EState * CreateExecutorState(void)
Definition: execUtils.c:90
uintptr_t Datum
Definition: postgres.h:367
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2198
ExprState * ExecInitExpr(Expr *node, PlanState *parent)
Definition: execExpr.c:123

◆ evaluate_function()

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 
)
static

Definition at line 3972 of file clauses.c.

References arg, generate_unaccent_rules::args, FuncExpr::args, COERCE_EXPLICIT_CALL, eval_const_expressions_context::estimate, evaluate_expr(), FuncExpr::funccollid, FuncExpr::funcformat, FuncExpr::funcid, FuncExpr::funcresulttype, FuncExpr::funcretset, FuncExpr::funcvariadic, GETSTRUCT, FuncExpr::inputcollid, IsA, lfirst, FuncExpr::location, makeNode, and makeNullConst().

Referenced by simplify_function().

3977 {
3978  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
3979  bool has_nonconst_input = false;
3980  bool has_null_input = false;
3981  ListCell *arg;
3982  FuncExpr *newexpr;
3983 
3984  /*
3985  * Can't simplify if it returns a set.
3986  */
3987  if (funcform->proretset)
3988  return NULL;
3989 
3990  /*
3991  * Can't simplify if it returns RECORD. The immediate problem is that it
3992  * will be needing an expected tupdesc which we can't supply here.
3993  *
3994  * In the case where it has OUT parameters, it could get by without an
3995  * expected tupdesc, but we still have issues: get_expr_result_type()
3996  * doesn't know how to extract type info from a RECORD constant, and in
3997  * the case of a NULL function result there doesn't seem to be any clean
3998  * way to fix that. In view of the likelihood of there being still other
3999  * gotchas, seems best to leave the function call unreduced.
4000  */
4001  if (funcform->prorettype == RECORDOID)
4002  return NULL;
4003 
4004  /*
4005  * Check for constant inputs and especially constant-NULL inputs.
4006  */
4007  foreach(arg, args)
4008  {
4009  if (IsA(lfirst(arg), Const))
4010  has_null_input |= ((Const *) lfirst(arg))->constisnull;
4011  else
4012  has_nonconst_input = true;
4013  }
4014 
4015  /*
4016  * If the function is strict and has a constant-NULL input, it will never
4017  * be called at all, so we can replace the call by a NULL constant, even
4018  * if there are other inputs that aren't constant, and even if the
4019  * function is not otherwise immutable.
4020  */
4021  if (funcform->proisstrict && has_null_input)
4022  return (Expr *) makeNullConst(result_type, result_typmod,
4023  result_collid);
4024 
4025  /*
4026  * Otherwise, can simplify only if all inputs are constants. (For a
4027  * non-strict function, constant NULL inputs are treated the same as
4028  * constant non-NULL inputs.)
4029  */
4030  if (has_nonconst_input)
4031  return NULL;
4032 
4033  /*
4034  * Ordinarily we are only allowed to simplify immutable functions. But for
4035  * purposes of estimation, we consider it okay to simplify functions that
4036  * are merely stable; the risk that the result might change from planning
4037  * time to execution time is worth taking in preference to not being able
4038  * to estimate the value at all.
4039  */
4040  if (funcform->provolatile == PROVOLATILE_IMMUTABLE)
4041  /* okay */ ;
4042  else if (context->estimate && funcform->provolatile == PROVOLATILE_STABLE)
4043  /* okay */ ;
4044  else
4045  return NULL;
4046 
4047  /*
4048  * OK, looks like we can simplify this operator/function.
4049  *
4050  * Build a new FuncExpr node containing the already-simplified arguments.
4051  */
4052  newexpr = makeNode(FuncExpr);
4053  newexpr->funcid = funcid;
4054  newexpr->funcresulttype = result_type;
4055  newexpr->funcretset = false;
4056  newexpr->funcvariadic = funcvariadic;
4057  newexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
4058  newexpr->funccollid = result_collid; /* doesn't matter */
4059  newexpr->inputcollid = input_collid;
4060  newexpr->args = args;
4061  newexpr->location = -1;
4062 
4063  return evaluate_expr((Expr *) newexpr, result_type, result_typmod,
4064  result_collid);
4065 }
Expr * evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod, Oid result_collation)
Definition: clauses.c:4497
Oid funcresulttype
Definition: primnodes.h:491
#define IsA(nodeptr, _type_)
Definition: nodes.h:584
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
List * args
Definition: primnodes.h:498
Oid funccollid
Definition: primnodes.h:496
bool funcretset
Definition: primnodes.h:492
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:337
CoercionForm funcformat
Definition: primnodes.h:495
Oid funcid
Definition: primnodes.h:490
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:133
#define makeNode(_type_)
Definition: nodes.h:581
Oid inputcollid
Definition: primnodes.h:497
#define lfirst(lc)
Definition: pg_list.h:169
void * arg
int location
Definition: primnodes.h:499
bool funcvariadic
Definition: primnodes.h:493

◆ expand_function_arguments()

List* expand_function_arguments ( List args,
Oid  result_type,
HeapTuple  func_tuple 
)

Definition at line 3755 of file clauses.c.

References add_function_defaults(), arg, generate_unaccent_rules::args, GETSTRUCT, IsA, lfirst, list_length(), recheck_cast_function_args(), and reorder_function_arguments().

Referenced by eval_const_expressions_mutator(), ExecuteCallStmt(), make_callstmt_target(), and simplify_function().

3756 {
3757  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
3758  bool has_named_args = false;
3759  ListCell *lc;
3760 
3761  /* Do we have any named arguments? */
3762  foreach(lc, args)
3763  {
3764  Node *arg = (Node *) lfirst(lc);
3765 
3766  if (IsA(arg, NamedArgExpr))
3767  {
3768  has_named_args = true;
3769  break;
3770  }
3771  }
3772 
3773  /* If so, we must apply reorder_function_arguments */
3774  if (has_named_args)
3775  {
3776  args = reorder_function_arguments(args, func_tuple);
3777  /* Recheck argument types and add casts if needed */
3778  recheck_cast_function_args(args, result_type, func_tuple);
3779  }
3780  else if (list_length(args) < funcform->pronargs)
3781  {
3782  /* No named args, but we seem to be short some defaults */
3783  args = add_function_defaults(args, func_tuple);
3784  /* Recheck argument types and add casts if needed */
3785  recheck_cast_function_args(args, result_type, func_tuple);
3786  }
3787 
3788  return args;
3789 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:584
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Definition: nodes.h:533
static void recheck_cast_function_args(List *args, Oid result_type, HeapTuple func_tuple)
Definition: clauses.c:3928
static List * add_function_defaults(List *args, HeapTuple func_tuple)
Definition: clauses.c:3868
static List * reorder_function_arguments(List *args, HeapTuple func_tuple)
Definition: clauses.c:3798
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:133
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
void * arg

◆ expression_returns_set_rows()

double expression_returns_set_rows ( PlannerInfo root,
Node clause 
)

Definition at line 282 of file clauses.c.

References clamp_row_est(), FuncExpr::funcid, FuncExpr::funcretset, get_function_rows(), IsA, OpExpr::opfuncid, OpExpr::opretset, and set_opfuncid().

Referenced by create_set_projection_path(), estimate_num_groups(), and set_function_size_estimates().

283 {
284  if (clause == NULL)
285  return 1.0;
286  if (IsA(clause, FuncExpr))
287  {
288  FuncExpr *expr = (FuncExpr *) clause;
289 
290  if (expr->funcretset)
291  return clamp_row_est(get_function_rows(root, expr->funcid, clause));
292  }
293  if (IsA(clause, OpExpr))
294  {
295  OpExpr *expr = (OpExpr *) clause;
296 
297  if (expr->opretset)
298  {
299  set_opfuncid(expr);
300  return clamp_row_est(get_function_rows(root, expr->opfuncid, clause));
301  }
302  }
303  return 1.0;
304 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:584
bool funcretset
Definition: primnodes.h:492
Oid funcid
Definition: primnodes.h:490
Oid opfuncid
Definition: primnodes.h:538
void set_opfuncid(OpExpr *opexpr)
Definition: nodeFuncs.c:1664
double clamp_row_est(double nrows)
Definition: costsize.c:196
bool opretset
Definition: primnodes.h:540
double get_function_rows(PlannerInfo *root, Oid funcid, Node *node)
Definition: plancat.c:1985

◆ fetch_function_defaults()

static List * fetch_function_defaults ( HeapTuple  func_tuple)
static

Definition at line 3893 of file clauses.c.

References castNode, elog, ERROR, pfree(), PROCOID, generate_unaccent_rules::str, stringToNode(), SysCacheGetAttr(), and TextDatumGetCString.

Referenced by add_function_defaults(), and reorder_function_arguments().

3894 {
3895  List *defaults;
3896  Datum proargdefaults;
3897  bool isnull;
3898  char *str;
3899 
3900  /* The error cases here shouldn't happen, but check anyway */
3901  proargdefaults = SysCacheGetAttr(PROCOID, func_tuple,
3902  Anum_pg_proc_proargdefaults,
3903  &isnull);
3904  if (isnull)
3905  elog(ERROR, "not enough default arguments");
3906  str = TextDatumGetCString(proargdefaults);
3907  defaults = castNode(List, stringToNode(str));
3908  pfree(str);
3909  return defaults;
3910 }
#define castNode(_type_, nodeptr)
Definition: nodes.h:602
void * stringToNode(const char *str)
Definition: read.c:89
void pfree(void *pointer)
Definition: mcxt.c:1057
#define ERROR
Definition: elog.h:45
#define TextDatumGetCString(d)
Definition: builtins.h:83
uintptr_t Datum
Definition: postgres.h:367
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1388
#define elog(elevel,...)
Definition: elog.h:227
Definition: pg_list.h:50

◆ find_forced_null_var()

Var* find_forced_null_var ( Node node)

Definition at line 1747 of file clauses.c.

References NullTest::arg, BooleanTest::arg, NullTest::argisrow, BooleanTest::booltesttype, IS_NULL, IS_UNKNOWN, IsA, NullTest::nulltesttype, and Var::varlevelsup.

Referenced by check_redundant_nullability_qual(), and find_forced_null_vars().

1748 {
1749  if (node == NULL)
1750  return NULL;
1751  if (IsA(node, NullTest))
1752  {
1753  /* check for var IS NULL */
1754  NullTest *expr = (NullTest *) node;
1755 
1756  if (expr->nulltesttype == IS_NULL && !expr->argisrow)
1757  {
1758  Var *var = (Var *) expr->arg;
1759 
1760  if (var && IsA(var, Var) &&
1761  var->varlevelsup == 0)
1762  return var;
1763  }
1764  }
1765  else if (IsA(node, BooleanTest))
1766  {
1767  /* var IS UNKNOWN is equivalent to var IS NULL */
1768  BooleanTest *expr = (BooleanTest *) node;
1769 
1770  if (expr->booltesttype == IS_UNKNOWN)
1771  {
1772  Var *var = (Var *) expr->arg;
1773 
1774  if (var && IsA(var, Var) &&
1775  var->varlevelsup == 0)
1776  return var;
1777  }
1778  }
1779  return NULL;
1780 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:584
Index varlevelsup
Definition: primnodes.h:191
Definition: primnodes.h:181
Expr * arg
Definition: primnodes.h:1243
Expr * arg
Definition: primnodes.h:1266
BoolTestType booltesttype
Definition: primnodes.h:1267
NullTestType nulltesttype
Definition: primnodes.h:1244
bool argisrow
Definition: primnodes.h:1245

◆ find_forced_null_vars()

List* find_forced_null_vars ( Node node)

Definition at line 1688 of file clauses.c.

References AND_EXPR, BoolExpr::args, BoolExpr::boolop, find_forced_null_var(), find_forced_null_vars(), IsA, lfirst, list_concat(), list_make1, and NIL.

Referenced by find_forced_null_vars(), and reduce_outer_joins_pass2().

1689 {
1690  List *result = NIL;
1691  Var *var;
1692  ListCell *l;
1693 
1694  if (node == NULL)
1695  return NIL;
1696  /* Check single-clause cases using subroutine */
1697  var = find_forced_null_var(node);
1698  if (var)
1699  {
1700  result = list_make1(var);
1701  }
1702  /* Otherwise, handle AND-conditions */
1703  else if (IsA(node, List))
1704  {
1705  /*
1706  * At top level, we are examining an implicit-AND list: if any of the
1707  * arms produces FALSE-or-NULL then the result is FALSE-or-NULL.
1708  */
1709  foreach(l, (List *) node)
1710  {
1711  result = list_concat(result,
1713  }
1714  }
1715  else if (IsA(node, BoolExpr))
1716  {
1717  BoolExpr *expr = (BoolExpr *) node;
1718 
1719  /*
1720  * We don't bother considering the OR case, because it's fairly
1721  * unlikely anyone would write "v1 IS NULL OR v1 IS NULL". Likewise,
1722  * the NOT case isn't worth expending code on.
1723  */
1724  if (expr->boolop == AND_EXPR)
1725  {
1726  /* At top level we can just recurse (to the List case) */
1727  result = find_forced_null_vars((Node *) expr->args);
1728  }
1729  }
1730  return result;
1731 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:584
Definition: nodes.h:533
List * list_concat(List *list1, const List *list2)
Definition: list.c:530
Definition: primnodes.h:181
List * find_forced_null_vars(Node *node)
Definition: clauses.c:1688
#define list_make1(x1)
Definition: pg_list.h:206
BoolExprType boolop
Definition: primnodes.h:603
#define lfirst(lc)
Definition: pg_list.h:169
List * args
Definition: primnodes.h:604
Definition: pg_list.h:50
Var * find_forced_null_var(Node *node)
Definition: clauses.c:1747

◆ find_nonnullable_rels()

Relids find_nonnullable_rels ( Node clause)

Definition at line 1270 of file clauses.c.

References find_nonnullable_rels_walker().

Referenced by make_outerjoininfo(), and reduce_outer_joins_pass2().

1271 {
1272  return find_nonnullable_rels_walker(clause, true);
1273 }
static Relids find_nonnullable_rels_walker(Node *node, bool top_level)
Definition: clauses.c:1276

◆ find_nonnullable_rels_walker()

static Relids find_nonnullable_rels_walker ( Node node,
bool  top_level 
)
static

Definition at line 1276 of file clauses.c.

References AND_EXPR, RelabelType::arg, CoerceViaIO::arg, ArrayCoerceExpr::arg, ConvertRowtypeExpr::arg, CollateExpr::arg, NullTest::arg, BooleanTest::arg, NullTest::argisrow, FuncExpr::args, OpExpr::args, ScalarArrayOpExpr::args, BoolExpr::args, bms_add_members(), bms_int_members(), bms_is_empty(), bms_join(), bms_make_singleton(), bms_membership(), BMS_SINGLETON, BoolExpr::boolop, BooleanTest::booltesttype, elog, ERROR, func_strict(), FuncExpr::funcid, IS_FALSE, IS_NOT_NULL, IS_NOT_UNKNOWN, is_strict_saop(), IS_TRUE, IsA, lfirst, NOT_EXPR, NullTest::nulltesttype, OpExpr::opfuncid, OR_EXPR, PlaceHolderVar::phexpr, PlaceHolderVar::phlevelsup, PlaceHolderVar::phrels, set_opfuncid(), Var::varlevelsup, and Var::varno.

Referenced by find_nonnullable_rels().

1277 {
1278  Relids result = NULL;
1279  ListCell *l;
1280 
1281  if (node == NULL)
1282  return NULL;
1283  if (IsA(node, Var))
1284  {
1285  Var *var = (Var *) node;
1286 
1287  if (var->varlevelsup == 0)
1288  result = bms_make_singleton(var->varno);
1289  }
1290  else if (IsA(node, List))
1291  {
1292  /*
1293  * At top level, we are examining an implicit-AND list: if any of the
1294  * arms produces FALSE-or-NULL then the result is FALSE-or-NULL. If
1295  * not at top level, we are examining the arguments of a strict
1296  * function: if any of them produce NULL then the result of the
1297  * function must be NULL. So in both cases, the set of nonnullable
1298  * rels is the union of those found in the arms, and we pass down the
1299  * top_level flag unmodified.
1300  */
1301  foreach(l, (List *) node)
1302  {
1303  result = bms_join(result,
1305  top_level));
1306  }
1307  }
1308  else if (IsA(node, FuncExpr))
1309  {
1310  FuncExpr *expr = (FuncExpr *) node;
1311 
1312  if (func_strict(expr->funcid))
1313  result = find_nonnullable_rels_walker((Node *) expr->args, false);
1314  }
1315  else if (IsA(node, OpExpr))
1316  {
1317  OpExpr *expr = (OpExpr *) node;
1318 
1319  set_opfuncid(expr);
1320  if (func_strict(expr->opfuncid))
1321  result = find_nonnullable_rels_walker((Node *) expr->args, false);
1322  }
1323  else if (IsA(node, ScalarArrayOpExpr))
1324  {
1325  ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1326 
1327  if (is_strict_saop(expr, true))
1328  result = find_nonnullable_rels_walker((Node *) expr->args, false);
1329  }
1330  else if (IsA(node, BoolExpr))
1331  {
1332  BoolExpr *expr = (BoolExpr *) node;
1333 
1334  switch (expr->boolop)
1335  {
1336  case AND_EXPR:
1337  /* At top level we can just recurse (to the List case) */
1338  if (top_level)
1339  {
1340  result = find_nonnullable_rels_walker((Node *) expr->args,
1341  top_level);
1342  break;
1343  }
1344 
1345  /*
1346  * Below top level, even if one arm produces NULL, the result
1347  * could be FALSE (hence not NULL). However, if *all* the
1348  * arms produce NULL then the result is NULL, so we can take
1349  * the intersection of the sets of nonnullable rels, just as
1350  * for OR. Fall through to share code.
1351  */
1352  /* FALL THRU */
1353  case OR_EXPR:
1354 
1355  /*
1356  * OR is strict if all of its arms are, so we can take the
1357  * intersection of the sets of nonnullable rels for each arm.
1358  * This works for both values of top_level.
1359  */
1360  foreach(l, expr->args)
1361  {
1362  Relids subresult;
1363 
1364  subresult = find_nonnullable_rels_walker(lfirst(l),
1365  top_level);
1366  if (result == NULL) /* first subresult? */
1367  result = subresult;
1368  else
1369  result = bms_int_members(result, subresult);
1370 
1371  /*
1372  * If the intersection is empty, we can stop looking. This
1373  * also justifies the test for first-subresult above.
1374  */
1375  if (bms_is_empty(result))
1376  break;
1377  }
1378  break;
1379  case NOT_EXPR:
1380  /* NOT will return null if its arg is null */
1381  result = find_nonnullable_rels_walker((Node *) expr->args,
1382  false);
1383  break;
1384  default:
1385  elog(ERROR, "unrecognized boolop: %d", (int) expr->boolop);
1386  break;
1387  }
1388  }
1389  else if (IsA(node, RelabelType))
1390  {
1391  RelabelType *expr = (RelabelType *) node;
1392 
1393  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1394  }
1395  else if (IsA(node, CoerceViaIO))
1396  {
1397  /* not clear this is useful, but it can't hurt */
1398  CoerceViaIO *expr = (CoerceViaIO *) node;
1399 
1400  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1401  }
1402  else if (IsA(node, ArrayCoerceExpr))
1403  {
1404  /* ArrayCoerceExpr is strict at the array level; ignore elemexpr */
1405  ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
1406 
1407  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1408  }
1409  else if (IsA(node, ConvertRowtypeExpr))
1410  {
1411  /* not clear this is useful, but it can't hurt */
1412  ConvertRowtypeExpr *expr = (ConvertRowtypeExpr *) node;
1413 
1414  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1415  }
1416  else if (IsA(node, CollateExpr))
1417  {
1418  CollateExpr *expr = (CollateExpr *) node;
1419 
1420  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1421  }
1422  else if (IsA(node, NullTest))
1423  {
1424  /* IS NOT NULL can be considered strict, but only at top level */
1425  NullTest *expr = (NullTest *) node;
1426 
1427  if (top_level && expr->nulltesttype == IS_NOT_NULL && !expr->argisrow)
1428  result = find_nonnullable_rels_walker((Node *) expr->arg, false);
1429  }
1430  else if (IsA(node, BooleanTest))
1431  {
1432  /* Boolean tests that reject NULL are strict at top level */
1433  BooleanTest *expr = (BooleanTest *) node;
1434 
1435  if (top_level &&
1436  (expr->booltesttype == IS_TRUE ||
1437  expr->booltesttype == IS_FALSE ||
1438  expr->booltesttype == IS_NOT_UNKNOWN))
1439  result = find_nonnullable_rels_walker((Node *) expr->arg, false);
1440  }
1441  else if (IsA(node, PlaceHolderVar))
1442  {
1443  PlaceHolderVar *phv = (PlaceHolderVar *) node;
1444 
1445  /*
1446  * If the contained expression forces any rels non-nullable, so does
1447  * the PHV.
1448  */
1449  result = find_nonnullable_rels_walker((Node *) phv->phexpr, top_level);
1450 
1451  /*
1452  * If the PHV's syntactic scope is exactly one rel, it will be forced
1453  * to be evaluated at that rel, and so it will behave like a Var of
1454  * that rel: if the rel's entire output goes to null, so will the PHV.
1455  * (If the syntactic scope is a join, we know that the PHV will go to
1456  * null if the whole join does; but that is AND semantics while we
1457  * need OR semantics for find_nonnullable_rels' result, so we can't do
1458  * anything with the knowledge.)
1459  */
1460  if (phv->phlevelsup == 0 &&
1462  result = bms_add_members(result, phv->phrels);
1463  }
1464  return result;
1465 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:584
Index varlevelsup
Definition: primnodes.h:191
List * args
Definition: primnodes.h:498
Expr * arg
Definition: primnodes.h:838
Definition: nodes.h:533
Definition: primnodes.h:181
Oid funcid
Definition: primnodes.h:490
#define ERROR
Definition: elog.h:45
Bitmapset * bms_join(Bitmapset *a, Bitmapset *b)
Definition: bitmapset.c:949
BoolExprType boolop
Definition: primnodes.h:603
Expr * arg
Definition: primnodes.h:1243
Bitmapset * bms_make_singleton(int x)
Definition: bitmapset.c:186
Expr * arg
Definition: primnodes.h:1266
Expr * arg
Definition: primnodes.h:858
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:701
Index varno
Definition: primnodes.h:184
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:672
BoolTestType booltesttype
Definition: primnodes.h:1267
Oid opfuncid
Definition: primnodes.h:538
static Relids find_nonnullable_rels_walker(Node *node, bool top_level)
Definition: clauses.c:1276
NullTestType nulltesttype
Definition: primnodes.h:1244
static bool is_strict_saop(ScalarArrayOpExpr *expr, bool falseOK)
Definition: clauses.c:1796
#define lfirst(lc)
Definition: pg_list.h:169
Expr * arg
Definition: primnodes.h:924
List * args
Definition: primnodes.h:604
bool func_strict(Oid funcid)
Definition: lsyscache.c:1732
Index phlevelsup
Definition: pathnodes.h:2128
void set_opfuncid(OpExpr *opexpr)
Definition: nodeFuncs.c:1664
#define elog(elevel,...)
Definition: elog.h:227
bool argisrow
Definition: primnodes.h:1245
List * args
Definition: primnodes.h:543
Bitmapset * bms_int_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:902
Definition: pg_list.h:50
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:793

◆ find_nonnullable_vars()

List* find_nonnullable_vars ( Node clause)

Definition at line 1495 of file clauses.c.

References find_nonnullable_vars_walker().

Referenced by reduce_outer_joins_pass2().

1496 {
1497  return find_nonnullable_vars_walker(clause, true);
1498 }
static List * find_nonnullable_vars_walker(Node *node, bool top_level)
Definition: clauses.c:1501

◆ find_nonnullable_vars_walker()

static List * find_nonnullable_vars_walker ( Node node,
bool  top_level 
)
static

Definition at line 1501 of file clauses.c.

References AND_EXPR, RelabelType::arg, CoerceViaIO::arg, ArrayCoerceExpr::arg, ConvertRowtypeExpr::arg, CollateExpr::arg, NullTest::arg, BooleanTest::arg, NullTest::argisrow, FuncExpr::args, OpExpr::args, ScalarArrayOpExpr::args, BoolExpr::args, BoolExpr::boolop, BooleanTest::booltesttype, elog, ERROR, func_strict(), FuncExpr::funcid, IS_FALSE, IS_NOT_NULL, IS_NOT_UNKNOWN, is_strict_saop(), IS_TRUE, IsA, lfirst, list_concat(), list_intersection(), list_make1, NIL, NOT_EXPR, NullTest::nulltesttype, OpExpr::opfuncid, OR_EXPR, PlaceHolderVar::phexpr, set_opfuncid(), and Var::varlevelsup.

Referenced by find_nonnullable_vars().

1502 {
1503  List *result = NIL;
1504  ListCell *l;
1505 
1506  if (node == NULL)
1507  return NIL;
1508  if (IsA(node, Var))
1509  {
1510  Var *var = (Var *) node;
1511 
1512  if (var->varlevelsup == 0)
1513  result = list_make1(var);
1514  }
1515  else if (IsA(node, List))
1516  {
1517  /*
1518  * At top level, we are examining an implicit-AND list: if any of the
1519  * arms produces FALSE-or-NULL then the result is FALSE-or-NULL. If
1520  * not at top level, we are examining the arguments of a strict
1521  * function: if any of them produce NULL then the result of the
1522  * function must be NULL. So in both cases, the set of nonnullable
1523  * vars is the union of those found in the arms, and we pass down the
1524  * top_level flag unmodified.
1525  */
1526  foreach(l, (List *) node)
1527  {
1528  result = list_concat(result,
1530  top_level));
1531  }
1532  }
1533  else if (IsA(node, FuncExpr))
1534  {
1535  FuncExpr *expr = (FuncExpr *) node;
1536 
1537  if (func_strict(expr->funcid))
1538  result = find_nonnullable_vars_walker((Node *) expr->args, false);
1539  }
1540  else if (IsA(node, OpExpr))
1541  {
1542  OpExpr *expr = (OpExpr *) node;
1543 
1544  set_opfuncid(expr);
1545  if (func_strict(expr->opfuncid))
1546  result = find_nonnullable_vars_walker((Node *) expr->args, false);
1547  }
1548  else if (IsA(node, ScalarArrayOpExpr))
1549  {
1550  ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1551 
1552  if (is_strict_saop(expr, true))
1553  result = find_nonnullable_vars_walker((Node *) expr->args, false);
1554  }
1555  else if (IsA(node, BoolExpr))
1556  {
1557  BoolExpr *expr = (BoolExpr *) node;
1558 
1559  switch (expr->boolop)
1560  {
1561  case AND_EXPR:
1562  /* At top level we can just recurse (to the List case) */
1563  if (top_level)
1564  {
1565  result = find_nonnullable_vars_walker((Node *) expr->args,
1566  top_level);
1567  break;
1568  }
1569 
1570  /*
1571  * Below top level, even if one arm produces NULL, the result
1572  * could be FALSE (hence not NULL). However, if *all* the
1573  * arms produce NULL then the result is NULL, so we can take
1574  * the intersection of the sets of nonnullable vars, just as
1575  * for OR. Fall through to share code.
1576  */
1577  /* FALL THRU */
1578  case OR_EXPR:
1579 
1580  /*
1581  * OR is strict if all of its arms are, so we can take the
1582  * intersection of the sets of nonnullable vars for each arm.
1583  * This works for both values of top_level.
1584  */
1585  foreach(l, expr->args)
1586  {
1587  List *subresult;
1588 
1589  subresult = find_nonnullable_vars_walker(lfirst(l),
1590  top_level);
1591  if (result == NIL) /* first subresult? */
1592  result = subresult;
1593  else
1594  result = list_intersection(result, subresult);
1595 
1596  /*
1597  * If the intersection is empty, we can stop looking. This
1598  * also justifies the test for first-subresult above.
1599  */
1600  if (result == NIL)
1601  break;
1602  }
1603  break;
1604  case NOT_EXPR:
1605  /* NOT will return null if its arg is null */
1606  result = find_nonnullable_vars_walker((Node *) expr->args,
1607  false);
1608  break;
1609  default:
1610  elog(ERROR, "unrecognized boolop: %d", (int) expr->boolop);
1611  break;
1612  }
1613  }
1614  else if (IsA(node, RelabelType))
1615  {
1616  RelabelType *expr = (RelabelType *) node;
1617 
1618  result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1619  }
1620  else if (IsA(node, CoerceViaIO))
1621  {
1622  /* not clear this is useful, but it can't hurt */
1623  CoerceViaIO *expr = (CoerceViaIO *) node;
1624 
1625  result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1626  }
1627  else if (IsA(node, ArrayCoerceExpr))
1628  {
1629  /* ArrayCoerceExpr is strict at the array level; ignore elemexpr */
1630  ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
1631 
1632  result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1633  }
1634  else if (IsA(node, ConvertRowtypeExpr))
1635  {
1636  /* not clear this is useful, but it can't hurt */
1637  ConvertRowtypeExpr *expr = (ConvertRowtypeExpr *) node;
1638 
1639  result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1640  }
1641  else if (IsA(node, CollateExpr))
1642  {
1643  CollateExpr *expr = (CollateExpr *) node;
1644 
1645  result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1646  }
1647  else if (IsA(node, NullTest))
1648  {
1649  /* IS NOT NULL can be considered strict, but only at top level */
1650  NullTest *expr = (NullTest *) node;
1651 
1652  if (top_level && expr->nulltesttype == IS_NOT_NULL && !expr->argisrow)
1653  result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1654  }
1655  else if (IsA(node, BooleanTest))
1656  {
1657  /* Boolean tests that reject NULL are strict at top level */
1658  BooleanTest *expr = (BooleanTest *) node;
1659 
1660  if (top_level &&
1661  (expr->booltesttype == IS_TRUE ||
1662  expr->booltesttype == IS_FALSE ||
1663  expr->booltesttype == IS_NOT_UNKNOWN))
1664  result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1665  }
1666  else if (IsA(node, PlaceHolderVar))
1667  {
1668  PlaceHolderVar *phv = (PlaceHolderVar *) node;
1669 
1670  result = find_nonnullable_vars_walker((Node *) phv->phexpr, top_level);
1671  }
1672  return result;
1673 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:584
Index varlevelsup
Definition: primnodes.h:191
List * args
Definition: primnodes.h:498
Expr * arg
Definition: primnodes.h:838
Definition: nodes.h:533
List * list_concat(List *list1, const List *list2)
Definition: list.c:530
Definition: primnodes.h:181
#define list_make1(x1)
Definition: pg_list.h:206
Oid funcid
Definition: primnodes.h:490
#define ERROR
Definition: elog.h:45
BoolExprType boolop
Definition: primnodes.h:603
Expr * arg
Definition: primnodes.h:1243
Expr * arg
Definition: primnodes.h:1266
List * list_intersection(const List *list1, const List *list2)
Definition: list.c:1033
static List * find_nonnullable_vars_walker(Node *node, bool top_level)
Definition: clauses.c:1501
Expr * arg
Definition: primnodes.h:858
BoolTestType booltesttype
Definition: primnodes.h:1267
Oid opfuncid
Definition: primnodes.h:538
NullTestType nulltesttype
Definition: primnodes.h:1244
static bool is_strict_saop(ScalarArrayOpExpr *expr, bool falseOK)
Definition: clauses.c:1796
#define lfirst(lc)
Definition: pg_list.h:169
Expr * arg
Definition: primnodes.h:924
List * args
Definition: primnodes.h:604
bool func_strict(Oid funcid)
Definition: lsyscache.c:1732
void set_opfuncid(OpExpr *opexpr)
Definition: nodeFuncs.c:1664
#define elog(elevel,...)
Definition: elog.h:227
bool argisrow
Definition: primnodes.h:1245
List * args
Definition: primnodes.h:543
Definition: pg_list.h:50

◆ find_window_functions()

WindowFuncLists* find_window_functions ( Node clause,
Index  maxWinRef 
)

Definition at line 220 of file clauses.c.

References find_window_functions_walker(), WindowFuncLists::maxWinRef, WindowFuncLists::numWindowFuncs, palloc(), palloc0(), and WindowFuncLists::windowFuncs.

Referenced by grouping_planner().

221 {
222  WindowFuncLists *lists = palloc(sizeof(WindowFuncLists));
223 
224  lists->numWindowFuncs = 0;
225  lists->maxWinRef = maxWinRef;
226  lists->windowFuncs = (List **) palloc0((maxWinRef + 1) * sizeof(List *));
227  (void) find_window_functions_walker(clause, lists);
228  return lists;
229 }
Index maxWinRef
Definition: clauses.h:22
int numWindowFuncs
Definition: clauses.h:21
void * palloc0(Size size)
Definition: mcxt.c:981
void * palloc(Size size)
Definition: mcxt.c:950
static bool find_window_functions_walker(Node *node, WindowFuncLists *lists)
Definition: clauses.c:232
Definition: pg_list.h:50
List ** windowFuncs
Definition: clauses.h:23

◆ find_window_functions_walker()

static bool find_window_functions_walker ( Node node,
WindowFuncLists lists 
)
static

Definition at line 232 of file clauses.c.

References Assert, elog, ERROR, expression_tree_walker(), IsA, lappend(), list_member(), WindowFuncLists::maxWinRef, WindowFuncLists::numWindowFuncs, WindowFuncLists::windowFuncs, and WindowFunc::winref.

Referenced by find_window_functions().

233 {
234  if (node == NULL)
235  return false;
236  if (IsA(node, WindowFunc))
237  {
238  WindowFunc *wfunc = (WindowFunc *) node;
239 
240  /* winref is unsigned, so one-sided test is OK */
241  if (wfunc->winref > lists->maxWinRef)
242  elog(ERROR, "WindowFunc contains out-of-range winref %u",
243  wfunc->winref);
244  /* eliminate duplicates, so that we avoid repeated computation */
245  if (!list_member(lists->windowFuncs[wfunc->winref], wfunc))
246  {
247  lists->windowFuncs[wfunc->winref] =
248  lappend(lists->windowFuncs[wfunc->winref], wfunc);
249  lists->numWindowFuncs++;
250  }
251 
252  /*
253  * We assume that the parser checked that there are no window
254  * functions in the arguments or filter clause. Hence, we need not
255  * recurse into them. (If either the parser or the planner screws up
256  * on this point, the executor will still catch it; see ExecInitExpr.)
257  */
258  return false;
259  }
260  Assert(!IsA(node, SubLink));
262  (void *) lists);
263 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:584
Index maxWinRef
Definition: clauses.h:22
int numWindowFuncs
Definition: clauses.h:21
Index winref
Definition: primnodes.h:387
#define ERROR
Definition: elog.h:45
bool list_member(const List *list, const void *datum)
Definition: list.c:628
List * lappend(List *list, void *datum)
Definition: list.c:336
#define Assert(condition)
Definition: c.h:804
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1885
#define elog(elevel,...)
Definition: elog.h:227
static bool find_window_functions_walker(Node *node, WindowFuncLists *lists)
Definition: clauses.c:232
List ** windowFuncs
Definition: clauses.h:23

◆ inline_function()

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 
)
static

Definition at line 4099 of file clauses.c.

References ACL_EXECUTE, ACLCHECK_OK, eval_const_expressions_context::active_fns, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, arg, ErrorContextCallback::arg, CollateExpr::arg, generate_unaccent_rules::args, FuncExpr::args, ErrorContextCallback::callback, check_sql_fn_retval(), CMD_SELECT, COERCE_EXPLICIT_CALL, CollateExpr::collOid, Query::commandType, contain_context_dependent_node(), contain_mutable_functions(), contain_nonstrict_functions(), contain_subplans(), contain_volatile_functions(), copyObject, cost_qual_eval(), cpu_operator_cost, Query::cteList, CurrentMemoryContext, Query::distinctClause, elog, ERROR, error_context_stack, eval_const_expressions_mutator(), exprCollation(), exprType(), FmgrHookIsNeeded, free_parsestate(), FromExpr::fromlist, FuncExpr::funccollid, FuncExpr::funcformat, FuncExpr::funcid, FuncExpr::funcresulttype, FuncExpr::funcretset, FuncExpr::funcvariadic, get_expr_result_type(), GETSTRUCT, GetUserId(), Query::groupClause, Query::groupingSets, Query::hasAggs, Query::hasSubLinks, Query::hasTargetSRFs, Query::hasWindowFuncs, Query::havingQual, heap_attisnull(), i, FuncExpr::inputcollid, IsA, Query::jointree, lappend_oid(), lfirst, Query::limitCount, Query::limitOffset, linitial, list_delete_last(), list_length(), list_make1, list_member_oid(), FuncExpr::location, CollateExpr::location, make_parsestate(), makeNode, MemoryContextDelete(), MemoryContextSwitchTo(), NameStr, OidIsValid, ParseState::p_sourcetext, palloc0(), QualCost::per_tuple, pg_parse_query(), pg_proc_aclcheck(), prepare_sql_fn_parse_info(), ErrorContextCallback::previous, PROCOID, inline_error_callback_arg::proname, inline_error_callback_arg::prosrc, FromExpr::quals, querytree(), record_plan_function_dependency(), eval_const_expressions_context::root, Query::rtable, Query::setOperations, Query::sortClause, sql_fn_parser_setup(), sql_inline_error_callback(), QualCost::startup, substitute_actual_parameters(), SysCacheGetAttr(), Query::targetList, TextDatumGetCString, transformTopLevelStmt(), and Query::windowClause.

Referenced by simplify_function().

4104 {
4105  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4106  char *src;
4107  Datum tmp;
4108  bool isNull;
4109  MemoryContext oldcxt;
4110  MemoryContext mycxt;
4111  inline_error_callback_arg callback_arg;
4112  ErrorContextCallback sqlerrcontext;
4113  FuncExpr *fexpr;
4115  TupleDesc rettupdesc;
4116  ParseState *pstate;
4117  List *raw_parsetree_list;
4118  List *querytree_list;
4119  Query *querytree;
4120  Node *newexpr;
4121  int *usecounts;
4122  ListCell *arg;
4123  int i;
4124 
4125  /*
4126  * Forget it if the function is not SQL-language or has other showstopper
4127  * properties. (The prokind and nargs checks are just paranoia.)
4128  */
4129  if (funcform->prolang != SQLlanguageId ||
4130  funcform->prokind != PROKIND_FUNCTION ||
4131  funcform->prosecdef ||
4132  funcform->proretset ||
4133  funcform->prorettype == RECORDOID ||
4134  !heap_attisnull(func_tuple, Anum_pg_proc_proconfig, NULL) ||
4135  funcform->pronargs != list_length(args))
4136  return NULL;
4137 
4138  /* Check for recursive function, and give up trying to expand if so */
4139  if (list_member_oid(context->active_fns, funcid))
4140  return NULL;
4141 
4142  /* Check permission to call function (fail later, if not) */
4144  return NULL;
4145 
4146  /* Check whether a plugin wants to hook function entry/exit */
4147  if (FmgrHookIsNeeded(funcid))
4148  return NULL;
4149 
4150  /*
4151  * Make a temporary memory context, so that we don't leak all the stuff
4152  * that parsing might create.
4153  */
4155  "inline_function",
4157  oldcxt = MemoryContextSwitchTo(mycxt);
4158 
4159  /* Fetch the function body */
4160  tmp = SysCacheGetAttr(PROCOID,
4161  func_tuple,
4162  Anum_pg_proc_prosrc,
4163  &isNull);
4164  if (isNull)
4165  elog(ERROR, "null prosrc for function %u", funcid);
4166  src = TextDatumGetCString(tmp);
4167 
4168  /*
4169  * Setup error traceback support for ereport(). This is so that we can
4170  * finger the function that bad information came from.
4171  */
4172  callback_arg.proname = NameStr(funcform->proname);
4173  callback_arg.prosrc = src;
4174 
4175  sqlerrcontext.callback = sql_inline_error_callback;
4176  sqlerrcontext.arg = (void *) &callback_arg;
4177  sqlerrcontext.previous = error_context_stack;
4178  error_context_stack = &sqlerrcontext;
4179 
4180  /*
4181  * Set up to handle parameters while parsing the function body. We need a
4182  * dummy FuncExpr node containing the already-simplified arguments to pass
4183  * to prepare_sql_fn_parse_info. (In some cases we don't really need
4184  * that, but for simplicity we always build it.)
4185  */
4186  fexpr = makeNode(FuncExpr);
4187  fexpr->funcid = funcid;
4188  fexpr->funcresulttype = result_type;
4189  fexpr->funcretset = false;
4190  fexpr->funcvariadic = funcvariadic;
4191  fexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
4192  fexpr->funccollid = result_collid; /* doesn't matter */
4193  fexpr->inputcollid = input_collid;
4194  fexpr->args = args;
4195  fexpr->location = -1;
4196 
4197  pinfo = prepare_sql_fn_parse_info(func_tuple,
4198  (Node *) fexpr,
4199  input_collid);
4200 
4201  /* fexpr also provides a convenient way to resolve a composite result */
4202  (void) get_expr_result_type((Node *) fexpr,
4203  NULL,
4204  &rettupdesc);
4205 
4206  /*
4207  * We just do parsing and parse analysis, not rewriting, because rewriting
4208  * will not affect table-free-SELECT-only queries, which is all that we
4209  * care about. Also, we can punt as soon as we detect more than one
4210  * command in the function body.
4211  */
4212  raw_parsetree_list = pg_parse_query(src);
4213  if (list_length(raw_parsetree_list) != 1)
4214  goto fail;
4215 
4216  pstate = make_parsestate(NULL);
4217  pstate->p_sourcetext = src;
4218  sql_fn_parser_setup(pstate, pinfo);
4219 
4220  querytree = transformTopLevelStmt(pstate, linitial(raw_parsetree_list));
4221 
4222  free_parsestate(pstate);
4223 
4224  /*
4225  * The single command must be a simple "SELECT expression".
4226  *
4227  * Note: if you change the tests involved in this, see also plpgsql's
4228  * exec_simple_check_plan(). That generally needs to have the same idea
4229  * of what's a "simple expression", so that inlining a function that
4230  * previously wasn't inlined won't change plpgsql's conclusion.
4231  */
4232  if (!IsA(querytree, Query) ||
4233  querytree->commandType != CMD_SELECT ||
4234  querytree->hasAggs ||
4235  querytree->hasWindowFuncs ||
4236  querytree->hasTargetSRFs ||
4237  querytree->hasSubLinks ||
4238  querytree->cteList ||
4239  querytree->rtable ||
4240  querytree->jointree->fromlist ||
4241  querytree->jointree->quals ||
4242  querytree->groupClause ||
4243  querytree->groupingSets ||
4244  querytree->havingQual ||
4245  querytree->windowClause ||
4246  querytree->distinctClause ||
4247  querytree->sortClause ||
4248  querytree->limitOffset ||
4249  querytree->limitCount ||
4250  querytree->setOperations ||
4251  list_length(querytree->targetList) != 1)
4252  goto fail;
4253 
4254  /*
4255  * Make sure the function (still) returns what it's declared to. This
4256  * will raise an error if wrong, but that's okay since the function would
4257  * fail at runtime anyway. Note that check_sql_fn_retval will also insert
4258  * a coercion if needed to make the tlist expression match the declared
4259  * type of the function.
4260  *
4261  * Note: we do not try this until we have verified that no rewriting was
4262  * needed; that's probably not important, but let's be careful.
4263  */
4264  querytree_list = list_make1(querytree);
4265  if (check_sql_fn_retval(list_make1(querytree_list),
4266  result_type, rettupdesc,
4267  false, NULL))
4268  goto fail; /* reject whole-tuple-result cases */
4269 
4270  /*
4271  * Given the tests above, check_sql_fn_retval shouldn't have decided to
4272  * inject a projection step, but let's just make sure.
4273  */
4274  if (querytree != linitial(querytree_list))
4275  goto fail;
4276 
4277  /* Now we can grab the tlist expression */
4278  newexpr = (Node *) ((TargetEntry *) linitial(querytree->targetList))->expr;
4279 
4280  /*
4281  * If the SQL function returns VOID, we can only inline it if it is a
4282  * SELECT of an expression returning VOID (ie, it's just a redirection to
4283  * another VOID-returning function). In all non-VOID-returning cases,
4284  * check_sql_fn_retval should ensure that newexpr returns the function's
4285  * declared result type, so this test shouldn't fail otherwise; but we may
4286  * as well cope gracefully if it does.
4287  */
4288  if (exprType(newexpr) != result_type)
4289  goto fail;
4290 
4291  /*
4292  * Additional validity checks on the expression. It mustn't be more
4293  * volatile than the surrounding function (this is to avoid breaking hacks
4294  * that involve pretending a function is immutable when it really ain't).
4295  * If the surrounding function is declared strict, then the expression
4296  * must contain only strict constructs and must use all of the function
4297  * parameters (this is overkill, but an exact analysis is hard).
4298  */
4299  if (funcform->provolatile == PROVOLATILE_IMMUTABLE &&
4300  contain_mutable_functions(newexpr))
4301  goto fail;
4302  else if (funcform->provolatile == PROVOLATILE_STABLE &&
4303  contain_volatile_functions(newexpr))
4304  goto fail;
4305 
4306  if (funcform->proisstrict &&
4307  contain_nonstrict_functions(newexpr))
4308  goto fail;
4309 
4310  /*
4311  * If any parameter expression contains a context-dependent node, we can't
4312  * inline, for fear of putting such a node into the wrong context.
4313  */
4314  if (contain_context_dependent_node((Node *) args))
4315  goto fail;
4316 
4317  /*
4318  * We may be able to do it; there are still checks on parameter usage to
4319  * make, but those are most easily done in combination with the actual
4320  * substitution of the inputs. So start building expression with inputs
4321  * substituted.
4322  */
4323  usecounts = (int *) palloc0(funcform->pronargs * sizeof(int));
4324  newexpr = substitute_actual_parameters(newexpr, funcform->pronargs,
4325  args, usecounts);
4326 
4327  /* Now check for parameter usage */
4328  i = 0;
4329  foreach(arg, args)
4330  {
4331  Node *param = lfirst(arg);
4332 
4333  if (usecounts[i] == 0)
4334  {
4335  /* Param not used at all: uncool if func is strict */
4336  if (funcform->proisstrict)
4337  goto fail;
4338  }
4339  else if (usecounts[i] != 1)
4340  {
4341  /* Param used multiple times: uncool if expensive or volatile */
4342  QualCost eval_cost;
4343 
4344  /*
4345  * We define "expensive" as "contains any subplan or more than 10
4346  * operators". Note that the subplan search has to be done
4347  * explicitly, since cost_qual_eval() will barf on unplanned
4348  * subselects.
4349  */
4350  if (contain_subplans(param))
4351  goto fail;
4352  cost_qual_eval(&eval_cost, list_make1(param), NULL);
4353  if (eval_cost.startup + eval_cost.per_tuple >
4354  10 * cpu_operator_cost)
4355  goto fail;
4356 
4357  /*
4358  * Check volatility last since this is more expensive than the
4359  * above tests
4360  */
4361  if (contain_volatile_functions(param))
4362  goto fail;
4363  }
4364  i++;
4365  }
4366 
4367  /*
4368  * Whew --- we can make the substitution. Copy the modified expression
4369  * out of the temporary memory context, and clean up.
4370  */
4371  MemoryContextSwitchTo(oldcxt);
4372 
4373  newexpr = copyObject(newexpr);
4374 
4375  MemoryContextDelete(mycxt);
4376 
4377  /*
4378  * If the result is of a collatable type, force the result to expose the
4379  * correct collation. In most cases this does not matter, but it's
4380  * possible that the function result is used directly as a sort key or in
4381  * other places where we expect exprCollation() to tell the truth.
4382  */
4383  if (OidIsValid(result_collid))
4384  {
4385  Oid exprcoll = exprCollation(newexpr);
4386 
4387  if (OidIsValid(exprcoll) && exprcoll != result_collid)
4388  {
4389  CollateExpr *newnode = makeNode(CollateExpr);
4390 
4391  newnode->arg = (Expr *) newexpr;
4392  newnode->collOid = result_collid;
4393  newnode->location = -1;
4394 
4395  newexpr = (Node *) newnode;
4396  }
4397  }
4398 
4399  /*
4400  * Since there is now no trace of the function in the plan tree, we must
4401  * explicitly record the plan's dependency on the function.
4402  */
4403  if (context->root)
4404  record_plan_function_dependency(context->root, funcid);
4405 
4406  /*
4407  * Recursively try to simplify the modified expression. Here we must add
4408  * the current function to the context list of active functions.
4409  */
4410  context->active_fns = lappend_oid(context->active_fns, funcid);
4411  newexpr = eval_const_expressions_mutator(newexpr, context);
4412  context->active_fns = list_delete_last(context->active_fns);
4413 
4414  error_context_stack = sqlerrcontext.previous;
4415 
4416  return (Expr *) newexpr;
4417 
4418  /* Here if func is not inlinable: release temp memory and return NULL */
4419 fail:
4420  MemoryContextSwitchTo(oldcxt);
4421  MemoryContextDelete(mycxt);
4422  error_context_stack = sqlerrcontext.previous;
4423 
4424  return NULL;
4425 }
Node * limitOffset
Definition: parsenodes.h:160
Oid funcresulttype
Definition: primnodes.h:491
bool check_sql_fn_retval(List *queryTreeLists, Oid rettype, TupleDesc rettupdesc, bool insertDroppedCols, List **resultTargetList)
Definition: functions.c:1601
#define IsA(nodeptr, _type_)
Definition: nodes.h:584
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:212
#define AllocSetContextCreate
Definition: memutils.h:170
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
List * sortClause
Definition: parsenodes.h:158
List * args
Definition: primnodes.h:498
FromExpr * jointree
Definition: parsenodes.h:138
Oid GetUserId(void)
Definition: miscinit.c:478
Oid funccollid
Definition: primnodes.h:496
void sql_fn_parser_setup(struct ParseState *pstate, SQLFunctionParseInfoPtr pinfo)
Definition: functions.c:280
bool hasAggs
Definition: parsenodes.h:125
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
List * groupingSets
Definition: parsenodes.h:150
Definition: nodes.h:533
bool heap_attisnull(HeapTuple tup, int attnum, TupleDesc tupleDesc)
Definition: heaptuple.c:359
bool funcretset
Definition: primnodes.h:492
List * fromlist
Definition: primnodes.h:1534
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:437
unsigned int Oid
Definition: postgres_ext.h:31
void(* callback)(void *arg)
Definition: elog.h:242
TypeFuncClass get_expr_result_type(Node *expr, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:223
List * lappend_oid(List *list, Oid datum)
Definition: list.c:372
struct ErrorContextCallback * previous
Definition: elog.h:241
#define OidIsValid(objectId)
Definition: c.h:710
#define FmgrHookIsNeeded(fn_oid)
Definition: fmgr.h:774
Node * quals
Definition: primnodes.h:1535
Cost startup
Definition: pathnodes.h:45
List * windowClause
Definition: parsenodes.h:154
List * targetList
Definition: parsenodes.h:140
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
ErrorContextCallback * error_context_stack
Definition: elog.c:93
#define list_make1(x1)
Definition: pg_list.h:206
bool contain_subplans(Node *clause)
Definition: clauses.c:323
CoercionForm funcformat
Definition: primnodes.h:495
Cost per_tuple
Definition: pathnodes.h:46
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2100
#define linitial(l)
Definition: pg_list.h:174
List * rtable
Definition: parsenodes.h:137
List * distinctClause
Definition: parsenodes.h:156
Oid funcid
Definition: primnodes.h:490
#define ERROR
Definition: elog.h:45
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:4161
List * pg_parse_query(const char *query_string)
Definition: postgres.c:562
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
Node * limitCount
Definition: parsenodes.h:161
List * list_delete_last(List *list)
Definition: list.c:892
double cpu_operator_cost
Definition: costsize.c:122
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
const char * p_sourcetext
Definition: parse_node.h:180
static Node * substitute_actual_parameters(Node *expr, int nargs, List *args, int *usecounts)
Definition: clauses.c:4431
static void sql_inline_error_callback(void *arg)
Definition: clauses.c:4473
#define TextDatumGetCString(d)
Definition: builtins.h:83
void * palloc0(Size size)
Definition: mcxt.c:981
uintptr_t Datum
Definition: postgres.h:367
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1388
void record_plan_function_dependency(PlannerInfo *root, Oid funcid)
Definition: setrefs.c:2905
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:133
CmdType commandType
Definition: parsenodes.h:112
bool hasTargetSRFs
Definition: parsenodes.h:127
#define makeNode(_type_)
Definition: nodes.h:581
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:689
Oid inputcollid
Definition: primnodes.h:497
#define lfirst(lc)
Definition: pg_list.h:169
bool hasWindowFuncs
Definition: parsenodes.h:126
Query * transformTopLevelStmt(ParseState *pstate, RawStmt *parseTree)
Definition: analyze.c:195
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
static int list_length(const List *l)
Definition: pg_list.h:149
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:759
Expr * arg
Definition: primnodes.h:924
Datum querytree(PG_FUNCTION_ARGS)
Definition: _int_bool.c:664
static bool contain_context_dependent_node(Node *clause)
Definition: clauses.c:993
List * cteList
Definition: parsenodes.h:135
Node * setOperations
Definition: parsenodes.h:166
List * groupClause
Definition: parsenodes.h:148
bool hasSubLinks
Definition: parsenodes.h:128
#define ACL_EXECUTE
Definition: parsenodes.h:81
#define elog(elevel,...)
Definition: elog.h:227
AclResult pg_proc_aclcheck(Oid proc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4606
int i
#define NameStr(name)
Definition: c.h:681
void * arg
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:358
int location
Definition: primnodes.h:499
bool contain_nonstrict_functions(Node *clause)
Definition: clauses.c:807
SQLFunctionParseInfoPtr prepare_sql_fn_parse_info(HeapTuple procedureTuple, Node *call_expr, Oid inputCollation)
Definition: functions.c:190
#define copyObject(obj)
Definition: nodes.h:649
Node * havingQual
Definition: parsenodes.h:152
int location
Definition: primnodes.h:926
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:77
Definition: pg_list.h:50
bool funcvariadic
Definition: primnodes.h:493

◆ inline_set_returning_function()

Query* inline_set_returning_function ( PlannerInfo root,
RangeTblEntry rte 
)

Definition at line 4589 of file clauses.c.

References ACL_EXECUTE, ACLCHECK_OK, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, ErrorContextCallback::arg, FuncExpr::args, Assert, BuildDescFromLists(), ErrorContextCallback::callback, check_sql_fn_retval(), check_stack_depth(), CMD_SELECT, Query::commandType, contain_subplans(), contain_volatile_functions(), copyObject, CurrentMemoryContext, elog, ERROR, error_context_stack, FmgrHookIsNeeded, RangeTblFunction::funccolcollations, RangeTblFunction::funccolnames, RangeTblFunction::funccoltypes, RangeTblFunction::funccoltypmods, RangeTblFunction::funcexpr, FuncExpr::funcid, RangeTblEntry::funcordinality, FuncExpr::funcretset, RangeTblEntry::functions, get_expr_result_type(), GETSTRUCT, GetUserId(), heap_attisnull(), HeapTupleIsValid, IsA, linitial, linitial_node, list_length(), list_make1, MemoryContextDelete(), MemoryContextSwitchTo(), NameStr, ObjectIdGetDatum, pg_analyze_and_rewrite_params(), pg_parse_query(), pg_proc_aclcheck(), prepare_sql_fn_parse_info(), ErrorContextCallback::previous, PROCOID, inline_error_callback_arg::proname, inline_error_callback_arg::prosrc, querytree(), record_plan_function_dependency(), ReleaseSysCache(), RTE_FUNCTION, RangeTblEntry::rtekind, SearchSysCache1(), sql_fn_parser_setup(), sql_inline_error_callback(), substitute_actual_srf_parameters(), SysCacheGetAttr(), TextDatumGetCString, TYPEFUNC_COMPOSITE, TYPEFUNC_COMPOSITE_DOMAIN, and TYPEFUNC_RECORD.

Referenced by preprocess_function_rtes().

4590 {
4591  RangeTblFunction *rtfunc;
4592  FuncExpr *fexpr;
4593  Oid func_oid;
4594  HeapTuple func_tuple;
4595  Form_pg_proc funcform;
4596  char *src;
4597  Datum tmp;
4598  bool isNull;
4599  MemoryContext oldcxt;
4600  MemoryContext mycxt;
4601  inline_error_callback_arg callback_arg;
4602  ErrorContextCallback sqlerrcontext;
4604  TypeFuncClass functypclass;
4605  TupleDesc rettupdesc;
4606  List *raw_parsetree_list;
4607  List *querytree_list;
4608  Query *querytree;
4609 
4610  Assert(rte->rtekind == RTE_FUNCTION);
4611 
4612  /*
4613  * It doesn't make a lot of sense for a SQL SRF to refer to itself in its
4614  * own FROM clause, since that must cause infinite recursion at runtime.
4615  * It will cause this code to recurse too, so check for stack overflow.
4616  * (There's no need to do more.)
4617  */
4619 
4620  /* Fail if the RTE has ORDINALITY - we don't implement that here. */
4621  if (rte->funcordinality)
4622  return NULL;
4623 
4624  /* Fail if RTE isn't a single, simple FuncExpr */
4625  if (list_length(rte->functions) != 1)
4626  return NULL;
4627  rtfunc = (RangeTblFunction *) linitial(rte->functions);
4628 
4629  if (!IsA(rtfunc->funcexpr, FuncExpr))
4630  return NULL;
4631  fexpr = (FuncExpr *) rtfunc->funcexpr;
4632 
4633  func_oid = fexpr->funcid;
4634 
4635  /*
4636  * The function must be declared to return a set, else inlining would
4637  * change the results if the contained SELECT didn't return exactly one
4638  * row.
4639  */
4640  if (!fexpr->funcretset)
4641  return NULL;
4642 
4643  /*
4644  * Refuse to inline if the arguments contain any volatile functions or
4645  * sub-selects. Volatile functions are rejected because inlining may
4646  * result in the arguments being evaluated multiple times, risking a
4647  * change in behavior. Sub-selects are rejected partly for implementation
4648  * reasons (pushing them down another level might change their behavior)
4649  * and partly because they're likely to be expensive and so multiple
4650  * evaluation would be bad.
4651  */
4652  if (contain_volatile_functions((Node *) fexpr->args) ||
4653  contain_subplans((Node *) fexpr->args))
4654  return NULL;
4655 
4656  /* Check permission to call function (fail later, if not) */
4657  if (pg_proc_aclcheck(func_oid, GetUserId(), ACL_EXECUTE) != ACLCHECK_OK)
4658  return NULL;
4659 
4660  /* Check whether a plugin wants to hook function entry/exit */
4661  if (FmgrHookIsNeeded(func_oid))
4662  return NULL;
4663 
4664  /*
4665  * OK, let's take a look at the function's pg_proc entry.
4666  */
4667  func_tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(func_oid));
4668  if (!HeapTupleIsValid(func_tuple))
4669  elog(ERROR, "cache lookup failed for function %u", func_oid);
4670  funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4671 
4672  /*
4673  * Forget it if the function is not SQL-language or has other showstopper
4674  * properties. In particular it mustn't be declared STRICT, since we
4675  * couldn't enforce that. It also mustn't be VOLATILE, because that is
4676  * supposed to cause it to be executed with its own snapshot, rather than
4677  * sharing the snapshot of the calling query. We also disallow returning
4678  * SETOF VOID, because inlining would result in exposing the actual result
4679  * of the function's last SELECT, which should not happen in that case.
4680  * (Rechecking prokind, proretset, and pronargs is just paranoia.)
4681  */
4682  if (funcform->prolang != SQLlanguageId ||
4683  funcform->prokind != PROKIND_FUNCTION ||
4684  funcform->proisstrict ||
4685  funcform->provolatile == PROVOLATILE_VOLATILE ||
4686  funcform->prorettype == VOIDOID ||
4687  funcform->prosecdef ||
4688  !funcform->proretset ||
4689  list_length(fexpr->args) != funcform->pronargs ||
4690  !heap_attisnull(func_tuple, Anum_pg_proc_proconfig, NULL))
4691  {
4692  ReleaseSysCache(func_tuple);
4693  return NULL;
4694  }
4695 
4696  /*
4697  * Make a temporary memory context, so that we don't leak all the stuff
4698  * that parsing might create.
4699  */
4701  "inline_set_returning_function",
4703  oldcxt = MemoryContextSwitchTo(mycxt);
4704 
4705  /* Fetch the function body */
4706  tmp = SysCacheGetAttr(PROCOID,
4707  func_tuple,
4708  Anum_pg_proc_prosrc,
4709  &isNull);
4710  if (isNull)
4711  elog(ERROR, "null prosrc for function %u", func_oid);
4712  src = TextDatumGetCString(tmp);
4713 
4714  /*
4715  * Setup error traceback support for ereport(). This is so that we can
4716  * finger the function that bad information came from.
4717  */
4718  callback_arg.proname = NameStr(funcform->proname);
4719  callback_arg.prosrc = src;
4720 
4721  sqlerrcontext.callback = sql_inline_error_callback;
4722  sqlerrcontext.arg = (void *) &callback_arg;
4723  sqlerrcontext.previous = error_context_stack;
4724  error_context_stack = &sqlerrcontext;
4725 
4726  /*
4727  * Set up to handle parameters while parsing the function body. We can
4728  * use the FuncExpr just created as the input for
4729  * prepare_sql_fn_parse_info.
4730  */
4731  pinfo = prepare_sql_fn_parse_info(func_tuple,
4732  (Node *) fexpr,
4733  fexpr->inputcollid);
4734 
4735  /*
4736  * Also resolve the actual function result tupdesc, if composite. If the
4737  * function is just declared to return RECORD, dig the info out of the AS
4738  * clause.
4739  */
4740  functypclass = get_expr_result_type((Node *) fexpr, NULL, &rettupdesc);
4741  if (functypclass == TYPEFUNC_RECORD)
4742  rettupdesc = BuildDescFromLists(rtfunc->funccolnames,
4743  rtfunc->funccoltypes,
4744  rtfunc->funccoltypmods,
4745  rtfunc->funccolcollations);
4746 
4747  /*
4748  * Parse, analyze, and rewrite (unlike inline_function(), we can't skip
4749  * rewriting here). We can fail as soon as we find more than one query,
4750  * though.
4751  */
4752  raw_parsetree_list = pg_parse_query(src);
4753  if (list_length(raw_parsetree_list) != 1)
4754  goto fail;
4755 
4756  querytree_list = pg_analyze_and_rewrite_params(linitial(raw_parsetree_list),
4757  src,
4759  pinfo, NULL);
4760  if (list_length(querytree_list) != 1)
4761  goto fail;
4762  querytree = linitial(querytree_list);
4763 
4764  /*
4765  * The single command must be a plain SELECT.
4766  */
4767  if (!IsA(querytree, Query) ||
4768  querytree->commandType != CMD_SELECT)
4769  goto fail;
4770 
4771  /*
4772  * Make sure the function (still) returns what it's declared to. This
4773  * will raise an error if wrong, but that's okay since the function would
4774  * fail at runtime anyway. Note that check_sql_fn_retval will also insert
4775  * coercions if needed to make the tlist expression(s) match the declared
4776  * type of the function. We also ask it to insert dummy NULL columns for
4777  * any dropped columns in rettupdesc, so that the elements of the modified
4778  * tlist match up to the attribute numbers.
4779  *
4780  * If the function returns a composite type, don't inline unless the check
4781  * shows it's returning a whole tuple result; otherwise what it's
4782  * returning is a single composite column which is not what we need.
4783  */
4784  if (!check_sql_fn_retval(list_make1(querytree_list),
4785  fexpr->funcresulttype, rettupdesc,
4786  true, NULL) &&
4787  (functypclass == TYPEFUNC_COMPOSITE ||
4788  functypclass == TYPEFUNC_COMPOSITE_DOMAIN ||
4789  functypclass == TYPEFUNC_RECORD))
4790  goto fail; /* reject not-whole-tuple-result cases */
4791 
4792  /*
4793  * check_sql_fn_retval might've inserted a projection step, but that's
4794  * fine; just make sure we use the upper Query.
4795  */
4796  querytree = linitial_node(Query, querytree_list);
4797 
4798  /*
4799  * Looks good --- substitute parameters into the query.
4800  */
4801  querytree = substitute_actual_srf_parameters(querytree,
4802  funcform->pronargs,
4803  fexpr->args);
4804 
4805  /*
4806  * Copy the modified query out of the temporary memory context, and clean
4807  * up.
4808  */
4809  MemoryContextSwitchTo(oldcxt);
4810 
4811  querytree = copyObject(querytree);
4812 
4813  MemoryContextDelete(mycxt);
4814  error_context_stack = sqlerrcontext.previous;
4815  ReleaseSysCache(func_tuple);
4816 
4817  /*
4818  * We don't have to fix collations here because the upper query is already
4819  * parsed, ie, the collations in the RTE are what count.
4820  */
4821 
4822  /*
4823  * Since there is now no trace of the function in the plan tree, we must
4824  * explicitly record the plan's dependency on the function.
4825  */
4826  record_plan_function_dependency(root, func_oid);
4827 
4828  return querytree;
4829 
4830  /* Here if func is not inlinable: release temp memory and return NULL */
4831 fail:
4832  MemoryContextSwitchTo(oldcxt);
4833  MemoryContextDelete(mycxt);
4834  error_context_stack = sqlerrcontext.previous;
4835  ReleaseSysCache(func_tuple);
4836 
4837  return NULL;
4838 }
Oid funcresulttype
Definition: primnodes.h:491
bool check_sql_fn_retval(List *queryTreeLists, Oid rettype, TupleDesc rettupdesc, bool insertDroppedCols, List **resultTargetList)
Definition: functions.c:1601
#define IsA(nodeptr, _type_)
Definition: nodes.h:584
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:212
#define AllocSetContextCreate
Definition: memutils.h:170
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
TupleDesc BuildDescFromLists(List *names, List *types, List *typmods, List *collations)
Definition: tupdesc.c:892
List * args
Definition: primnodes.h:498
Oid GetUserId(void)
Definition: miscinit.c:478
void sql_fn_parser_setup(struct ParseState *pstate, SQLFunctionParseInfoPtr pinfo)
Definition: functions.c:280
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Definition: nodes.h:533
bool heap_attisnull(HeapTuple tup, int attnum, TupleDesc tupleDesc)
Definition: heaptuple.c:359
bool funcretset
Definition: primnodes.h:492
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:437
bool funcordinality
Definition: parsenodes.h:1069
unsigned int Oid
Definition: postgres_ext.h:31
#define linitial_node(type, l)
Definition: pg_list.h:177
void(* callback)(void *arg)
Definition: elog.h:242
TypeFuncClass get_expr_result_type(Node *expr, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:223
struct ErrorContextCallback * previous
Definition: elog.h:241
#define FmgrHookIsNeeded(fn_oid)
Definition: fmgr.h:774
ErrorContextCallback * error_context_stack
Definition: elog.c:93
#define list_make1(x1)
Definition: pg_list.h:206
bool contain_subplans(Node *clause)
Definition: clauses.c:323
#define linitial(l)
Definition: pg_list.h:174
Oid funcid
Definition: primnodes.h:490
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:45
List * pg_parse_query(const char *query_string)
Definition: postgres.c:562
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
void(* ParserSetupHook)(struct ParseState *pstate, void *arg)
Definition: params.h:108
void check_stack_depth(void)
Definition: postgres.c:3310