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/rewriteHandler.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 1072 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 2265 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:4785
Definition: nodes.h:536
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41

Definition at line 2269 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:536
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2279

Definition at line 2256 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 2109 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 4128 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().

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

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

References contain_agg_clause_walker().

Referenced by get_eclass_for_sort_expr(), and subquery_planner().

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

◆ contain_agg_clause_walker()

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

Definition at line 181 of file clauses.c.

References Assert, expression_tree_walker(), and IsA.

Referenced by contain_agg_clause().

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

References contain_context_dependent_node_walker().

Referenced by inline_function().

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

◆ contain_context_dependent_node_walker()

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

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

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

◆ contain_exec_param()

bool contain_exec_param ( Node clause,
List param_ids 
)

Definition at line 1023 of file clauses.c.

References contain_exec_param_walker().

Referenced by test_opexpr_is_hashable().

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

◆ contain_exec_param_walker()

static bool contain_exec_param_walker ( Node node,
List param_ids 
)
static

Definition at line 1029 of file clauses.c.

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

Referenced by contain_exec_param().

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

◆ contain_leaked_vars()

bool contain_leaked_vars ( Node clause)

Definition at line 1149 of file clauses.c.

References contain_leaked_vars_walker().

Referenced by make_restrictinfo_internal(), and qual_is_pushdown_safe().

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

◆ contain_leaked_vars_checker()

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

Definition at line 1155 of file clauses.c.

References get_func_leakproof().

Referenced by contain_leaked_vars_walker().

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

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

◆ contain_mutable_functions()

◆ contain_mutable_functions_checker()

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

Definition at line 369 of file clauses.c.

References func_volatile().

Referenced by contain_mutable_functions_walker().

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

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

References expression_tree_walker(), and IsA.

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

◆ contain_nonstrict_functions()

bool contain_nonstrict_functions ( Node clause)

Definition at line 879 of file clauses.c.

References contain_nonstrict_functions_walker().

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

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

◆ contain_nonstrict_functions_checker()

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

Definition at line 885 of file clauses.c.

References func_strict().

Referenced by contain_nonstrict_functions_walker().

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

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

◆ contain_subplans()

bool contain_subplans ( Node clause)

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

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

◆ contain_subplans_walker()

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

Definition at line 334 of file clauses.c.

References expression_tree_walker(), and IsA.

Referenced by contain_subplans().

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

◆ contain_volatile_functions()

◆ contain_volatile_functions_checker()

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

Definition at line 458 of file clauses.c.

References func_volatile().

Referenced by contain_volatile_functions_walker().

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

References contain_volatile_functions_not_nextval_walker().

Referenced by BeginCopyFrom().

560 {
562 }
static bool contain_volatile_functions_not_nextval_walker(Node *node, void *context)
Definition: clauses.c:572

◆ contain_volatile_functions_not_nextval_checker()

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

Definition at line 565 of file clauses.c.

References func_volatile().

Referenced by contain_volatile_functions_not_nextval_walker().

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

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

◆ contain_volatile_functions_walker()

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

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

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

References contain_windowfuncs().

Referenced by get_eclass_for_sort_expr(), and qual_is_pushdown_safe().

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

References convert_saop_to_hashed_saop_walker().

Referenced by preprocess_expression().

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

◆ convert_saop_to_hashed_saop_walker()

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

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

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

◆ ece_function_is_safe()

static bool ece_function_is_safe ( Oid  funcid,
eval_const_expressions_context context 
)
static

Definition at line 3554 of file clauses.c.

References eval_const_expressions_context::estimate, and func_volatile().

Referenced by eval_const_expressions_mutator().

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

◆ estimate_expression_value()

Node* estimate_expression_value ( PlannerInfo root,
Node node 
)

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

2235 {
2237 
2238  context.boundParams = root->glob->boundParams; /* bound Params */
2239  /* we do not need to mark the plan as depending on inlined functions */
2240  context.root = NULL;
2241  context.active_fns = NIL; /* nothing being recursively simplified */
2242  context.case_val = NULL; /* no CASE being examined */
2243  context.estimate = true; /* unsafe transformations OK */
2244  return eval_const_expressions_mutator(node, &context);
2245 }
#define NIL
Definition: pg_list.h:65
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2279
ParamListInfo boundParams
Definition: clauses.c:60
PlannerGlobal * glob
Definition: pathnodes.h:164
ParamListInfo boundParams
Definition: pathnodes.h:94

◆ eval_const_expressions()

Node* eval_const_expressions ( PlannerInfo root,
Node node 
)

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

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

◆ eval_const_expressions_mutator()

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

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

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

◆ evaluate_expr()

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

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

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

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

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

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

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

1820 {
1821  if (node == NULL)
1822  return NULL;
1823  if (IsA(node, NullTest))
1824  {
1825  /* check for var IS NULL */
1826  NullTest *expr = (NullTest *) node;
1827 
1828  if (expr->nulltesttype == IS_NULL && !expr->argisrow)
1829  {
1830  Var *var = (Var *) expr->arg;
1831 
1832  if (var && IsA(var, Var) &&
1833  var->varlevelsup == 0)
1834  return var;
1835  }
1836  }
1837  else if (IsA(node, BooleanTest))
1838  {
1839  /* var IS UNKNOWN is equivalent to var IS NULL */
1840  BooleanTest *expr = (BooleanTest *) node;
1841 
1842  if (expr->booltesttype == IS_UNKNOWN)
1843  {
1844  Var *var = (Var *) expr->arg;
1845 
1846  if (var && IsA(var, Var) &&
1847  var->varlevelsup == 0)
1848  return var;
1849  }
1850  }
1851  return NULL;
1852 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:587
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 1760 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().

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

◆ find_nonnullable_rels()

Relids find_nonnullable_rels ( Node clause)

Definition at line 1342 of file clauses.c.

References find_nonnullable_rels_walker().

Referenced by make_outerjoininfo(), and reduce_outer_joins_pass2().

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

◆ find_nonnullable_rels_walker()

static Relids find_nonnullable_rels_walker ( Node node,
bool  top_level 
)
static

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

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

References find_nonnullable_vars_walker().

Referenced by reduce_outer_joins_pass2().

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

◆ find_nonnullable_vars_walker()

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

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

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

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

Referenced by grouping_planner().

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

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

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