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 MIN_ARRAY_SIZE_FOR_HASHED_SAOP   9
 
#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 bool convert_saop_to_hashed_saop_walker (Node *node, void *context)
 
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)
 
void convert_saop_to_hashed_saop (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 1068 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 2217 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:4680
Definition: nodes.h:539
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41

Definition at line 2221 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:2598
Definition: nodes.h:539
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2231

Definition at line 2208 of file clauses.c.

Referenced by eval_const_expressions_mutator().

◆ MIN_ARRAY_SIZE_FOR_HASHED_SAOP

#define MIN_ARRAY_SIZE_FOR_HASHED_SAOP   9

Definition at line 2105 of file clauses.c.

Referenced by convert_saop_to_hashed_saop_walker().

Function Documentation

◆ add_function_defaults()

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

Definition at line 4029 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().

4030 {
4031  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4032  int nargsprovided = list_length(args);
4033  List *defaults;
4034  int ndelete;
4035 
4036  /* Get all the default expressions from the pg_proc tuple */
4037  defaults = fetch_function_defaults(func_tuple);
4038 
4039  /* Delete any unused defaults from the list */
4040  ndelete = nargsprovided + list_length(defaults) - funcform->pronargs;
4041  if (ndelete < 0)
4042  elog(ERROR, "not enough default arguments");
4043  if (ndelete > 0)
4044  defaults = list_copy_tail(defaults, ndelete);
4045 
4046  /* And form the combined argument list, not modifying the input list */
4047  return list_concat_copy(args, defaults);
4048 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
List * list_copy_tail(const List *oldlist, int nskip)
Definition: list.c:1437
#define ERROR
Definition: elog.h:46
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:4054
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:136
static int list_length(const List *l)
Definition: pg_list.h:149
#define elog(elevel,...)
Definition: elog.h:232
Definition: pg_list.h:50

◆ CommuteOpExpr()

void CommuteOpExpr ( OpExpr clause)

Definition at line 1983 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().

1984 {
1985  Oid opoid;
1986  Node *temp;
1987 
1988  /* Sanity checks: caller is at fault if these fail */
1989  if (!is_opclause(clause) ||
1990  list_length(clause->args) != 2)
1991  elog(ERROR, "cannot commute non-binary-operator clause");
1992 
1993  opoid = get_commutator(clause->opno);
1994 
1995  if (!OidIsValid(opoid))
1996  elog(ERROR, "could not find commutator for operator %u",
1997  clause->opno);
1998 
1999  /*
2000  * modify the clause in-place!
2001  */
2002  clause->opno = opoid;
2003  clause->opfuncid = InvalidOid;
2004  /* opresulttype, opretset, opcollid, inputcollid need not change */
2005 
2006  temp = linitial(clause->args);
2007  linitial(clause->args) = lsecond(clause->args);
2008  lsecond(clause->args) = temp;
2009 }
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1480
Definition: nodes.h:539
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:46
Oid opfuncid
Definition: primnodes.h:543
#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:232
Oid opno
Definition: primnodes.h:542
static bool is_opclause(const void *clause)
Definition: nodeFuncs.h:66
List * args
Definition: primnodes.h:548

◆ contain_agg_clause()

bool contain_agg_clause ( Node clause)

Definition at line 171 of file clauses.c.

References contain_agg_clause_walker().

Referenced by get_eclass_for_sort_expr(), and subquery_planner().

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

◆ contain_agg_clause_walker()

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

Definition at line 177 of file clauses.c.

References Assert, expression_tree_walker(), and IsA.

Referenced by contain_agg_clause().

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

◆ contain_context_dependent_node()

static bool contain_context_dependent_node ( Node clause)
static

Definition at line 1061 of file clauses.c.

References contain_context_dependent_node_walker().

Referenced by inline_function().

1062 {
1063  int flags = 0;
1064 
1065  return contain_context_dependent_node_walker(clause, &flags);
1066 }
static bool contain_context_dependent_node_walker(Node *node, int *flags)
Definition: clauses.c:1071

◆ contain_context_dependent_node_walker()

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

Definition at line 1071 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().

1072 {
1073  if (node == NULL)
1074  return false;
1075  if (IsA(node, CaseTestExpr))
1076  return !(*flags & CCDN_CASETESTEXPR_OK);
1077  else if (IsA(node, CaseExpr))
1078  {
1079  CaseExpr *caseexpr = (CaseExpr *) node;
1080 
1081  /*
1082  * If this CASE doesn't have a test expression, then it doesn't create
1083  * a context in which CaseTestExprs should appear, so just fall
1084  * through and treat it as a generic expression node.
1085  */
1086  if (caseexpr->arg)
1087  {
1088  int save_flags = *flags;
1089  bool res;
1090 
1091  /*
1092  * Note: in principle, we could distinguish the various sub-parts
1093  * of a CASE construct and set the flag bit only for some of them,
1094  * since we are only expecting CaseTestExprs to appear in the
1095  * "expr" subtree of the CaseWhen nodes. But it doesn't really
1096  * seem worth any extra code. If there are any bare CaseTestExprs
1097  * elsewhere in the CASE, something's wrong already.
1098  */
1099  *flags |= CCDN_CASETESTEXPR_OK;
1100  res = expression_tree_walker(node,
1102  (void *) flags);
1103  *flags = save_flags;
1104  return res;
1105  }
1106  }
1107  else if (IsA(node, ArrayCoerceExpr))
1108  {
1109  ArrayCoerceExpr *ac = (ArrayCoerceExpr *) node;
1110  int save_flags;
1111  bool res;
1112 
1113  /* Check the array expression */
1114  if (contain_context_dependent_node_walker((Node *) ac->arg, flags))
1115  return true;
1116 
1117  /* Check the elemexpr, which is allowed to contain CaseTestExpr */
1118  save_flags = *flags;
1119  *flags |= CCDN_CASETESTEXPR_OK;
1121  flags);
1122  *flags = save_flags;
1123  return res;
1124  }
1126  (void *) flags);
1127 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
Definition: nodes.h:539
#define CCDN_CASETESTEXPR_OK
Definition: clauses.c:1068
Expr * elemexpr
Definition: primnodes.h:895
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1904
Expr * arg
Definition: primnodes.h:968
static bool contain_context_dependent_node_walker(Node *node, int *flags)
Definition: clauses.c:1071

◆ contain_exec_param()

bool contain_exec_param ( Node clause,
List param_ids 
)

Definition at line 1019 of file clauses.c.

References contain_exec_param_walker().

Referenced by test_opexpr_is_hashable().

1020 {
1021  return contain_exec_param_walker(clause, param_ids);
1022 }
static bool contain_exec_param_walker(Node *node, List *param_ids)
Definition: clauses.c:1025

◆ contain_exec_param_walker()

static bool contain_exec_param_walker ( Node node,
List param_ids 
)
static

Definition at line 1025 of file clauses.c.

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

Referenced by contain_exec_param().

1026 {
1027  if (node == NULL)
1028  return false;
1029  if (IsA(node, Param))
1030  {
1031  Param *p = (Param *) node;
1032 
1033  if (p->paramkind == PARAM_EXEC &&
1034  list_member_int(param_ids, p->paramid))
1035  return true;
1036  }
1037  return expression_tree_walker(node, contain_exec_param_walker, param_ids);
1038 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
ParamKind paramkind
Definition: primnodes.h:267
bool list_member_int(const List *list, int datum)
Definition: list.c:669
int paramid
Definition: primnodes.h:268
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1904
static bool contain_exec_param_walker(Node *node, List *param_ids)
Definition: clauses.c:1025

◆ contain_leaked_vars()

bool contain_leaked_vars ( Node clause)

Definition at line 1145 of file clauses.c.

References contain_leaked_vars_walker().

Referenced by make_restrictinfo_internal(), and qual_is_pushdown_safe().

1146 {
1147  return contain_leaked_vars_walker(clause, NULL);
1148 }
static bool contain_leaked_vars_walker(Node *node, void *context)
Definition: clauses.c:1157

◆ contain_leaked_vars_checker()

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

Definition at line 1151 of file clauses.c.

References get_func_leakproof().

Referenced by contain_leaked_vars_walker().

1152 {
1153  return !get_func_leakproof(func_id);
1154 }
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 1157 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().

1158 {
1159  if (node == NULL)
1160  return false;
1161 
1162  switch (nodeTag(node))
1163  {
1164  case T_Var:
1165  case T_Const:
1166  case T_Param:
1167  case T_ArrayExpr:
1168  case T_FieldSelect:
1169  case T_FieldStore:
1170  case T_NamedArgExpr:
1171  case T_BoolExpr:
1172  case T_RelabelType:
1173  case T_CollateExpr:
1174  case T_CaseExpr:
1175  case T_CaseTestExpr:
1176  case T_RowExpr:
1177  case T_SQLValueFunction:
1178  case T_NullTest:
1179  case T_BooleanTest:
1180  case T_NextValueExpr:
1181  case T_List:
1182 
1183  /*
1184  * We know these node types don't contain function calls; but
1185  * something further down in the node tree might.
1186  */
1187  break;
1188 
1189  case T_FuncExpr:
1190  case T_OpExpr:
1191  case T_DistinctExpr:
1192  case T_NullIfExpr:
1193  case T_ScalarArrayOpExpr:
1194  case T_CoerceViaIO:
1195  case T_ArrayCoerceExpr:
1196 
1197  /*
1198  * If node contains a leaky function call, and there's any Var
1199  * underneath it, reject.
1200  */
1202  context) &&
1203  contain_var_clause(node))
1204  return true;
1205  break;
1206 
1207  case T_SubscriptingRef:
1208  {
1209  SubscriptingRef *sbsref = (SubscriptingRef *) node;
1210  const SubscriptRoutines *sbsroutines;
1211 
1212  /* Consult the subscripting support method info */
1213  sbsroutines = getSubscriptingRoutines(sbsref->refcontainertype,
1214  NULL);
1215  if (!sbsroutines ||
1216  !(sbsref->refassgnexpr != NULL ?
1217  sbsroutines->store_leakproof :
1218  sbsroutines->fetch_leakproof))
1219  {
1220  /* Node is leaky, so reject if it contains Vars */
1221  if (contain_var_clause(node))
1222  return true;
1223  }
1224  }
1225  break;
1226 
1227  case T_RowCompareExpr:
1228  {
1229  /*
1230  * It's worth special-casing this because a leaky comparison
1231  * function only compromises one pair of row elements, which
1232  * might not contain Vars while others do.
1233  */
1234  RowCompareExpr *rcexpr = (RowCompareExpr *) node;
1235  ListCell *opid;
1236  ListCell *larg;
1237  ListCell *rarg;
1238 
1239  forthree(opid, rcexpr->opnos,
1240  larg, rcexpr->largs,
1241  rarg, rcexpr->rargs)
1242  {
1243  Oid funcid = get_opcode(lfirst_oid(opid));
1244 
1245  if (!get_func_leakproof(funcid) &&
1246  (contain_var_clause((Node *) lfirst(larg)) ||
1247  contain_var_clause((Node *) lfirst(rarg))))
1248  return true;
1249  }
1250  }
1251  break;
1252 
1253  case T_MinMaxExpr:
1254  {
1255  /*
1256  * MinMaxExpr is leakproof if the comparison function it calls
1257  * is leakproof.
1258  */
1259  MinMaxExpr *minmaxexpr = (MinMaxExpr *) node;
1260  TypeCacheEntry *typentry;
1261  bool leakproof;
1262 
1263  /* Look up the btree comparison function for the datatype */
1264  typentry = lookup_type_cache(minmaxexpr->minmaxtype,
1266  if (OidIsValid(typentry->cmp_proc))
1267  leakproof = get_func_leakproof(typentry->cmp_proc);
1268  else
1269  {
1270  /*
1271  * The executor will throw an error, but here we just
1272  * treat the missing function as leaky.
1273  */
1274  leakproof = false;
1275  }
1276 
1277  if (!leakproof &&
1278  contain_var_clause((Node *) minmaxexpr->args))
1279  return true;
1280  }
1281  break;
1282 
1283  case T_CurrentOfExpr:
1284 
1285  /*
1286  * WHERE CURRENT OF doesn't contain leaky function calls.
1287  * Moreover, it is essential that this is considered non-leaky,
1288  * since the planner must always generate a TID scan when CURRENT
1289  * OF is present -- cf. cost_tidscan.
1290  */
1291  return false;
1292 
1293  default:
1294 
1295  /*
1296  * If we don't recognize the node tag, assume it might be leaky.
1297  * This prevents an unexpected security hole if someone adds a new
1298  * node type that can call a function.
1299  */
1300  return true;
1301  }
1303  context);
1304 }
Oid minmaxtype
Definition: primnodes.h:1138
bool get_func_leakproof(Oid funcid)
Definition: lsyscache.c:1808
List * args
Definition: primnodes.h:1142
#define forthree(cell1, list1, cell2, list2, cell3, list3)
Definition: pg_list.h:491
Definition: nodes.h:539
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:1721
Definition: nodes.h:305
Definition: nodes.h:158
Definition: nodes.h:157
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:1904
#define nodeTag(nodeptr)
Definition: nodes.h:544
Expr * refassgnexpr
Definition: primnodes.h:451
static bool contain_leaked_vars_checker(Oid func_id, void *context)
Definition: clauses.c:1151
Oid refcontainertype
Definition: primnodes.h:439
static bool contain_leaked_vars_walker(Node *node, void *context)
Definition: clauses.c:1157
#define lfirst_oid(lc)
Definition: pg_list.h:171
Definition: nodes.h:159

◆ contain_mutable_functions()

◆ contain_mutable_functions_checker()

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

Definition at line 365 of file clauses.c.

References func_volatile().

Referenced by contain_mutable_functions_walker().

366 {
367  return (func_volatile(func_id) != PROVOLATILE_IMMUTABLE);
368 }
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 371 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().

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

◆ contain_non_const_walker()

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

Definition at line 3486 of file clauses.c.

References expression_tree_walker(), and IsA.

3487 {
3488  if (node == NULL)
3489  return false;
3490  if (IsA(node, Const))
3491  return false;
3492  if (IsA(node, List))
3493  return expression_tree_walker(node, contain_non_const_walker, context);
3494  /* Otherwise, abort the tree traversal and return true */
3495  return true;
3496 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1904
Definition: pg_list.h:50
static bool contain_non_const_walker(Node *node, void *context)
Definition: clauses.c:3486

◆ contain_nonstrict_functions()

bool contain_nonstrict_functions ( Node clause)

Definition at line 875 of file clauses.c.

References contain_nonstrict_functions_walker().

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

876 {
877  return contain_nonstrict_functions_walker(clause, NULL);
878 }
static bool contain_nonstrict_functions_walker(Node *node, void *context)
Definition: clauses.c:887

◆ contain_nonstrict_functions_checker()

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

Definition at line 881 of file clauses.c.

References func_strict().

Referenced by contain_nonstrict_functions_walker().

882 {
883  return !func_strict(func_id);
884 }
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 887 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().

888 {
889  if (node == NULL)
890  return false;
891  if (IsA(node, Aggref))
892  {
893  /* an aggregate could return non-null with null input */
894  return true;
895  }
896  if (IsA(node, GroupingFunc))
897  {
898  /*
899  * A GroupingFunc doesn't evaluate its arguments, and therefore must
900  * be treated as nonstrict.
901  */
902  return true;
903  }
904  if (IsA(node, WindowFunc))
905  {
906  /* a window function could return non-null with null input */
907  return true;
908  }
909  if (IsA(node, SubscriptingRef))
910  {
911  SubscriptingRef *sbsref = (SubscriptingRef *) node;
912  const SubscriptRoutines *sbsroutines;
913 
914  /* Subscripting assignment is always presumed nonstrict */
915  if (sbsref->refassgnexpr != NULL)
916  return true;
917  /* Otherwise we must look up the subscripting support methods */
918  sbsroutines = getSubscriptingRoutines(sbsref->refcontainertype, NULL);
919  if (!(sbsroutines && sbsroutines->fetch_strict))
920  return true;
921  /* else fall through to check args */
922  }
923  if (IsA(node, DistinctExpr))
924  {
925  /* IS DISTINCT FROM is inherently non-strict */
926  return true;
927  }
928  if (IsA(node, NullIfExpr))
929  {
930  /* NULLIF is inherently non-strict */
931  return true;
932  }
933  if (IsA(node, BoolExpr))
934  {
935  BoolExpr *expr = (BoolExpr *) node;
936 
937  switch (expr->boolop)
938  {
939  case AND_EXPR:
940  case OR_EXPR:
941  /* AND, OR are inherently non-strict */
942  return true;
943  default:
944  break;
945  }
946  }
947  if (IsA(node, SubLink))
948  {
949  /* In some cases a sublink might be strict, but in general not */
950  return true;
951  }
952  if (IsA(node, SubPlan))
953  return true;
954  if (IsA(node, AlternativeSubPlan))
955  return true;
956  if (IsA(node, FieldStore))
957  return true;
958  if (IsA(node, CoerceViaIO))
959  {
960  /*
961  * CoerceViaIO is strict regardless of whether the I/O functions are,
962  * so just go look at its argument; asking check_functions_in_node is
963  * useless expense and could deliver the wrong answer.
964  */
966  context);
967  }
968  if (IsA(node, ArrayCoerceExpr))
969  {
970  /*
971  * ArrayCoerceExpr is strict at the array level, regardless of what
972  * the per-element expression is; so we should ignore elemexpr and
973  * recurse only into the arg.
974  */
976  context);
977  }
978  if (IsA(node, CaseExpr))
979  return true;
980  if (IsA(node, ArrayExpr))
981  return true;
982  if (IsA(node, RowExpr))
983  return true;
984  if (IsA(node, RowCompareExpr))
985  return true;
986  if (IsA(node, CoalesceExpr))
987  return true;
988  if (IsA(node, MinMaxExpr))
989  return true;
990  if (IsA(node, XmlExpr))
991  return true;
992  if (IsA(node, NullTest))
993  return true;
994  if (IsA(node, BooleanTest))
995  return true;
996 
997  /* Check other function-containing nodes */
999  context))
1000  return true;
1001 
1003  context);
1004 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
Definition: nodes.h:539
static bool contain_nonstrict_functions_walker(Node *node, void *context)
Definition: clauses.c:887
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:1721
BoolExprType boolop
Definition: primnodes.h:615
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1904
Expr * refassgnexpr
Definition: primnodes.h:451
void * arg
Oid refcontainertype
Definition: primnodes.h:439
static bool contain_nonstrict_functions_checker(Oid func_id, void *context)
Definition: clauses.c:881

◆ contain_subplans()

bool contain_subplans ( Node clause)

Definition at line 324 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().

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

◆ contain_subplans_walker()

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

Definition at line 330 of file clauses.c.

References expression_tree_walker(), and IsA.

Referenced by contain_subplans().

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

◆ contain_volatile_functions()

◆ contain_volatile_functions_checker()

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

Definition at line 454 of file clauses.c.

References func_volatile().

Referenced by contain_volatile_functions_walker().

455 {
456  return (func_volatile(func_id) == PROVOLATILE_VOLATILE);
457 }
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 555 of file clauses.c.

References contain_volatile_functions_not_nextval_walker().

Referenced by BeginCopyFrom().

556 {
558 }
static bool contain_volatile_functions_not_nextval_walker(Node *node, void *context)
Definition: clauses.c:568

◆ contain_volatile_functions_not_nextval_checker()

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

Definition at line 561 of file clauses.c.

References func_volatile().

Referenced by contain_volatile_functions_not_nextval_walker().

562 {
563  return (func_id != F_NEXTVAL &&
564  func_volatile(func_id) == PROVOLATILE_VOLATILE);
565 }
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 568 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().

569 {
570  if (node == NULL)
571  return false;
572  /* Check for volatile functions in node itself */
573  if (check_functions_in_node(node,
575  context))
576  return true;
577 
578  /*
579  * See notes in contain_mutable_functions_walker about why we treat
580  * MinMaxExpr, XmlExpr, and CoerceToDomain as immutable, while
581  * SQLValueFunction is stable. Hence, none of them are of interest here.
582  * Also, since we're intentionally ignoring nextval(), presumably we
583  * should ignore NextValueExpr.
584  */
585 
586  /* Recurse to check arguments */
587  if (IsA(node, Query))
588  {
589  /* Recurse into subselects */
590  return query_tree_walker((Query *) node,
592  context, 0);
593  }
594  return expression_tree_walker(node,
596  context);
597 }
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2355
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
static bool contain_volatile_functions_not_nextval_walker(Node *node, void *context)
Definition: clauses.c:568
bool check_functions_in_node(Node *node, check_function_callback checker, void *context)
Definition: nodeFuncs.c:1721
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1904
static bool contain_volatile_functions_not_nextval_checker(Oid func_id, void *context)
Definition: clauses.c:561

◆ contain_volatile_functions_walker()

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

Definition at line 460 of file clauses.c.

References check_functions_in_node(), RestrictInfo::clause, contain_volatile_functions_checker(), expression_tree_walker(), PathTarget::exprs, RestrictInfo::has_volatile, PathTarget::has_volatile_expr, IsA, query_tree_walker(), VOLATILITY_NOVOLATILE, and VOLATILITY_VOLATILE.

Referenced by contain_volatile_functions().

461 {
462  if (node == NULL)
463  return false;
464  /* Check for volatile functions in node itself */
466  context))
467  return true;
468 
469  if (IsA(node, NextValueExpr))
470  {
471  /* NextValueExpr is volatile */
472  return true;
473  }
474 
475  if (IsA(node, RestrictInfo))
476  {
477  RestrictInfo *rinfo = (RestrictInfo *) node;
478 
479  /*
480  * For RestrictInfo, check if we've checked the volatility of it
481  * before. If so, we can just use the cached value and not bother
482  * checking it again. Otherwise, check it and cache if whether we
483  * found any volatile functions.
484  */
485  if (rinfo->has_volatile == VOLATILITY_NOVOLATILE)
486  return false;
487  else if (rinfo->has_volatile == VOLATILITY_VOLATILE)
488  return true;
489  else
490  {
491  bool hasvolatile;
492 
493  hasvolatile = contain_volatile_functions_walker((Node *) rinfo->clause,
494  context);
495  if (hasvolatile)
497  else
499 
500  return hasvolatile;
501  }
502  }
503 
504  if (IsA(node, PathTarget))
505  {
506  PathTarget *target = (PathTarget *) node;
507 
508  /*
509  * We also do caching for PathTarget the same as we do above for
510  * RestrictInfos.
511  */
513  return false;
514  else if (target->has_volatile_expr == VOLATILITY_VOLATILE)
515  return true;
516  else
517  {
518  bool hasvolatile;
519 
520  hasvolatile = contain_volatile_functions_walker((Node *) target->exprs,
521  context);
522 
523  if (hasvolatile)
525  else
527 
528  return hasvolatile;
529  }
530  }
531 
532  /*
533  * See notes in contain_mutable_functions_walker about why we treat
534  * MinMaxExpr, XmlExpr, and CoerceToDomain as immutable, while
535  * SQLValueFunction is stable. Hence, none of them are of interest here.
536  */
537 
538  /* Recurse to check arguments */
539  if (IsA(node, Query))
540  {
541  /* Recurse into subselects */
542  return query_tree_walker((Query *) node,
544  context, 0);
545  }
547  context);
548 }
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2355
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
Definition: nodes.h:539
bool check_functions_in_node(Node *node, check_function_callback checker, void *context)
Definition: nodeFuncs.c:1721
static bool contain_volatile_functions_walker(Node *node, void *context)
Definition: clauses.c:460
VolatileFunctionStatus has_volatile
Definition: pathnodes.h:2057
Expr * clause
Definition: pathnodes.h:2045
List * exprs
Definition: pathnodes.h:1102
VolatileFunctionStatus has_volatile_expr
Definition: pathnodes.h:1106
static bool contain_volatile_functions_checker(Oid func_id, void *context)
Definition: clauses.c:454
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1904

◆ contain_window_function()

bool contain_window_function ( Node clause)

Definition at line 208 of file clauses.c.

References contain_windowfuncs().

Referenced by get_eclass_for_sort_expr(), and qual_is_pushdown_safe().

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

◆ convert_saop_to_hashed_saop()

void convert_saop_to_hashed_saop ( Node node)

Definition at line 2122 of file clauses.c.

References convert_saop_to_hashed_saop_walker().

Referenced by preprocess_expression().

2123 {
2124  (void) convert_saop_to_hashed_saop_walker(node, NULL);
2125 }
static bool convert_saop_to_hashed_saop_walker(Node *node, void *context)
Definition: clauses.c:2128

◆ convert_saop_to_hashed_saop_walker()

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

Definition at line 2128 of file clauses.c.

References ScalarArrayOpExpr::args, ARR_DIMS, ARR_NDIM, ArrayGetNItems(), DatumGetPointer, expression_tree_walker(), get_op_hash_functions(), ScalarArrayOpExpr::hashfuncid, IsA, lsecond, MIN_ARRAY_SIZE_FOR_HASHED_SAOP, ScalarArrayOpExpr::opno, and ScalarArrayOpExpr::useOr.

Referenced by convert_saop_to_hashed_saop().

2129 {
2130  if (node == NULL)
2131  return false;
2132 
2133  if (IsA(node, ScalarArrayOpExpr))
2134  {
2135  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
2136  Expr *arrayarg = (Expr *) lsecond(saop->args);
2137  Oid lefthashfunc;
2138  Oid righthashfunc;
2139 
2140  if (saop->useOr && arrayarg && IsA(arrayarg, Const) &&
2141  !((Const *) arrayarg)->constisnull &&
2142  get_op_hash_functions(saop->opno, &lefthashfunc, &righthashfunc) &&
2143  lefthashfunc == righthashfunc)
2144  {
2145  Datum arrdatum = ((Const *) arrayarg)->constvalue;
2146  ArrayType *arr = (ArrayType *) DatumGetPointer(arrdatum);
2147  int nitems;
2148 
2149  /*
2150  * Only fill in the hash functions if the array looks large enough
2151  * for it to be worth hashing instead of doing a linear search.
2152  */
2153  nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr));
2154 
2155  if (nitems >= MIN_ARRAY_SIZE_FOR_HASHED_SAOP)
2156  {
2157  /* Looks good. Fill in the hash functions */
2158  saop->hashfuncid = lefthashfunc;
2159  }
2160  return true;
2161  }
2162  }
2163 
2165 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
bool get_op_hash_functions(Oid opno, RegProcedure *lhs_procno, RegProcedure *rhs_procno)
Definition: lsyscache.c:508
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:76
static bool convert_saop_to_hashed_saop_walker(Node *node, void *context)
Definition: clauses.c:2128
unsigned int Oid
Definition: postgres_ext.h:31
#define lsecond(l)
Definition: pg_list.h:179
#define ARR_DIMS(a)
Definition: array.h:287
uintptr_t Datum
Definition: postgres.h:411
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1904
#define ARR_NDIM(a)
Definition: array.h:283
#define DatumGetPointer(X)
Definition: postgres.h:593
#define MIN_ARRAY_SIZE_FOR_HASHED_SAOP
Definition: clauses.c:2105

◆ ece_function_is_safe()

static bool ece_function_is_safe ( Oid  funcid,
eval_const_expressions_context context 
)
static

Definition at line 3502 of file clauses.c.

References eval_const_expressions_context::estimate, and func_volatile().

Referenced by eval_const_expressions_mutator().

3503 {
3504  char provolatile = func_volatile(funcid);
3505 
3506  /*
3507  * Ordinarily we are only allowed to simplify immutable functions. But for
3508  * purposes of estimation, we consider it okay to simplify functions that
3509  * are merely stable; the risk that the result might change from planning
3510  * time to execution time is worth taking in preference to not being able
3511  * to estimate the value at all.
3512  */
3513  if (provolatile == PROVOLATILE_IMMUTABLE)
3514  return true;
3515  if (context->estimate && provolatile == PROVOLATILE_STABLE)
3516  return true;
3517  return false;
3518 }
char func_volatile(Oid funcid)
Definition: lsyscache.c:1751

◆ estimate_expression_value()

Node* estimate_expression_value ( PlannerInfo root,
Node node 
)

Definition at line 2186 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().

2187 {
2189 
2190  context.boundParams = root->glob->boundParams; /* bound Params */
2191  /* we do not need to mark the plan as depending on inlined functions */
2192  context.root = NULL;
2193  context.active_fns = NIL; /* nothing being recursively simplified */
2194  context.case_val = NULL; /* no CASE being examined */
2195  context.estimate = true; /* unsafe transformations OK */
2196  return eval_const_expressions_mutator(node, &context);
2197 }
#define NIL
Definition: pg_list.h:65
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2231
ParamListInfo boundParams
Definition: clauses.c:59
PlannerGlobal * glob
Definition: pathnodes.h:163
ParamListInfo boundParams
Definition: pathnodes.h:93

◆ eval_const_expressions()

Node* eval_const_expressions ( PlannerInfo root,
Node node 
)

Definition at line 2090 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(), DetachAddConstraintIfNeeded(), DoCopy(), expression_planner(), expression_planner_with_deps(), fetch_statentries_for_relation(), get_proposed_default_constraint(), get_relation_constraints(), get_relation_statistics(), preprocess_expression(), preprocess_function_rtes(), process_implied_equality(), RelationBuildPartitionKey(), RelationGetIndexExpressions(), RelationGetIndexPredicate(), and simplify_EXISTS_query().

2091 {
2093 
2094  if (root)
2095  context.boundParams = root->glob->boundParams; /* bound Params */
2096  else
2097  context.boundParams = NULL;
2098  context.root = root; /* for inlined-function dependencies */
2099  context.active_fns = NIL; /* nothing being recursively simplified */
2100  context.case_val = NULL; /* no CASE being examined */
2101  context.estimate = false; /* safe transformations only */
2102  return eval_const_expressions_mutator(node, &context);
2103 }
#define NIL
Definition: pg_list.h:65
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2231
ParamListInfo boundParams
Definition: clauses.c:59
PlannerGlobal * glob
Definition: pathnodes.h:163
ParamListInfo boundParams
Definition: pathnodes.h:93

◆ eval_const_expressions_mutator()

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

Definition at line 2231 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_NullIfExpr, 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().

2233 {
2234  if (node == NULL)
2235  return NULL;
2236  switch (nodeTag(node))
2237  {
2238  case T_Param:
2239  {
2240  Param *param = (Param *) node;
2241  ParamListInfo paramLI = context->boundParams;
2242 
2243  /* Look to see if we've been given a value for this Param */
2244  if (param->paramkind == PARAM_EXTERN &&
2245  paramLI != NULL &&
2246  param->paramid > 0 &&
2247  param->paramid <= paramLI->numParams)
2248  {
2249  ParamExternData *prm;
2250  ParamExternData prmdata;
2251 
2252  /*
2253  * Give hook a chance in case parameter is dynamic. Tell
2254  * it that this fetch is speculative, so it should avoid
2255  * erroring out if parameter is unavailable.
2256  */
2257  if (paramLI->paramFetch != NULL)
2258  prm = paramLI->paramFetch(paramLI, param->paramid,
2259  true, &prmdata);
2260  else
2261  prm = &paramLI->params[param->paramid - 1];
2262 
2263  /*
2264  * We don't just check OidIsValid, but insist that the
2265  * fetched type match the Param, just in case the hook did
2266  * something unexpected. No need to throw an error here
2267  * though; leave that for runtime.
2268  */
2269  if (OidIsValid(prm->ptype) &&
2270  prm->ptype == param->paramtype)
2271  {
2272  /* OK to substitute parameter value? */
2273  if (context->estimate ||
2274  (prm->pflags & PARAM_FLAG_CONST))
2275  {
2276  /*
2277  * Return a Const representing the param value.
2278  * Must copy pass-by-ref datatypes, since the
2279  * Param might be in a memory context
2280  * shorter-lived than our output plan should be.
2281  */
2282  int16 typLen;
2283  bool typByVal;
2284  Datum pval;
2285 
2286  get_typlenbyval(param->paramtype,
2287  &typLen, &typByVal);
2288  if (prm->isnull || typByVal)
2289  pval = prm->value;
2290  else
2291  pval = datumCopy(prm->value, typByVal, typLen);
2292  return (Node *) makeConst(param->paramtype,
2293  param->paramtypmod,
2294  param->paramcollid,
2295  (int) typLen,
2296  pval,
2297  prm->isnull,
2298  typByVal);
2299  }
2300  }
2301  }
2302 
2303  /*
2304  * Not replaceable, so just copy the Param (no need to
2305  * recurse)
2306  */
2307  return (Node *) copyObject(param);
2308  }
2309  case T_WindowFunc:
2310  {
2311  WindowFunc *expr = (WindowFunc *) node;
2312  Oid funcid = expr->winfnoid;
2313  List *args;
2314  Expr *aggfilter;
2315  HeapTuple func_tuple;
2316  WindowFunc *newexpr;
2317 
2318  /*
2319  * We can't really simplify a WindowFunc node, but we mustn't
2320  * just fall through to the default processing, because we
2321  * have to apply expand_function_arguments to its argument
2322  * list. That takes care of inserting default arguments and
2323  * expanding named-argument notation.
2324  */
2325  func_tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
2326  if (!HeapTupleIsValid(func_tuple))
2327  elog(ERROR, "cache lookup failed for function %u", funcid);
2328 
2329  args = expand_function_arguments(expr->args, expr->wintype,
2330  func_tuple);
2331 
2332  ReleaseSysCache(func_tuple);
2333 
2334  /* Now, recursively simplify the args (which are a List) */
2335  args = (List *)
2338  (void *) context);
2339  /* ... and the filter expression, which isn't */
2340  aggfilter = (Expr *)
2342  context);
2343 
2344  /* And build the replacement WindowFunc node */
2345  newexpr = makeNode(WindowFunc);
2346  newexpr->winfnoid = expr->winfnoid;
2347  newexpr->wintype = expr->wintype;
2348  newexpr->wincollid = expr->wincollid;
2349  newexpr->inputcollid = expr->inputcollid;
2350  newexpr->args = args;
2351  newexpr->aggfilter = aggfilter;
2352  newexpr->winref = expr->winref;
2353  newexpr->winstar = expr->winstar;
2354  newexpr->winagg = expr->winagg;
2355  newexpr->location = expr->location;
2356 
2357  return (Node *) newexpr;
2358  }
2359  case T_FuncExpr:
2360  {
2361  FuncExpr *expr = (FuncExpr *) node;
2362  List *args = expr->args;
2363  Expr *simple;
2364  FuncExpr *newexpr;
2365 
2366  /*
2367  * Code for op/func reduction is pretty bulky, so split it out
2368  * as a separate function. Note: exprTypmod normally returns
2369  * -1 for a FuncExpr, but not when the node is recognizably a
2370  * length coercion; we want to preserve the typmod in the
2371  * eventual Const if so.
2372  */
2373  simple = simplify_function(expr->funcid,
2374  expr->funcresulttype,
2375  exprTypmod(node),
2376  expr->funccollid,
2377  expr->inputcollid,
2378  &args,
2379  expr->funcvariadic,
2380  true,
2381  true,
2382  context);
2383  if (simple) /* successfully simplified it */
2384  return (Node *) simple;
2385 
2386  /*
2387  * The expression cannot be simplified any further, so build
2388  * and return a replacement FuncExpr node using the
2389  * possibly-simplified arguments. Note that we have also
2390  * converted the argument list to positional notation.
2391  */
2392  newexpr = makeNode(FuncExpr);
2393  newexpr->funcid = expr->funcid;
2394  newexpr->funcresulttype = expr->funcresulttype;
2395  newexpr->funcretset = expr->funcretset;
2396  newexpr->funcvariadic = expr->funcvariadic;
2397  newexpr->funcformat = expr->funcformat;
2398  newexpr->funccollid = expr->funccollid;
2399  newexpr->inputcollid = expr->inputcollid;
2400  newexpr->args = args;
2401  newexpr->location = expr->location;
2402  return (Node *) newexpr;
2403  }
2404  case T_OpExpr:
2405  {
2406  OpExpr *expr = (OpExpr *) node;
2407  List *args = expr->args;
2408  Expr *simple;
2409  OpExpr *newexpr;
2410 
2411  /*
2412  * Need to get OID of underlying function. Okay to scribble
2413  * on input to this extent.
2414  */
2415  set_opfuncid(expr);
2416 
2417  /*
2418  * Code for op/func reduction is pretty bulky, so split it out
2419  * as a separate function.
2420  */
2421  simple = simplify_function(expr->opfuncid,
2422  expr->opresulttype, -1,
2423  expr->opcollid,
2424  expr->inputcollid,
2425  &args,
2426  false,
2427  true,
2428  true,
2429  context);
2430  if (simple) /* successfully simplified it */
2431  return (Node *) simple;
2432 
2433  /*
2434  * If the operator is boolean equality or inequality, we know
2435  * how to simplify cases involving one constant and one
2436  * non-constant argument.
2437  */
2438  if (expr->opno == BooleanEqualOperator ||
2439  expr->opno == BooleanNotEqualOperator)
2440  {
2441  simple = (Expr *) simplify_boolean_equality(expr->opno,
2442  args);
2443  if (simple) /* successfully simplified it */
2444  return (Node *) simple;
2445  }
2446 
2447  /*
2448  * The expression cannot be simplified any further, so build
2449  * and return a replacement OpExpr node using the
2450  * possibly-simplified arguments.
2451  */
2452  newexpr = makeNode(OpExpr);
2453  newexpr->opno = expr->opno;
2454  newexpr->opfuncid = expr->opfuncid;
2455  newexpr->opresulttype = expr->opresulttype;
2456  newexpr->opretset = expr->opretset;
2457  newexpr->opcollid = expr->opcollid;
2458  newexpr->inputcollid = expr->inputcollid;
2459  newexpr->args = args;
2460  newexpr->location = expr->location;
2461  return (Node *) newexpr;
2462  }
2463  case T_DistinctExpr:
2464  {
2465  DistinctExpr *expr = (DistinctExpr *) node;
2466  List *args;
2467  ListCell *arg;
2468  bool has_null_input = false;
2469  bool all_null_input = true;
2470  bool has_nonconst_input = false;
2471  Expr *simple;
2472  DistinctExpr *newexpr;
2473 
2474  /*
2475  * Reduce constants in the DistinctExpr's arguments. We know
2476  * args is either NIL or a List node, so we can call
2477  * expression_tree_mutator directly rather than recursing to
2478  * self.
2479  */
2480  args = (List *) expression_tree_mutator((Node *) expr->args,
2482  (void *) context);
2483 
2484  /*
2485  * We must do our own check for NULLs because DistinctExpr has
2486  * different results for NULL input than the underlying
2487  * operator does.
2488  */
2489  foreach(arg, args)
2490  {
2491  if (IsA(lfirst(arg), Const))
2492  {
2493  has_null_input |= ((Const *) lfirst(arg))->constisnull;
2494  all_null_input &= ((Const *) lfirst(arg))->constisnull;
2495  }
2496  else
2497  has_nonconst_input = true;
2498  }
2499 
2500  /* all constants? then can optimize this out */
2501  if (!has_nonconst_input)
2502  {
2503  /* all nulls? then not distinct */
2504  if (all_null_input)
2505  return makeBoolConst(false, false);
2506 
2507  /* one null? then distinct */
2508  if (has_null_input)
2509  return makeBoolConst(true, false);
2510 
2511  /* otherwise try to evaluate the '=' operator */
2512  /* (NOT okay to try to inline it, though!) */
2513 
2514  /*
2515  * Need to get OID of underlying function. Okay to
2516  * scribble on input to this extent.
2517  */
2518  set_opfuncid((OpExpr *) expr); /* rely on struct
2519  * equivalence */
2520 
2521  /*
2522  * Code for op/func reduction is pretty bulky, so split it
2523  * out as a separate function.
2524  */
2525  simple = simplify_function(expr->opfuncid,
2526  expr->opresulttype, -1,
2527  expr->opcollid,
2528  expr->inputcollid,
2529  &args,
2530  false,
2531  false,
2532  false,
2533  context);
2534  if (simple) /* successfully simplified it */
2535  {
2536  /*
2537  * Since the underlying operator is "=", must negate
2538  * its result
2539  */
2540  Const *csimple = castNode(Const, simple);
2541 
2542  csimple->constvalue =
2543  BoolGetDatum(!DatumGetBool(csimple->constvalue));
2544  return (Node *) csimple;
2545  }
2546  }
2547 
2548  /*
2549  * The expression cannot be simplified any further, so build
2550  * and return a replacement DistinctExpr node using the
2551  * possibly-simplified arguments.
2552  */
2553  newexpr = makeNode(DistinctExpr);
2554  newexpr->opno = expr->opno;
2555  newexpr->opfuncid = expr->opfuncid;
2556  newexpr->opresulttype = expr->opresulttype;
2557  newexpr->opretset = expr->opretset;
2558  newexpr->opcollid = expr->opcollid;
2559  newexpr->inputcollid = expr->inputcollid;
2560  newexpr->args = args;
2561  newexpr->location = expr->location;
2562  return (Node *) newexpr;
2563  }
2564  case T_NullIfExpr:
2565  {
2566  NullIfExpr *expr;
2567  ListCell *arg;
2568  bool has_nonconst_input = false;
2569 
2570  /* Copy the node and const-simplify its arguments */
2571  expr = (NullIfExpr *) ece_generic_processing(node);
2572 
2573  /* If either argument is NULL they can't be equal */
2574  foreach(arg, expr->args)
2575  {
2576  if (!IsA(lfirst(arg), Const))
2577  has_nonconst_input = true;
2578  else if (((Const *) lfirst(arg))->constisnull)
2579  return (Node *) linitial(expr->args);
2580  }
2581 
2582  /*
2583  * Need to get OID of underlying function before checking if
2584  * the function is OK to evaluate.
2585  */
2586  set_opfuncid((OpExpr *) expr);
2587 
2588  if (!has_nonconst_input &&
2589  ece_function_is_safe(expr->opfuncid, context))
2590  return ece_evaluate_expr(expr);
2591 
2592  return (Node *) expr;
2593  }
2594  case T_ScalarArrayOpExpr:
2595  {
2596  ScalarArrayOpExpr *saop;
2597 
2598  /* Copy the node and const-simplify its arguments */
2599  saop = (ScalarArrayOpExpr *) ece_generic_processing(node);
2600 
2601  /* Make sure we know underlying function */
2602  set_sa_opfuncid(saop);
2603 
2604  /*
2605  * If all arguments are Consts, and it's a safe function, we
2606  * can fold to a constant
2607  */
2608  if (ece_all_arguments_const(saop) &&
2609  ece_function_is_safe(saop->opfuncid, context))
2610  return ece_evaluate_expr(saop);
2611  return (Node *) saop;
2612  }
2613  case T_BoolExpr:
2614  {
2615  BoolExpr *expr = (BoolExpr *) node;
2616 
2617  switch (expr->boolop)
2618  {
2619  case OR_EXPR:
2620  {
2621  List *newargs;
2622  bool haveNull = false;
2623  bool forceTrue = false;
2624 
2625  newargs = simplify_or_arguments(expr->args,
2626  context,
2627  &haveNull,
2628  &forceTrue);
2629  if (forceTrue)
2630  return makeBoolConst(true, false);
2631  if (haveNull)
2632  newargs = lappend(newargs,
2633  makeBoolConst(false, true));
2634  /* If all the inputs are FALSE, result is FALSE */
2635  if (newargs == NIL)
2636  return makeBoolConst(false, false);
2637 
2638  /*
2639  * If only one nonconst-or-NULL input, it's the
2640  * result
2641  */
2642  if (list_length(newargs) == 1)
2643  return (Node *) linitial(newargs);
2644  /* Else we still need an OR node */
2645  return (Node *) make_orclause(newargs);
2646  }
2647  case AND_EXPR:
2648  {
2649  List *newargs;
2650  bool haveNull = false;
2651  bool forceFalse = false;
2652 
2653  newargs = simplify_and_arguments(expr->args,
2654  context,
2655  &haveNull,
2656  &forceFalse);
2657  if (forceFalse)
2658  return makeBoolConst(false, false);
2659  if (haveNull)
2660  newargs = lappend(newargs,
2661  makeBoolConst(false, true));
2662  /* If all the inputs are TRUE, result is TRUE */
2663  if (newargs == NIL)
2664  return makeBoolConst(true, false);
2665 
2666  /*
2667  * If only one nonconst-or-NULL input, it's the
2668  * result
2669  */
2670  if (list_length(newargs) == 1)
2671  return (Node *) linitial(newargs);
2672  /* Else we still need an AND node */
2673  return (Node *) make_andclause(newargs);
2674  }
2675  case NOT_EXPR:
2676  {
2677  Node *arg;
2678 
2679  Assert(list_length(expr->args) == 1);
2681  context);
2682 
2683  /*
2684  * Use negate_clause() to see if we can simplify
2685  * away the NOT.
2686  */
2687  return negate_clause(arg);
2688  }
2689  default:
2690  elog(ERROR, "unrecognized boolop: %d",
2691  (int) expr->boolop);
2692  break;
2693  }
2694  break;
2695  }
2696  case T_SubPlan:
2697  case T_AlternativeSubPlan:
2698 
2699  /*
2700  * Return a SubPlan unchanged --- too late to do anything with it.
2701  *
2702  * XXX should we ereport() here instead? Probably this routine
2703  * should never be invoked after SubPlan creation.
2704  */
2705  return node;
2706  case T_RelabelType:
2707  {
2708  RelabelType *relabel = (RelabelType *) node;
2709  Node *arg;
2710 
2711  /* Simplify the input ... */
2712  arg = eval_const_expressions_mutator((Node *) relabel->arg,
2713  context);
2714  /* ... and attach a new RelabelType node, if needed */
2715  return applyRelabelType(arg,
2716  relabel->resulttype,
2717  relabel->resulttypmod,
2718  relabel->resultcollid,
2719  relabel->relabelformat,
2720  relabel->location,
2721  true);
2722  }
2723  case T_CoerceViaIO:
2724  {
2725  CoerceViaIO *expr = (CoerceViaIO *) node;
2726  List *args;
2727  Oid outfunc;
2728  bool outtypisvarlena;
2729  Oid infunc;
2730  Oid intypioparam;
2731  Expr *simple;
2732  CoerceViaIO *newexpr;
2733 
2734  /* Make a List so we can use simplify_function */
2735  args = list_make1(expr->arg);
2736 
2737  /*
2738  * CoerceViaIO represents calling the source type's output
2739  * function then the result type's input function. So, try to
2740  * simplify it as though it were a stack of two such function
2741  * calls. First we need to know what the functions are.
2742  *
2743  * Note that the coercion functions are assumed not to care
2744  * about input collation, so we just pass InvalidOid for that.
2745  */
2746  getTypeOutputInfo(exprType((Node *) expr->arg),
2747  &outfunc, &outtypisvarlena);
2749  &infunc, &intypioparam);
2750 
2751  simple = simplify_function(outfunc,
2752  CSTRINGOID, -1,
2753  InvalidOid,
2754  InvalidOid,
2755  &args,
2756  false,
2757  true,
2758  true,
2759  context);
2760  if (simple) /* successfully simplified output fn */
2761  {
2762  /*
2763  * Input functions may want 1 to 3 arguments. We always
2764  * supply all three, trusting that nothing downstream will
2765  * complain.
2766  */
2767  args = list_make3(simple,
2768  makeConst(OIDOID,
2769  -1,
2770  InvalidOid,
2771  sizeof(Oid),
2772  ObjectIdGetDatum(intypioparam),
2773  false,
2774  true),
2775  makeConst(INT4OID,
2776  -1,
2777  InvalidOid,
2778  sizeof(int32),
2779  Int32GetDatum(-1),
2780  false,
2781  true));
2782 
2783  simple = simplify_function(infunc,
2784  expr->resulttype, -1,
2785  expr->resultcollid,
2786  InvalidOid,
2787  &args,
2788  false,
2789  false,
2790  true,
2791  context);
2792  if (simple) /* successfully simplified input fn */
2793  return (Node *) simple;
2794  }
2795 
2796  /*
2797  * The expression cannot be simplified any further, so build
2798  * and return a replacement CoerceViaIO node using the
2799  * possibly-simplified argument.
2800  */
2801  newexpr = makeNode(CoerceViaIO);
2802  newexpr->arg = (Expr *) linitial(args);
2803  newexpr->resulttype = expr->resulttype;
2804  newexpr->resultcollid = expr->resultcollid;
2805  newexpr->coerceformat = expr->coerceformat;
2806  newexpr->location = expr->location;
2807  return (Node *) newexpr;
2808  }
2809  case T_ArrayCoerceExpr:
2810  {
2812  Node *save_case_val;
2813 
2814  /*
2815  * Copy the node and const-simplify its arguments. We can't
2816  * use ece_generic_processing() here because we need to mess
2817  * with case_val only while processing the elemexpr.
2818  */
2819  memcpy(ac, node, sizeof(ArrayCoerceExpr));
2820  ac->arg = (Expr *)
2822  context);
2823 
2824  /*
2825  * Set up for the CaseTestExpr node contained in the elemexpr.
2826  * We must prevent it from absorbing any outer CASE value.
2827  */
2828  save_case_val = context->case_val;
2829  context->case_val = NULL;
2830 
2831  ac->elemexpr = (Expr *)
2833  context);
2834 
2835  context->case_val = save_case_val;
2836 
2837  /*
2838  * If constant argument and the per-element expression is
2839  * immutable, we can simplify the whole thing to a constant.
2840  * Exception: although contain_mutable_functions considers
2841  * CoerceToDomain immutable for historical reasons, let's not
2842  * do so here; this ensures coercion to an array-over-domain
2843  * does not apply the domain's constraints until runtime.
2844  */
2845  if (ac->arg && IsA(ac->arg, Const) &&
2846  ac->elemexpr && !IsA(ac->elemexpr, CoerceToDomain) &&
2848  return ece_evaluate_expr(ac);
2849 
2850  return (Node *) ac;
2851  }
2852  case T_CollateExpr:
2853  {
2854  /*
2855  * We replace CollateExpr with RelabelType, so as to improve
2856  * uniformity of expression representation and thus simplify
2857  * comparison of expressions. Hence this looks very nearly
2858  * the same as the RelabelType case, and we can apply the same
2859  * optimizations to avoid unnecessary RelabelTypes.
2860  */
2861  CollateExpr *collate = (CollateExpr *) node;
2862  Node *arg;
2863 
2864  /* Simplify the input ... */
2865  arg = eval_const_expressions_mutator((Node *) collate->arg,
2866  context);
2867  /* ... and attach a new RelabelType node, if needed */
2868  return applyRelabelType(arg,
2869  exprType(arg),
2870  exprTypmod(arg),
2871  collate->collOid,
2873  collate->location,
2874  true);
2875  }
2876  case T_CaseExpr:
2877  {
2878  /*----------
2879  * CASE expressions can be simplified if there are constant
2880  * condition clauses:
2881  * FALSE (or NULL): drop the alternative
2882  * TRUE: drop all remaining alternatives
2883  * If the first non-FALSE alternative is a constant TRUE,
2884  * we can simplify the entire CASE to that alternative's
2885  * expression. If there are no non-FALSE alternatives,
2886  * we simplify the entire CASE to the default result (ELSE).
2887  *
2888  * If we have a simple-form CASE with constant test
2889  * expression, we substitute the constant value for contained
2890  * CaseTestExpr placeholder nodes, so that we have the
2891  * opportunity to reduce constant test conditions. For
2892  * example this allows
2893  * CASE 0 WHEN 0 THEN 1 ELSE 1/0 END
2894  * to reduce to 1 rather than drawing a divide-by-0 error.
2895  * Note that when the test expression is constant, we don't
2896  * have to include it in the resulting CASE; for example
2897  * CASE 0 WHEN x THEN y ELSE z END
2898  * is transformed by the parser to
2899  * CASE 0 WHEN CaseTestExpr = x THEN y ELSE z END
2900  * which we can simplify to
2901  * CASE WHEN 0 = x THEN y ELSE z END
2902  * It is not necessary for the executor to evaluate the "arg"
2903  * expression when executing the CASE, since any contained
2904  * CaseTestExprs that might have referred to it will have been
2905  * replaced by the constant.
2906  *----------
2907  */
2908  CaseExpr *caseexpr = (CaseExpr *) node;
2909  CaseExpr *newcase;
2910  Node *save_case_val;
2911  Node *newarg;
2912  List *newargs;
2913  bool const_true_cond;
2914  Node *defresult = NULL;
2915  ListCell *arg;
2916 
2917  /* Simplify the test expression, if any */
2918  newarg = eval_const_expressions_mutator((Node *) caseexpr->arg,
2919  context);
2920 
2921  /* Set up for contained CaseTestExpr nodes */
2922  save_case_val = context->case_val;
2923  if (newarg && IsA(newarg, Const))
2924  {
2925  context->case_val = newarg;
2926  newarg = NULL; /* not needed anymore, see above */
2927  }
2928  else
2929  context->case_val = NULL;
2930 
2931  /* Simplify the WHEN clauses */
2932  newargs = NIL;
2933  const_true_cond = false;
2934  foreach(arg, caseexpr->args)
2935  {
2936  CaseWhen *oldcasewhen = lfirst_node(CaseWhen, arg);
2937  Node *casecond;
2938  Node *caseresult;
2939 
2940  /* Simplify this alternative's test condition */
2941  casecond = eval_const_expressions_mutator((Node *) oldcasewhen->expr,
2942  context);
2943 
2944  /*
2945  * If the test condition is constant FALSE (or NULL), then
2946  * drop this WHEN clause completely, without processing
2947  * the result.
2948  */
2949  if (casecond && IsA(casecond, Const))
2950  {
2951  Const *const_input = (Const *) casecond;
2952 
2953  if (const_input->constisnull ||
2954  !DatumGetBool(const_input->constvalue))
2955  continue; /* drop alternative with FALSE cond */
2956  /* Else it's constant TRUE */
2957  const_true_cond = true;
2958  }
2959 
2960  /* Simplify this alternative's result value */
2961  caseresult = eval_const_expressions_mutator((Node *) oldcasewhen->result,
2962  context);
2963 
2964  /* If non-constant test condition, emit a new WHEN node */
2965  if (!const_true_cond)
2966  {
2967  CaseWhen *newcasewhen = makeNode(CaseWhen);
2968 
2969  newcasewhen->expr = (Expr *) casecond;
2970  newcasewhen->result = (Expr *) caseresult;
2971  newcasewhen->location = oldcasewhen->location;
2972  newargs = lappend(newargs, newcasewhen);
2973  continue;
2974  }
2975 
2976  /*
2977  * Found a TRUE condition, so none of the remaining
2978  * alternatives can be reached. We treat the result as
2979  * the default result.
2980  */
2981  defresult = caseresult;
2982  break;
2983  }
2984 
2985  /* Simplify the default result, unless we replaced it above */
2986  if (!const_true_cond)
2987  defresult = eval_const_expressions_mutator((Node *) caseexpr->defresult,
2988  context);
2989 
2990  context->case_val = save_case_val;
2991 
2992  /*
2993  * If no non-FALSE alternatives, CASE reduces to the default
2994  * result
2995  */
2996  if (newargs == NIL)
2997  return defresult;
2998  /* Otherwise we need a new CASE node */
2999  newcase = makeNode(CaseExpr);
3000  newcase->casetype = caseexpr->casetype;
3001  newcase->casecollid = caseexpr->casecollid;
3002  newcase->arg = (Expr *) newarg;
3003  newcase->args = newargs;
3004  newcase->defresult = (Expr *) defresult;
3005  newcase->location = caseexpr->location;
3006  return (Node *) newcase;
3007  }
3008  case T_CaseTestExpr:
3009  {
3010  /*
3011  * If we know a constant test value for the current CASE
3012  * construct, substitute it for the placeholder. Else just
3013  * return the placeholder as-is.
3014  */
3015  if (context->case_val)
3016  return copyObject(context->case_val);
3017  else
3018  return copyObject(node);
3019  }
3020  case T_SubscriptingRef:
3021  case T_ArrayExpr:
3022  case T_RowExpr:
3023  case T_MinMaxExpr:
3024  {
3025  /*
3026  * Generic handling for node types whose own processing is
3027  * known to be immutable, and for which we need no smarts
3028  * beyond "simplify if all inputs are constants".
3029  *
3030  * Treating SubscriptingRef this way assumes that subscripting
3031  * fetch and assignment are both immutable. This constrains
3032  * type-specific subscripting implementations; maybe we should
3033  * relax it someday.
3034  *
3035  * Treating MinMaxExpr this way amounts to assuming that the
3036  * btree comparison function it calls is immutable; see the
3037  * reasoning in contain_mutable_functions_walker.
3038  */
3039 
3040  /* Copy the node and const-simplify its arguments */
3041  node = ece_generic_processing(node);
3042  /* If all arguments are Consts, we can fold to a constant */
3043  if (ece_all_arguments_const(node))
3044  return ece_evaluate_expr(node);
3045  return node;
3046  }
3047  case T_CoalesceExpr:
3048  {
3049  CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
3050  CoalesceExpr *newcoalesce;
3051  List *newargs;
3052  ListCell *arg;
3053 
3054  newargs = NIL;
3055  foreach(arg, coalesceexpr->args)
3056  {
3057  Node *e;
3058 
3060  context);
3061 
3062  /*
3063  * We can remove null constants from the list. For a
3064  * non-null constant, if it has not been preceded by any
3065  * other non-null-constant expressions then it is the
3066  * result. Otherwise, it's the next argument, but we can
3067  * drop following arguments since they will never be
3068  * reached.
3069  */
3070  if (IsA(e, Const))
3071  {
3072  if (((Const *) e)->constisnull)
3073  continue; /* drop null constant */
3074  if (newargs == NIL)
3075  return e; /* first expr */
3076  newargs = lappend(newargs, e);
3077  break;
3078  }
3079  newargs = lappend(newargs, e);
3080  }
3081 
3082  /*
3083  * If all the arguments were constant null, the result is just
3084  * null
3085  */
3086  if (newargs == NIL)
3087  return (Node *) makeNullConst(coalesceexpr->coalescetype,
3088  -1,
3089  coalesceexpr->coalescecollid);
3090 
3091  newcoalesce = makeNode(CoalesceExpr);
3092  newcoalesce->coalescetype = coalesceexpr->coalescetype;
3093  newcoalesce->coalescecollid = coalesceexpr->coalescecollid;
3094  newcoalesce->args = newargs;
3095  newcoalesce->location = coalesceexpr->location;
3096  return (Node *) newcoalesce;
3097  }
3098  case T_SQLValueFunction:
3099  {
3100  /*
3101  * All variants of SQLValueFunction are stable, so if we are
3102  * estimating the expression's value, we should evaluate the
3103  * current function value. Otherwise just copy.
3104  */
3105  SQLValueFunction *svf = (SQLValueFunction *) node;
3106 
3107  if (context->estimate)
3108  return (Node *) evaluate_expr((Expr *) svf,
3109  svf->type,
3110  svf->typmod,
3111  InvalidOid);
3112  else
3113  return copyObject((Node *) svf);
3114  }
3115  case T_FieldSelect:
3116  {
3117  /*
3118  * We can optimize field selection from a whole-row Var into a
3119  * simple Var. (This case won't be generated directly by the
3120  * parser, because ParseComplexProjection short-circuits it.
3121  * But it can arise while simplifying functions.) Also, we
3122  * can optimize field selection from a RowExpr construct, or
3123  * of course from a constant.
3124  *
3125  * However, replacing a whole-row Var in this way has a
3126  * pitfall: if we've already built the rel targetlist for the
3127  * source relation, then the whole-row Var is scheduled to be
3128  * produced by the relation scan, but the simple Var probably
3129  * isn't, which will lead to a failure in setrefs.c. This is
3130  * not a problem when handling simple single-level queries, in
3131  * which expression simplification always happens first. It
3132  * is a risk for lateral references from subqueries, though.
3133  * To avoid such failures, don't optimize uplevel references.
3134  *
3135  * We must also check that the declared type of the field is
3136  * still the same as when the FieldSelect was created --- this
3137  * can change if someone did ALTER COLUMN TYPE on the rowtype.
3138  * If it isn't, we skip the optimization; the case will
3139  * probably fail at runtime, but that's not our problem here.
3140  */
3141  FieldSelect *fselect = (FieldSelect *) node;
3142  FieldSelect *newfselect;
3143  Node *arg;
3144 
3145  arg = eval_const_expressions_mutator((Node *) fselect->arg,
3146  context);
3147  if (arg && IsA(arg, Var) &&
3148  ((Var *) arg)->varattno == InvalidAttrNumber &&
3149  ((Var *) arg)->varlevelsup == 0)
3150  {
3151  if (rowtype_field_matches(((Var *) arg)->vartype,
3152  fselect->fieldnum,
3153  fselect->resulttype,
3154  fselect->resulttypmod,
3155  fselect->resultcollid))
3156  return (Node *) makeVar(((Var *) arg)->varno,
3157  fselect->fieldnum,
3158  fselect->resulttype,
3159  fselect->resulttypmod,
3160  fselect->resultcollid,
3161  ((Var *) arg)->varlevelsup);
3162  }
3163  if (arg && IsA(arg, RowExpr))
3164  {
3165  RowExpr *rowexpr = (RowExpr *) arg;
3166 
3167  if (fselect->fieldnum > 0 &&
3168  fselect->fieldnum <= list_length(rowexpr->args))
3169  {
3170  Node *fld = (Node *) list_nth(rowexpr->args,
3171  fselect->fieldnum - 1);
3172 
3173  if (rowtype_field_matches(rowexpr->row_typeid,
3174  fselect->fieldnum,
3175  fselect->resulttype,
3176  fselect->resulttypmod,
3177  fselect->resultcollid) &&
3178  fselect->resulttype == exprType(fld) &&
3179  fselect->resulttypmod == exprTypmod(fld) &&
3180  fselect->resultcollid == exprCollation(fld))
3181  return fld;
3182  }
3183  }
3184  newfselect = makeNode(FieldSelect);
3185  newfselect->arg = (Expr *) arg;
3186  newfselect->fieldnum = fselect->fieldnum;
3187  newfselect->resulttype = fselect->resulttype;
3188  newfselect->resulttypmod = fselect->resulttypmod;
3189  newfselect->resultcollid = fselect->resultcollid;
3190  if (arg && IsA(arg, Const))
3191  {
3192  Const *con = (Const *) arg;
3193 
3195  newfselect->fieldnum,
3196  newfselect->resulttype,
3197  newfselect->resulttypmod,
3198  newfselect->resultcollid))
3199  return ece_evaluate_expr(newfselect);
3200  }
3201  return (Node *) newfselect;
3202  }
3203  case T_NullTest:
3204  {
3205  NullTest *ntest = (NullTest *) node;
3206  NullTest *newntest;
3207  Node *arg;
3208 
3209  arg = eval_const_expressions_mutator((Node *) ntest->arg,
3210  context);
3211  if (ntest->argisrow && arg && IsA(arg, RowExpr))
3212  {
3213  /*
3214  * We break ROW(...) IS [NOT] NULL into separate tests on
3215  * its component fields. This form is usually more
3216  * efficient to evaluate, as well as being more amenable
3217  * to optimization.
3218  */
3219  RowExpr *rarg = (RowExpr *) arg;
3220  List *newargs = NIL;
3221  ListCell *l;
3222 
3223  foreach(l, rarg->args)
3224  {
3225  Node *relem = (Node *) lfirst(l);
3226 
3227  /*
3228  * A constant field refutes the whole NullTest if it's
3229  * of the wrong nullness; else we can discard it.
3230  */
3231  if (relem && IsA(relem, Const))
3232  {
3233  Const *carg = (Const *) relem;
3234 
3235  if (carg->constisnull ?
3236  (ntest->nulltesttype == IS_NOT_NULL) :
3237  (ntest->nulltesttype == IS_NULL))
3238  return makeBoolConst(false, false);
3239  continue;
3240  }
3241 
3242  /*
3243  * Else, make a scalar (argisrow == false) NullTest
3244  * for this field. Scalar semantics are required
3245  * because IS [NOT] NULL doesn't recurse; see comments
3246  * in ExecEvalRowNullInt().
3247  */
3248  newntest = makeNode(NullTest);
3249  newntest->arg = (Expr *) relem;
3250  newntest->nulltesttype = ntest->nulltesttype;
3251  newntest->argisrow = false;
3252  newntest->location = ntest->location;
3253  newargs = lappend(newargs, newntest);
3254  }
3255  /* If all the inputs were constants, result is TRUE */
3256  if (newargs == NIL)
3257  return makeBoolConst(true, false);
3258  /* If only one nonconst input, it's the result */
3259  if (list_length(newargs) == 1)
3260  return (Node *) linitial(newargs);
3261  /* Else we need an AND node */
3262  return (Node *) make_andclause(newargs);
3263  }
3264  if (!ntest->argisrow && arg && IsA(arg, Const))
3265  {
3266  Const *carg = (Const *) arg;
3267  bool result;
3268 
3269  switch (ntest->nulltesttype)
3270  {
3271  case IS_NULL:
3272  result = carg->constisnull;
3273  break;
3274  case IS_NOT_NULL:
3275  result = !carg->constisnull;
3276  break;
3277  default:
3278  elog(ERROR, "unrecognized nulltesttype: %d",
3279  (int) ntest->nulltesttype);
3280  result = false; /* keep compiler quiet */
3281  break;
3282  }
3283 
3284  return makeBoolConst(result, false);
3285  }
3286 
3287  newntest = makeNode(NullTest);
3288  newntest->arg = (Expr *) arg;
3289  newntest->nulltesttype = ntest->nulltesttype;
3290  newntest->argisrow = ntest->argisrow;
3291  newntest->location = ntest->location;
3292  return (Node *) newntest;
3293  }
3294  case T_BooleanTest:
3295  {
3296  /*
3297  * This case could be folded into the generic handling used
3298  * for ArrayExpr etc. But because the simplification logic is
3299  * so trivial, applying evaluate_expr() to perform it would be
3300  * a heavy overhead. BooleanTest is probably common enough to
3301  * justify keeping this bespoke implementation.
3302  */
3303  BooleanTest *btest = (BooleanTest *) node;
3304  BooleanTest *newbtest;
3305  Node *arg;
3306 
3307  arg = eval_const_expressions_mutator((Node *) btest->arg,
3308  context);
3309  if (arg && IsA(arg, Const))
3310  {
3311  Const *carg = (Const *) arg;
3312  bool result;
3313 
3314  switch (btest->booltesttype)
3315  {
3316  case IS_TRUE:
3317  result = (!carg->constisnull &&
3318  DatumGetBool(carg->constvalue));
3319  break;
3320  case IS_NOT_TRUE:
3321  result = (carg->constisnull ||
3322  !DatumGetBool(carg->constvalue));
3323  break;
3324  case IS_FALSE:
3325  result = (!carg->constisnull &&
3326  !DatumGetBool(carg->constvalue));
3327  break;
3328  case IS_NOT_FALSE:
3329  result = (carg->constisnull ||
3330  DatumGetBool(carg->constvalue));
3331  break;
3332  case IS_UNKNOWN:
3333  result = carg->constisnull;
3334  break;
3335  case IS_NOT_UNKNOWN:
3336  result = !carg->constisnull;
3337  break;
3338  default:
3339  elog(ERROR, "unrecognized booltesttype: %d",
3340  (int) btest->booltesttype);
3341  result = false; /* keep compiler quiet */
3342  break;
3343  }
3344 
3345  return makeBoolConst(result, false);
3346  }
3347 
3348  newbtest = makeNode(BooleanTest);
3349  newbtest->arg = (Expr *) arg;
3350  newbtest->booltesttype = btest->booltesttype;
3351  newbtest->location = btest->location;
3352  return (Node *) newbtest;
3353  }
3354  case T_CoerceToDomain:
3355  {
3356  /*
3357  * If the domain currently has no constraints, we replace the
3358  * CoerceToDomain node with a simple RelabelType, which is
3359  * both far faster to execute and more amenable to later
3360  * optimization. We must then mark the plan as needing to be
3361  * rebuilt if the domain's constraints change.
3362  *
3363  * Also, in estimation mode, always replace CoerceToDomain
3364  * nodes, effectively assuming that the coercion will succeed.
3365  */
3366  CoerceToDomain *cdomain = (CoerceToDomain *) node;
3367  CoerceToDomain *newcdomain;
3368  Node *arg;
3369 
3370  arg = eval_const_expressions_mutator((Node *) cdomain->arg,
3371  context);
3372  if (context->estimate ||
3373  !DomainHasConstraints(cdomain->resulttype))
3374  {
3375  /* Record dependency, if this isn't estimation mode */
3376  if (context->root && !context->estimate)
3377  record_plan_type_dependency(context->root,
3378  cdomain->resulttype);
3379 
3380  /* Generate RelabelType to substitute for CoerceToDomain */
3381  return applyRelabelType(arg,
3382  cdomain->resulttype,
3383  cdomain->resulttypmod,
3384  cdomain->resultcollid,
3385  cdomain->coercionformat,
3386  cdomain->location,
3387  true);
3388  }
3389 
3390  newcdomain = makeNode(CoerceToDomain);
3391  newcdomain->arg = (Expr *) arg;
3392  newcdomain->resulttype = cdomain->resulttype;
3393  newcdomain->resulttypmod = cdomain->resulttypmod;
3394  newcdomain->resultcollid = cdomain->resultcollid;
3395  newcdomain->coercionformat = cdomain->coercionformat;
3396  newcdomain->location = cdomain->location;
3397  return (Node *) newcdomain;
3398  }
3399  case T_PlaceHolderVar:
3400 
3401  /*
3402  * In estimation mode, just strip the PlaceHolderVar node
3403  * altogether; this amounts to estimating that the contained value
3404  * won't be forced to null by an outer join. In regular mode we
3405  * just use the default behavior (ie, simplify the expression but
3406  * leave the PlaceHolderVar node intact).
3407  */
3408  if (context->estimate)
3409  {
3410  PlaceHolderVar *phv = (PlaceHolderVar *) node;
3411 
3412  return eval_const_expressions_mutator((Node *) phv->phexpr,
3413  context);
3414  }
3415  break;
3416  case T_ConvertRowtypeExpr:
3417  {
3419  Node *arg;
3420  ConvertRowtypeExpr *newcre;
3421 
3422  arg = eval_const_expressions_mutator((Node *) cre->arg,
3423  context);
3424 
3425  newcre = makeNode(ConvertRowtypeExpr);
3426  newcre->resulttype = cre->resulttype;
3427  newcre->convertformat = cre->convertformat;
3428  newcre->location = cre->location;
3429 
3430  /*
3431  * In case of a nested ConvertRowtypeExpr, we can convert the
3432  * leaf row directly to the topmost row format without any
3433  * intermediate conversions. (This works because
3434  * ConvertRowtypeExpr is used only for child->parent
3435  * conversion in inheritance trees, which works by exact match
3436  * of column name, and a column absent in an intermediate
3437  * result can't be present in the final result.)
3438  *
3439  * No need to check more than one level deep, because the
3440  * above recursion will have flattened anything else.
3441  */
3442  if (arg != NULL && IsA(arg, ConvertRowtypeExpr))
3443  {
3444  ConvertRowtypeExpr *argcre = (ConvertRowtypeExpr *) arg;
3445 
3446  arg = (Node *) argcre->arg;
3447 
3448  /*
3449  * Make sure an outer implicit conversion can't hide an
3450  * inner explicit one.
3451  */
3452  if (newcre->convertformat == COERCE_IMPLICIT_CAST)
3453  newcre->convertformat = argcre->convertformat;
3454  }
3455 
3456  newcre->arg = (Expr *) arg;
3457 
3458  if (arg != NULL && IsA(arg, Const))
3459  return ece_evaluate_expr((Node *) newcre);
3460  return (Node *) newcre;
3461  }
3462  default:
3463  break;
3464  }
3465 
3466  /*
3467  * For any node type not handled above, copy the node unchanged but
3468  * const-simplify its subexpressions. This is the correct thing for node
3469  * types whose behavior might change between planning and execution, such
3470  * as CurrentOfExpr. It's also a safe default for new node types not
3471  * known to this routine.
3472  */
3473  return ece_generic_processing(node);
3474 }
Datum constvalue
Definition: primnodes.h:219
#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:4680
signed short int16
Definition: c.h:428
Oid funcresulttype
Definition: primnodes.h:496
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:2208
List * args
Definition: primnodes.h:1058
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
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:3809
Node * negate_clause(Node *node)
Definition: prepqual.c:74
Node * expression_tree_mutator(Node *node, Node *(*mutator)(), void *context)
Definition: nodeFuncs.c:2598
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:3916
List * args
Definition: primnodes.h:390
List * args
Definition: primnodes.h:503
Oid wincollid
Definition: primnodes.h:388
int32 resulttypmod
Definition: primnodes.h:1297
Oid resulttype
Definition: primnodes.h:800
#define castNode(_type_, nodeptr)
Definition: nodes.h:608
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:501
Oid resulttype
Definition: primnodes.h:871
Oid casecollid
Definition: primnodes.h:967
Expr * arg
Definition: primnodes.h:850
ParamKind paramkind
Definition: primnodes.h:267
Definition: nodes.h:539
CoercionForm coercionformat
Definition: primnodes.h:1299
Expr * arg
Definition: primnodes.h:798
bool funcretset
Definition: primnodes.h:497
Oid casetype
Definition: primnodes.h:966
unsigned int Oid
Definition: postgres_ext.h:31
Expr * make_orclause(List *orclauses)
Definition: makefuncs.c:652
Index winref
Definition: primnodes.h:392
Definition: primnodes.h:186
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:2217
int location
Definition: primnodes.h:982
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:215
CoercionForm funcformat
Definition: primnodes.h:500
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2231
Oid opresulttype
Definition: primnodes.h:544
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:495
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
static bool rowtype_field_matches(Oid rowtypeid, int fieldnum, Oid expectedtype, int32 expectedtypmod, Oid expectedcollation)
Definition: clauses.c:2022
Oid paramcollid
Definition: primnodes.h:271
static void * list_nth(const List *list, int n)
Definition: pg_list.h:278
List * args
Definition: primnodes.h:1122
BoolExprType boolop
Definition: primnodes.h:615
Node * makeBoolConst(bool value, bool isnull)
Definition: makefuncs.c:357
Expr * arg
Definition: primnodes.h:1255
Oid resultcollid
Definition: primnodes.h:803
#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:549
Expr * arg
Definition: primnodes.h:1278
#define DatumGetBool(X)
Definition: postgres.h:437
Oid winfnoid
Definition: primnodes.h:386
Expr * arg
Definition: primnodes.h:870
Expr * elemexpr
Definition: primnodes.h:895
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2821
Oid opcollid
Definition: primnodes.h:546
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:969
BoolTestType booltesttype
Definition: primnodes.h:1279
uintptr_t Datum
Definition: postgres.h:411
CoercionForm convertformat
Definition: primnodes.h:922
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
Oid resultcollid
Definition: primnodes.h:873
Oid opfuncid
Definition: primnodes.h:543
Oid resulttype
Definition: primnodes.h:851
NullTestType nulltesttype
Definition: primnodes.h:1256
#define BoolGetDatum(X)
Definition: postgres.h:446
Oid resultcollid
Definition: primnodes.h:853
#define InvalidOid
Definition: postgres_ext.h:36
int32 paramtypmod
Definition: primnodes.h:270
#define makeNode(_type_)
Definition: nodes.h:587
static Node * simplify_boolean_equality(Oid opno, List *args)
Definition: clauses.c:3740
int location
Definition: primnodes.h:875
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
int location
Definition: primnodes.h:395
Oid inputcollid
Definition: primnodes.h:502
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
Expr * aggfilter
Definition: primnodes.h:391
int paramid
Definition: primnodes.h:268
uint16 pflags
Definition: params.h:94
int location
Definition: primnodes.h:1258
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:3646
Oid row_typeid
Definition: primnodes.h:1059
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:936
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2198
int location
Definition: primnodes.h:971
Oid inputcollid
Definition: primnodes.h:547
static bool ece_function_is_safe(Oid funcid, eval_const_expressions_context *context)
Definition: clauses.c:3502
Oid inputcollid
Definition: primnodes.h:389
List * args
Definition: primnodes.h:616
#define InvalidAttrNumber
Definition: attnum.h:23
#define nodeTag(nodeptr)
Definition: nodes.h:544
Oid wintype
Definition: primnodes.h:387
CoercionForm coerceformat
Definition: primnodes.h:874
static List * simplify_or_arguments(List *args, eval_const_expressions_context *context, bool *haveNull, bool *forceTrue)
Definition: clauses.c:3540
#define Int32GetDatum(X)
Definition: postgres.h:523
e
Definition: preproc-init.c:82
void set_opfuncid(OpExpr *opexpr)
Definition: nodeFuncs.c:1683
bool winagg
Definition: primnodes.h:394
#define elog(elevel,...)
Definition: elog.h:232
Oid coalescetype
Definition: primnodes.h:1120
void * arg
NodeTag type
Definition: primnodes.h:138
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:359
bool argisrow
Definition: primnodes.h:1257
int32 resulttypmod
Definition: primnodes.h:852
Expr * arg
Definition: primnodes.h:968
int location
Definition: primnodes.h:504
Oid opno
Definition: primnodes.h:542
Expr * result
Definition: primnodes.h:981
#define copyObject(obj)
Definition: nodes.h:655
List * args
Definition: primnodes.h:548
CoercionForm relabelformat
Definition: primnodes.h:854
Expr * defresult
Definition: primnodes.h:970
Expr * expr
Definition: primnodes.h:980
int location
Definition: primnodes.h:938
Definition: pg_list.h:50
bool isnull
Definition: params.h:93
void set_sa_opfuncid(ScalarArrayOpExpr *opexpr)
Definition: nodeFuncs.c:1694
Oid paramtype
Definition: primnodes.h:269
int location
Definition: primnodes.h:855
bool constisnull
Definition: primnodes.h:220
Oid coalescecollid
Definition: primnodes.h:1121
bool funcvariadic
Definition: primnodes.h:498
#define PARAM_FLAG_CONST
Definition: params.h:88
bool opretset
Definition: primnodes.h:545
int32 resulttypmod
Definition: primnodes.h:802
bool winstar
Definition: primnodes.h:393
void record_plan_type_dependency(PlannerInfo *root, Oid typid)
Definition: setrefs.c:2983
Definition: nodes.h:159
AttrNumber fieldnum
Definition: primnodes.h:799
#define ece_evaluate_expr(node)
Definition: clauses.c:2221

◆ evaluate_expr()

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

Definition at line 4680 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().

4682 {
4683  EState *estate;
4684  ExprState *exprstate;
4685  MemoryContext oldcontext;
4686  Datum const_val;
4687  bool const_is_null;
4688  int16 resultTypLen;
4689  bool resultTypByVal;
4690 
4691  /*
4692  * To use the executor, we need an EState.
4693  */
4694  estate = CreateExecutorState();
4695 
4696  /* We can use the estate's working context to avoid memory leaks. */
4697  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
4698 
4699  /* Make sure any opfuncids are filled in. */
4700  fix_opfuncids((Node *) expr);
4701 
4702  /*
4703  * Prepare expr for execution. (Note: we can't use ExecPrepareExpr
4704  * because it'd result in recursively invoking eval_const_expressions.)
4705  */
4706  exprstate = ExecInitExpr(expr, NULL);
4707 
4708  /*
4709  * And evaluate it.
4710  *
4711  * It is OK to use a default econtext because none of the ExecEvalExpr()
4712  * code used in this situation will use econtext. That might seem
4713  * fortuitous, but it's not so unreasonable --- a constant expression does
4714  * not depend on context, by definition, n'est ce pas?
4715  */
4716  const_val = ExecEvalExprSwitchContext(exprstate,
4717  GetPerTupleExprContext(estate),
4718  &const_is_null);
4719 
4720  /* Get info needed about result datatype */
4721  get_typlenbyval(result_type, &resultTypLen, &resultTypByVal);
4722 
4723  /* Get back to outer memory context */
4724  MemoryContextSwitchTo(oldcontext);
4725 
4726  /*
4727  * Must copy result out of sub-context used by expression eval.
4728  *
4729  * Also, if it's varlena, forcibly detoast it. This protects us against
4730  * storing TOAST pointers into plans that might outlive the referenced
4731  * data. (makeConst would handle detoasting anyway, but it's worth a few
4732  * extra lines here so that we can do the copy and detoast in one step.)
4733  */
4734  if (!const_is_null)
4735  {
4736  if (resultTypLen == -1)
4737  const_val = PointerGetDatum(PG_DETOAST_DATUM_COPY(const_val));
4738  else
4739  const_val = datumCopy(const_val, resultTypByVal, resultTypLen);
4740  }
4741 
4742  /* Release all the junk we just created */
4743  FreeExecutorState(estate);
4744 
4745  /*
4746  * Make the constant result node.
4747  */
4748  return (Expr *) makeConst(result_type, result_typmod, result_collation,
4749  resultTypLen,
4750  const_val, const_is_null,
4751  resultTypByVal);
4752 }
signed short int16
Definition: c.h:428
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:331
#define PG_DETOAST_DATUM_COPY(datum)
Definition: fmgr.h:242
#define PointerGetDatum(X)
Definition: postgres.h:600
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1652
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Definition: nodes.h:539
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:533
MemoryContext es_query_cxt
Definition: execnodes.h:599
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:411
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 4133 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().

4138 {
4139  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4140  bool has_nonconst_input = false;
4141  bool has_null_input = false;
4142  ListCell *arg;
4143  FuncExpr *newexpr;
4144 
4145  /*
4146  * Can't simplify if it returns a set.
4147  */
4148  if (funcform->proretset)
4149  return NULL;
4150 
4151  /*
4152  * Can't simplify if it returns RECORD. The immediate problem is that it
4153  * will be needing an expected tupdesc which we can't supply here.
4154  *
4155  * In the case where it has OUT parameters, it could get by without an
4156  * expected tupdesc, but we still have issues: get_expr_result_type()
4157  * doesn't know how to extract type info from a RECORD constant, and in
4158  * the case of a NULL function result there doesn't seem to be any clean
4159  * way to fix that. In view of the likelihood of there being still other
4160  * gotchas, seems best to leave the function call unreduced.
4161  */
4162  if (funcform->prorettype == RECORDOID)
4163  return NULL;
4164 
4165  /*
4166  * Check for constant inputs and especially constant-NULL inputs.
4167  */
4168  foreach(arg, args)
4169  {
4170  if (IsA(lfirst(arg), Const))
4171  has_null_input |= ((Const *) lfirst(arg))->constisnull;
4172  else
4173  has_nonconst_input = true;
4174  }
4175 
4176  /*
4177  * If the function is strict and has a constant-NULL input, it will never
4178  * be called at all, so we can replace the call by a NULL constant, even
4179  * if there are other inputs that aren't constant, and even if the
4180  * function is not otherwise immutable.
4181  */
4182  if (funcform->proisstrict && has_null_input)
4183  return (Expr *) makeNullConst(result_type, result_typmod,
4184  result_collid);
4185 
4186  /*
4187  * Otherwise, can simplify only if all inputs are constants. (For a
4188  * non-strict function, constant NULL inputs are treated the same as
4189  * constant non-NULL inputs.)
4190  */
4191  if (has_nonconst_input)
4192  return NULL;
4193 
4194  /*
4195  * Ordinarily we are only allowed to simplify immutable functions. But for
4196  * purposes of estimation, we consider it okay to simplify functions that
4197  * are merely stable; the risk that the result might change from planning
4198  * time to execution time is worth taking in preference to not being able
4199  * to estimate the value at all.
4200  */
4201  if (funcform->provolatile == PROVOLATILE_IMMUTABLE)
4202  /* okay */ ;
4203  else if (context->estimate && funcform->provolatile == PROVOLATILE_STABLE)
4204  /* okay */ ;
4205  else
4206  return NULL;
4207 
4208  /*
4209  * OK, looks like we can simplify this operator/function.
4210  *
4211  * Build a new FuncExpr node containing the already-simplified arguments.
4212  */
4213  newexpr = makeNode(FuncExpr);
4214  newexpr->funcid = funcid;
4215  newexpr->funcresulttype = result_type;
4216  newexpr->funcretset = false;
4217  newexpr->funcvariadic = funcvariadic;
4218  newexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
4219  newexpr->funccollid = result_collid; /* doesn't matter */
4220  newexpr->inputcollid = input_collid;
4221  newexpr->args = args;
4222  newexpr->location = -1;
4223 
4224  return evaluate_expr((Expr *) newexpr, result_type, result_typmod,
4225  result_collid);
4226 }
Expr * evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod, Oid result_collation)
Definition: clauses.c:4680
Oid funcresulttype
Definition: primnodes.h:496
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
List * args
Definition: primnodes.h:503
Oid funccollid
Definition: primnodes.h:501
bool funcretset
Definition: primnodes.h:497
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:337
CoercionForm funcformat
Definition: primnodes.h:500
Oid funcid
Definition: primnodes.h:495
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:136
#define makeNode(_type_)
Definition: nodes.h:587
Oid inputcollid
Definition: primnodes.h:502
#define lfirst(lc)
Definition: pg_list.h:169
void * arg
int location
Definition: primnodes.h:504
bool funcvariadic
Definition: primnodes.h:498

◆ expand_function_arguments()

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

Definition at line 3916 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().

3917 {
3918  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
3919  bool has_named_args = false;
3920  ListCell *lc;
3921 
3922  /* Do we have any named arguments? */
3923  foreach(lc, args)
3924  {
3925  Node *arg = (Node *) lfirst(lc);
3926 
3927  if (IsA(arg, NamedArgExpr))
3928  {
3929  has_named_args = true;
3930  break;
3931  }
3932  }
3933 
3934  /* If so, we must apply reorder_function_arguments */
3935  if (has_named_args)
3936  {
3937  args = reorder_function_arguments(args, func_tuple);
3938  /* Recheck argument types and add casts if needed */
3939  recheck_cast_function_args(args, result_type, func_tuple);
3940  }
3941  else if (list_length(args) < funcform->pronargs)
3942  {
3943  /* No named args, but we seem to be short some defaults */
3944  args = add_function_defaults(args, func_tuple);
3945  /* Recheck argument types and add casts if needed */
3946  recheck_cast_function_args(args, result_type, func_tuple);
3947  }
3948 
3949  return args;
3950 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
Definition: nodes.h:539
static void recheck_cast_function_args(List *args, Oid result_type, HeapTuple func_tuple)
Definition: clauses.c:4089
static List * add_function_defaults(List *args, HeapTuple func_tuple)
Definition: clauses.c:4029
static List * reorder_function_arguments(List *args, HeapTuple func_tuple)
Definition: clauses.c:3959
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:136
#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 283 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().

284 {
285  if (clause == NULL)
286  return 1.0;
287  if (IsA(clause, FuncExpr))
288  {
289  FuncExpr *expr = (FuncExpr *) clause;
290 
291  if (expr->funcretset)
292  return clamp_row_est(get_function_rows(root, expr->funcid, clause));
293  }
294  if (IsA(clause, OpExpr))
295  {
296  OpExpr *expr = (OpExpr *) clause;
297 
298  if (expr->opretset)
299  {
300  set_opfuncid(expr);
301  return clamp_row_est(get_function_rows(root, expr->opfuncid, clause));
302  }
303  }
304  return 1.0;
305 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
bool funcretset
Definition: primnodes.h:497
Oid funcid
Definition: primnodes.h:495
Oid opfuncid
Definition: primnodes.h:543
void set_opfuncid(OpExpr *opexpr)
Definition: nodeFuncs.c:1683
double clamp_row_est(double nrows)
Definition: costsize.c:199
bool opretset
Definition: primnodes.h:545
double get_function_rows(PlannerInfo *root, Oid funcid, Node *node)
Definition: plancat.c:2028

◆ fetch_function_defaults()

static List * fetch_function_defaults ( HeapTuple  func_tuple)
static

Definition at line 4054 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().

4055 {
4056  List *defaults;
4057  Datum proargdefaults;
4058  bool isnull;
4059  char *str;
4060 
4061  /* The error cases here shouldn't happen, but check anyway */
4062  proargdefaults = SysCacheGetAttr(PROCOID, func_tuple,
4063  Anum_pg_proc_proargdefaults,
4064  &isnull);
4065  if (isnull)
4066  elog(ERROR, "not enough default arguments");
4067  str = TextDatumGetCString(proargdefaults);
4068  defaults = castNode(List, stringToNode(str));
4069  pfree(str);
4070  return defaults;
4071 }
#define castNode(_type_, nodeptr)
Definition: nodes.h:608
void * stringToNode(const char *str)
Definition: read.c:89
void pfree(void *pointer)
Definition: mcxt.c:1169
#define ERROR
Definition: elog.h:46
#define TextDatumGetCString(d)
Definition: builtins.h:83
uintptr_t Datum
Definition: postgres.h:411
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1388
#define elog(elevel,...)
Definition: elog.h:232
Definition: pg_list.h:50

◆ find_forced_null_var()

Var* find_forced_null_var ( Node node)

Definition at line 1815 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().

1816 {
1817  if (node == NULL)
1818  return NULL;
1819  if (IsA(node, NullTest))
1820  {
1821  /* check for var IS NULL */
1822  NullTest *expr = (NullTest *) node;
1823 
1824  if (expr->nulltesttype == IS_NULL && !expr->argisrow)
1825  {
1826  Var *var = (Var *) expr->arg;
1827 
1828  if (var && IsA(var, Var) &&
1829  var->varlevelsup == 0)
1830  return var;
1831  }
1832  }
1833  else if (IsA(node, BooleanTest))
1834  {
1835  /* var IS UNKNOWN is equivalent to var IS NULL */
1836  BooleanTest *expr = (BooleanTest *) node;
1837 
1838  if (expr->booltesttype == IS_UNKNOWN)
1839  {
1840  Var *var = (Var *) expr->arg;
1841 
1842  if (var && IsA(var, Var) &&
1843  var->varlevelsup == 0)
1844  return var;
1845  }
1846  }
1847  return NULL;
1848 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
Index varlevelsup
Definition: primnodes.h:196
Definition: primnodes.h:186
Expr * arg
Definition: primnodes.h:1255
Expr * arg
Definition: primnodes.h:1278
BoolTestType booltesttype
Definition: primnodes.h:1279
NullTestType nulltesttype
Definition: primnodes.h:1256
bool argisrow
Definition: primnodes.h:1257

◆ find_forced_null_vars()

List* find_forced_null_vars ( Node node)

Definition at line 1756 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().

1757 {
1758  List *result = NIL;
1759  Var *var;
1760  ListCell *l;
1761 
1762  if (node == NULL)
1763  return NIL;
1764  /* Check single-clause cases using subroutine */
1765  var = find_forced_null_var(node);
1766  if (var)
1767  {
1768  result = list_make1(var);
1769  }
1770  /* Otherwise, handle AND-conditions */
1771  else if (IsA(node, List))
1772  {
1773  /*
1774  * At top level, we are examining an implicit-AND list: if any of the
1775  * arms produces FALSE-or-NULL then the result is FALSE-or-NULL.
1776  */
1777  foreach(l, (List *) node)
1778  {
1779  result = list_concat(result,
1781  }
1782  }
1783  else if (IsA(node, BoolExpr))
1784  {
1785  BoolExpr *expr = (BoolExpr *) node;
1786 
1787  /*
1788  * We don't bother considering the OR case, because it's fairly
1789  * unlikely anyone would write "v1 IS NULL OR v1 IS NULL". Likewise,
1790  * the NOT case isn't worth expending code on.
1791  */
1792  if (expr->boolop == AND_EXPR)
1793  {
1794  /* At top level we can just recurse (to the List case) */
1795  result = find_forced_null_vars((Node *) expr->args);
1796  }
1797  }
1798  return result;
1799 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
Definition: nodes.h:539
List * list_concat(List *list1, const List *list2)
Definition: list.c:530
Definition: primnodes.h:186
List * find_forced_null_vars(Node *node)
Definition: clauses.c:1756
#define list_make1(x1)
Definition: pg_list.h:206
BoolExprType boolop
Definition: primnodes.h:615
#define lfirst(lc)
Definition: pg_list.h:169
List * args
Definition: primnodes.h:616
Definition: pg_list.h:50
Var * find_forced_null_var(Node *node)
Definition: clauses.c:1815

◆ find_nonnullable_rels()

Relids find_nonnullable_rels ( Node clause)

Definition at line 1338 of file clauses.c.

References find_nonnullable_rels_walker().

Referenced by make_outerjoininfo(), and reduce_outer_joins_pass2().

1339 {
1340  return find_nonnullable_rels_walker(clause, true);
1341 }
static Relids find_nonnullable_rels_walker(Node *node, bool top_level)
Definition: clauses.c:1344

◆ find_nonnullable_rels_walker()

static Relids find_nonnullable_rels_walker ( Node node,
bool  top_level 
)
static

Definition at line 1344 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().

1345 {
1346  Relids result = NULL;
1347  ListCell *l;
1348 
1349  if (node == NULL)
1350  return NULL;
1351  if (IsA(node, Var))
1352  {
1353  Var *var = (Var *) node;
1354 
1355  if (var->varlevelsup == 0)
1356  result = bms_make_singleton(var->varno);
1357  }
1358  else if (IsA(node, List))
1359  {
1360  /*
1361  * At top level, we are examining an implicit-AND list: if any of the
1362  * arms produces FALSE-or-NULL then the result is FALSE-or-NULL. If
1363  * not at top level, we are examining the arguments of a strict
1364  * function: if any of them produce NULL then the result of the
1365  * function must be NULL. So in both cases, the set of nonnullable
1366  * rels is the union of those found in the arms, and we pass down the
1367  * top_level flag unmodified.
1368  */
1369  foreach(l, (List *) node)
1370  {
1371  result = bms_join(result,
1373  top_level));
1374  }
1375  }
1376  else if (IsA(node, FuncExpr))
1377  {
1378  FuncExpr *expr = (FuncExpr *) node;
1379 
1380  if (func_strict(expr->funcid))
1381  result = find_nonnullable_rels_walker((Node *) expr->args, false);
1382  }
1383  else if (IsA(node, OpExpr))
1384  {
1385  OpExpr *expr = (OpExpr *) node;
1386 
1387  set_opfuncid(expr);
1388  if (func_strict(expr->opfuncid))
1389  result = find_nonnullable_rels_walker((Node *) expr->args, false);
1390  }
1391  else if (IsA(node, ScalarArrayOpExpr))
1392  {
1393  ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1394 
1395  if (is_strict_saop(expr, true))
1396  result = find_nonnullable_rels_walker((Node *) expr->args, false);
1397  }
1398  else if (IsA(node, BoolExpr))
1399  {
1400  BoolExpr *expr = (BoolExpr *) node;
1401 
1402  switch (expr->boolop)
1403  {
1404  case AND_EXPR:
1405  /* At top level we can just recurse (to the List case) */
1406  if (top_level)
1407  {
1408  result = find_nonnullable_rels_walker((Node *) expr->args,
1409  top_level);
1410  break;
1411  }
1412 
1413  /*
1414  * Below top level, even if one arm produces NULL, the result
1415  * could be FALSE (hence not NULL). However, if *all* the
1416  * arms produce NULL then the result is NULL, so we can take
1417  * the intersection of the sets of nonnullable rels, just as
1418  * for OR. Fall through to share code.
1419  */
1420  /* FALL THRU */
1421  case OR_EXPR:
1422 
1423  /*
1424  * OR is strict if all of its arms are, so we can take the
1425  * intersection of the sets of nonnullable rels for each arm.
1426  * This works for both values of top_level.
1427  */
1428  foreach(l, expr->args)
1429  {
1430  Relids subresult;
1431 
1432  subresult = find_nonnullable_rels_walker(lfirst(l),
1433  top_level);
1434  if (result == NULL) /* first subresult? */
1435  result = subresult;
1436  else
1437  result = bms_int_members(result, subresult);
1438 
1439  /*
1440  * If the intersection is empty, we can stop looking. This
1441  * also justifies the test for first-subresult above.
1442  */
1443  if (bms_is_empty(result))
1444  break;
1445  }
1446  break;
1447  case NOT_EXPR:
1448  /* NOT will return null if its arg is null */
1449  result = find_nonnullable_rels_walker((Node *) expr->args,
1450  false);
1451  break;
1452  default:
1453  elog(ERROR, "unrecognized boolop: %d", (int) expr->boolop);
1454  break;
1455  }
1456  }
1457  else if (IsA(node, RelabelType))
1458  {
1459  RelabelType *expr = (RelabelType *) node;
1460 
1461  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1462  }
1463  else if (IsA(node, CoerceViaIO))
1464  {
1465  /* not clear this is useful, but it can't hurt */
1466  CoerceViaIO *expr = (CoerceViaIO *) node;
1467 
1468  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1469  }
1470  else if (IsA(node, ArrayCoerceExpr))
1471  {
1472  /* ArrayCoerceExpr is strict at the array level; ignore elemexpr */
1473  ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
1474 
1475  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1476  }
1477  else if (IsA(node, ConvertRowtypeExpr))
1478  {
1479  /* not clear this is useful, but it can't hurt */
1480  ConvertRowtypeExpr *expr = (ConvertRowtypeExpr *) node;
1481 
1482  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1483  }
1484  else if (IsA(node, CollateExpr))
1485  {
1486  CollateExpr *expr = (CollateExpr *) node;
1487 
1488  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1489  }
1490  else if (IsA(node, NullTest))
1491  {
1492  /* IS NOT NULL can be considered strict, but only at top level */
1493  NullTest *expr = (NullTest *) node;
1494 
1495  if (top_level && expr->nulltesttype == IS_NOT_NULL && !expr->argisrow)
1496  result = find_nonnullable_rels_walker((Node *) expr->arg, false);
1497  }
1498  else if (IsA(node, BooleanTest))
1499  {
1500  /* Boolean tests that reject NULL are strict at top level */
1501  BooleanTest *expr = (BooleanTest *) node;
1502 
1503  if (top_level &&
1504  (expr->booltesttype == IS_TRUE ||
1505  expr->booltesttype == IS_FALSE ||
1506  expr->booltesttype == IS_NOT_UNKNOWN))
1507  result = find_nonnullable_rels_walker((Node *) expr->arg, false);
1508  }
1509  else if (IsA(node, PlaceHolderVar))
1510  {
1511  PlaceHolderVar *phv = (PlaceHolderVar *) node;
1512 
1513  /*
1514  * If the contained expression forces any rels non-nullable, so does
1515  * the PHV.
1516  */
1517  result = find_nonnullable_rels_walker((Node *) phv->phexpr, top_level);
1518 
1519  /*
1520  * If the PHV's syntactic scope is exactly one rel, it will be forced
1521  * to be evaluated at that rel, and so it will behave like a Var of
1522  * that rel: if the rel's entire output goes to null, so will the PHV.
1523  * (If the syntactic scope is a join, we know that the PHV will go to
1524  * null if the whole join does; but that is AND semantics while we
1525  * need OR semantics for find_nonnullable_rels' result, so we can't do
1526  * anything with the knowledge.)
1527  */
1528  if (phv->phlevelsup == 0 &&
1530  result = bms_add_members(result, phv->phrels);
1531  }
1532  return result;
1533 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
Index varlevelsup
Definition: primnodes.h:196
List * args
Definition: primnodes.h:503
Expr * arg
Definition: primnodes.h:850
Definition: nodes.h:539
Definition: primnodes.h:186
Oid funcid
Definition: primnodes.h:495
#define ERROR
Definition: elog.h:46
Bitmapset * bms_join(Bitmapset *a, Bitmapset *b)
Definition: bitmapset.c:949
BoolExprType boolop
Definition: primnodes.h:615
Expr * arg
Definition: primnodes.h:1255
Bitmapset * bms_make_singleton(int x)
Definition: bitmapset.c:186
Expr * arg
Definition: primnodes.h:1278
Expr * arg
Definition: primnodes.h:870
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:701
Index varno
Definition: primnodes.h:189
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:672
BoolTestType booltesttype
Definition: primnodes.h:1279
Oid opfuncid
Definition: primnodes.h:543
static Relids find_nonnullable_rels_walker(Node *node, bool top_level)
Definition: clauses.c:1344
NullTestType nulltesttype
Definition: primnodes.h:1256
static bool is_strict_saop(ScalarArrayOpExpr *expr, bool falseOK)
Definition: clauses.c:1864
#define lfirst(lc)
Definition: pg_list.h:169
Expr * arg
Definition: primnodes.h:936
List * args
Definition: primnodes.h:616
bool func_strict(Oid funcid)
Definition: lsyscache.c:1732
Index phlevelsup
Definition: pathnodes.h:2173
void set_opfuncid(OpExpr *opexpr)
Definition: nodeFuncs.c:1683
#define elog(elevel,...)
Definition: elog.h:232
bool argisrow
Definition: primnodes.h:1257
List * args
Definition: primnodes.h:548
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 1563 of file clauses.c.

References find_nonnullable_vars_walker().

Referenced by reduce_outer_joins_pass2().

1564 {
1565  return find_nonnullable_vars_walker(clause, true);
1566 }
static List * find_nonnullable_vars_walker(Node *node, bool top_level)
Definition: clauses.c:1569

◆ find_nonnullable_vars_walker()

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

Definition at line 1569 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().

1570 {
1571  List *result = NIL;
1572  ListCell *l;
1573 
1574  if (node == NULL)
1575  return NIL;
1576  if (IsA(node, Var))
1577  {
1578  Var *var = (Var *) node;
1579 
1580  if (var->varlevelsup == 0)
1581  result = list_make1(var);
1582  }
1583  else if (IsA(node, List))
1584  {
1585  /*
1586  * At top level, we are examining an implicit-AND list: if any of the
1587  * arms produces FALSE-or-NULL then the result is FALSE-or-NULL. If
1588  * not at top level, we are examining the arguments of a strict
1589  * function: if any of them produce NULL then the result of the
1590  * function must be NULL. So in both cases, the set of nonnullable
1591  * vars is the union of those found in the arms, and we pass down the
1592  * top_level flag unmodified.
1593  */
1594  foreach(l, (List *) node)
1595  {
1596  result = list_concat(result,
1598  top_level));
1599  }
1600  }
1601  else if (IsA(node, FuncExpr))
1602  {
1603  FuncExpr *expr = (FuncExpr *) node;
1604 
1605  if (func_strict(expr->funcid))
1606  result = find_nonnullable_vars_walker((Node *) expr->args, false);
1607  }
1608  else if (IsA(node, OpExpr))
1609  {
1610  OpExpr *expr = (OpExpr *) node;
1611 
1612  set_opfuncid(expr);
1613  if (func_strict(expr->opfuncid))
1614  result = find_nonnullable_vars_walker((Node *) expr->args, false);
1615  }
1616  else if (IsA(node, ScalarArrayOpExpr))
1617  {
1618  ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1619 
1620  if (is_strict_saop(expr, true))
1621  result = find_nonnullable_vars_walker((Node *) expr->args, false);
1622  }
1623  else if (IsA(node, BoolExpr))
1624  {
1625  BoolExpr *expr = (BoolExpr *) node;
1626 
1627  switch (expr->boolop)
1628  {
1629  case AND_EXPR:
1630  /* At top level we can just recurse (to the List case) */
1631  if (top_level)
1632  {
1633  result = find_nonnullable_vars_walker((Node *) expr->args,
1634  top_level);
1635  break;
1636  }
1637 
1638  /*
1639  * Below top level, even if one arm produces NULL, the result
1640  * could be FALSE (hence not NULL). However, if *all* the
1641  * arms produce NULL then the result is NULL, so we can take
1642  * the intersection of the sets of nonnullable vars, just as
1643  * for OR. Fall through to share code.
1644  */
1645  /* FALL THRU */
1646  case OR_EXPR:
1647 
1648  /*
1649  * OR is strict if all of its arms are, so we can take the
1650  * intersection of the sets of nonnullable vars for each arm.
1651  * This works for both values of top_level.
1652  */
1653  foreach(l, expr->args)
1654  {
1655  List *subresult;
1656 
1657  subresult = find_nonnullable_vars_walker(lfirst(l),
1658  top_level);
1659  if (result == NIL) /* first subresult? */
1660  result = subresult;
1661  else
1662  result = list_intersection(result, subresult);
1663 
1664  /*
1665  * If the intersection is empty, we can stop looking. This
1666  * also justifies the test for first-subresult above.
1667  */
1668  if (result == NIL)
1669  break;
1670  }
1671  break;
1672  case NOT_EXPR:
1673  /* NOT will return null if its arg is null */
1674  result = find_nonnullable_vars_walker((Node *) expr->args,
1675  false);
1676  break;
1677  default:
1678  elog(ERROR, "unrecognized boolop: %d", (int) expr->boolop);
1679  break;
1680  }
1681  }
1682  else if (IsA(node, RelabelType))
1683  {
1684  RelabelType *expr = (RelabelType *) node;
1685 
1686  result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1687  }
1688  else if (IsA(node, CoerceViaIO))
1689  {
1690  /* not clear this is useful, but it can't hurt */
1691  CoerceViaIO *expr = (CoerceViaIO *) node;
1692 
1693  result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1694  }
1695  else if (IsA(node, ArrayCoerceExpr))
1696  {
1697  /* ArrayCoerceExpr is strict at the array level; ignore elemexpr */
1698  ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
1699 
1700  result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1701  }
1702  else if (IsA(node, ConvertRowtypeExpr))
1703  {
1704  /* not clear this is useful, but it can't hurt */
1705  ConvertRowtypeExpr *expr = (ConvertRowtypeExpr *) node;
1706 
1707  result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1708  }
1709  else if (IsA(node, CollateExpr))
1710  {
1711  CollateExpr *expr = (CollateExpr *) node;
1712 
1713  result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1714  }
1715  else if (IsA(node, NullTest))
1716  {
1717  /* IS NOT NULL can be considered strict, but only at top level */
1718  NullTest *expr = (NullTest *) node;
1719 
1720  if (top_level && expr->nulltesttype == IS_NOT_NULL && !expr->argisrow)
1721  result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1722  }
1723  else if (IsA(node, BooleanTest))
1724  {
1725  /* Boolean tests that reject NULL are strict at top level */
1726  BooleanTest *expr = (BooleanTest *) node;
1727 
1728  if (top_level &&
1729  (expr->booltesttype == IS_TRUE ||
1730  expr->booltesttype == IS_FALSE ||
1731  expr->booltesttype == IS_NOT_UNKNOWN))
1732  result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1733  }
1734  else if (IsA(node, PlaceHolderVar))
1735  {
1736  PlaceHolderVar *phv = (PlaceHolderVar *) node;
1737 
1738  result = find_nonnullable_vars_walker((Node *) phv->phexpr, top_level);
1739  }
1740  return result;
1741 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
Index varlevelsup
Definition: primnodes.h:196
List * args
Definition: primnodes.h:503
Expr * arg
Definition: primnodes.h:850
Definition: nodes.h:539
List * list_concat(List *list1, const List *list2)
Definition: list.c:530
Definition: primnodes.h:186
#define list_make1(x1)
Definition: pg_list.h:206
Oid funcid
Definition: primnodes.h:495
#define ERROR
Definition: elog.h:46
BoolExprType boolop
Definition: primnodes.h:615
Expr * arg
Definition: primnodes.h:1255
Expr * arg
Definition: primnodes.h:1278
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:1569
Expr * arg
Definition: primnodes.h:870
BoolTestType booltesttype
Definition: primnodes.h:1279
Oid opfuncid
Definition: primnodes.h:543
NullTestType nulltesttype
Definition: primnodes.h:1256
static bool is_strict_saop(ScalarArrayOpExpr *expr, bool falseOK)
Definition: clauses.c:1864
#define lfirst(lc)
Definition: pg_list.h:169
Expr * arg
Definition: primnodes.h:936
List * args
Definition: primnodes.h:616
bool func_strict(Oid funcid)
Definition: lsyscache.c:1732
void set_opfuncid(OpExpr *opexpr)
Definition: nodeFuncs.c:1683
#define elog(elevel,...)
Definition: elog.h:232
bool argisrow
Definition: primnodes.h:1257
List * args
Definition: primnodes.h:548
Definition: pg_list.h:50

◆ find_window_functions()

WindowFuncLists* find_window_functions ( Node clause,
Index  maxWinRef 
)

Definition at line 221 of file clauses.c.

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

Referenced by grouping_planner().

222 {
223  WindowFuncLists *lists = palloc(sizeof(WindowFuncLists));
224 
225  lists->numWindowFuncs = 0;
226  lists->maxWinRef = maxWinRef;
227  lists->windowFuncs = (List **) palloc0((maxWinRef + 1) * sizeof(List *));
228  (void) find_window_functions_walker(clause, lists);
229  return lists;
230 }
Index maxWinRef
Definition: clauses.h:22
int numWindowFuncs
Definition: clauses.h:21
void * palloc0(Size size)
Definition: mcxt.c:1093
void * palloc(Size size)
Definition: mcxt.c:1062
static bool find_window_functions_walker(Node *node, WindowFuncLists *lists)
Definition: clauses.c:233
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 233 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().

234 {
235  if (node == NULL)
236  return false;
237  if (IsA(node, WindowFunc))
238  {
239  WindowFunc *wfunc = (WindowFunc *) node;
240 
241  /* winref is unsigned, so one-sided test is OK */
242  if (wfunc->winref > lists->maxWinRef)
243  elog(ERROR, "WindowFunc contains out-of-range winref %u",
244  wfunc->winref);
245  /* eliminate duplicates, so that we avoid repeated computation */
246  if (!list_member(lists->windowFuncs[wfunc->winref], wfunc))
247  {
248  lists->windowFuncs[wfunc->winref] =
249  lappend(lists->windowFuncs[wfunc->winref], wfunc);
250  lists->numWindowFuncs++;
251  }
252 
253  /*
254  * We assume that the parser checked that there are no window
255  * functions in the arguments or filter clause. Hence, we need not
256  * recurse into them. (If either the parser or the planner screws up
257  * on this point, the executor will still catch it; see ExecInitExpr.)
258  */
259  return false;
260  }
261  Assert(!IsA(node, SubLink));
263  (void *) lists);
264 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
Index maxWinRef
Definition: clauses.h:22
int numWindowFuncs
Definition: clauses.h:21
Index winref
Definition: primnodes.h:392
#define ERROR
Definition: elog.h:46
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:1904
#define elog(elevel,...)
Definition: elog.h:232
static bool find_window_functions_walker(Node *node, WindowFuncLists *lists)
Definition: clauses.c:233
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 4260 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, castNode, 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, linitial_node, 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, stringToNode(), substitute_actual_parameters(), SysCacheGetAttr(), Query::targetList, TextDatumGetCString, transformTopLevelStmt(), and Query::windowClause.

Referenced by simplify_function().

4265 {
4266  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4267  char *src;
4268  Datum tmp;
4269  bool isNull;
4270  MemoryContext oldcxt;
4271  MemoryContext mycxt;
4272  inline_error_callback_arg callback_arg;
4273  ErrorContextCallback sqlerrcontext;
4274  FuncExpr *fexpr;
4276  TupleDesc rettupdesc;
4277  ParseState *pstate;
4278  List *raw_parsetree_list;
4279  List *querytree_list;
4280  Query *querytree;
4281  Node *newexpr;
4282  int *usecounts;
4283  ListCell *arg;
4284  int i;
4285 
4286  /*
4287  * Forget it if the function is not SQL-language or has other showstopper
4288  * properties. (The prokind and nargs checks are just paranoia.)
4289  */
4290  if (funcform->prolang != SQLlanguageId ||
4291  funcform->prokind != PROKIND_FUNCTION ||
4292  funcform->prosecdef ||
4293  funcform->proretset ||
4294  funcform->prorettype == RECORDOID ||
4295  !heap_attisnull(func_tuple, Anum_pg_proc_proconfig, NULL) ||
4296  funcform->pronargs != list_length(args))
4297  return NULL;
4298 
4299  /* Check for recursive function, and give up trying to expand if so */
4300  if (list_member_oid(context->active_fns, funcid))
4301  return NULL;
4302 
4303  /* Check permission to call function (fail later, if not) */
4305  return NULL;
4306 
4307  /* Check whether a plugin wants to hook function entry/exit */
4308  if (FmgrHookIsNeeded(funcid))
4309  return NULL;
4310 
4311  /*
4312  * Make a temporary memory context, so that we don't leak all the stuff
4313  * that parsing might create.
4314  */
4316  "inline_function",
4318  oldcxt = MemoryContextSwitchTo(mycxt);
4319 
4320  /* Fetch the function body */
4321  tmp = SysCacheGetAttr(PROCOID,
4322  func_tuple,
4323  Anum_pg_proc_prosrc,
4324  &isNull);
4325  if (isNull)
4326  elog(ERROR, "null prosrc for function %u", funcid);
4327  src = TextDatumGetCString(tmp);
4328 
4329  /*
4330  * Setup error traceback support for ereport(). This is so that we can
4331  * finger the function that bad information came from.
4332  */
4333  callback_arg.proname = NameStr(funcform->proname);
4334  callback_arg.prosrc = src;
4335 
4336  sqlerrcontext.callback = sql_inline_error_callback;
4337  sqlerrcontext.arg = (void *) &callback_arg;
4338  sqlerrcontext.previous = error_context_stack;
4339  error_context_stack = &sqlerrcontext;
4340 
4341  /* If we have prosqlbody, pay attention to that not prosrc */
4342  tmp = SysCacheGetAttr(PROCOID,
4343  func_tuple,
4344  Anum_pg_proc_prosqlbody,
4345  &isNull);
4346  if (!isNull)
4347  {
4348  Node *n;
4349  List *querytree_list;
4350 
4352  if (IsA(n, List))
4353  querytree_list = linitial_node(List, castNode(List, n));
4354  else
4355  querytree_list = list_make1(n);
4356  if (list_length(querytree_list) != 1)
4357  goto fail;
4358  querytree = linitial(querytree_list);
4359  }
4360  else
4361  {
4362  /*
4363  * Set up to handle parameters while parsing the function body. We need a
4364  * dummy FuncExpr node containing the already-simplified arguments to pass
4365  * to prepare_sql_fn_parse_info. (In some cases we don't really need
4366  * that, but for simplicity we always build it.)
4367  */
4368  fexpr = makeNode(FuncExpr);
4369  fexpr->funcid = funcid;
4370  fexpr->funcresulttype = result_type;
4371  fexpr->funcretset = false;
4372  fexpr->funcvariadic = funcvariadic;
4373  fexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
4374  fexpr->funccollid = result_collid; /* doesn't matter */
4375  fexpr->inputcollid = input_collid;
4376  fexpr->args = args;
4377  fexpr->location = -1;
4378 
4379  pinfo = prepare_sql_fn_parse_info(func_tuple,
4380  (Node *) fexpr,
4381  input_collid);
4382 
4383  /* fexpr also provides a convenient way to resolve a composite result */
4384  (void) get_expr_result_type((Node *) fexpr,
4385  NULL,
4386  &rettupdesc);
4387 
4388  /*
4389  * We just do parsing and parse analysis, not rewriting, because rewriting
4390  * will not affect table-free-SELECT-only queries, which is all that we
4391  * care about. Also, we can punt as soon as we detect more than one
4392  * command in the function body.
4393  */
4394  raw_parsetree_list = pg_parse_query(src);
4395  if (list_length(raw_parsetree_list) != 1)
4396  goto fail;
4397 
4398  pstate = make_parsestate(NULL);
4399  pstate->p_sourcetext = src;
4400  sql_fn_parser_setup(pstate, pinfo);
4401 
4402  querytree = transformTopLevelStmt(pstate, linitial(raw_parsetree_list));
4403 
4404  free_parsestate(pstate);
4405  }
4406 
4407  /*
4408  * The single command must be a simple "SELECT expression".
4409  *
4410  * Note: if you change the tests involved in this, see also plpgsql's
4411  * exec_simple_check_plan(). That generally needs to have the same idea
4412  * of what's a "simple expression", so that inlining a function that
4413  * previously wasn't inlined won't change plpgsql's conclusion.
4414  */
4415  if (!IsA(querytree, Query) ||
4416  querytree->commandType != CMD_SELECT ||
4417  querytree->hasAggs ||
4418  querytree->hasWindowFuncs ||
4419  querytree->hasTargetSRFs ||
4420  querytree->hasSubLinks ||
4421  querytree->cteList ||
4422  querytree->rtable ||
4423  querytree->jointree->fromlist ||
4424  querytree->jointree->quals ||
4425  querytree->groupClause ||
4426  querytree->groupingSets ||
4427  querytree->havingQual ||
4428  querytree->windowClause ||
4429  querytree->distinctClause ||
4430  querytree->sortClause ||
4431  querytree->limitOffset ||
4432  querytree->limitCount ||
4433  querytree->setOperations ||
4434  list_length(querytree->targetList) != 1)
4435  goto fail;
4436 
4437  /*
4438  * Make sure the function (still) returns what it's declared to. This
4439  * will raise an error if wrong, but that's okay since the function would
4440  * fail at runtime anyway. Note that check_sql_fn_retval will also insert
4441  * a coercion if needed to make the tlist expression match the declared
4442  * type of the function.
4443  *
4444  * Note: we do not try this until we have verified that no rewriting was
4445  * needed; that's probably not important, but let's be careful.
4446  */
4447  querytree_list = list_make1(querytree);
4448  if (check_sql_fn_retval(list_make1(querytree_list),
4449  result_type, rettupdesc,
4450  false, NULL))
4451  goto fail; /* reject whole-tuple-result cases */
4452 
4453  /*
4454  * Given the tests above, check_sql_fn_retval shouldn't have decided to
4455  * inject a projection step, but let's just make sure.
4456  */
4457  if (querytree != linitial(querytree_list))
4458  goto fail;
4459 
4460  /* Now we can grab the tlist expression */
4461  newexpr = (Node *) ((TargetEntry *) linitial(querytree->targetList))->expr;
4462 
4463  /*
4464  * If the SQL function returns VOID, we can only inline it if it is a
4465  * SELECT of an expression returning VOID (ie, it's just a redirection to
4466  * another VOID-returning function). In all non-VOID-returning cases,
4467  * check_sql_fn_retval should ensure that newexpr returns the function's
4468  * declared result type, so this test shouldn't fail otherwise; but we may
4469  * as well cope gracefully if it does.
4470  */
4471  if (exprType(newexpr) != result_type)
4472  goto fail;
4473 
4474  /*
4475  * Additional validity checks on the expression. It mustn't be more
4476  * volatile than the surrounding function (this is to avoid breaking hacks
4477  * that involve pretending a function is immutable when it really ain't).
4478  * If the surrounding function is declared strict, then the expression
4479  * must contain only strict constructs and must use all of the function
4480  * parameters (this is overkill, but an exact analysis is hard).
4481  */
4482  if (funcform->provolatile == PROVOLATILE_IMMUTABLE &&
4483  contain_mutable_functions(newexpr))
4484  goto fail;
4485  else if (funcform->provolatile == PROVOLATILE_STABLE &&
4486  contain_volatile_functions(newexpr))
4487  goto fail;
4488 
4489  if (funcform->proisstrict &&
4490  contain_nonstrict_functions(newexpr))
4491  goto fail;
4492 
4493  /*
4494  * If any parameter expression contains a context-dependent node, we can't
4495  * inline, for fear of putting such a node into the wrong context.
4496  */
4497  if (contain_context_dependent_node((Node *) args))
4498  goto fail;
4499 
4500  /*
4501  * We may be able to do it; there are still checks on parameter usage to
4502  * make, but those are most easily done in combination with the actual
4503  * substitution of the inputs. So start building expression with inputs
4504  * substituted.
4505  */
4506  usecounts = (int *) palloc0(funcform->pronargs * sizeof(int));
4507  newexpr = substitute_actual_parameters(newexpr, funcform->pronargs,
4508  args, usecounts);
4509 
4510  /* Now check for parameter usage */
4511  i = 0;
4512  foreach(arg, args)
4513  {
4514  Node *param = lfirst(arg);
4515 
4516  if (usecounts[i] == 0)
4517  {
4518  /* Param not used at all: uncool if func is strict */
4519  if (funcform->proisstrict)
4520  goto fail;
4521  }
4522  else if (usecounts[i] != 1)
4523  {
4524  /* Param used multiple times: uncool if expensive or volatile */
4525  QualCost eval_cost;
4526 
4527  /*
4528  * We define "expensive" as "contains any subplan or more than 10
4529  * operators". Note that the subplan search has to be done
4530  * explicitly, since cost_qual_eval() will barf on unplanned
4531  * subselects.
4532  */
4533  if (contain_subplans(param))
4534  goto fail;
4535  cost_qual_eval(&eval_cost, list_make1(param), NULL);
4536  if (eval_cost.startup + eval_cost.per_tuple >
4537  10 * cpu_operator_cost)
4538  goto fail;
4539 
4540  /*
4541  * Check volatility last since this is more expensive than the
4542  * above tests
4543  */
4544  if (contain_volatile_functions(param))
4545  goto fail;
4546  }
4547  i++;
4548  }
4549 
4550  /*
4551  * Whew --- we can make the substitution. Copy the modified expression
4552  * out of the temporary memory context, and clean up.
4553  */
4554  MemoryContextSwitchTo(oldcxt);
4555 
4556  newexpr = copyObject(newexpr);
4557 
4558  MemoryContextDelete(mycxt);
4559 
4560  /*
4561  * If the result is of a collatable type, force the result to expose the
4562  * correct collation. In most cases this does not matter, but it's
4563  * possible that the function result is used directly as a sort key or in
4564  * other places where we expect exprCollation() to tell the truth.
4565  */
4566  if (OidIsValid(result_collid))
4567  {
4568  Oid exprcoll = exprCollation(newexpr);
4569 
4570  if (OidIsValid(exprcoll) && exprcoll != result_collid)
4571  {
4572  CollateExpr *newnode = makeNode(CollateExpr);
4573 
4574  newnode->arg = (Expr *) newexpr;
4575  newnode->collOid = result_collid;
4576  newnode->location = -1;
4577 
4578  newexpr = (Node *) newnode;
4579  }
4580  }
4581 
4582  /*
4583  * Since there is now no trace of the function in the plan tree, we must
4584  * explicitly record the plan's dependency on the function.
4585  */
4586  if (context->root)
4587  record_plan_function_dependency(context->root, funcid);
4588 
4589  /*
4590  * Recursively try to simplify the modified expression. Here we must add
4591  * the current function to the context list of active functions.
4592  */
4593  context->active_fns = lappend_oid(context->active_fns, funcid);
4594  newexpr = eval_const_expressions_mutator(newexpr, context);
4595  context->active_fns = list_delete_last(context->active_fns);
4596 
4597  error_context_stack = sqlerrcontext.previous;
4598 
4599  return (Expr *) newexpr;
4600 
4601  /* Here if func is not inlinable: release temp memory and return NULL */
4602 fail:
4603  MemoryContextSwitchTo(oldcxt);
4604  MemoryContextDelete(mycxt);
4605  error_context_stack = sqlerrcontext.previous;
4606 
4607  return NULL;
4608 }
Node * limitOffset
Definition: parsenodes.h:171
Oid funcresulttype
Definition: primnodes.h:496
bool check_sql_fn_retval(List *queryTreeLists, Oid rettype, TupleDesc rettupdesc, bool insertDroppedCols, List **resultTargetList)
Definition: functions.c:1618
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
#define AllocSetContextCreate
Definition: memutils.h:173
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
List * sortClause
Definition: parsenodes.h:169
List * args
Definition: primnodes.h:503
FromExpr * jointree
Definition: parsenodes.h:148
Oid GetUserId(void)
Definition: miscinit.c:478
#define castNode(_type_, nodeptr)
Definition: nodes.h:608
Oid funccollid
Definition: primnodes.h:501
void sql_fn_parser_setup(struct ParseState *pstate, SQLFunctionParseInfoPtr pinfo)
Definition: functions.c:266
bool hasAggs
Definition: parsenodes.h:133
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
List * groupingSets
Definition: parsenodes.h:161
Definition: nodes.h:539
void * stringToNode(const char *str)
Definition: read.c:89
bool heap_attisnull(HeapTuple tup, int attnum, TupleDesc tupleDesc)
Definition: heaptuple.c:359
bool funcretset
Definition: primnodes.h:497
List * fromlist
Definition: primnodes.h:1553
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:448
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:247
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:246
#define OidIsValid(objectId)
Definition: c.h:710
#define FmgrHookIsNeeded(fn_oid)
Definition: fmgr.h:774
Node * quals
Definition: primnodes.h:1554
Cost startup
Definition: pathnodes.h:45
List * windowClause
Definition: parsenodes.h:165
List * targetList
Definition: parsenodes.h:150
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:324
CoercionForm funcformat
Definition: primnodes.h:500
Cost per_tuple
Definition: pathnodes.h:46
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2231
#define linitial(l)
Definition: pg_list.h:174
List * rtable
Definition: parsenodes.h:147
List * distinctClause
Definition: parsenodes.h:167
Oid funcid
Definition: primnodes.h:495
#define ERROR
Definition: elog.h:46
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:4311
List * pg_parse_query(const char *query_string)
Definition: postgres.c:594
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:195
Node * limitCount
Definition: parsenodes.h:172
List * list_delete_last(List *list)
Definition: list.c:892
double cpu_operator_cost
Definition: costsize.c:123
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
const char * p_sourcetext
Definition: parse_node.h:181
static Node * substitute_actual_parameters(Node *expr, int nargs, List *args, int *usecounts)
Definition: clauses.c:4614
static void sql_inline_error_callback(void *arg)
Definition: clauses.c:4656
#define TextDatumGetCString(d)
Definition: builtins.h:83
void * palloc0(Size size)
Definition: mcxt.c:1093
uintptr_t Datum
Definition: postgres.h:411
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:2943
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:136
CmdType commandType
Definition: parsenodes.h:120
bool hasTargetSRFs
Definition: parsenodes.h:135
#define makeNode(_type_)
Definition: nodes.h:587
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:689
Oid inputcollid
Definition: primnodes.h:502
#define lfirst(lc)
Definition: pg_list.h:169
bool hasWindowFuncs
Definition: parsenodes.h:134
Query * transformTopLevelStmt(ParseState *pstate, RawStmt *parseTree)
Definition: analyze.c:211
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:936
Datum querytree(PG_FUNCTION_ARGS)
Definition: _int_bool.c:664
static bool contain_context_dependent_node(Node *clause)
Definition: clauses.c:1061
List * cteList
Definition: parsenodes.h:145
Node * setOperations
Definition: parsenodes.h:177
List * groupClause
Definition: parsenodes.h:158
bool hasSubLinks
Definition: parsenodes.h:136
#define ACL_EXECUTE
Definition: parsenodes.h:89
#define elog(elevel,...)
Definition: elog.h:232
AclResult pg_proc_aclcheck(Oid proc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4723
int i
#define NameStr(name)
Definition: c.h:681
void * arg
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:359
int location
Definition: primnodes.h:504
bool contain_nonstrict_functions(Node *clause)
Definition: clauses.c:875
SQLFunctionParseInfoPtr prepare_sql_fn_parse_info(HeapTuple procedureTuple, Node *call_expr, Oid inputCollation)
Definition: functions.c:176
#define copyObject(obj)
Definition: nodes.h:655
Node * havingQual
Definition: parsenodes.h:163
int location
Definition: primnodes.h:938
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:77
Definition: pg_list.h:50
bool funcvariadic
Definition: primnodes.h:498

◆ inline_set_returning_function()

Query* inline_set_returning_function ( PlannerInfo root,
RangeTblEntry rte 
)

Definition at line 4772 of file clauses.c.

References ACL_EXECUTE, ACLCHECK_OK, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, ErrorContextCallback::arg, FuncExpr::args, Assert, BuildDescFromLists(), ErrorContextCallback::callback, castNode, 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(), pg_rewrite_query(), 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(), stringToNode(), substitute_actual_srf_parameters(), SysCacheGetAttr(), TextDatumGetCString, TYPEFUNC_COMPOSITE, TYPEFUNC_COMPOSITE_DOMAIN, and TYPEFUNC_RECORD.

Referenced by preprocess_function_rtes().

4773 {
4774  RangeTblFunction *rtfunc;
4775  FuncExpr *fexpr;
4776  Oid func_oid;
4777  HeapTuple func_tuple;
4778  Form_pg_proc funcform;
4779  char *src;
4780  Datum tmp;
4781  bool isNull;
4782  MemoryContext oldcxt;
4783  MemoryContext mycxt;
4784  inline_error_callback_arg callback_arg;
4785  ErrorContextCallback sqlerrcontext;
4787  TypeFuncClass functypclass;
4788  TupleDesc rettupdesc;
4789  List *raw_parsetree_list;
4790  List *querytree_list;
4791  Query *querytree;
4792 
4793  Assert(rte->rtekind == RTE_FUNCTION);
4794 
4795  /*
4796  * It doesn't make a lot of sense for a SQL SRF to refer to itself in its
4797  * own FROM clause, since that must cause infinite recursion at runtime.
4798  * It will cause this code to recurse too, so check for stack overflow.
4799  * (There's no need to do more.)
4800  */
4802 
4803  /* Fail if the RTE has ORDINALITY - we don't implement that here. */
4804  if (rte->funcordinality)
4805  return NULL;
4806 
4807  /* Fail if RTE isn't a single, simple FuncExpr */
4808  if (list_length(rte->functions) != 1)
4809  return NULL;
4810  rtfunc = (RangeTblFunction *) linitial(rte->functions);
4811 
4812  if (!IsA(rtfunc->funcexpr, FuncExpr))
4813  return NULL;
4814  fexpr = (FuncExpr *) rtfunc->funcexpr;
4815 
4816  func_oid = fexpr->funcid;
4817 
4818  /*
4819  * The function must be declared to return a set, else inlining would
4820  * change the results if the contained SELECT didn't return exactly one
4821  * row.
4822  */
4823  if (!fexpr->funcretset)
4824  return NULL;
4825 
4826  /*
4827  * Refuse to inline if the arguments contain any volatile functions or
4828  * sub-selects. Volatile functions are rejected because inlining may
4829  * result in the arguments being evaluated multiple times, risking a
4830  * change in behavior. Sub-selects are rejected partly for implementation
4831  * reasons (pushing them down another level might change their behavior)
4832  * and partly because they're likely to be expensive and so multiple
4833  * evaluation would be bad.
4834  */
4835  if (contain_volatile_functions((Node *) fexpr->args) ||
4836  contain_subplans((Node *) fexpr->args))
4837  return NULL;
4838 
4839  /* Check permission to call function (fail later, if not) */
4840  if (pg_proc_aclcheck(func_oid, GetUserId(), ACL_EXECUTE) != ACLCHECK_OK)
4841  return NULL;
4842 
4843  /* Check whether a plugin wants to hook function entry/exit */
4844  if (FmgrHookIsNeeded(func_oid))
<