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, int pronargs, HeapTuple func_tuple)
 
static Listadd_function_defaults (List *args, int pronargs, HeapTuple func_tuple)
 
static Listfetch_function_defaults (HeapTuple func_tuple)
 
static void recheck_cast_function_args (List *args, Oid result_type, Oid *proargtypes, int pronargs, 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, bool include_out_arguments, 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 1071 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 2264 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:4778
Definition: nodes.h:539
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41

Definition at line 2268 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:2278

Definition at line 2255 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 2108 of file clauses.c.

Referenced by convert_saop_to_hashed_saop_walker().

Function Documentation

◆ add_function_defaults()

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

Definition at line 4127 of file clauses.c.

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

Referenced by expand_function_arguments().

4128 {
4129  int nargsprovided = list_length(args);
4130  List *defaults;
4131  int ndelete;
4132 
4133  /* Get all the default expressions from the pg_proc tuple */
4134  defaults = fetch_function_defaults(func_tuple);
4135 
4136  /* Delete any unused defaults from the list */
4137  ndelete = nargsprovided + list_length(defaults) - pronargs;
4138  if (ndelete < 0)
4139  elog(ERROR, "not enough default arguments");
4140  if (ndelete > 0)
4141  defaults = list_copy_tail(defaults, ndelete);
4142 
4143  /* And form the combined argument list, not modifying the input list */
4144  return list_concat_copy(args, defaults);
4145 }
List * list_copy_tail(const List *oldlist, int nskip)
Definition: list.c:1437
int16 pronargs
Definition: pg_proc.h:81
#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:4151
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 1986 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().

1987 {
1988  Oid opoid;
1989  Node *temp;
1990 
1991  /* Sanity checks: caller is at fault if these fail */
1992  if (!is_opclause(clause) ||
1993  list_length(clause->args) != 2)
1994  elog(ERROR, "cannot commute non-binary-operator clause");
1995 
1996  opoid = get_commutator(clause->opno);
1997 
1998  if (!OidIsValid(opoid))
1999  elog(ERROR, "could not find commutator for operator %u",
2000  clause->opno);
2001 
2002  /*
2003  * modify the clause in-place!
2004  */
2005  clause->opno = opoid;
2006  clause->opfuncid = InvalidOid;
2007  /* opresulttype, opretset, opcollid, inputcollid need not change */
2008 
2009  temp = linitial(clause->args);
2010  linitial(clause->args) = lsecond(clause->args);
2011  lsecond(clause->args) = temp;
2012 }
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 174 of file clauses.c.

References contain_agg_clause_walker().

Referenced by get_eclass_for_sort_expr(), and subquery_planner().

175 {
176  return contain_agg_clause_walker(clause, NULL);
177 }
static bool contain_agg_clause_walker(Node *node, void *context)
Definition: clauses.c:180

◆ contain_agg_clause_walker()

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

Definition at line 180 of file clauses.c.

References Assert, expression_tree_walker(), and IsA.

Referenced by contain_agg_clause().

181 {
182  if (node == NULL)
183  return false;
184  if (IsA(node, Aggref))
185  {
186  Assert(((Aggref *) node)->agglevelsup == 0);
187  return true; /* abort the tree traversal and return true */
188  }
189  if (IsA(node, GroupingFunc))
190  {
191  Assert(((GroupingFunc *) node)->agglevelsup == 0);
192  return true; /* abort the tree traversal and return true */
193  }
194  Assert(!IsA(node, SubLink));
195  return expression_tree_walker(node, contain_agg_clause_walker, context);
196 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
static bool contain_agg_clause_walker(Node *node, void *context)
Definition: clauses.c:180
#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 1064 of file clauses.c.

References contain_context_dependent_node_walker().

Referenced by inline_function().

1065 {
1066  int flags = 0;
1067 
1068  return contain_context_dependent_node_walker(clause, &flags);
1069 }
static bool contain_context_dependent_node_walker(Node *node, int *flags)
Definition: clauses.c:1074

◆ contain_context_dependent_node_walker()

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

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

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

◆ contain_exec_param()

bool contain_exec_param ( Node clause,
List param_ids 
)

Definition at line 1022 of file clauses.c.

References contain_exec_param_walker().

Referenced by test_opexpr_is_hashable().

1023 {
1024  return contain_exec_param_walker(clause, param_ids);
1025 }
static bool contain_exec_param_walker(Node *node, List *param_ids)
Definition: clauses.c:1028

◆ contain_exec_param_walker()

static bool contain_exec_param_walker ( Node node,
List param_ids 
)
static

Definition at line 1028 of file clauses.c.

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

Referenced by contain_exec_param().

1029 {
1030  if (node == NULL)
1031  return false;
1032  if (IsA(node, Param))
1033  {
1034  Param *p = (Param *) node;
1035 
1036  if (p->paramkind == PARAM_EXEC &&
1037  list_member_int(param_ids, p->paramid))
1038  return true;
1039  }
1040  return expression_tree_walker(node, contain_exec_param_walker, param_ids);
1041 }
#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:1028

◆ contain_leaked_vars()

bool contain_leaked_vars ( Node clause)

Definition at line 1148 of file clauses.c.

References contain_leaked_vars_walker().

Referenced by make_restrictinfo_internal(), and qual_is_pushdown_safe().

1149 {
1150  return contain_leaked_vars_walker(clause, NULL);
1151 }
static bool contain_leaked_vars_walker(Node *node, void *context)
Definition: clauses.c:1160

◆ contain_leaked_vars_checker()

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

Definition at line 1154 of file clauses.c.

References get_func_leakproof().

Referenced by contain_leaked_vars_walker().

1155 {
1156  return !get_func_leakproof(func_id);
1157 }
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 1160 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().

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

References func_volatile().

Referenced by contain_mutable_functions_walker().

369 {
370  return (func_volatile(func_id) != PROVOLATILE_IMMUTABLE);
371 }
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 374 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().

375 {
376  if (node == NULL)
377  return false;
378  /* Check for mutable functions in node itself */
380  context))
381  return true;
382 
383  if (IsA(node, SQLValueFunction))
384  {
385  /* all variants of SQLValueFunction are stable */
386  return true;
387  }
388 
389  if (IsA(node, NextValueExpr))
390  {
391  /* NextValueExpr is volatile */
392  return true;
393  }
394 
395  /*
396  * It should be safe to treat MinMaxExpr as immutable, because it will
397  * depend on a non-cross-type btree comparison function, and those should
398  * always be immutable. Treating XmlExpr as immutable is more dubious,
399  * and treating CoerceToDomain as immutable is outright dangerous. But we
400  * have done so historically, and changing this would probably cause more
401  * problems than it would fix. In practice, if you have a non-immutable
402  * domain constraint you are in for pain anyhow.
403  */
404 
405  /* Recurse to check arguments */
406  if (IsA(node, Query))
407  {
408  /* Recurse into subselects */
409  return query_tree_walker((Query *) node,
411  context, 0);
412  }
414  context);
415 }
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:374
static bool contain_mutable_functions_checker(Oid func_id, void *context)
Definition: clauses.c:368
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 3537 of file clauses.c.

References expression_tree_walker(), and IsA.

3538 {
3539  if (node == NULL)
3540  return false;
3541  if (IsA(node, Const))
3542  return false;
3543  if (IsA(node, List))
3544  return expression_tree_walker(node, contain_non_const_walker, context);
3545  /* Otherwise, abort the tree traversal and return true */
3546  return true;
3547 }
#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:3537

◆ contain_nonstrict_functions()

bool contain_nonstrict_functions ( Node clause)

Definition at line 878 of file clauses.c.

References contain_nonstrict_functions_walker().

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

879 {
880  return contain_nonstrict_functions_walker(clause, NULL);
881 }
static bool contain_nonstrict_functions_walker(Node *node, void *context)
Definition: clauses.c:890

◆ contain_nonstrict_functions_checker()

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

Definition at line 884 of file clauses.c.

References func_strict().

Referenced by contain_nonstrict_functions_walker().

885 {
886  return !func_strict(func_id);
887 }
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 890 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().

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

◆ contain_subplans()

bool contain_subplans ( Node clause)

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

328 {
329  return contain_subplans_walker(clause, NULL);
330 }
static bool contain_subplans_walker(Node *node, void *context)
Definition: clauses.c:333

◆ contain_subplans_walker()

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

Definition at line 333 of file clauses.c.

References expression_tree_walker(), and IsA.

Referenced by contain_subplans().

334 {
335  if (node == NULL)
336  return false;
337  if (IsA(node, SubPlan) ||
338  IsA(node, AlternativeSubPlan) ||
339  IsA(node, SubLink))
340  return true; /* abort the tree traversal and return true */
341  return expression_tree_walker(node, contain_subplans_walker, context);
342 }
#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:333

◆ contain_volatile_functions()

◆ contain_volatile_functions_checker()

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

Definition at line 457 of file clauses.c.

References func_volatile().

Referenced by contain_volatile_functions_walker().

458 {
459  return (func_volatile(func_id) == PROVOLATILE_VOLATILE);
460 }
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 558 of file clauses.c.

References contain_volatile_functions_not_nextval_walker().

Referenced by BeginCopyFrom().

559 {
561 }
static bool contain_volatile_functions_not_nextval_walker(Node *node, void *context)
Definition: clauses.c:571

◆ contain_volatile_functions_not_nextval_checker()

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

Definition at line 564 of file clauses.c.

References func_volatile().

Referenced by contain_volatile_functions_not_nextval_walker().

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

572 {
573  if (node == NULL)
574  return false;
575  /* Check for volatile functions in node itself */
576  if (check_functions_in_node(node,
578  context))
579  return true;
580 
581  /*
582  * See notes in contain_mutable_functions_walker about why we treat
583  * MinMaxExpr, XmlExpr, and CoerceToDomain as immutable, while
584  * SQLValueFunction is stable. Hence, none of them are of interest here.
585  * Also, since we're intentionally ignoring nextval(), presumably we
586  * should ignore NextValueExpr.
587  */
588 
589  /* Recurse to check arguments */
590  if (IsA(node, Query))
591  {
592  /* Recurse into subselects */
593  return query_tree_walker((Query *) node,
595  context, 0);
596  }
597  return expression_tree_walker(node,
599  context);
600 }
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:571
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:564

◆ contain_volatile_functions_walker()

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

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

464 {
465  if (node == NULL)
466  return false;
467  /* Check for volatile functions in node itself */
469  context))
470  return true;
471 
472  if (IsA(node, NextValueExpr))
473  {
474  /* NextValueExpr is volatile */
475  return true;
476  }
477 
478  if (IsA(node, RestrictInfo))
479  {
480  RestrictInfo *rinfo = (RestrictInfo *) node;
481 
482  /*
483  * For RestrictInfo, check if we've checked the volatility of it
484  * before. If so, we can just use the cached value and not bother
485  * checking it again. Otherwise, check it and cache if whether we
486  * found any volatile functions.
487  */
488  if (rinfo->has_volatile == VOLATILITY_NOVOLATILE)
489  return false;
490  else if (rinfo->has_volatile == VOLATILITY_VOLATILE)
491  return true;
492  else
493  {
494  bool hasvolatile;
495 
496  hasvolatile = contain_volatile_functions_walker((Node *) rinfo->clause,
497  context);
498  if (hasvolatile)
500  else
502 
503  return hasvolatile;
504  }
505  }
506 
507  if (IsA(node, PathTarget))
508  {
509  PathTarget *target = (PathTarget *) node;
510 
511  /*
512  * We also do caching for PathTarget the same as we do above for
513  * RestrictInfos.
514  */
516  return false;
517  else if (target->has_volatile_expr == VOLATILITY_VOLATILE)
518  return true;
519  else
520  {
521  bool hasvolatile;
522 
523  hasvolatile = contain_volatile_functions_walker((Node *) target->exprs,
524  context);
525 
526  if (hasvolatile)
528  else
530 
531  return hasvolatile;
532  }
533  }
534 
535  /*
536  * See notes in contain_mutable_functions_walker about why we treat
537  * MinMaxExpr, XmlExpr, and CoerceToDomain as immutable, while
538  * SQLValueFunction is stable. Hence, none of them are of interest here.
539  */
540 
541  /* Recurse to check arguments */
542  if (IsA(node, Query))
543  {
544  /* Recurse into subselects */
545  return query_tree_walker((Query *) node,
547  context, 0);
548  }
550  context);
551 }
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:463
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:457
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 211 of file clauses.c.

References contain_windowfuncs().

Referenced by get_eclass_for_sort_expr(), and qual_is_pushdown_safe().

212 {
213  return contain_windowfuncs(clause);
214 }
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 2125 of file clauses.c.

References convert_saop_to_hashed_saop_walker().

Referenced by preprocess_expression().

2126 {
2127  (void) convert_saop_to_hashed_saop_walker(node, NULL);
2128 }
static bool convert_saop_to_hashed_saop_walker(Node *node, void *context)
Definition: clauses.c:2131

◆ convert_saop_to_hashed_saop_walker()

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

Definition at line 2131 of file clauses.c.

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

Referenced by convert_saop_to_hashed_saop().

2132 {
2133  if (node == NULL)
2134  return false;
2135 
2136  if (IsA(node, ScalarArrayOpExpr))
2137  {
2138  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
2139  Expr *arrayarg = (Expr *) lsecond(saop->args);
2140  Oid lefthashfunc;
2141  Oid righthashfunc;
2142 
2143  if (arrayarg && IsA(arrayarg, Const) &&
2144  !((Const *) arrayarg)->constisnull)
2145  {
2146  if (saop->useOr)
2147  {
2148  if (get_op_hash_functions(saop->opno, &lefthashfunc, &righthashfunc) &&
2149  lefthashfunc == righthashfunc)
2150  {
2151  Datum arrdatum = ((Const *) arrayarg)->constvalue;
2152  ArrayType *arr = (ArrayType *) DatumGetPointer(arrdatum);
2153  int nitems;
2154 
2155  /*
2156  * Only fill in the hash functions if the array looks
2157  * large enough for it to be worth hashing instead of
2158  * doing a linear search.
2159  */
2160  nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr));
2161 
2162  if (nitems >= MIN_ARRAY_SIZE_FOR_HASHED_SAOP)
2163  {
2164  /* Looks good. Fill in the hash functions */
2165  saop->hashfuncid = lefthashfunc;
2166  }
2167  return true;
2168  }
2169  }
2170  else /* !saop->useOr */
2171  {
2172  Oid negator = get_negator(saop->opno);
2173 
2174  /*
2175  * Check if this is a NOT IN using an operator whose negator
2176  * is hashable. If so we can still build a hash table and
2177  * just ensure the lookup items are not in the hash table.
2178  */
2179  if (OidIsValid(negator) &&
2180  get_op_hash_functions(negator, &lefthashfunc, &righthashfunc) &&
2181  lefthashfunc == righthashfunc)
2182  {
2183  Datum arrdatum = ((Const *) arrayarg)->constvalue;
2184  ArrayType *arr = (ArrayType *) DatumGetPointer(arrdatum);
2185  int nitems;
2186 
2187  /*
2188  * Only fill in the hash functions if the array looks
2189  * large enough for it to be worth hashing instead of
2190  * doing a linear search.
2191  */
2192  nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr));
2193 
2194  if (nitems >= MIN_ARRAY_SIZE_FOR_HASHED_SAOP)
2195  {
2196  /* Looks good. Fill in the hash functions */
2197  saop->hashfuncid = lefthashfunc;
2198 
2199  /*
2200  * Also set the negfuncid. The executor will need
2201  * that to perform hashtable lookups.
2202  */
2203  saop->negfuncid = get_opcode(negator);
2204  }
2205  return true;
2206  }
2207  }
2208  }
2209  }
2210 
2212 }
#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:2131
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
#define lsecond(l)
Definition: pg_list.h:179
#define ARR_DIMS(a)
Definition: array.h:287
uintptr_t Datum
Definition: postgres.h:411
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1256
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
Oid get_negator(Oid opno)
Definition: lsyscache.c:1504
#define MIN_ARRAY_SIZE_FOR_HASHED_SAOP
Definition: clauses.c:2108

◆ ece_function_is_safe()

static bool ece_function_is_safe ( Oid  funcid,
eval_const_expressions_context context 
)
static

Definition at line 3553 of file clauses.c.

References eval_const_expressions_context::estimate, and func_volatile().

Referenced by eval_const_expressions_mutator().

3554 {
3555  char provolatile = func_volatile(funcid);
3556 
3557  /*
3558  * Ordinarily we are only allowed to simplify immutable functions. But for
3559  * purposes of estimation, we consider it okay to simplify functions that
3560  * are merely stable; the risk that the result might change from planning
3561  * time to execution time is worth taking in preference to not being able
3562  * to estimate the value at all.
3563  */
3564  if (provolatile == PROVOLATILE_IMMUTABLE)
3565  return true;
3566  if (context->estimate && provolatile == PROVOLATILE_STABLE)
3567  return true;
3568  return false;
3569 }
char func_volatile(Oid funcid)
Definition: lsyscache.c:1751

◆ estimate_expression_value()

Node* estimate_expression_value ( PlannerInfo root,
Node node 
)

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

2234 {
2236 
2237  context.boundParams = root->glob->boundParams; /* bound Params */
2238  /* we do not need to mark the plan as depending on inlined functions */
2239  context.root = NULL;
2240  context.active_fns = NIL; /* nothing being recursively simplified */
2241  context.case_val = NULL; /* no CASE being examined */
2242  context.estimate = true; /* unsafe transformations OK */
2243  return eval_const_expressions_mutator(node, &context);
2244 }
#define NIL
Definition: pg_list.h:65
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2278
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 2093 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().

2094 {
2096 
2097  if (root)
2098  context.boundParams = root->glob->boundParams; /* bound Params */
2099  else
2100  context.boundParams = NULL;
2101  context.root = root; /* for inlined-function dependencies */
2102  context.active_fns = NIL; /* nothing being recursively simplified */
2103  context.case_val = NULL; /* no CASE being examined */
2104  context.estimate = false; /* safe transformations only */
2105  return eval_const_expressions_mutator(node, &context);
2106 }
#define NIL
Definition: pg_list.h:65
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2278
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 2278 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(), Const::location, Param::location, 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().

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

◆ evaluate_expr()

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

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

4780 {
4781  EState *estate;
4782  ExprState *exprstate;
4783  MemoryContext oldcontext;
4784  Datum const_val;
4785  bool const_is_null;
4786  int16 resultTypLen;
4787  bool resultTypByVal;
4788 
4789  /*
4790  * To use the executor, we need an EState.
4791  */
4792  estate = CreateExecutorState();
4793 
4794  /* We can use the estate's working context to avoid memory leaks. */
4795  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
4796 
4797  /* Make sure any opfuncids are filled in. */
4798  fix_opfuncids((Node *) expr);
4799 
4800  /*
4801  * Prepare expr for execution. (Note: we can't use ExecPrepareExpr
4802  * because it'd result in recursively invoking eval_const_expressions.)
4803  */
4804  exprstate = ExecInitExpr(expr, NULL);
4805 
4806  /*
4807  * And evaluate it.
4808  *
4809  * It is OK to use a default econtext because none of the ExecEvalExpr()
4810  * code used in this situation will use econtext. That might seem
4811  * fortuitous, but it's not so unreasonable --- a constant expression does
4812  * not depend on context, by definition, n'est ce pas?
4813  */
4814  const_val = ExecEvalExprSwitchContext(exprstate,
4815  GetPerTupleExprContext(estate),
4816  &const_is_null);
4817 
4818  /* Get info needed about result datatype */
4819  get_typlenbyval(result_type, &resultTypLen, &resultTypByVal);
4820 
4821  /* Get back to outer memory context */
4822  MemoryContextSwitchTo(oldcontext);
4823 
4824  /*
4825  * Must copy result out of sub-context used by expression eval.
4826  *
4827  * Also, if it's varlena, forcibly detoast it. This protects us against
4828  * storing TOAST pointers into plans that might outlive the referenced
4829  * data. (makeConst would handle detoasting anyway, but it's worth a few
4830  * extra lines here so that we can do the copy and detoast in one step.)
4831  */
4832  if (!const_is_null)
4833  {
4834  if (resultTypLen == -1)
4835  const_val = PointerGetDatum(PG_DETOAST_DATUM_COPY(const_val));
4836  else
4837  const_val = datumCopy(const_val, resultTypByVal, resultTypLen);
4838  }
4839 
4840  /* Release all the junk we just created */
4841  FreeExecutorState(estate);
4842 
4843  /*
4844  * Make the constant result node.
4845  */
4846  return (Expr *) makeConst(result_type, result_typmod, result_collation,
4847  resultTypLen,
4848  const_val, const_is_null,
4849  resultTypByVal);
4850 }
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:600
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 4231 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().

4236 {
4237  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4238  bool has_nonconst_input = false;
4239  bool has_null_input = false;
4240  ListCell *arg;
4241  FuncExpr *newexpr;
4242 
4243  /*
4244  * Can't simplify if it returns a set.
4245  */
4246  if (funcform->proretset)
4247  return NULL;
4248 
4249  /*
4250  * Can't simplify if it returns RECORD. The immediate problem is that it
4251  * will be needing an expected tupdesc which we can't supply here.
4252  *
4253  * In the case where it has OUT parameters, it could get by without an
4254  * expected tupdesc, but we still have issues: get_expr_result_type()
4255  * doesn't know how to extract type info from a RECORD constant, and in
4256  * the case of a NULL function result there doesn't seem to be any clean
4257  * way to fix that. In view of the likelihood of there being still other
4258  * gotchas, seems best to leave the function call unreduced.
4259  */
4260  if (funcform->prorettype == RECORDOID)
4261  return NULL;
4262 
4263  /*
4264  * Check for constant inputs and especially constant-NULL inputs.
4265  */
4266  foreach(arg, args)
4267  {
4268  if (IsA(lfirst(arg), Const))
4269  has_null_input |= ((Const *) lfirst(arg))->constisnull;
4270  else
4271  has_nonconst_input = true;
4272  }
4273 
4274  /*
4275  * If the function is strict and has a constant-NULL input, it will never
4276  * be called at all, so we can replace the call by a NULL constant, even
4277  * if there are other inputs that aren't constant, and even if the
4278  * function is not otherwise immutable.
4279  */
4280  if (funcform->proisstrict && has_null_input)
4281  return (Expr *) makeNullConst(result_type, result_typmod,
4282  result_collid);
4283 
4284  /*
4285  * Otherwise, can simplify only if all inputs are constants. (For a
4286  * non-strict function, constant NULL inputs are treated the same as
4287  * constant non-NULL inputs.)
4288  */
4289  if (has_nonconst_input)
4290  return NULL;
4291 
4292  /*
4293  * Ordinarily we are only allowed to simplify immutable functions. But for
4294  * purposes of estimation, we consider it okay to simplify functions that
4295  * are merely stable; the risk that the result might change from planning
4296  * time to execution time is worth taking in preference to not being able
4297  * to estimate the value at all.
4298  */
4299  if (funcform->provolatile == PROVOLATILE_IMMUTABLE)
4300  /* okay */ ;
4301  else if (context->estimate && funcform->provolatile == PROVOLATILE_STABLE)
4302  /* okay */ ;
4303  else
4304  return NULL;
4305 
4306  /*
4307  * OK, looks like we can simplify this operator/function.
4308  *
4309  * Build a new FuncExpr node containing the already-simplified arguments.
4310  */
4311  newexpr = makeNode(FuncExpr);
4312  newexpr->funcid = funcid;
4313  newexpr->funcresulttype = result_type;
4314  newexpr->funcretset = false;
4315  newexpr->funcvariadic = funcvariadic;
4316  newexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
4317  newexpr->funccollid = result_collid; /* doesn't matter */
4318  newexpr->inputcollid = input_collid;
4319  newexpr->args = args;
4320  newexpr->location = -1;
4321 
4322  return evaluate_expr((Expr *) newexpr, result_type, result_typmod,
4323  result_collid);
4324 }
Expr * evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod, Oid result_collation)
Definition: clauses.c:4778
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,
bool  include_out_arguments,
Oid  result_type,
HeapTuple  func_tuple 
)

Definition at line 3976 of file clauses.c.

References add_function_defaults(), arg, generate_unaccent_rules::args, ARR_DATA_PTR, ARR_DIMS, ARR_ELEMTYPE, ARR_HASNULL, ARR_NDIM, Assert, DatumGetArrayTypeP, elog, ERROR, GETSTRUCT, IsA, lfirst, list_length(), PROCOID, pronargs, recheck_cast_function_args(), reorder_function_arguments(), and SysCacheGetAttr().

Referenced by eval_const_expressions_mutator(), simplify_function(), and transformCallStmt().

3978 {
3979  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
3980  Oid *proargtypes = funcform->proargtypes.values;
3981  int pronargs = funcform->pronargs;
3982  bool has_named_args = false;
3983  ListCell *lc;
3984 
3985  /*
3986  * If we are asked to match to OUT arguments, then use the proallargtypes
3987  * array (which includes those); otherwise use proargtypes (which
3988  * doesn't). Of course, if proallargtypes is null, we always use
3989  * proargtypes. (Fetching proallargtypes is annoyingly expensive
3990  * considering that we may have nothing to do here, but fortunately the
3991  * common case is include_out_arguments == false.)
3992  */
3993  if (include_out_arguments)
3994  {
3995  Datum proallargtypes;
3996  bool isNull;
3997 
3998  proallargtypes = SysCacheGetAttr(PROCOID, func_tuple,
3999  Anum_pg_proc_proallargtypes,
4000  &isNull);
4001  if (!isNull)
4002  {
4003  ArrayType *arr = DatumGetArrayTypeP(proallargtypes);
4004 
4005  pronargs = ARR_DIMS(arr)[0];
4006  if (ARR_NDIM(arr) != 1 ||
4007  pronargs < 0 ||
4008  ARR_HASNULL(arr) ||
4009  ARR_ELEMTYPE(arr) != OIDOID)
4010  elog(ERROR, "proallargtypes is not a 1-D Oid array or it contains nulls");
4011  Assert(pronargs >= funcform->pronargs);
4012  proargtypes = (Oid *) ARR_DATA_PTR(arr);
4013  }
4014  }
4015 
4016  /* Do we have any named arguments? */
4017  foreach(lc, args)
4018  {
4019  Node *arg = (Node *) lfirst(lc);
4020 
4021  if (IsA(arg, NamedArgExpr))
4022  {
4023  has_named_args = true;
4024  break;
4025  }
4026  }
4027 
4028  /* If so, we must apply reorder_function_arguments */
4029  if (has_named_args)
4030  {
4031  args = reorder_function_arguments(args, pronargs, func_tuple);
4032  /* Recheck argument types and add casts if needed */
4033  recheck_cast_function_args(args, result_type,
4034  proargtypes, pronargs,
4035  func_tuple);
4036  }
4037  else if (list_length(args) < pronargs)
4038  {
4039  /* No named args, but we seem to be short some defaults */
4040  args = add_function_defaults(args, pronargs, func_tuple);
4041  /* Recheck argument types and add casts if needed */
4042  recheck_cast_function_args(args, result_type,
4043  proargtypes, pronargs,
4044  func_tuple);
4045  }
4046 
4047  return args;
4048 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
Definition: nodes.h:539
int16 pronargs
Definition: pg_proc.h:81
unsigned int Oid
Definition: postgres_ext.h:31
static List * reorder_function_arguments(List *args, int pronargs, HeapTuple func_tuple)
Definition: clauses.c:4057
static List * add_function_defaults(List *args, int pronargs, HeapTuple func_tuple)
Definition: clauses.c:4127
#define ERROR
Definition: elog.h:46
#define ARR_DIMS(a)
Definition: array.h:287
#define ARR_DATA_PTR(a)
Definition: array.h:315
#define ARR_HASNULL(a)
Definition: array.h:284
uintptr_t Datum
Definition: postgres.h:411
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1388
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:136
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
#define ARR_NDIM(a)
Definition: array.h:283
#define elog(elevel,...)
Definition: elog.h:232
static void recheck_cast_function_args(List *args, Oid result_type, Oid *proargtypes, int pronargs, HeapTuple func_tuple)
Definition: clauses.c:4186
void * arg
#define ARR_ELEMTYPE(a)
Definition: array.h:285
#define DatumGetArrayTypeP(X)
Definition: array.h:254

◆ expression_returns_set_rows()

double expression_returns_set_rows ( PlannerInfo root,
Node clause 
)

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

287 {
288  if (clause == NULL)
289  return 1.0;
290  if (IsA(clause, FuncExpr))
291  {
292  FuncExpr *expr = (FuncExpr *) clause;
293 
294  if (expr->funcretset)
295  return clamp_row_est(get_function_rows(root, expr->funcid, clause));
296  }
297  if (IsA(clause, OpExpr))
298  {
299  OpExpr *expr = (OpExpr *) clause;
300 
301  if (expr->opretset)
302  {
303  set_opfuncid(expr);
304  return clamp_row_est(get_function_rows(root, expr->opfuncid, clause));
305  }
306  }
307  return 1.0;
308 }
#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 4151 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().

4152 {
4153  List *defaults;
4154  Datum proargdefaults;
4155  bool isnull;
4156  char *str;
4157 
4158  /* The error cases here shouldn't happen, but check anyway */
4159  proargdefaults = SysCacheGetAttr(PROCOID, func_tuple,
4160  Anum_pg_proc_proargdefaults,
4161  &isnull);
4162  if (isnull)
4163  elog(ERROR, "not enough default arguments");
4164  str = TextDatumGetCString(proargdefaults);
4165  defaults = castNode(List, stringToNode(str));
4166  pfree(str);
4167  return defaults;
4168 }
#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 1818 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().

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

◆ find_forced_null_vars()

List* find_forced_null_vars ( Node node)

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

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

◆ find_nonnullable_rels()

Relids find_nonnullable_rels ( Node clause)

Definition at line 1341 of file clauses.c.

References find_nonnullable_rels_walker().

Referenced by make_outerjoininfo(), and reduce_outer_joins_pass2().

1342 {
1343  return find_nonnullable_rels_walker(clause, true);
1344 }
static Relids find_nonnullable_rels_walker(Node *node, bool top_level)
Definition: clauses.c:1347

◆ find_nonnullable_rels_walker()

static Relids find_nonnullable_rels_walker ( Node node,
bool  top_level 
)
static

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

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

References find_nonnullable_vars_walker().

Referenced by reduce_outer_joins_pass2().

1567 {
1568  return find_nonnullable_vars_walker(clause, true);
1569 }
static List * find_nonnullable_vars_walker(Node *node, bool top_level)
Definition: clauses.c:1572

◆ find_nonnullable_vars_walker()

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

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

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

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

Referenced by grouping_planner().

225 {
226  WindowFuncLists *lists = palloc(sizeof(WindowFuncLists));
227 
228  lists->numWindowFuncs = 0;
229  lists->maxWinRef = maxWinRef;
230  lists->windowFuncs = (List **) palloc0((maxWinRef + 1) * sizeof(List *));
231  (void) find_window_functions_walker(clause, lists);
232  return lists;
233 }
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:236
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 236 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().

237 {
238  if (node == NULL)
239  return false;
240  if (IsA(node, WindowFunc))
241  {
242  WindowFunc *wfunc = (WindowFunc *) node;
243 
244  /* winref is unsigned, so one-sided test is OK */
245  if (wfunc->winref > lists->maxWinRef)
246  elog(ERROR, "WindowFunc contains out-of-range winref %u",
247  wfunc->winref);
248  /* eliminate duplicates, so that we avoid repeated computation */
249  if (!list_member(lists->windowFuncs[wfunc->winref], wfunc))
250  {
251  lists->windowFuncs[wfunc->winref] =
252  lappend(lists->windowFuncs[wfunc->winref], wfunc);
253  lists->numWindowFuncs++;
254  }
255 
256  /*
257  * We assume that the parser checked that there are no window
258  * functions in the arguments or filter clause. Hence, we need not
259  * recurse into them. (If either the parser or the planner screws up
260  * on this point, the executor will still catch it; see ExecInitExpr.)
261  */
262  return false;
263  }
264  Assert(!IsA(node, SubLink));
266  (void *) lists);
267 }
#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:236
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 4358 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().

4363 {
4364  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4365  char *src;
4366  Datum tmp;
4367  bool isNull;
4368  MemoryContext oldcxt;
4369  MemoryContext mycxt;
4370  inline_error_callback_arg callback_arg;
4371  ErrorContextCallback sqlerrcontext;
4372  FuncExpr *fexpr;
4374  TupleDesc rettupdesc;
4375  ParseState *pstate;
4376  List *raw_parsetree_list;
4377  List *querytree_list;
4378  Query *querytree;
4379  Node *newexpr;
4380  int *usecounts;
4381  ListCell *arg;
4382  int i;
4383 
4384  /*
4385  * Forget it if the function is not SQL-language or has other showstopper
4386  * properties. (The prokind and nargs checks are just paranoia.)
4387  */
4388  if (funcform->prolang != SQLlanguageId ||
4389  funcform->prokind != PROKIND_FUNCTION ||
4390  funcform->prosecdef ||
4391  funcform->proretset ||
4392  funcform->prorettype == RECORDOID ||
4393  !heap_attisnull(func_tuple, Anum_pg_proc_proconfig, NULL) ||
4394  funcform->pronargs != list_length(args))
4395  return NULL;
4396 
4397  /* Check for recursive function, and give up trying to expand if so */
4398  if (list_member_oid(context->active_fns, funcid))
4399  return NULL;
4400 
4401  /* Check permission to call function (fail later, if not) */
4403  return NULL;
4404 
4405  /* Check whether a plugin wants to hook function entry/exit */
4406  if (FmgrHookIsNeeded(funcid))
4407  return NULL;
4408 
4409  /*
4410  * Make a temporary memory context, so that we don't leak all the stuff
4411  * that parsing might create.
4412  */
4414  "inline_function",
4416  oldcxt = MemoryContextSwitchTo(mycxt);
4417 
4418  /*
4419  * We need a dummy FuncExpr node containing the already-simplified
4420  * arguments. (In some cases we don't really need it, but building it is
4421  * cheap enough that it's not worth contortions to avoid.)
4422  */
4423  fexpr = makeNode(FuncExpr);
4424  fexpr->funcid = funcid;
4425  fexpr->funcresulttype = result_type;
4426  fexpr->funcretset = false;
4427  fexpr->funcvariadic = funcvariadic;
4428  fexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
4429  fexpr->funccollid = result_collid; /* doesn't matter */
4430  fexpr->inputcollid = input_collid;
4431  fexpr->args = args;
4432  fexpr->location = -1;
4433 
4434  /* Fetch the function body */
4435  tmp = SysCacheGetAttr(PROCOID,
4436  func_tuple,
4437  Anum_pg_proc_prosrc,
4438  &isNull);
4439  if (isNull)
4440  elog(ERROR, "null prosrc for function %u", funcid);
4441  src = TextDatumGetCString(tmp);
4442 
4443  /*
4444  * Setup error traceback support for ereport(). This is so that we can
4445  * finger the function that bad information came from.
4446  */
4447  callback_arg.proname = NameStr(funcform->proname);
4448  callback_arg.prosrc = src;
4449 
4450  sqlerrcontext.callback = sql_inline_error_callback;
4451  sqlerrcontext.arg = (void *) &callback_arg;
4452  sqlerrcontext.previous = error_context_stack;
4453  error_context_stack = &sqlerrcontext;
4454 
4455  /* If we have prosqlbody, pay attention to that not prosrc */
4456  tmp = SysCacheGetAttr(PROCOID,
4457  func_tuple,
4458  Anum_pg_proc_prosqlbody,
4459  &isNull);
4460  if (!isNull)
4461  {
4462  Node *n;
4463  List *querytree_list;
4464 
4466  if (IsA(n, List))
4467  querytree_list = linitial_node(List, castNode(List, n));
4468  else
4469  querytree_list = list_make1(n);
4470  if (list_length(querytree_list) != 1)
4471  goto fail;
4472  querytree = linitial(querytree_list);
4473  }
4474  else
4475  {
4476  /* Set up to handle parameters while parsing the function body. */
4477  pinfo = prepare_sql_fn_parse_info(func_tuple,
4478  (Node *) fexpr,
4479  input_collid);
4480 
4481  /*
4482  * We just do parsing and parse analysis, not rewriting, because
4483  * rewriting will not affect table-free-SELECT-only queries, which is
4484  * all that we care about. Also, we can punt as soon as we detect
4485  * more than one command in the function body.
4486  */
4487  raw_parsetree_list = pg_parse_query(src);
4488  if (list_length(raw_parsetree_list) != 1)
4489  goto fail;
4490 
4491  pstate = make_parsestate(NULL);
4492  pstate->p_sourcetext = src;
4493  sql_fn_parser_setup(pstate, pinfo);
4494 
4495  querytree = transformTopLevelStmt(pstate, linitial(raw_parsetree_list));
4496 
4497  free_parsestate(pstate);
4498  }
4499 
4500  /*
4501  * The single command must be a simple "SELECT expression".
4502  *
4503  * Note: if you change the tests involved in this, see also plpgsql's
4504  * exec_simple_check_plan(). That generally needs to have the same idea
4505  * of what's a "simple expression", so that inlining a function that
4506  * previously wasn't inlined won't change plpgsql's conclusion.
4507  */
4508  if (!IsA(querytree, Query) ||
4509  querytree->commandType != CMD_SELECT ||
4510  querytree->hasAggs ||
4511  querytree->hasWindowFuncs ||
4512  querytree->hasTargetSRFs ||
4513  querytree->hasSubLinks ||
4514  querytree->cteList ||
4515  querytree->rtable ||
4516  querytree->jointree->fromlist ||
4517  querytree->jointree->quals ||
4518  querytree->groupClause ||
4519  querytree->groupingSets ||
4520  querytree->havingQual ||
4521  querytree->windowClause ||
4522  querytree->distinctClause ||
4523  querytree->sortClause ||
4524  querytree->limitOffset ||
4525  querytree->limitCount ||
4526  querytree->setOperations ||
4527  list_length(querytree->targetList) != 1)
4528  goto fail;
4529 
4530  /* If the function result is composite, resolve it */
4531  (void) get_expr_result_type((Node *) fexpr,
4532  NULL,
4533  &rettupdesc);
4534 
4535  /*
4536  * Make sure the function (still) returns what it's declared to. This
4537  * will raise an error if wrong, but that's okay since the function would
4538  * fail at runtime anyway. Note that check_sql_fn_retval will also insert
4539  * a coercion if needed to make the tlist expression match the declared
4540  * type of the function.
4541  *
4542  * Note: we do not try this until we have verified that no rewriting was
4543  * needed; that's probably not important, but let's be careful.
4544  */
4545  querytree_list = list_make1(querytree);
4546  if (check_sql_fn_retval(list_make1(querytree_list),
4547  result_type, rettupdesc,
4548  false, NULL))
4549  goto fail; /* reject whole-tuple-result cases */
4550 
4551  /*
4552  * Given the tests above, check_sql_fn_retval shouldn't have decided to
4553  * inject a projection step, but let's just make sure.
4554  */
4555  if (querytree != linitial(querytree_list))
4556  goto fail;
4557 
4558  /* Now we can grab the tlist expression */
4559  newexpr = (Node *) ((TargetEntry *) linitial(querytree->targetList))->expr;
4560 
4561  /*
4562  * If the SQL function returns VOID, we can only inline it if it is a
4563  * SELECT of an expression returning VOID (ie, it's just a redirection to
4564  * another VOID-returning function). In all non-VOID-returning cases,
4565  * check_sql_fn_retval should ensure that newexpr returns the function's
4566  * declared result type, so this test shouldn't fail otherwise; but we may
4567  * as well cope gracefully if it does.
4568  */
4569  if (exprType(newexpr) != result_type)
4570  goto fail;
4571 
4572  /*
4573  * Additional validity checks on the expression. It mustn't be more
4574  * volatile than the surrounding function (this is to avoid breaking hacks
4575  * that involve pretending a function is immutable when it really ain't).
4576  * If the surrounding function is declared strict, then the expression
4577  * must contain only strict constructs and must use all of the function
4578  * parameters (this is overkill, but an exact analysis is hard).
4579  */
4580  if (funcform->provolatile == PROVOLATILE_IMMUTABLE &&
4581  contain_mutable_functions(newexpr))
4582  goto fail;
4583  else if (funcform->provolatile == PROVOLATILE_STABLE &&
4584  contain_volatile_functions(newexpr))
4585  goto fail;
4586 
4587  if (funcform->proisstrict &&
4588  contain_nonstrict_functions(newexpr))
4589  goto fail;
4590 
4591  /*
4592  * If any parameter expression contains a context-dependent node, we can't
4593  * inline, for fear of putting such a node into the wrong context.
4594  */
4595  if (contain_context_dependent_node((Node *) args))
4596  goto fail;
4597 
4598  /*
4599  * We may be able to do it; there are still checks on parameter usage to
4600  * make, but those are most easily done in combination with the actual
4601  * substitution of the inputs. So start building expression with inputs
4602  * substituted.
4603  */
4604  usecounts = (int *) palloc0(funcform->pronargs * sizeof(int));
4605  newexpr = substitute_actual_parameters(newexpr, funcform->pronargs,
4606  args, usecounts);
4607 
4608  /* Now check for parameter usage */
4609  i = 0;
4610  foreach(arg, args)
4611  {
4612  Node *param = lfirst(arg);
4613 
4614  if (usecounts[i] == 0)
4615  {
4616  /* Param not used at all: uncool if func is strict */
4617  if (funcform->proisstrict)
4618  goto fail;
4619  }
4620  else if (usecounts[i] != 1)
4621  {
4622  /* Param used multiple times: uncool if expensive or volatile */
4623  QualCost eval_cost;
4624 
4625  /*
4626  * We define "expensive" as "contains any subplan or more than 10
4627  * operators". Note that the subplan search has to be done
4628  * explicitly, since cost_qual_eval() will barf on unplanned
4629  * subselects.
4630  */
4631  if (contain_subplans(param))
4632  goto fail;
4633  cost_qual_eval(&eval_cost, list_make1(param), NULL);
4634  if (eval_cost.startup + eval_cost.per_tuple >
4635  10 * cpu_operator_cost)
4636  goto fail;
4637 
4638  /*
4639  * Check volatility last since this is more expensive than the
4640  * above tests
4641  */
4642  if (contain_volatile_functions(param))
4643  goto fail;
4644  }
4645  i++;
4646  }
4647 
4648  /*
4649  * Whew --- we can make the substitution. Copy the modified expression
4650  * out of the temporary memory context, and clean up.
4651  */
4652  MemoryContextSwitchTo(oldcxt);
4653 
4654  newexpr = copyObject(newexpr);
4655 
4656  MemoryContextDelete(mycxt);
4657 
4658  /*
4659  * If the result is of a collatable type, force the result to expose the
4660  * correct collation. In most cases this does not matter, but it's
4661  * possible that the function result is used directly as a sort key or in
4662  * other places where we expect exprCollation() to tell the truth.
4663  */
4664  if (OidIsValid(result_collid))
4665  {
4666  Oid exprcoll = exprCollation(newexpr);
4667 
4668  if (OidIsValid(exprcoll) && exprcoll != result_collid)
4669  {
4670  CollateExpr *newnode = makeNode(CollateExpr);
4671 
4672  newnode->arg = (Expr *) newexpr;
4673  newnode->collOid = result_collid;
4674  newnode->location = -1;
4675 
4676  newexpr = (Node *) newnode;
4677  }
4678  }
4679 
4680  /*
4681  * Since there is now no trace of the function in the plan tree, we must
4682  * explicitly record the plan's dependency on the function.
4683  */
4684  if (context->root)
4685  record_plan_function_dependency(context->root, funcid);
4686 
4687  /*
4688  * Recursively try to simplify the modified expression. Here we must add
4689  * the current function to the context list of active functions.
4690  */
4691  context->active_fns = lappend_oid(context->active_fns, funcid);
4692  newexpr = eval_const_expressions_mutator(newexpr, context);
4693  context->active_fns = list_delete_last(context->active_fns);
4694 
4695  error_context_stack = sqlerrcontext.previous;
4696 
4697  return (Expr *) newexpr;
4698 
4699  /* Here if func is not inlinable: release temp memory and return NULL */
4700 fail:
4701  MemoryContextSwitchTo(oldcxt);
4702  MemoryContextDelete(mycxt);
4703  error_context_stack = sqlerrcontext.previous;
4704 
4705  return NULL;
4706 }
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:1599
#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:265
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:1563
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:451
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:1564
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:327
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:2278
#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:4308
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:4712
static void sql_inline_error_callback(void *arg)
Definition: clauses.c:4754
#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:2952
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:213
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:946
Datum querytree(PG_FUNCTION_ARGS)
Definition: _int_bool.c:664
static bool contain_context_dependent_node(Node *clause)
Definition: clauses.c:1064
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:4718
int i
#define NameStr(name)
Definition: c.h:681
void * arg
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:362
int location
Definition