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/multibitmapset.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/json.h"
#include "utils/jsonb.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)
 
static bool pull_paramids_walker (Node *node, Bitmapset **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)
 
Bitmapsetpull_paramids (Expr *expr)
 

Macro Definition Documentation

◆ CCDN_CASETESTEXPR_OK

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

Definition at line 1103 of file clauses.c.

◆ ece_all_arguments_const

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

Definition at line 2343 of file clauses.c.

◆ 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:4866
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:43
Definition: nodes.h:129

Definition at line 2347 of file clauses.c.

◆ ece_generic_processing

#define ece_generic_processing (   node)
Value:
(void *) context)
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2357
#define expression_tree_mutator(n, m, c)
Definition: nodeFuncs.h:153

Definition at line 2334 of file clauses.c.

◆ MIN_ARRAY_SIZE_FOR_HASHED_SAOP

#define MIN_ARRAY_SIZE_FOR_HASHED_SAOP   9

Definition at line 2186 of file clauses.c.

Function Documentation

◆ add_function_defaults()

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

Definition at line 4219 of file clauses.c.

4220 {
4221  int nargsprovided = list_length(args);
4222  List *defaults;
4223  int ndelete;
4224 
4225  /* Get all the default expressions from the pg_proc tuple */
4226  defaults = fetch_function_defaults(func_tuple);
4227 
4228  /* Delete any unused defaults from the list */
4229  ndelete = nargsprovided + list_length(defaults) - pronargs;
4230  if (ndelete < 0)
4231  elog(ERROR, "not enough default arguments");
4232  if (ndelete > 0)
4233  defaults = list_delete_first_n(defaults, ndelete);
4234 
4235  /* And form the combined argument list, not modifying the input list */
4236  return list_concat_copy(args, defaults);
4237 }
static List * fetch_function_defaults(HeapTuple func_tuple)
Definition: clauses.c:4243
#define ERROR
Definition: elog.h:39
List * list_delete_first_n(List *list, int n)
Definition: list.c:982
List * list_concat_copy(const List *list1, const List *list2)
Definition: list.c:597
static int list_length(const List *l)
Definition: pg_list.h:152
int16 pronargs
Definition: pg_proc.h:81
Definition: pg_list.h:54

References generate_unaccent_rules::args, elog(), ERROR, fetch_function_defaults(), list_concat_copy(), list_delete_first_n(), list_length(), and pronargs.

Referenced by expand_function_arguments().

◆ CommuteOpExpr()

void CommuteOpExpr ( OpExpr clause)

Definition at line 2064 of file clauses.c.

2065 {
2066  Oid opoid;
2067  Node *temp;
2068 
2069  /* Sanity checks: caller is at fault if these fail */
2070  if (!is_opclause(clause) ||
2071  list_length(clause->args) != 2)
2072  elog(ERROR, "cannot commute non-binary-operator clause");
2073 
2074  opoid = get_commutator(clause->opno);
2075 
2076  if (!OidIsValid(opoid))
2077  elog(ERROR, "could not find commutator for operator %u",
2078  clause->opno);
2079 
2080  /*
2081  * modify the clause in-place!
2082  */
2083  clause->opno = opoid;
2084  clause->opfuncid = InvalidOid;
2085  /* opresulttype, opretset, opcollid, inputcollid need not change */
2086 
2087  temp = linitial(clause->args);
2088  linitial(clause->args) = lsecond(clause->args);
2089  lsecond(clause->args) = temp;
2090 }
#define OidIsValid(objectId)
Definition: c.h:764
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1513
static bool is_opclause(const void *clause)
Definition: nodeFuncs.h:74
#define linitial(l)
Definition: pg_list.h:178
#define lsecond(l)
Definition: pg_list.h:183
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
Oid opno
Definition: primnodes.h:745
List * args
Definition: primnodes.h:763

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

Referenced by get_switched_clauses().

◆ contain_agg_clause()

bool contain_agg_clause ( Node clause)

Definition at line 179 of file clauses.c.

180 {
181  return contain_agg_clause_walker(clause, NULL);
182 }
static bool contain_agg_clause_walker(Node *node, void *context)
Definition: clauses.c:185

References contain_agg_clause_walker().

Referenced by get_eclass_for_sort_expr(), and subquery_planner().

◆ contain_agg_clause_walker()

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

Definition at line 185 of file clauses.c.

186 {
187  if (node == NULL)
188  return false;
189  if (IsA(node, Aggref))
190  {
191  Assert(((Aggref *) node)->agglevelsup == 0);
192  return true; /* abort the tree traversal and return true */
193  }
194  if (IsA(node, GroupingFunc))
195  {
196  Assert(((GroupingFunc *) node)->agglevelsup == 0);
197  return true; /* abort the tree traversal and return true */
198  }
199  Assert(!IsA(node, SubLink));
200  return expression_tree_walker(node, contain_agg_clause_walker, context);
201 }
Assert(fmt[strlen(fmt) - 1] !='\n')
#define expression_tree_walker(n, w, c)
Definition: nodeFuncs.h:151
#define IsA(nodeptr, _type_)
Definition: nodes.h:179

References Assert(), expression_tree_walker, and IsA.

Referenced by contain_agg_clause().

◆ contain_context_dependent_node()

static bool contain_context_dependent_node ( Node clause)
static

Definition at line 1096 of file clauses.c.

1097 {
1098  int flags = 0;
1099 
1100  return contain_context_dependent_node_walker(clause, &flags);
1101 }
static bool contain_context_dependent_node_walker(Node *node, int *flags)
Definition: clauses.c:1106

References contain_context_dependent_node_walker().

Referenced by inline_function().

◆ contain_context_dependent_node_walker()

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

Definition at line 1106 of file clauses.c.

1107 {
1108  if (node == NULL)
1109  return false;
1110  if (IsA(node, CaseTestExpr))
1111  return !(*flags & CCDN_CASETESTEXPR_OK);
1112  else if (IsA(node, CaseExpr))
1113  {
1114  CaseExpr *caseexpr = (CaseExpr *) node;
1115 
1116  /*
1117  * If this CASE doesn't have a test expression, then it doesn't create
1118  * a context in which CaseTestExprs should appear, so just fall
1119  * through and treat it as a generic expression node.
1120  */
1121  if (caseexpr->arg)
1122  {
1123  int save_flags = *flags;
1124  bool res;
1125 
1126  /*
1127  * Note: in principle, we could distinguish the various sub-parts
1128  * of a CASE construct and set the flag bit only for some of them,
1129  * since we are only expecting CaseTestExprs to appear in the
1130  * "expr" subtree of the CaseWhen nodes. But it doesn't really
1131  * seem worth any extra code. If there are any bare CaseTestExprs
1132  * elsewhere in the CASE, something's wrong already.
1133  */
1134  *flags |= CCDN_CASETESTEXPR_OK;
1135  res = expression_tree_walker(node,
1137  (void *) flags);
1138  *flags = save_flags;
1139  return res;
1140  }
1141  }
1142  else if (IsA(node, ArrayCoerceExpr))
1143  {
1144  ArrayCoerceExpr *ac = (ArrayCoerceExpr *) node;
1145  int save_flags;
1146  bool res;
1147 
1148  /* Check the array expression */
1149  if (contain_context_dependent_node_walker((Node *) ac->arg, flags))
1150  return true;
1151 
1152  /* Check the elemexpr, which is allowed to contain CaseTestExpr */
1153  save_flags = *flags;
1154  *flags |= CCDN_CASETESTEXPR_OK;
1156  flags);
1157  *flags = save_flags;
1158  return res;
1159  }
1161  (void *) flags);
1162 }
#define CCDN_CASETESTEXPR_OK
Definition: clauses.c:1103
Expr * arg
Definition: primnodes.h:1240

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

Referenced by contain_context_dependent_node().

◆ contain_exec_param()

bool contain_exec_param ( Node clause,
List param_ids 
)

Definition at line 1054 of file clauses.c.

1055 {
1056  return contain_exec_param_walker(clause, param_ids);
1057 }
static bool contain_exec_param_walker(Node *node, List *param_ids)
Definition: clauses.c:1060

References contain_exec_param_walker().

Referenced by test_opexpr_is_hashable().

◆ contain_exec_param_walker()

static bool contain_exec_param_walker ( Node node,
List param_ids 
)
static

Definition at line 1060 of file clauses.c.

1061 {
1062  if (node == NULL)
1063  return false;
1064  if (IsA(node, Param))
1065  {
1066  Param *p = (Param *) node;
1067 
1068  if (p->paramkind == PARAM_EXEC &&
1069  list_member_int(param_ids, p->paramid))
1070  return true;
1071  }
1072  return expression_tree_walker(node, contain_exec_param_walker, param_ids);
1073 }
bool list_member_int(const List *list, int datum)
Definition: list.c:701
@ PARAM_EXEC
Definition: primnodes.h:346
int paramid
Definition: primnodes.h:355
ParamKind paramkind
Definition: primnodes.h:354

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

Referenced by contain_exec_param().

◆ contain_leaked_vars()

bool contain_leaked_vars ( Node clause)

Definition at line 1180 of file clauses.c.

1181 {
1182  return contain_leaked_vars_walker(clause, NULL);
1183 }
static bool contain_leaked_vars_walker(Node *node, void *context)
Definition: clauses.c:1192

References contain_leaked_vars_walker().

Referenced by make_restrictinfo_internal(), and qual_is_pushdown_safe().

◆ contain_leaked_vars_checker()

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

Definition at line 1186 of file clauses.c.

1187 {
1188  return !get_func_leakproof(func_id);
1189 }
bool get_func_leakproof(Oid funcid)
Definition: lsyscache.c:1841

References get_func_leakproof().

Referenced by contain_leaked_vars_walker().

◆ contain_leaked_vars_walker()

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

Definition at line 1192 of file clauses.c.

1193 {
1194  if (node == NULL)
1195  return false;
1196 
1197  switch (nodeTag(node))
1198  {
1199  case T_Var:
1200  case T_Const:
1201  case T_Param:
1202  case T_ArrayExpr:
1203  case T_FieldSelect:
1204  case T_FieldStore:
1205  case T_NamedArgExpr:
1206  case T_BoolExpr:
1207  case T_RelabelType:
1208  case T_CollateExpr:
1209  case T_CaseExpr:
1210  case T_CaseTestExpr:
1211  case T_RowExpr:
1212  case T_SQLValueFunction:
1213  case T_NullTest:
1214  case T_BooleanTest:
1215  case T_NextValueExpr:
1216  case T_List:
1217 
1218  /*
1219  * We know these node types don't contain function calls; but
1220  * something further down in the node tree might.
1221  */
1222  break;
1223 
1224  case T_FuncExpr:
1225  case T_OpExpr:
1226  case T_DistinctExpr:
1227  case T_NullIfExpr:
1228  case T_ScalarArrayOpExpr:
1229  case T_CoerceViaIO:
1230  case T_ArrayCoerceExpr:
1231 
1232  /*
1233  * If node contains a leaky function call, and there's any Var
1234  * underneath it, reject.
1235  */
1237  context) &&
1238  contain_var_clause(node))
1239  return true;
1240  break;
1241 
1242  case T_SubscriptingRef:
1243  {
1244  SubscriptingRef *sbsref = (SubscriptingRef *) node;
1245  const SubscriptRoutines *sbsroutines;
1246 
1247  /* Consult the subscripting support method info */
1248  sbsroutines = getSubscriptingRoutines(sbsref->refcontainertype,
1249  NULL);
1250  if (!sbsroutines ||
1251  !(sbsref->refassgnexpr != NULL ?
1252  sbsroutines->store_leakproof :
1253  sbsroutines->fetch_leakproof))
1254  {
1255  /* Node is leaky, so reject if it contains Vars */
1256  if (contain_var_clause(node))
1257  return true;
1258  }
1259  }
1260  break;
1261 
1262  case T_RowCompareExpr:
1263  {
1264  /*
1265  * It's worth special-casing this because a leaky comparison
1266  * function only compromises one pair of row elements, which
1267  * might not contain Vars while others do.
1268  */
1269  RowCompareExpr *rcexpr = (RowCompareExpr *) node;
1270  ListCell *opid;
1271  ListCell *larg;
1272  ListCell *rarg;
1273 
1274  forthree(opid, rcexpr->opnos,
1275  larg, rcexpr->largs,
1276  rarg, rcexpr->rargs)
1277  {
1278  Oid funcid = get_opcode(lfirst_oid(opid));
1279 
1280  if (!get_func_leakproof(funcid) &&
1281  (contain_var_clause((Node *) lfirst(larg)) ||
1282  contain_var_clause((Node *) lfirst(rarg))))
1283  return true;
1284  }
1285  }
1286  break;
1287 
1288  case T_MinMaxExpr:
1289  {
1290  /*
1291  * MinMaxExpr is leakproof if the comparison function it calls
1292  * is leakproof.
1293  */
1294  MinMaxExpr *minmaxexpr = (MinMaxExpr *) node;
1295  TypeCacheEntry *typentry;
1296  bool leakproof;
1297 
1298  /* Look up the btree comparison function for the datatype */
1299  typentry = lookup_type_cache(minmaxexpr->minmaxtype,
1301  if (OidIsValid(typentry->cmp_proc))
1302  leakproof = get_func_leakproof(typentry->cmp_proc);
1303  else
1304  {
1305  /*
1306  * The executor will throw an error, but here we just
1307  * treat the missing function as leaky.
1308  */
1309  leakproof = false;
1310  }
1311 
1312  if (!leakproof &&
1313  contain_var_clause((Node *) minmaxexpr->args))
1314  return true;
1315  }
1316  break;
1317 
1318  case T_CurrentOfExpr:
1319 
1320  /*
1321  * WHERE CURRENT OF doesn't contain leaky function calls.
1322  * Moreover, it is essential that this is considered non-leaky,
1323  * since the planner must always generate a TID scan when CURRENT
1324  * OF is present -- cf. cost_tidscan.
1325  */
1326  return false;
1327 
1328  default:
1329 
1330  /*
1331  * If we don't recognize the node tag, assume it might be leaky.
1332  * This prevents an unexpected security hole if someone adds a new
1333  * node type that can call a function.
1334  */
1335  return true;
1336  }
1338  context);
1339 }
static bool contain_leaked_vars_checker(Oid func_id, void *context)
Definition: clauses.c:1186
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1289
const struct SubscriptRoutines * getSubscriptingRoutines(Oid typid, Oid *typelemp)
Definition: lsyscache.c:3112
bool check_functions_in_node(Node *node, check_function_callback checker, void *context)
Definition: nodeFuncs.c:1817
#define nodeTag(nodeptr)
Definition: nodes.h:133
#define lfirst(lc)
Definition: pg_list.h:172
#define forthree(cell1, list1, cell2, list2, cell3, list3)
Definition: pg_list.h:512
#define lfirst_oid(lc)
Definition: pg_list.h:174
List * args
Definition: primnodes.h:1445
Expr * refassgnexpr
Definition: primnodes.h:630
TypeCacheEntry * lookup_type_cache(Oid type_id, int flags)
Definition: typcache.c:344
#define TYPECACHE_CMP_PROC
Definition: typcache.h:139
bool contain_var_clause(Node *node)
Definition: var.c:403

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(), nodeTag, OidIsValid, RowCompareExpr::rargs, SubscriptingRef::refassgnexpr, SubscriptRoutines::store_leakproof, and TYPECACHE_CMP_PROC.

Referenced by contain_leaked_vars().

◆ contain_mutable_functions()

◆ contain_mutable_functions_checker()

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

Definition at line 373 of file clauses.c.

374 {
375  return (func_volatile(func_id) != PROVOLATILE_IMMUTABLE);
376 }
char func_volatile(Oid funcid)
Definition: lsyscache.c:1784

References func_volatile().

Referenced by contain_mutable_functions_walker().

◆ contain_mutable_functions_walker()

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

Definition at line 379 of file clauses.c.

380 {
381  if (node == NULL)
382  return false;
383  /* Check for mutable functions in node itself */
385  context))
386  return true;
387 
388  if (IsA(node, JsonConstructorExpr))
389  {
390  const JsonConstructorExpr *ctor = (JsonConstructorExpr *) node;
391  ListCell *lc;
392  bool is_jsonb;
393 
394  is_jsonb = ctor->returning->format->format_type == JS_FORMAT_JSONB;
395 
396  /*
397  * Check argument_type => json[b] conversions specifically. We still
398  * recurse to check 'args' below, but here we want to specifically
399  * check whether or not the emitted clause would fail to be immutable
400  * because of TimeZone, for example.
401  */
402  foreach(lc, ctor->args)
403  {
404  Oid typid = exprType(lfirst(lc));
405 
406  if (is_jsonb ?
407  !to_jsonb_is_immutable(typid) :
408  !to_json_is_immutable(typid))
409  return true;
410  }
411 
412  /* Check all subnodes */
413  }
414 
415  if (IsA(node, SQLValueFunction))
416  {
417  /* all variants of SQLValueFunction are stable */
418  return true;
419  }
420 
421  if (IsA(node, NextValueExpr))
422  {
423  /* NextValueExpr is volatile */
424  return true;
425  }
426 
427  /*
428  * It should be safe to treat MinMaxExpr as immutable, because it will
429  * depend on a non-cross-type btree comparison function, and those should
430  * always be immutable. Treating XmlExpr as immutable is more dubious,
431  * and treating CoerceToDomain as immutable is outright dangerous. But we
432  * have done so historically, and changing this would probably cause more
433  * problems than it would fix. In practice, if you have a non-immutable
434  * domain constraint you are in for pain anyhow.
435  */
436 
437  /* Recurse to check arguments */
438  if (IsA(node, Query))
439  {
440  /* Recurse into subselects */
441  return query_tree_walker((Query *) node,
443  context, 0);
444  }
446  context);
447 }
static bool contain_mutable_functions_checker(Oid func_id, void *context)
Definition: clauses.c:373
bool to_json_is_immutable(Oid typoid)
Definition: json.c:667
bool to_jsonb_is_immutable(Oid typoid)
Definition: jsonb.c:1053
#define query_tree_walker(q, w, c, f)
Definition: nodeFuncs.h:156
@ JS_FORMAT_JSONB
Definition: primnodes.h:1567
JsonReturning * returning
Definition: primnodes.h:1633
JsonFormatType format_type
Definition: primnodes.h:1578
JsonFormat * format
Definition: primnodes.h:1590

References JsonConstructorExpr::args, check_functions_in_node(), contain_mutable_functions_checker(), expression_tree_walker, exprType(), JsonReturning::format, JsonFormat::format_type, IsA, JS_FORMAT_JSONB, lfirst, query_tree_walker, JsonConstructorExpr::returning, to_json_is_immutable(), and to_jsonb_is_immutable().

Referenced by contain_mutable_functions().

◆ contain_non_const_walker()

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

Definition at line 3629 of file clauses.c.

3630 {
3631  if (node == NULL)
3632  return false;
3633  if (IsA(node, Const))
3634  return false;
3635  if (IsA(node, List))
3636  return expression_tree_walker(node, contain_non_const_walker, context);
3637  /* Otherwise, abort the tree traversal and return true */
3638  return true;
3639 }
static bool contain_non_const_walker(Node *node, void *context)
Definition: clauses.c:3629

References expression_tree_walker, and IsA.

◆ contain_nonstrict_functions()

bool contain_nonstrict_functions ( Node clause)

Definition at line 910 of file clauses.c.

911 {
912  return contain_nonstrict_functions_walker(clause, NULL);
913 }
static bool contain_nonstrict_functions_walker(Node *node, void *context)
Definition: clauses.c:922

References contain_nonstrict_functions_walker().

Referenced by inline_function().

◆ contain_nonstrict_functions_checker()

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

Definition at line 916 of file clauses.c.

917 {
918  return !func_strict(func_id);
919 }
bool func_strict(Oid funcid)
Definition: lsyscache.c:1765

References func_strict().

Referenced by contain_nonstrict_functions_walker().

◆ contain_nonstrict_functions_walker()

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

Definition at line 922 of file clauses.c.

923 {
924  if (node == NULL)
925  return false;
926  if (IsA(node, Aggref))
927  {
928  /* an aggregate could return non-null with null input */
929  return true;
930  }
931  if (IsA(node, GroupingFunc))
932  {
933  /*
934  * A GroupingFunc doesn't evaluate its arguments, and therefore must
935  * be treated as nonstrict.
936  */
937  return true;
938  }
939  if (IsA(node, WindowFunc))
940  {
941  /* a window function could return non-null with null input */
942  return true;
943  }
944  if (IsA(node, SubscriptingRef))
945  {
946  SubscriptingRef *sbsref = (SubscriptingRef *) node;
947  const SubscriptRoutines *sbsroutines;
948 
949  /* Subscripting assignment is always presumed nonstrict */
950  if (sbsref->refassgnexpr != NULL)
951  return true;
952  /* Otherwise we must look up the subscripting support methods */
953  sbsroutines = getSubscriptingRoutines(sbsref->refcontainertype, NULL);
954  if (!(sbsroutines && sbsroutines->fetch_strict))
955  return true;
956  /* else fall through to check args */
957  }
958  if (IsA(node, DistinctExpr))
959  {
960  /* IS DISTINCT FROM is inherently non-strict */
961  return true;
962  }
963  if (IsA(node, NullIfExpr))
964  {
965  /* NULLIF is inherently non-strict */
966  return true;
967  }
968  if (IsA(node, BoolExpr))
969  {
970  BoolExpr *expr = (BoolExpr *) node;
971 
972  switch (expr->boolop)
973  {
974  case AND_EXPR:
975  case OR_EXPR:
976  /* AND, OR are inherently non-strict */
977  return true;
978  default:
979  break;
980  }
981  }
982  if (IsA(node, SubLink))
983  {
984  /* In some cases a sublink might be strict, but in general not */
985  return true;
986  }
987  if (IsA(node, SubPlan))
988  return true;
989  if (IsA(node, AlternativeSubPlan))
990  return true;
991  if (IsA(node, FieldStore))
992  return true;
993  if (IsA(node, CoerceViaIO))
994  {
995  /*
996  * CoerceViaIO is strict regardless of whether the I/O functions are,
997  * so just go look at its argument; asking check_functions_in_node is
998  * useless expense and could deliver the wrong answer.
999  */
1000  return contain_nonstrict_functions_walker((Node *) ((CoerceViaIO *) node)->arg,
1001  context);
1002  }
1003  if (IsA(node, ArrayCoerceExpr))
1004  {
1005  /*
1006  * ArrayCoerceExpr is strict at the array level, regardless of what
1007  * the per-element expression is; so we should ignore elemexpr and
1008  * recurse only into the arg.
1009  */
1011  context);
1012  }
1013  if (IsA(node, CaseExpr))
1014  return true;
1015  if (IsA(node, ArrayExpr))
1016  return true;
1017  if (IsA(node, RowExpr))
1018  return true;
1019  if (IsA(node, RowCompareExpr))
1020  return true;
1021  if (IsA(node, CoalesceExpr))
1022  return true;
1023  if (IsA(node, MinMaxExpr))
1024  return true;
1025  if (IsA(node, XmlExpr))
1026  return true;
1027  if (IsA(node, NullTest))
1028  return true;
1029  if (IsA(node, BooleanTest))
1030  return true;
1031 
1032  /* Check other function-containing nodes */
1034  context))
1035  return true;
1036 
1038  context);
1039 }
static bool contain_nonstrict_functions_checker(Oid func_id, void *context)
Definition: clauses.c:916
void * arg
@ AND_EXPR
Definition: primnodes.h:858
@ OR_EXPR
Definition: primnodes.h:858
BoolExprType boolop
Definition: primnodes.h:866

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

Referenced by contain_nonstrict_functions().

◆ contain_subplans()

bool contain_subplans ( Node clause)

Definition at line 332 of file clauses.c.

333 {
334  return contain_subplans_walker(clause, NULL);
335 }
static bool contain_subplans_walker(Node *node, void *context)
Definition: clauses.c:338

References contain_subplans_walker().

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

◆ contain_subplans_walker()

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

Definition at line 338 of file clauses.c.

339 {
340  if (node == NULL)
341  return false;
342  if (IsA(node, SubPlan) ||
343  IsA(node, AlternativeSubPlan) ||
344  IsA(node, SubLink))
345  return true; /* abort the tree traversal and return true */
346  return expression_tree_walker(node, contain_subplans_walker, context);
347 }

References expression_tree_walker, and IsA.

Referenced by contain_subplans().

◆ contain_volatile_functions()

◆ contain_volatile_functions_checker()

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

Definition at line 489 of file clauses.c.

490 {
491  return (func_volatile(func_id) == PROVOLATILE_VOLATILE);
492 }

References func_volatile().

Referenced by contain_volatile_functions_walker().

◆ contain_volatile_functions_not_nextval()

bool contain_volatile_functions_not_nextval ( Node clause)

Definition at line 590 of file clauses.c.

591 {
593 }
static bool contain_volatile_functions_not_nextval_walker(Node *node, void *context)
Definition: clauses.c:603

References contain_volatile_functions_not_nextval_walker().

Referenced by BeginCopyFrom().

◆ contain_volatile_functions_not_nextval_checker()

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

Definition at line 596 of file clauses.c.

597 {
598  return (func_id != F_NEXTVAL &&
599  func_volatile(func_id) == PROVOLATILE_VOLATILE);
600 }

References func_volatile().

Referenced by contain_volatile_functions_not_nextval_walker().

◆ contain_volatile_functions_not_nextval_walker()

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

Definition at line 603 of file clauses.c.

604 {
605  if (node == NULL)
606  return false;
607  /* Check for volatile functions in node itself */
608  if (check_functions_in_node(node,
610  context))
611  return true;
612 
613  /*
614  * See notes in contain_mutable_functions_walker about why we treat
615  * MinMaxExpr, XmlExpr, and CoerceToDomain as immutable, while
616  * SQLValueFunction is stable. Hence, none of them are of interest here.
617  * Also, since we're intentionally ignoring nextval(), presumably we
618  * should ignore NextValueExpr.
619  */
620 
621  /* Recurse to check arguments */
622  if (IsA(node, Query))
623  {
624  /* Recurse into subselects */
625  return query_tree_walker((Query *) node,
627  context, 0);
628  }
629  return expression_tree_walker(node,
631  context);
632 }
static bool contain_volatile_functions_not_nextval_checker(Oid func_id, void *context)
Definition: clauses.c:596

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().

◆ contain_volatile_functions_walker()

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

Definition at line 495 of file clauses.c.

496 {
497  if (node == NULL)
498  return false;
499  /* Check for volatile functions in node itself */
501  context))
502  return true;
503 
504  if (IsA(node, NextValueExpr))
505  {
506  /* NextValueExpr is volatile */
507  return true;
508  }
509 
510  if (IsA(node, RestrictInfo))
511  {
512  RestrictInfo *rinfo = (RestrictInfo *) node;
513 
514  /*
515  * For RestrictInfo, check if we've checked the volatility of it
516  * before. If so, we can just use the cached value and not bother
517  * checking it again. Otherwise, check it and cache if whether we
518  * found any volatile functions.
519  */
520  if (rinfo->has_volatile == VOLATILITY_NOVOLATILE)
521  return false;
522  else if (rinfo->has_volatile == VOLATILITY_VOLATILE)
523  return true;
524  else
525  {
526  bool hasvolatile;
527 
528  hasvolatile = contain_volatile_functions_walker((Node *) rinfo->clause,
529  context);
530  if (hasvolatile)
531  rinfo->has_volatile = VOLATILITY_VOLATILE;
532  else
533  rinfo->has_volatile = VOLATILITY_NOVOLATILE;
534 
535  return hasvolatile;
536  }
537  }
538 
539  if (IsA(node, PathTarget))
540  {
541  PathTarget *target = (PathTarget *) node;
542 
543  /*
544  * We also do caching for PathTarget the same as we do above for
545  * RestrictInfos.
546  */
548  return false;
549  else if (target->has_volatile_expr == VOLATILITY_VOLATILE)
550  return true;
551  else
552  {
553  bool hasvolatile;
554 
555  hasvolatile = contain_volatile_functions_walker((Node *) target->exprs,
556  context);
557 
558  if (hasvolatile)
560  else
562 
563  return hasvolatile;
564  }
565  }
566 
567  /*
568  * See notes in contain_mutable_functions_walker about why we treat
569  * MinMaxExpr, XmlExpr, and CoerceToDomain as immutable, while
570  * SQLValueFunction is stable. Hence, none of them are of interest here.
571  */
572 
573  /* Recurse to check arguments */
574  if (IsA(node, Query))
575  {
576  /* Recurse into subselects */
577  return query_tree_walker((Query *) node,
579  context, 0);
580  }
582  context);
583 }
static bool contain_volatile_functions_checker(Oid func_id, void *context)
Definition: clauses.c:489
@ VOLATILITY_NOVOLATILE
Definition: pathnodes.h:1468
@ VOLATILITY_VOLATILE
Definition: pathnodes.h:1467
VolatileFunctionStatus has_volatile_expr
Definition: pathnodes.h:1513
List * exprs
Definition: pathnodes.h:1501
Expr * clause
Definition: pathnodes.h:2529

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

Referenced by contain_volatile_functions().

◆ contain_window_function()

bool contain_window_function ( Node clause)

Definition at line 216 of file clauses.c.

217 {
218  return contain_windowfuncs(clause);
219 }
bool contain_windowfuncs(Node *node)
Definition: rewriteManip.c:215

References contain_windowfuncs().

Referenced by get_eclass_for_sort_expr().

◆ convert_saop_to_hashed_saop()

void convert_saop_to_hashed_saop ( Node node)

Definition at line 2204 of file clauses.c.

2205 {
2206  (void) convert_saop_to_hashed_saop_walker(node, NULL);
2207 }
static bool convert_saop_to_hashed_saop_walker(Node *node, void *context)
Definition: clauses.c:2210

References convert_saop_to_hashed_saop_walker().

Referenced by preprocess_expression().

◆ convert_saop_to_hashed_saop_walker()

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

Definition at line 2210 of file clauses.c.

2211 {
2212  if (node == NULL)
2213  return false;
2214 
2215  if (IsA(node, ScalarArrayOpExpr))
2216  {
2217  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
2218  Expr *arrayarg = (Expr *) lsecond(saop->args);
2219  Oid lefthashfunc;
2220  Oid righthashfunc;
2221 
2222  if (arrayarg && IsA(arrayarg, Const) &&
2223  !((Const *) arrayarg)->constisnull)
2224  {
2225  if (saop->useOr)
2226  {
2227  if (get_op_hash_functions(saop->opno, &lefthashfunc, &righthashfunc) &&
2228  lefthashfunc == righthashfunc)
2229  {
2230  Datum arrdatum = ((Const *) arrayarg)->constvalue;
2231  ArrayType *arr = (ArrayType *) DatumGetPointer(arrdatum);
2232  int nitems;
2233 
2234  /*
2235  * Only fill in the hash functions if the array looks
2236  * large enough for it to be worth hashing instead of
2237  * doing a linear search.
2238  */
2239  nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr));
2240 
2242  {
2243  /* Looks good. Fill in the hash functions */
2244  saop->hashfuncid = lefthashfunc;
2245  }
2246  return true;
2247  }
2248  }
2249  else /* !saop->useOr */
2250  {
2251  Oid negator = get_negator(saop->opno);
2252 
2253  /*
2254  * Check if this is a NOT IN using an operator whose negator
2255  * is hashable. If so we can still build a hash table and
2256  * just ensure the lookup items are not in the hash table.
2257  */
2258  if (OidIsValid(negator) &&
2259  get_op_hash_functions(negator, &lefthashfunc, &righthashfunc) &&
2260  lefthashfunc == righthashfunc)
2261  {
2262  Datum arrdatum = ((Const *) arrayarg)->constvalue;
2263  ArrayType *arr = (ArrayType *) DatumGetPointer(arrdatum);
2264  int nitems;
2265 
2266  /*
2267  * Only fill in the hash functions if the array looks
2268  * large enough for it to be worth hashing instead of
2269  * doing a linear search.
2270  */
2271  nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr));
2272 
2274  {
2275  /* Looks good. Fill in the hash functions */
2276  saop->hashfuncid = lefthashfunc;
2277 
2278  /*
2279  * Also set the negfuncid. The executor will need
2280  * that to perform hashtable lookups.
2281  */
2282  saop->negfuncid = get_opcode(negator);
2283  }
2284  return true;
2285  }
2286  }
2287  }
2288  }
2289 
2291 }
#define ARR_NDIM(a)
Definition: array.h:283
#define ARR_DIMS(a)
Definition: array.h:287
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:76
#define MIN_ARRAY_SIZE_FOR_HASHED_SAOP
Definition: clauses.c:2186
#define nitems(x)
Definition: indent.h:31
bool get_op_hash_functions(Oid opno, RegProcedure *lhs_procno, RegProcedure *rhs_procno)
Definition: lsyscache.c:509
Oid get_negator(Oid opno)
Definition: lsyscache.c:1537
uintptr_t Datum
Definition: postgres.h:64
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:312

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

Referenced by convert_saop_to_hashed_saop().

◆ ece_function_is_safe()

static bool ece_function_is_safe ( Oid  funcid,
eval_const_expressions_context context 
)
static

Definition at line 3645 of file clauses.c.

3646 {
3647  char provolatile = func_volatile(funcid);
3648 
3649  /*
3650  * Ordinarily we are only allowed to simplify immutable functions. But for
3651  * purposes of estimation, we consider it okay to simplify functions that
3652  * are merely stable; the risk that the result might change from planning
3653  * time to execution time is worth taking in preference to not being able
3654  * to estimate the value at all.
3655  */
3656  if (provolatile == PROVOLATILE_IMMUTABLE)
3657  return true;
3658  if (context->estimate && provolatile == PROVOLATILE_STABLE)
3659  return true;
3660  return false;
3661 }

References eval_const_expressions_context::estimate, and func_volatile().

Referenced by eval_const_expressions_mutator().

◆ estimate_expression_value()

Node* estimate_expression_value ( PlannerInfo root,
Node node 
)

Definition at line 2312 of file clauses.c.

2313 {
2315 
2316  context.boundParams = root->glob->boundParams; /* bound Params */
2317  /* we do not need to mark the plan as depending on inlined functions */
2318  context.root = NULL;
2319  context.active_fns = NIL; /* nothing being recursively simplified */
2320  context.case_val = NULL; /* no CASE being examined */
2321  context.estimate = true; /* unsafe transformations OK */
2322  return eval_const_expressions_mutator(node, &context);
2323 }
#define NIL
Definition: pg_list.h:68
PlannerGlobal * glob
Definition: pathnodes.h:202
ParamListInfo boundParams
Definition: clauses.c:63

References eval_const_expressions_context::active_fns, eval_const_expressions_context::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().

◆ eval_const_expressions()

◆ eval_const_expressions_mutator()

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

Definition at line 2357 of file clauses.c.

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

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, 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, castNode, COERCE_IMPLICIT_CAST, CollateExpr::collOid, Const::consttype, contain_mutable_functions(), 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, JsonValueExpr::formatted_expr, FuncExpr::funcid, get_typlenbyval(), getTypeInputInfo(), getTypeOutputInfo(), HeapTupleIsValid, if(), 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(), 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::opno, OR_EXPR, PARAM_EXTERN, PARAM_FLAG_CONST, ParamListInfoData::paramFetch, Param::paramid, Param::paramkind, ParamListInfoData::params, Param::paramtype, ParamExternData::pflags, PROCOID, ParamExternData::ptype, record_plan_type_dependency(), ReleaseSysCache(), CaseWhen::result, RelabelType::resulttype, CoerceViaIO::resulttype, ConvertRowtypeExpr::resulttype, CoerceToDomain::resulttype, eval_const_expressions_context::root, rowtype_field_matches(), SearchSysCache1(), set_opfuncid(), set_sa_opfuncid(), simplify_and_arguments(), simplify_boolean_equality(), simplify_function(), simplify_or_arguments(), SQLValueFunction::typmod, ParamExternData::value, WindowFunc::winfnoid, and WindowFunc::winref.

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

◆ evaluate_expr()

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

Definition at line 4866 of file clauses.c.

4868 {
4869  EState *estate;
4870  ExprState *exprstate;
4871  MemoryContext oldcontext;
4872  Datum const_val;
4873  bool const_is_null;
4874  int16 resultTypLen;
4875  bool resultTypByVal;
4876 
4877  /*
4878  * To use the executor, we need an EState.
4879  */
4880  estate = CreateExecutorState();
4881 
4882  /* We can use the estate's working context to avoid memory leaks. */
4883  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
4884 
4885  /* Make sure any opfuncids are filled in. */
4886  fix_opfuncids((Node *) expr);
4887 
4888  /*
4889  * Prepare expr for execution. (Note: we can't use ExecPrepareExpr
4890  * because it'd result in recursively invoking eval_const_expressions.)
4891  */
4892  exprstate = ExecInitExpr(expr, NULL);
4893 
4894  /*
4895  * And evaluate it.
4896  *
4897  * It is OK to use a default econtext because none of the ExecEvalExpr()
4898  * code used in this situation will use econtext. That might seem
4899  * fortuitous, but it's not so unreasonable --- a constant expression does
4900  * not depend on context, by definition, n'est ce pas?
4901  */
4902  const_val = ExecEvalExprSwitchContext(exprstate,
4903  GetPerTupleExprContext(estate),
4904  &const_is_null);
4905 
4906  /* Get info needed about result datatype */
4907  get_typlenbyval(result_type, &resultTypLen, &resultTypByVal);
4908 
4909  /* Get back to outer memory context */
4910  MemoryContextSwitchTo(oldcontext);
4911 
4912  /*
4913  * Must copy result out of sub-context used by expression eval.
4914  *
4915  * Also, if it's varlena, forcibly detoast it. This protects us against
4916  * storing TOAST pointers into plans that might outlive the referenced
4917  * data. (makeConst would handle detoasting anyway, but it's worth a few
4918  * extra lines here so that we can do the copy and detoast in one step.)
4919  */
4920  if (!const_is_null)
4921  {
4922  if (resultTypLen == -1)
4923  const_val = PointerGetDatum(PG_DETOAST_DATUM_COPY(const_val));
4924  else
4925  const_val = datumCopy(const_val, resultTypByVal, resultTypLen);
4926  }
4927 
4928  /* Release all the junk we just created */
4929  FreeExecutorState(estate);
4930 
4931  /*
4932  * Make the constant result node.
4933  */
4934  return (Expr *) makeConst(result_type, result_typmod, result_collation,
4935  resultTypLen,
4936  const_val, const_is_null,
4937  resultTypByVal);
4938 }
ExprState * ExecInitExpr(Expr *node, PlanState *parent)
Definition: execExpr.c:128
EState * CreateExecutorState(void)
Definition: execUtils.c:93
void FreeExecutorState(EState *estate)
Definition: execUtils.c:194
#define GetPerTupleExprContext(estate)
Definition: executor.h:549
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:347
#define PG_DETOAST_DATUM_COPY(datum)
Definition: fmgr.h:242
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1748
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:138
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:322
MemoryContext es_query_cxt
Definition: execnodes.h:659

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().

◆ 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 4318 of file clauses.c.

4323 {
4324  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4325  bool has_nonconst_input = false;
4326  bool has_null_input = false;
4327  ListCell *arg;
4328  FuncExpr *newexpr;
4329 
4330  /*
4331  * Can't simplify if it returns a set.
4332  */
4333  if (funcform->proretset)
4334  return NULL;
4335 
4336  /*
4337  * Can't simplify if it returns RECORD. The immediate problem is that it
4338  * will be needing an expected tupdesc which we can't supply here.
4339  *
4340  * In the case where it has OUT parameters, it could get by without an
4341  * expected tupdesc, but we still have issues: get_expr_result_type()
4342  * doesn't know how to extract type info from a RECORD constant, and in
4343  * the case of a NULL function result there doesn't seem to be any clean
4344  * way to fix that. In view of the likelihood of there being still other
4345  * gotchas, seems best to leave the function call unreduced.
4346  */
4347  if (funcform->prorettype == RECORDOID)
4348  return NULL;
4349 
4350  /*
4351  * Check for constant inputs and especially constant-NULL inputs.
4352  */
4353  foreach(arg, args)
4354  {
4355  if (IsA(lfirst(arg), Const))
4356  has_null_input |= ((Const *) lfirst(arg))->constisnull;
4357  else
4358  has_nonconst_input = true;
4359  }
4360 
4361  /*
4362  * If the function is strict and has a constant-NULL input, it will never
4363  * be called at all, so we can replace the call by a NULL constant, even
4364  * if there are other inputs that aren't constant, and even if the
4365  * function is not otherwise immutable.
4366  */
4367  if (funcform->proisstrict && has_null_input)
4368  return (Expr *) makeNullConst(result_type, result_typmod,
4369  result_collid);
4370 
4371  /*
4372  * Otherwise, can simplify only if all inputs are constants. (For a
4373  * non-strict function, constant NULL inputs are treated the same as
4374  * constant non-NULL inputs.)
4375  */
4376  if (has_nonconst_input)
4377  return NULL;
4378 
4379  /*
4380  * Ordinarily we are only allowed to simplify immutable functions. But for
4381  * purposes of estimation, we consider it okay to simplify functions that
4382  * are merely stable; the risk that the result might change from planning
4383  * time to execution time is worth taking in preference to not being able
4384  * to estimate the value at all.
4385  */
4386  if (funcform->provolatile == PROVOLATILE_IMMUTABLE)
4387  /* okay */ ;
4388  else if (context->estimate && funcform->provolatile == PROVOLATILE_STABLE)
4389  /* okay */ ;
4390  else
4391  return NULL;
4392 
4393  /*
4394  * OK, looks like we can simplify this operator/function.
4395  *
4396  * Build a new FuncExpr node containing the already-simplified arguments.
4397  */
4398  newexpr = makeNode(FuncExpr);
4399  newexpr->funcid = funcid;
4400  newexpr->funcresulttype = result_type;
4401  newexpr->funcretset = false;
4402  newexpr->funcvariadic = funcvariadic;
4403  newexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
4404  newexpr->funccollid = result_collid; /* doesn't matter */
4405  newexpr->inputcollid = input_collid;
4406  newexpr->args = args;
4407  newexpr->location = -1;
4408 
4409  return evaluate_expr((Expr *) newexpr, result_type, result_typmod,
4410  result_collid);
4411 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:136
@ COERCE_EXPLICIT_CALL
Definition: primnodes.h:661

References arg, generate_unaccent_rules::args, FuncExpr::args, COERCE_EXPLICIT_CALL, eval_const_expressions_context::estimate, evaluate_expr(), FuncExpr::funcid, GETSTRUCT, IsA, lfirst, FuncExpr::location, makeNode, and makeNullConst().

Referenced by simplify_function().

◆ expand_function_arguments()

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

Definition at line 4068 of file clauses.c.

4070 {
4071  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4072  Oid *proargtypes = funcform->proargtypes.values;
4073  int pronargs = funcform->pronargs;
4074  bool has_named_args = false;
4075  ListCell *lc;
4076 
4077  /*
4078  * If we are asked to match to OUT arguments, then use the proallargtypes
4079  * array (which includes those); otherwise use proargtypes (which
4080  * doesn't). Of course, if proallargtypes is null, we always use
4081  * proargtypes. (Fetching proallargtypes is annoyingly expensive
4082  * considering that we may have nothing to do here, but fortunately the
4083  * common case is include_out_arguments == false.)
4084  */
4085  if (include_out_arguments)
4086  {
4087  Datum proallargtypes;
4088  bool isNull;
4089 
4090  proallargtypes = SysCacheGetAttr(PROCOID, func_tuple,
4091  Anum_pg_proc_proallargtypes,
4092  &isNull);
4093  if (!isNull)
4094  {
4095  ArrayType *arr = DatumGetArrayTypeP(proallargtypes);
4096 
4097  pronargs = ARR_DIMS(arr)[0];
4098  if (ARR_NDIM(arr) != 1 ||
4099  pronargs < 0 ||
4100  ARR_HASNULL(arr) ||
4101  ARR_ELEMTYPE(arr) != OIDOID)
4102  elog(ERROR, "proallargtypes is not a 1-D Oid array or it contains nulls");
4103  Assert(pronargs >= funcform->pronargs);
4104  proargtypes = (Oid *) ARR_DATA_PTR(arr);
4105  }
4106  }
4107 
4108  /* Do we have any named arguments? */
4109  foreach(lc, args)
4110  {
4111  Node *arg = (Node *) lfirst(lc);
4112 
4113  if (IsA(arg, NamedArgExpr))
4114  {
4115  has_named_args = true;
4116  break;
4117  }
4118  }
4119 
4120  /* If so, we must apply reorder_function_arguments */
4121  if (has_named_args)
4122  {
4123  args = reorder_function_arguments(args, pronargs, func_tuple);
4124  /* Recheck argument types and add casts if needed */
4125  recheck_cast_function_args(args, result_type,
4126  proargtypes, pronargs,
4127  func_tuple);
4128  }
4129  else if (list_length(args) < pronargs)
4130  {
4131  /* No named args, but we seem to be short some defaults */
4132  args = add_function_defaults(args, pronargs, func_tuple);
4133  /* Recheck argument types and add casts if needed */
4134  recheck_cast_function_args(args, result_type,
4135  proargtypes, pronargs,
4136  func_tuple);
4137  }
4138 
4139  return args;
4140 }
#define ARR_DATA_PTR(a)
Definition: array.h:315
#define DatumGetArrayTypeP(X)
Definition: array.h:254
#define ARR_ELEMTYPE(a)
Definition: array.h:285
#define ARR_HASNULL(a)
Definition: array.h:284
static List * add_function_defaults(List *args, int pronargs, HeapTuple func_tuple)
Definition: clauses.c:4219
static List * reorder_function_arguments(List *args, int pronargs, HeapTuple func_tuple)
Definition: clauses.c:4149
static void recheck_cast_function_args(List *args, Oid result_type, Oid *proargtypes, int pronargs, HeapTuple func_tuple)
Definition: clauses.c:4273
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1081

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().

◆ expression_returns_set_rows()

double expression_returns_set_rows ( PlannerInfo root,
Node clause 
)

Definition at line 291 of file clauses.c.

292 {
293  if (clause == NULL)
294  return 1.0;
295  if (IsA(clause, FuncExpr))
296  {
297  FuncExpr *expr = (FuncExpr *) clause;
298 
299  if (expr->funcretset)
300  return clamp_row_est(get_function_rows(root, expr->funcid, clause));
301  }
302  if (IsA(clause, OpExpr))
303  {
304  OpExpr *expr = (OpExpr *) clause;
305 
306  if (expr->opretset)
307  {
308  set_opfuncid(expr);
309  return clamp_row_est(get_function_rows(root, expr->opfuncid, clause));
310  }
311  }
312  return 1.0;
313 }
double clamp_row_est(double nrows)
Definition: costsize.c:203
double get_function_rows(PlannerInfo *root, Oid funcid, Node *node)
Definition: plancat.c:2104

References clamp_row_est(), FuncExpr::funcid, get_function_rows(), IsA, and set_opfuncid().

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

◆ fetch_function_defaults()

static List * fetch_function_defaults ( HeapTuple  func_tuple)
static

Definition at line 4243 of file clauses.c.

4244 {
4245  List *defaults;
4246  Datum proargdefaults;
4247  char *str;
4248 
4249  proargdefaults = SysCacheGetAttrNotNull(PROCOID, func_tuple,
4250  Anum_pg_proc_proargdefaults);
4251  str = TextDatumGetCString(proargdefaults);
4252  defaults = castNode(List, stringToNode(str));
4253  pfree(str);
4254  return defaults;
4255 }
#define TextDatumGetCString(d)
Definition: builtins.h:95
void pfree(void *pointer)
Definition: mcxt.c:1456
void * stringToNode(const char *str)
Definition: read.c:90
Datum SysCacheGetAttrNotNull(int cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition: syscache.c:1112

References castNode, pfree(), PROCOID, generate_unaccent_rules::str, stringToNode(), SysCacheGetAttrNotNull(), and TextDatumGetCString.

Referenced by add_function_defaults(), and reorder_function_arguments().

◆ find_forced_null_var()

Var* find_forced_null_var ( Node node)

Definition at line 1894 of file clauses.c.

1895 {
1896  if (node == NULL)
1897  return NULL;
1898  if (IsA(node, NullTest))
1899  {
1900  /* check for var IS NULL */
1901  NullTest *expr = (NullTest *) node;
1902 
1903  if (expr->nulltesttype == IS_NULL && !expr->argisrow)
1904  {
1905  Var *var = (Var *) expr->arg;
1906 
1907  if (var && IsA(var, Var) &&
1908  var->varlevelsup == 0)
1909  return var;
1910  }
1911  }
1912  else if (IsA(node, BooleanTest))
1913  {
1914  /* var IS UNKNOWN is equivalent to var IS NULL */
1915  BooleanTest *expr = (BooleanTest *) node;
1916 
1917  if (expr->booltesttype == IS_UNKNOWN)
1918  {
1919  Var *var = (Var *) expr->arg;
1920 
1921  if (var && IsA(var, Var) &&
1922  var->varlevelsup == 0)
1923  return var;
1924  }
1925  }
1926  return NULL;
1927 }
Index varlevelsup
Definition: primnodes.h:258

References NullTest::arg, BooleanTest::arg, BooleanTest::booltesttype, if(), IS_NULL, IS_UNKNOWN, IsA, NullTest::nulltesttype, and Var::varlevelsup.

Referenced by check_redundant_nullability_qual(), and find_forced_null_vars().

◆ find_forced_null_vars()

List* find_forced_null_vars ( Node node)

Definition at line 1833 of file clauses.c.

1834 {
1835  List *result = NIL;
1836  Var *var;
1837  ListCell *l;
1838 
1839  if (node == NULL)
1840  return NIL;
1841  /* Check single-clause cases using subroutine */
1842  var = find_forced_null_var(node);
1843  if (var)
1844  {
1845  result = mbms_add_member(result,
1846  var->varno,
1848  }
1849  /* Otherwise, handle AND-conditions */
1850  else if (IsA(node, List))
1851  {
1852  /*
1853  * At top level, we are examining an implicit-AND list: if any of the
1854  * arms produces FALSE-or-NULL then the result is FALSE-or-NULL.
1855  */
1856  foreach(l, (List *) node)
1857  {
1858  result = mbms_add_members(result,
1860  }
1861  }
1862  else if (IsA(node, BoolExpr))
1863  {
1864  BoolExpr *expr = (BoolExpr *) node;
1865 
1866  /*
1867  * We don't bother considering the OR case, because it's fairly
1868  * unlikely anyone would write "v1 IS NULL OR v1 IS NULL". Likewise,
1869  * the NOT case isn't worth expending code on.
1870  */
1871  if (expr->boolop == AND_EXPR)
1872  {
1873  /* At top level we can just recurse (to the List case) */
1874  result = find_forced_null_vars((Node *) expr->args);
1875  }
1876  }
1877  return result;
1878 }
Var * find_forced_null_var(Node *node)
Definition: clauses.c:1894
List * find_forced_null_vars(Node *node)
Definition: clauses.c:1833
List * mbms_add_member(List *a, int listidx, int bitidx)
List * mbms_add_members(List *a, const List *b)
AttrNumber varattno
Definition: primnodes.h:238
int varno
Definition: primnodes.h:233
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27

References AND_EXPR, BoolExpr::args, BoolExpr::boolop, find_forced_null_var(), FirstLowInvalidHeapAttributeNumber, IsA, lfirst, mbms_add_member(), mbms_add_members(), NIL, Var::varattno, and Var::varno.

Referenced by reduce_outer_joins_pass2().

◆ find_nonnullable_rels()

Relids find_nonnullable_rels ( Node clause)

Definition at line 1373 of file clauses.c.

1374 {
1375  return find_nonnullable_rels_walker(clause, true);
1376 }
static Relids find_nonnullable_rels_walker(Node *node, bool top_level)
Definition: clauses.c:1379

References find_nonnullable_rels_walker().

Referenced by make_outerjoininfo(), and reduce_outer_joins_pass2().

◆ find_nonnullable_rels_walker()

static Relids find_nonnullable_rels_walker ( Node node,
bool  top_level 
)
static

Definition at line 1379 of file clauses.c.

1380 {
1381  Relids result = NULL;
1382  ListCell *l;
1383 
1384  if (node == NULL)
1385  return NULL;
1386  if (IsA(node, Var))
1387  {
1388  Var *var = (Var *) node;
1389 
1390  if (var->varlevelsup == 0)
1391  result = bms_make_singleton(var->varno);
1392  }
1393  else if (IsA(node, List))
1394  {
1395  /*
1396  * At top level, we are examining an implicit-AND list: if any of the
1397  * arms produces FALSE-or-NULL then the result is FALSE-or-NULL. If
1398  * not at top level, we are examining the arguments of a strict
1399  * function: if any of them produce NULL then the result of the
1400  * function must be NULL. So in both cases, the set of nonnullable
1401  * rels is the union of those found in the arms, and we pass down the
1402  * top_level flag unmodified.
1403  */
1404  foreach(l, (List *) node)
1405  {
1406  result = bms_join(result,
1408  top_level));
1409  }
1410  }
1411  else if (IsA(node, FuncExpr))
1412  {
1413  FuncExpr *expr = (FuncExpr *) node;
1414 
1415  if (func_strict(expr->funcid))
1416  result = find_nonnullable_rels_walker((Node *) expr->args, false);
1417  }
1418  else if (IsA(node, OpExpr))
1419  {
1420  OpExpr *expr = (OpExpr *) node;
1421 
1422  set_opfuncid(expr);
1423  if (func_strict(expr->opfuncid))
1424  result = find_nonnullable_rels_walker((Node *) expr->args, false);
1425  }
1426  else if (IsA(node, ScalarArrayOpExpr))
1427  {
1428  ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1429 
1430  if (is_strict_saop(expr, true))
1431  result = find_nonnullable_rels_walker((Node *) expr->args, false);
1432  }
1433  else if (IsA(node, BoolExpr))
1434  {
1435  BoolExpr *expr = (BoolExpr *) node;
1436 
1437  switch (expr->boolop)
1438  {
1439  case AND_EXPR:
1440  /* At top level we can just recurse (to the List case) */
1441  if (top_level)
1442  {
1443  result = find_nonnullable_rels_walker((Node *) expr->args,
1444  top_level);
1445  break;
1446  }
1447 
1448  /*
1449  * Below top level, even if one arm produces NULL, the result
1450  * could be FALSE (hence not NULL). However, if *all* the
1451  * arms produce NULL then the result is NULL, so we can take
1452  * the intersection of the sets of nonnullable rels, just as
1453  * for OR. Fall through to share code.
1454  */
1455  /* FALL THRU */
1456  case OR_EXPR:
1457 
1458  /*
1459  * OR is strict if all of its arms are, so we can take the
1460  * intersection of the sets of nonnullable rels for each arm.
1461  * This works for both values of top_level.
1462  */
1463  foreach(l, expr->args)
1464  {
1465  Relids subresult;
1466 
1467  subresult = find_nonnullable_rels_walker(lfirst(l),
1468  top_level);
1469  if (result == NULL) /* first subresult? */
1470  result = subresult;
1471  else
1472  result = bms_int_members(result, subresult);
1473 
1474  /*
1475  * If the intersection is empty, we can stop looking. This
1476  * also justifies the test for first-subresult above.
1477  */
1478  if (bms_is_empty(result))
1479  break;
1480  }
1481  break;
1482  case NOT_EXPR:
1483  /* NOT will return null if its arg is null */
1484  result = find_nonnullable_rels_walker((Node *) expr->args,
1485  false);
1486  break;
1487  default:
1488  elog(ERROR, "unrecognized boolop: %d", (int) expr->boolop);
1489  break;
1490  }
1491  }
1492  else if (IsA(node, RelabelType))
1493  {
1494  RelabelType *expr = (RelabelType *) node;
1495 
1496  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1497  }
1498  else if (IsA(node, CoerceViaIO))
1499  {
1500  /* not clear this is useful, but it can't hurt */
1501  CoerceViaIO *expr = (CoerceViaIO *) node;
1502 
1503  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1504  }
1505  else if (IsA(node, ArrayCoerceExpr))
1506  {
1507  /* ArrayCoerceExpr is strict at the array level; ignore elemexpr */
1508  ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
1509 
1510  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1511  }
1512  else if (IsA(node, ConvertRowtypeExpr))
1513  {
1514  /* not clear this is useful, but it can't hurt */
1515  ConvertRowtypeExpr *expr = (ConvertRowtypeExpr *) node;
1516 
1517  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1518  }
1519  else if (IsA(node, CollateExpr))
1520  {
1521  CollateExpr *expr = (CollateExpr *) node;
1522 
1523  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1524  }
1525  else if (IsA(node, NullTest))
1526  {
1527  /* IS NOT NULL can be considered strict, but only at top level */
1528  NullTest *expr = (NullTest *) node;
1529 
1530  if (top_level && expr->nulltesttype == IS_NOT_NULL && !expr->argisrow)
1531  result = find_nonnullable_rels_walker((Node *) expr->arg, false);
1532  }
1533  else if (IsA(node, BooleanTest))
1534  {
1535  /* Boolean tests that reject NULL are strict at top level */
1536  BooleanTest *expr = (BooleanTest *) node;
1537 
1538  if (top_level &&
1539  (expr->booltesttype == IS_TRUE ||
1540  expr->booltesttype == IS_FALSE ||
1541  expr->booltesttype == IS_NOT_UNKNOWN))
1542  result = find_nonnullable_rels_walker((Node *) expr->arg, false);
1543  }
1544  else if (IsA(node, SubPlan))
1545  {
1546  SubPlan *splan = (SubPlan *) node;
1547 
1548  /*
1549  * For some types of SubPlan, we can infer strictness from Vars in the
1550  * testexpr (the LHS of the original SubLink).
1551  *
1552  * For ANY_SUBLINK, if the subquery produces zero rows, the result is
1553  * always FALSE. If the subquery produces more than one row, the
1554  * per-row results of the testexpr are combined using OR semantics.
1555  * Hence ANY_SUBLINK can be strict only at top level, but there it's
1556  * as strict as the testexpr is.
1557  *
1558  * For ROWCOMPARE_SUBLINK, if the subquery produces zero rows, the
1559  * result is always NULL. Otherwise, the result is as strict as the
1560  * testexpr is. So we can check regardless of top_level.
1561  *
1562  * We can't prove anything for other sublink types (in particular,
1563  * note that ALL_SUBLINK will return TRUE if the subquery is empty).
1564  */
1565  if ((top_level && splan->subLinkType == ANY_SUBLINK) ||
1566  splan->subLinkType == ROWCOMPARE_SUBLINK)
1567  result = find_nonnullable_rels_walker(splan->testexpr, top_level);
1568  }
1569  else if (IsA(node, PlaceHolderVar))
1570  {
1571  PlaceHolderVar *phv = (PlaceHolderVar *) node;
1572 
1573  /*
1574  * If the contained expression forces any rels non-nullable, so does
1575  * the PHV.
1576  */
1577  result = find_nonnullable_rels_walker((Node *) phv->phexpr, top_level);
1578 
1579  /*
1580  * If the PHV's syntactic scope is exactly one rel, it will be forced
1581  * to be evaluated at that rel, and so it will behave like a Var of
1582  * that rel: if the rel's entire output goes to null, so will the PHV.
1583  * (If the syntactic scope is a join, we know that the PHV will go to
1584  * null if the whole join does; but that is AND semantics while we
1585  * need OR semantics for find_nonnullable_rels' result, so we can't do
1586  * anything with the knowledge.)
1587  */
1588  if (phv->phlevelsup == 0 &&
1589  bms_membership(phv->phrels) == BMS_SINGLETON)
1590  result = bms_add_members(result, phv->phrels);
1591  }
1592  return result;
1593 }
Bitmapset * bms_join(Bitmapset *a, Bitmapset *b)
Definition: bitmapset.c:1051
Bitmapset * bms_make_singleton(int x)
Definition: bitmapset.c:171
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:835
Bitmapset * bms_int_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:951
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:712
#define bms_is_empty(a)
Definition: bitmapset.h:105
@ BMS_SINGLETON
Definition: bitmapset.h:72
static bool is_strict_saop(ScalarArrayOpExpr *expr, bool falseOK)
Definition: clauses.c:1943
@ ANY_SUBLINK
Definition: primnodes.h:926
@ ROWCOMPARE_SUBLINK
Definition: primnodes.h:927
static SPIPlanPtr splan
Definition: regress.c:270
Index phlevelsup
Definition: pathnodes.h:2759

References AND_EXPR, ANY_SUBLINK, RelabelType::arg, CoerceViaIO::arg, ArrayCoerceExpr::arg, ConvertRowtypeExpr::arg, CollateExpr::arg, NullTest::arg, BooleanTest::arg, 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, OR_EXPR, PlaceHolderVar::phlevelsup, ROWCOMPARE_SUBLINK, set_opfuncid(), splan, Var::varlevelsup, and Var::varno.

Referenced by find_nonnullable_rels().

◆ find_nonnullable_vars()

List* find_nonnullable_vars ( Node clause)

Definition at line 1624 of file clauses.c.

1625 {
1626  return find_nonnullable_vars_walker(clause, true);
1627 }
static List * find_nonnullable_vars_walker(Node *node, bool top_level)
Definition: clauses.c:1630

References find_nonnullable_vars_walker().

Referenced by reduce_outer_joins_pass2().

◆ find_nonnullable_vars_walker()

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

Definition at line 1630 of file clauses.c.

1631 {
1632  List *result = NIL;
1633  ListCell *l;
1634 
1635  if (node == NULL)
1636  return NIL;
1637  if (IsA(node, Var))
1638  {
1639  Var *var = (Var *) node;
1640 
1641  if (var->varlevelsup == 0)
1642  result = mbms_add_member(result,
1643  var->varno,
1645  }
1646  else if (IsA(node, List))
1647  {
1648  /*
1649  * At top level, we are examining an implicit-AND list: if any of the
1650  * arms produces FALSE-or-NULL then the result is FALSE-or-NULL. If
1651  * not at top level, we are examining the arguments of a strict
1652  * function: if any of them produce NULL then the result of the
1653  * function must be NULL. So in both cases, the set of nonnullable
1654  * vars is the union of those found in the arms, and we pass down the
1655  * top_level flag unmodified.
1656  */
1657  foreach(l, (List *) node)
1658  {
1659  result = mbms_add_members(result,
1661  top_level));
1662  }
1663  }
1664  else if (IsA(node, FuncExpr))
1665  {
1666  FuncExpr *expr = (FuncExpr *) node;
1667 
1668  if (func_strict(expr->funcid))
1669  result = find_nonnullable_vars_walker((Node *) expr->args, false);
1670  }
1671  else if (IsA(node, OpExpr))
1672  {
1673  OpExpr *expr = (OpExpr *) node;
1674 
1675  set_opfuncid(expr);
1676  if (func_strict(expr->opfuncid))
1677  result = find_nonnullable_vars_walker((Node *) expr->args, false);
1678  }
1679  else if (IsA(node, ScalarArrayOpExpr))
1680  {
1681  ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1682 
1683  if (is_strict_saop(expr, true))
1684  result = find_nonnullable_vars_walker((Node *) expr->args, false);
1685  }
1686  else if (IsA(node, BoolExpr))
1687  {
1688  BoolExpr *expr = (BoolExpr *) node;
1689 
1690  switch (expr->boolop)
1691  {
1692  case AND_EXPR:
1693 
1694  /*
1695  * At top level we can just recurse (to the List case), since
1696  * the result should be the union of what we can prove in each
1697  * arm.
1698  */
1699  if (top_level)
1700  {
1701  result = find_nonnullable_vars_walker((Node *) expr->args,
1702  top_level);
1703  break;
1704  }
1705 
1706  /*
1707  * Below top level, even if one arm produces NULL, the result
1708  * could be FALSE (hence not NULL). However, if *all* the
1709  * arms produce NULL then the result is NULL, so we can take
1710  * the intersection of the sets of nonnullable vars, just as
1711  * for OR. Fall through to share code.
1712  */
1713  /* FALL THRU */
1714  case OR_EXPR:
1715 
1716  /*
1717  * OR is strict if all of its arms are, so we can take the
1718  * intersection of the sets of nonnullable vars for each arm.
1719  * This works for both values of top_level.
1720  */
1721  foreach(l, expr->args)
1722  {
1723  List *subresult;
1724 
1725  subresult = find_nonnullable_vars_walker(lfirst(l),
1726  top_level);
1727  if (result == NIL) /* first subresult? */
1728  result = subresult;
1729  else
1730  result = mbms_int_members(result, subresult);
1731 
1732  /*
1733  * If the intersection is empty, we can stop looking. This
1734  * also justifies the test for first-subresult above.
1735  */
1736  if (result == NIL)
1737  break;
1738  }
1739  break;
1740  case NOT_EXPR:
1741  /* NOT will return null if its arg is null */
1742  result = find_nonnullable_vars_walker((Node *) expr->args,
1743  false);
1744  break;
1745  default:
1746  elog(ERROR, "unrecognized boolop: %d", (int) expr->boolop);
1747  break;
1748  }
1749  }
1750  else if (IsA(node, RelabelType))
1751  {
1752  RelabelType *expr = (RelabelType *) node;
1753 
1754  result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1755  }
1756  else if (IsA(node, CoerceViaIO))
1757  {
1758  /* not clear this is useful, but it can't hurt */
1759  CoerceViaIO *expr = (CoerceViaIO *) node;
1760 
1761  result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1762  }
1763  else if (IsA(node, ArrayCoerceExpr))
1764  {
1765  /* ArrayCoerceExpr is strict at the array level; ignore elemexpr */
1766  ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
1767 
1768  result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1769  }
1770  else if (IsA(node, ConvertRowtypeExpr))
1771  {
1772  /* not clear this is useful, but it can't hurt */
1773  ConvertRowtypeExpr *expr = (ConvertRowtypeExpr *) node;
1774 
1775  result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1776  }
1777  else if (IsA(node, CollateExpr))
1778  {
1779  CollateExpr *expr = (CollateExpr *) node;
1780 
1781  result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1782  }
1783  else if (IsA(node, NullTest))
1784  {
1785  /* IS NOT NULL can be considered strict, but only at top level */
1786  NullTest *expr = (NullTest *) node;
1787 
1788  if (top_level && expr->nulltesttype == IS_NOT_NULL && !expr->argisrow)
1789  result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1790  }
1791  else if (IsA(node, BooleanTest))
1792  {
1793  /* Boolean tests that reject NULL are strict at top level */
1794  BooleanTest *expr = (BooleanTest *) node;
1795 
1796  if (top_level &&
1797  (expr->booltesttype == IS_TRUE ||
1798  expr->booltesttype == IS_FALSE ||
1799  expr->booltesttype == IS_NOT_UNKNOWN))
1800  result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1801  }
1802  else if (IsA(node, SubPlan))
1803  {
1804  SubPlan *splan = (SubPlan *) node;
1805 
1806  /* See analysis in find_nonnullable_rels_walker */
1807  if ((top_level && splan->subLinkType == ANY_SUBLINK) ||
1808  splan->subLinkType == ROWCOMPARE_SUBLINK)
1809  result = find_nonnullable_vars_walker(splan->testexpr, top_level);
1810  }
1811  else if (IsA(node, PlaceHolderVar))
1812  {
1813  PlaceHolderVar *phv = (PlaceHolderVar *) node;
1814 
1815  result = find_nonnullable_vars_walker((Node *) phv->phexpr, top_level);
1816  }
1817  return result;
1818 }
List * mbms_int_members(List *a, const List *b)

References AND_EXPR, ANY_SUBLINK, RelabelType::arg, CoerceViaIO::arg, ArrayCoerceExpr::arg, ConvertRowtypeExpr::arg, CollateExpr::arg, NullTest::arg, BooleanTest::arg, FuncExpr::args, OpExpr::args, ScalarArrayOpExpr::args, BoolExpr::args, BoolExpr::boolop, BooleanTest::booltesttype, elog(), ERROR, FirstLowInvalidHeapAttributeNumber, func_strict(), FuncExpr::funcid, IS_FALSE, IS_NOT_NULL, IS_NOT_UNKNOWN, is_strict_saop(), IS_TRUE, IsA, lfirst, mbms_add_member(), mbms_add_members(), mbms_int_members(), NIL, NOT_EXPR, NullTest::nulltesttype, OR_EXPR, ROWCOMPARE_SUBLINK, set_opfuncid(), splan, Var::varattno, Var::varlevelsup, and Var::varno.

Referenced by find_nonnullable_vars().

◆ find_window_functions()

WindowFuncLists* find_window_functions ( Node clause,
Index  maxWinRef 
)

Definition at line 229 of file clauses.c.

230 {
231  WindowFuncLists *lists = palloc(sizeof(WindowFuncLists));
232 
233  lists->numWindowFuncs = 0;
234  lists->maxWinRef = maxWinRef;
235  lists->windowFuncs = (List **) palloc0((maxWinRef + 1) * sizeof(List *));
236  (void) find_window_functions_walker(clause, lists);
237  return lists;
238 }
static bool find_window_functions_walker(Node *node, WindowFuncLists *lists)
Definition: clauses.c:241
void * palloc0(Size size)
Definition: mcxt.c:1257
void * palloc(Size size)
Definition: mcxt.c:1226
List ** windowFuncs
Definition: clauses.h:23
Index maxWinRef
Definition: clauses.h:22
int numWindowFuncs
Definition: clauses.h:21

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

Referenced by grouping_planner().

◆ find_window_functions_walker()

static bool find_window_functions_walker ( Node node,
WindowFuncLists lists 
)
static

Definition at line 241 of file clauses.c.

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

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().

◆ 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 4445 of file clauses.c.

4450 {
4451  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4452  char *src;
4453  Datum tmp;
4454  bool isNull;
4455  MemoryContext oldcxt;
4456  MemoryContext mycxt;
4457  inline_error_callback_arg callback_arg;
4458  ErrorContextCallback sqlerrcontext;
4459  FuncExpr *fexpr;
4461  TupleDesc rettupdesc;
4462  ParseState *pstate;
4463  List *raw_parsetree_list;
4464  List *querytree_list;
4465  Query *querytree;
4466  Node *newexpr;
4467  int *usecounts;
4468  ListCell *arg;
4469  int i;
4470 
4471  /*
4472  * Forget it if the function is not SQL-language or has other showstopper
4473  * properties. (The prokind and nargs checks are just paranoia.)
4474  */
4475  if (funcform->prolang != SQLlanguageId ||
4476  funcform->prokind != PROKIND_FUNCTION ||
4477  funcform->prosecdef ||
4478  funcform->proretset ||
4479  funcform->prorettype == RECORDOID ||
4480  !heap_attisnull(func_tuple, Anum_pg_proc_proconfig, NULL) ||
4481  funcform->pronargs != list_length(args))
4482  return NULL;
4483 
4484  /* Check for recursive function, and give up trying to expand if so */
4485  if (list_member_oid(context->active_fns, funcid))
4486  return NULL;
4487 
4488  /* Check permission to call function (fail later, if not) */
4489  if (object_aclcheck(ProcedureRelationId, funcid, GetUserId(), ACL_EXECUTE) != ACLCHECK_OK)
4490  return NULL;
4491 
4492  /* Check whether a plugin wants to hook function entry/exit */
4493  if (FmgrHookIsNeeded(funcid))
4494  return NULL;
4495 
4496  /*
4497  * Make a temporary memory context, so that we don't leak all the stuff
4498  * that parsing might create.
4499  */
4501  "inline_function",
4503  oldcxt = MemoryContextSwitchTo(mycxt);
4504 
4505  /*
4506  * We need a dummy FuncExpr node containing the already-simplified
4507  * arguments. (In some cases we don't really need it, but building it is
4508  * cheap enough that it's not worth contortions to avoid.)
4509  */
4510  fexpr = makeNode(FuncExpr);
4511  fexpr->funcid = funcid;
4512  fexpr->funcresulttype = result_type;
4513  fexpr->funcretset = false;
4514  fexpr->funcvariadic = funcvariadic;
4515  fexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
4516  fexpr->funccollid = result_collid; /* doesn't matter */
4517  fexpr->inputcollid = input_collid;
4518  fexpr->args = args;
4519  fexpr->location = -1;
4520 
4521  /* Fetch the function body */
4522  tmp = SysCacheGetAttrNotNull(PROCOID, func_tuple, Anum_pg_proc_prosrc);
4523  src = TextDatumGetCString(tmp);
4524 
4525  /*
4526  * Setup error traceback support for ereport(). This is so that we can
4527  * finger the function that bad information came from.
4528  */
4529  callback_arg.proname = NameStr(funcform->proname);
4530  callback_arg.prosrc = src;
4531 
4532  sqlerrcontext.callback = sql_inline_error_callback;
4533  sqlerrcontext.arg = (void *) &callback_arg;
4534  sqlerrcontext.previous = error_context_stack;
4535  error_context_stack = &sqlerrcontext;
4536 
4537  /* If we have prosqlbody, pay attention to that not prosrc */
4538  tmp = SysCacheGetAttr(PROCOID,
4539  func_tuple,
4540  Anum_pg_proc_prosqlbody,
4541  &isNull);
4542  if (!isNull)
4543  {
4544  Node *n;
4545  List *query_list;
4546 
4548  if (IsA(n, List))
4549  query_list = linitial_node(List, castNode(List, n));
4550  else
4551  query_list = list_make1(n);
4552  if (list_length(query_list) != 1)
4553  goto fail;
4554  querytree = linitial(query_list);
4555 
4556  /*
4557  * Because we'll insist below that the querytree have an empty rtable
4558  * and no sublinks, it cannot have any relation references that need
4559  * to be locked or rewritten. So we can omit those steps.
4560  */
4561  }
4562  else
4563  {
4564  /* Set up to handle parameters while parsing the function body. */
4565  pinfo = prepare_sql_fn_parse_info(func_tuple,
4566  (Node *) fexpr,
4567  input_collid);
4568 
4569  /*
4570  * We just do parsing and parse analysis, not rewriting, because
4571  * rewriting will not affect table-free-SELECT-only queries, which is
4572  * all that we care about. Also, we can punt as soon as we detect
4573  * more than one command in the function body.
4574  */
4575  raw_parsetree_list = pg_parse_query(src);
4576  if (list_length(raw_parsetree_list) != 1)
4577  goto fail;
4578 
4579  pstate = make_parsestate(NULL);
4580  pstate->p_sourcetext = src;
4581  sql_fn_parser_setup(pstate, pinfo);
4582 
4583  querytree = transformTopLevelStmt(pstate, linitial(raw_parsetree_list));
4584 
4585  free_parsestate(pstate);
4586  }
4587 
4588  /*
4589  * The single command must be a simple "SELECT expression".
4590  *
4591  * Note: if you change the tests involved in this, see also plpgsql's
4592  * exec_simple_check_plan(). That generally needs to have the same idea
4593  * of what's a "simple expression", so that inlining a function that
4594  * previously wasn't inlined won't change plpgsql's conclusion.
4595  */
4596  if (!IsA(querytree, Query) ||
4597  querytree->commandType != CMD_SELECT ||
4598  querytree->hasAggs ||
4599  querytree->hasWindowFuncs ||
4600  querytree->hasTargetSRFs ||
4601  querytree->hasSubLinks ||
4602  querytree->cteList ||
4603  querytree->rtable ||
4604  querytree->jointree->fromlist ||
4605  querytree->jointree->quals ||
4606  querytree->groupClause ||
4607  querytree->groupingSets ||
4608  querytree->havingQual ||
4609  querytree->windowClause ||
4610  querytree->distinctClause ||
4611  querytree->sortClause ||
4612  querytree->limitOffset ||
4613  querytree->limitCount ||
4614  querytree->setOperations ||
4615  list_length(querytree->targetList) != 1)
4616  goto fail;
4617 
4618  /* If the function result is composite, resolve it */
4619  (void) get_expr_result_type((Node *) fexpr,
4620  NULL,
4621  &rettupdesc);
4622 
4623  /*
4624  * Make sure the function (still) returns what it's declared to. This
4625  * will raise an error if wrong, but that's okay since the function would
4626  * fail at runtime anyway. Note that check_sql_fn_retval will also insert
4627  * a coercion if needed to make the tlist expression match the declared
4628  * type of the function.
4629  *
4630  * Note: we do not try this until we have verified that no rewriting was
4631  * needed; that's probably not important, but let's be careful.
4632  */
4633  querytree_list = list_make1(querytree);
4634  if (check_sql_fn_retval(list_make1(querytree_list),
4635  result_type, rettupdesc,
4636  false, NULL))
4637  goto fail; /* reject whole-tuple-result cases */
4638 
4639  /*
4640  * Given the tests above, check_sql_fn_retval shouldn't have decided to
4641  * inject a projection step, but let's just make sure.
4642  */
4643  if (querytree != linitial(querytree_list))
4644  goto fail;
4645 
4646  /* Now we can grab the tlist expression */
4647  newexpr = (Node *) ((TargetEntry *) linitial(querytree->targetList))->expr;
4648 
4649  /*
4650  * If the SQL function returns VOID, we can only inline it if it is a
4651  * SELECT of an expression returning VOID (ie, it's just a redirection to
4652  * another VOID-returning function). In all non-VOID-returning cases,
4653  * check_sql_fn_retval should ensure that newexpr returns the function's
4654  * declared result type, so this test shouldn't fail otherwise; but we may
4655  * as well cope gracefully if it does.
4656  */
4657  if (exprType(newexpr) != result_type)
4658  goto fail;
4659 
4660  /*
4661  * Additional validity checks on the expression. It mustn't be more
4662  * volatile than the surrounding function (this is to avoid breaking hacks
4663  * that involve pretending a function is immutable when it really ain't).
4664  * If the surrounding function is declared strict, then the expression
4665  * must contain only strict constructs and must use all of the function
4666  * parameters (this is overkill, but an exact analysis is hard).
4667  */
4668  if (funcform->provolatile == PROVOLATILE_IMMUTABLE &&
4669  contain_mutable_functions(newexpr))
4670  goto fail;
4671  else if (funcform->provolatile == PROVOLATILE_STABLE &&
4672  contain_volatile_functions(newexpr))
4673  goto fail;
4674 
4675  if (funcform->proisstrict &&
4676  contain_nonstrict_functions(newexpr))
4677  goto fail;
4678 
4679  /*
4680  * If any parameter expression contains a context-dependent node, we can't
4681  * inline, for fear of putting such a node into the wrong context.
4682  */
4684  goto fail;
4685 
4686  /*
4687  * We may be able to do it; there are still checks on parameter usage to
4688  * make, but those are most easily done in combination with the actual
4689  * substitution of the inputs. So start building expression with inputs
4690  * substituted.
4691  */
4692  usecounts = (int *) palloc0(funcform->pronargs * sizeof(int));
4693  newexpr = substitute_actual_parameters(newexpr, funcform->pronargs,
4694  args, usecounts);
4695 
4696  /* Now check for parameter usage */
4697  i = 0;
4698  foreach(arg, args)
4699  {
4700  Node *param = lfirst(arg);
4701 
4702  if (usecounts[i] == 0)
4703  {
4704  /* Param not used at all: uncool if func is strict */
4705  if (funcform->proisstrict)
4706  goto fail;
4707  }
4708  else if (usecounts[i] != 1)
4709  {
4710  /* Param used multiple times: uncool if expensive or volatile */
4711  QualCost eval_cost;
4712 
4713  /*
4714  * We define "expensive" as "contains any subplan or more than 10
4715  * operators". Note that the subplan search has to be done
4716  * explicitly, since cost_qual_eval() will barf on unplanned
4717  * subselects.
4718  */
4719  if (contain_subplans(param))
4720  goto fail;
4721  cost_qual_eval(&eval_cost, list_make1(param), NULL);
4722  if (eval_cost.startup + eval_cost.per_tuple >
4723  10 * cpu_operator_cost)
4724  goto fail;
4725 
4726  /*
4727  * Check volatility last since this is more expensive than the
4728  * above tests
4729  */
4730  if (contain_volatile_functions(param))
4731  goto fail;
4732  }
4733  i++;
4734  }
4735 
4736  /*
4737  * Whew --- we can make the substitution. Copy the modified expression
4738  * out of the temporary memory context, and clean up.
4739  */
4740  MemoryContextSwitchTo(oldcxt);
4741 
4742  newexpr = copyObject(newexpr);
4743 
4744  MemoryContextDelete(mycxt);
4745 
4746  /*
4747  * If the result is of a collatable type, force the result to expose the
4748  * correct collation. In most cases this does not matter, but it's
4749  * possible that the function result is used directly as a sort key or in
4750  * other places where we expect exprCollation() to tell the truth.
4751  */
4752  if (OidIsValid(result_collid))
4753  {
4754  Oid exprcoll = exprCollation(newexpr);
4755 
4756  if (OidIsValid(exprcoll) && exprcoll != result_collid)
4757  {
4758  CollateExpr *newnode = makeNode(CollateExpr);
4759 
4760  newnode->arg = (Expr *) newexpr;
4761  newnode->collOid = result_collid;
4762  newnode->location = -1;
4763 
4764  newexpr = (Node *) newnode;
4765  }
4766  }
4767 
4768  /*
4769  * Since there is now no trace of the function in the plan tree, we must
4770  * explicitly record the plan's dependency on the function.
4771  */
4772  if (context->root)
4773  record_plan_function_dependency(context->root, funcid);
4774 
4775  /*
4776  * Recursively try to simplify the modified expression. Here we must add
4777  * the current function to the context list of active functions.
4778  */
4779  context->active_fns = lappend_oid(context->active_fns, funcid);
4780  newexpr = eval_const_expressions_mutator(newexpr, context);
4781  context->active_fns = list_delete_last(context->active_fns);
4782 
4783  error_context_stack = sqlerrcontext.previous;
4784 
4785  return (Expr *) newexpr;
4786 
4787  /* Here if func is not inlinable: release temp memory and return NULL */
4788 fail:
4789  MemoryContextSwitchTo(oldcxt);
4790  MemoryContextDelete(mycxt);
4791  error_context_stack = sqlerrcontext.previous;
4792 
4793  return NULL;
4794 }
Datum querytree(PG_FUNCTION_ARGS)
Definition: _int_bool.c:666
@ ACLCHECK_OK
Definition: acl.h:182
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition: aclchk.c:3760
#define NameStr(name)
Definition: c.h:735
static Node * substitute_actual_parameters(Node *expr, int nargs, List *args, int *usecounts)
Definition: clauses.c:4800
static void sql_inline_error_callback(void *arg)
Definition: clauses.c:4842
static bool contain_context_dependent_node(Node *clause)
Definition: clauses.c:1096
bool contain_nonstrict_functions(Node *clause)
Definition: clauses.c:910
bool contain_subplans(Node *clause)
Definition: clauses.c:332
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:483
double cpu_operator_cost
Definition: costsize.c:124
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:4612
ErrorContextCallback * error_context_stack
Definition: elog.c:95
#define FmgrHookIsNeeded(fn_oid)
Definition: fmgr.h:797
TypeFuncClass get_expr_result_type(Node *expr, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:292
bool check_sql_fn_retval(List *queryTreeLists, Oid rettype, TupleDesc rettupdesc, bool insertDroppedCols, List **resultTargetList)
Definition: functions.c:1607
void sql_fn_parser_setup(struct ParseState *pstate, SQLFunctionParseInfoPtr pinfo)
Definition: functions.c:265
SQLFunctionParseInfoPtr prepare_sql_fn_parse_info(HeapTuple procedureTuple, Node *call_expr, Oid inputCollation)
Definition: functions.c:176
bool heap_attisnull(HeapTuple tup, int attnum, TupleDesc tupleDesc)
Definition: heaptuple.c:447
int i
Definition: isn.c:73
List * lappend_oid(List *list, Oid datum)
Definition: list.c:374
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:721
List * list_delete_last(List *list)
Definition: list.c:956
MemoryContext CurrentMemoryContext
Definition: mcxt.c:135
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:403
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:153
Oid GetUserId(void)
Definition: miscinit.c:509
@ CMD_SELECT
Definition: nodes.h:276
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:77
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
#define ACL_EXECUTE
Definition: parsenodes.h:90
Query * transformTopLevelStmt(ParseState *pstate, RawStmt *parseTree)
Definition: analyze.c:251
#define linitial_node(type, l)
Definition: pg_list.h:181
List * pg_parse_query(const char *query_string)
Definition: postgres.c:609
void record_plan_function_dependency(PlannerInfo *root, Oid funcid)
Definition: setrefs.c:3438
struct ErrorContextCallback * previous
Definition: elog.h:295
void(* callback)(void *arg)
Definition: elog.h:296
const char * p_sourcetext
Definition: parse_node.h:192
Cost per_tuple
Definition: pathnodes.h:48
Cost startup
Definition: pathnodes.h:47

References ACL_EXECUTE, ACLCHECK_OK, eval_const_expressions_context::active_fns, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, arg, CollateExpr::arg, ErrorContextCallback::arg, generate_unaccent_rules::args, FuncExpr::args, ErrorContextCallback::callback, castNode, check_sql_fn_retval(), CMD_SELECT, COERCE_EXPLICIT_CALL, CollateExpr::collOid, contain_context_dependent_node(), contain_mutable_functions(), contain_nonstrict_functions(), contain_subplans(), contain_volatile_functions(), copyObject, cost_qual_eval(), cpu_operator_cost, CurrentMemoryContext, error_context_stack, eval_const_expressions_mutator(), exprCollation(), exprType(), FmgrHookIsNeeded, free_parsestate(), FuncExpr::funcid, get_expr_result_type(), GETSTRUCT, GetUserId(), heap_attisnull(), i, IsA, lappend_oid(), lfirst, linitial, linitial_node, list_delete_last(), list_length(), list_make1, list_member_oid(), FuncExpr::location, CollateExpr::location, make_parsestate(), makeNode, MemoryContextDelete(), MemoryContextSwitchTo(), NameStr, object_aclcheck(), OidIsValid, ParseState::p_sourcetext, palloc0(), QualCost::per_tuple, pg_parse_query(), prepare_sql_fn_parse_info(), ErrorContextCallback::previous, PROCOID, inline_error_callback_arg::proname, inline_error_callback_arg::prosrc, querytree(), record_plan_function_dependency(), eval_const_expressions_context::root, sql_fn_parser_setup(), sql_inline_error_callback(), QualCost::startup, stringToNode(), substitute_actual_parameters(), SysCacheGetAttr(), SysCacheGetAttrNotNull(), TextDatumGetCString, and transformTopLevelStmt().

Referenced by simplify_function().

◆ inline_set_returning_function()

Query* inline_set_returning_function ( PlannerInfo root,
RangeTblEntry rte 
)

Definition at line 4958 of file clauses.c.

4959 {
4960  RangeTblFunction *rtfunc;
4961  FuncExpr *fexpr;
4962  Oid func_oid;
4963  HeapTuple func_tuple;
4964  Form_pg_proc funcform;
4965  char *src;
4966  Datum tmp;
4967  bool isNull;
4968  MemoryContext oldcxt;
4969  MemoryContext mycxt;
4970  inline_error_callback_arg callback_arg;
4971  ErrorContextCallback sqlerrcontext;
4973  TypeFuncClass functypclass;
4974  TupleDesc rettupdesc;
4975  List *raw_parsetree_list;
4976  List *querytree_list;
4977  Query *querytree;
4978 
4979  Assert(rte->rtekind == RTE_FUNCTION);
4980 
4981  /*
4982  * It doesn't make a lot of sense for a SQL SRF to refer to itself in its
4983  * own FROM clause, since that must cause infinite recursion at runtime.
4984  * It will cause this code to recurse too, so check for stack overflow.
4985  * (There's no need to do more.)
4986  */
4988 
4989  /* Fail if the RTE has ORDINALITY - we don't implement that here. */
4990  if (rte->funcordinality)
4991  return NULL;
4992 
4993  /* Fail if RTE isn't a single, simple FuncExpr */
4994  if (list_length(rte->functions) != 1)
4995  return NULL;
4996  rtfunc = (RangeTblFunction *) linitial(rte->functions);
4997 
4998  if (!IsA(rtfunc->funcexpr, FuncExpr))
4999  return NULL;
5000  fexpr = (FuncExpr *) rtfunc->funcexpr;
5001 
5002  func_oid = fexpr->funcid;
5003 
5004  /*
5005  * The function must be declared to return a set, else inlining would
5006  * change the results if the contained SELECT didn't return exactly one
5007  * row.
5008  */
5009  if (!fexpr->funcretset)
5010  return NULL;
5011 
5012  /*
5013  * Refuse to inline if the arguments contain any volatile functions or
5014  * sub-selects. Volatile functions are rejected because inlining may
5015  * result in the arguments being evaluated multiple times, risking a
5016  * change in behavior. Sub-selects are rejected partly for implementation
5017  * reasons (pushing them down another level might change their behavior)
5018  * and partly because they're likely to be expensive and so multiple
5019  * evaluation would be bad.
5020  */
5021  if (contain_volatile_functions((Node *) fexpr->args) ||
5022  contain_subplans((Node *) fexpr->args))
5023  return NULL;
5024 
5025  /* Check permission to call function (fail later, if not) */
5026  if (object_aclcheck(ProcedureRelationId, func_oid, GetUserId(), ACL_EXECUTE) != ACLCHECK_OK)
5027  return NULL;
5028 
5029  /* Check whether a plugin wants to hook function entry/exit */
5030  if (FmgrHookIsNeeded(func_oid))
5031  return NULL;
5032 
5033  /*
5034  * OK, let's take a look at the function's pg_proc entry.
5035  */
5036  func_tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(func_oid));
5037  if (!HeapTupleIsValid(func_tuple))
5038  elog(ERROR, "cache lookup failed for function %u", func_oid);
5039  funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
5040 
5041  /*
5042  * Forget it if the function is not SQL-language or has other showstopper
5043  * properties. In particular it mustn't be declared STRICT, since we
5044  * couldn't enforce that. It also mustn't be VOLATILE, because that is
5045  * supposed to cause it to be executed with its own snapshot, rather than
5046  * sharing the snapshot of the calling query. We also disallow returning
5047  * SETOF VOID, because inlining would result in exposing the actual result
5048  * of the function's last SELECT, which should not happen in that case.
5049  * (Rechecking prokind, proretset, and pronargs is just paranoia.)
5050  */
5051  if (funcform->prolang != SQLlanguageId ||
5052  funcform->prokind != PROKIND_FUNCTION ||
5053  funcform->proisstrict ||
5054  funcform->provolatile == PROVOLATILE_VOLATILE ||
5055  funcform->prorettype == VOIDOID ||
5056  funcform->prosecdef ||
5057  !funcform->proretset ||
5058  list_length(fexpr->args) != funcform->pronargs ||
5059  !heap_attisnull(func_tuple, Anum_pg_proc_proconfig, NULL))
5060  {
5061  ReleaseSysCache(func_tuple);
5062  return NULL;
5063  }
5064 
5065  /*
5066  * Make a temporary memory context, so that we don't leak all the stuff
5067  * that parsing might create.
5068  */
5070  "inline_set_returning_function",
5072  oldcxt = MemoryContextSwitchTo(mycxt);
5073 
5074  /* Fetch the function body */
5075  tmp = SysCacheGetAttrNotNull(PROCOID, func_tuple, Anum_pg_proc_prosrc);
5076  src = TextDatumGetCString(tmp);
5077 
5078  /*
5079  * Setup error traceback support for ereport(). This is so that we can
5080  * finger the function that bad information came from.
5081  */
5082  callback_arg.proname = NameStr(funcform->proname);
5083  callback_arg.prosrc = src;
5084 
5085  sqlerrcontext.callback = sql_inline_error_callback;
5086  sqlerrcontext.arg = (void *) &callback_arg;
5087  sqlerrcontext.previous = error_context_stack;
5088  error_context_stack = &sqlerrcontext;
5089 
5090  /* If we have prosqlbody, pay attention to that not prosrc */
5091  tmp = SysCacheGetAttr(PROCOID,
5092  func_tuple,
5093  Anum_pg_proc_prosqlbody,
5094  &isNull);
5095  if (!isNull)
5096  {
5097  Node *n;
5098 
5100  if (IsA(n, List))
5101  querytree_list = linitial_node(List, castNode(List, n));
5102  else
5103  querytree_list = list_make1(n);
5104  if (list_length(querytree_list) != 1)
5105  goto fail;
5106  querytree = linitial(querytree_list);
5107 
5108  /* Acquire necessary locks, then apply rewriter. */
5109  AcquireRewriteLocks(querytree, true, false);
5110  querytree_list = pg_rewrite_query(querytree);
5111  if (list_length(querytree_list) != 1)
5112  goto fail;
5113  querytree = linitial(querytree_list);
5114  }
5115  else
5116  {
5117  /*
5118  * Set up to handle parameters while parsing the function body. We
5119  * can use the FuncExpr just created as the input for
5120  * prepare_sql_fn_parse_info.
5121  */
5122  pinfo = prepare_sql_fn_parse_info(func_tuple,
5123  (Node *) fexpr,
5124  fexpr->inputcollid);
5125 
5126  /*
5127  * Parse, analyze, and rewrite (unlike inline_function(), we can't
5128  * skip rewriting here). We can fail as soon as we find more than one
5129  * query, though.
5130  */
5131  raw_parsetree_list = pg_parse_query(src);
5132  if (list_length(raw_parsetree_list) != 1)
5133  goto fail;
5134 
5135  querytree_list = pg_analyze_and_rewrite_withcb(linitial(raw_parsetree_list),
5136  src,
5138  pinfo, NULL);
5139  if (list_length(querytree_list) != 1)
5140  goto fail;
5141  querytree = linitial(querytree_list);
5142  }
5143 
5144  /*
5145  * Also resolve the actual function result tupdesc, if composite. If the
5146  * function is just declared to return RECORD, dig the info out of the AS
5147  * clause.
5148  */
5149  functypclass = get_expr_result_type((Node *) fexpr, NULL, &rettupdesc);
5150  if (functypclass == TYPEFUNC_RECORD)
5151  rettupdesc = BuildDescFromLists(rtfunc->funccolnames,
5152  rtfunc->funccoltypes,
5153  rtfunc->funccoltypmods,
5154  rtfunc->funccolcollations);
5155 
5156  /*
5157  * The single command must be a plain SELECT.
5158  */
5159  if (!IsA(querytree, Query) ||
5160  querytree->commandType != CMD_SELECT)
5161  goto fail;
5162 
5163  /*
5164  * Make sure the function (still) returns what it's declared to. This
5165  * will raise an error if wrong, but that's okay since the function would
5166  * fail at runtime anyway. Note that check_sql_fn_retval will also insert
5167  * coercions if needed to make the tlist expression(s) match the declared
5168  * type of the function. We also ask it to insert dummy NULL columns for
5169  * any dropped columns in rettupdesc, so that the elements of the modified
5170  * tlist match up to the attribute numbers.
5171  *
5172  * If the function returns a composite type, don't inline unless the check
5173  * shows it's returning a whole tuple result; otherwise what it's
5174  * returning is a single composite column which is not what we need.
5175  */
5176  if (!check_sql_fn_retval(list_make1(querytree_list),
5177  fexpr->funcresulttype, rettupdesc,
5178  true, NULL) &&
5179  (functypclass == TYPEFUNC_COMPOSITE ||
5180  functypclass == TYPEFUNC_COMPOSITE_DOMAIN ||
5181  functypclass == TYPEFUNC_RECORD))
5182  goto fail; /* reject not-whole-tuple-result cases */
5183 
5184  /*
5185  * check_sql_fn_retval might've inserted a projection step, but that's
5186  * fine; just make sure we use the upper Query.
5187  */
5188  querytree = linitial_node(Query, querytree_list);
5189 
5190  /*
5191  * Looks good --- substitute parameters into the query.
5192  */
5194  funcform->pronargs,
5195  fexpr->args);
5196 
5197  /*
5198  * Copy the modified query out of the temporary memory context, and clean
5199  * up.
5200  */
5201  MemoryContextSwitchTo(oldcxt);
5202 
5204 
5205  MemoryContextDelete(mycxt);
5206  error_context_stack = sqlerrcontext.previous;
5207  ReleaseSysCache(func_tuple);
5208 
5209  /*
5210  * We don't have to fix collations here because the upper query is already
5211  * parsed, ie, the collations in the RTE are what count.
5212  */
5213 
5214  /*
5215  * Since there is now no trace of the function in the plan tree, we must
5216  * explicitly record the plan's dependency on the function.
5217  */
5218  record_plan_function_dependency(root, func_oid);
5219 
5220  /*
5221  * We must also notice if the inserted query adds a dependency on the
5222  * calling role due to RLS quals.
5223  */
5224  if (querytree->hasRowSecurity)
5225  root->glob->dependsOnRole = true;
5226 
5227  return querytree;
5228 
5229  /* Here if func is not inlinable: release temp memory and return NULL */
5230 fail:
5231  MemoryContextSwitchTo(oldcxt);
5232  MemoryContextDelete(mycxt);
5233  error_context_stack = sqlerrcontext.previous;
5234  ReleaseSysCache(func_tuple);
5235 
5236  return NULL;
5237 }
static Query * substitute_actual_srf_parameters(Query *expr, int nargs, List *args)
Definition: clauses.c:5246
TypeFuncClass
Definition: funcapi.h:147
@ TYPEFUNC_COMPOSITE
Definition: funcapi.h:149
@ TYPEFUNC_RECORD
Definition: funcapi.h:151
@ TYPEFUNC_COMPOSITE_DOMAIN
Definition: funcapi.h:150
void(* ParserSetupHook)(struct ParseState *pstate, void *arg)
Definition: params.h:108
@ RTE_FUNCTION
Definition: parsenodes.h:1016
List * pg_analyze_and_rewrite_withcb(RawStmt *parsetree, const char *query_string, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
Definition: postgres.c:762
List * pg_rewrite_query(Query *query)
Definition: postgres.c:802
void check_stack_depth(void)
Definition: postgres.c:3523
void AcquireRewriteLocks(Query *parsetree, bool forExecute, bool forUpdatePushedDown)
bool dependsOnRole
Definition: pathnodes.h:150
bool funcordinality
Definition: parsenodes.h:1148
List * functions
Definition: parsenodes.h:1147
RTEKind rtekind
Definition: parsenodes.h:1032
TupleDesc BuildDescFromLists(const List *names, const List *types, const List *typmods, const List *collations)
Definition: tupdesc.c:894

References ACL_EXECUTE, ACLCHECK_OK, AcquireRewriteLocks(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, ErrorContextCallback::arg, FuncExpr::args, Assert(), BuildDescFromLists(), ErrorContextCallback::callback, castNode, check_sql_fn_retval(), check_stack_depth(), CMD_SELECT, contain_subplans(), contain_volatile_functions(), copyObject, CurrentMemoryContext, PlannerGlobal::dependsOnRole, elog(), ERROR, error_context_stack, FmgrHookIsNeeded, RangeTblFunction::funcexpr, FuncExpr::funcid, RangeTblEntry::funcordinality, RangeTblEntry::functions, get_expr_result_type(), GETSTRUCT, GetUserId(), PlannerInfo::glob, heap_attisnull(), HeapTupleIsValid, if(), IsA, linitial, linitial_node, list_length(), list_make1, MemoryContextDelete(), MemoryContextSwitchTo(), NameStr, object_aclcheck(), ObjectIdGetDatum(), pg_analyze_and_rewrite_withcb(), pg_parse_query(), pg_rewrite_query(), prepare_sql_fn_parse_info(), ErrorContextCallback::previous, PROCOID, inline_error_callback_arg::proname, inline_error_callback_arg::prosrc, querytree(), record_plan_function_dependency(), ReleaseSysCache(), RTE_FUNCTION, RangeTblEntry::rtekind, SearchSysCache1(), sql_fn_parser_setup(), sql_inline_error_callback(), stringToNode(), substitute_actual_srf_parameters(), SysCacheGetAttr(), SysCacheGetAttrNotNull(), TextDatumGetCString, TYPEFUNC_COMPOSITE, TYPEFUNC_COMPOSITE_DOMAIN, and TYPEFUNC_RECORD.

Referenced by preprocess_function_rtes().

◆ is_parallel_safe()

bool is_parallel_safe ( PlannerInfo root,
Node node 
)

Definition at line 670 of file clauses.c.

671 {
673  PlannerInfo *proot;
674  ListCell *l;
675 
676  /*
677  * Even if the original querytree contained nothing unsafe, we need to
678  * search the expression if we have generated any PARAM_EXEC Params while
679  * planning, because those are parallel-restricted and there might be one
680  * in this expression. But otherwise we don't need to look.
681  */
682  if (root->glob->maxParallelHazard == PROPARALLEL_SAFE &&
683  root->glob->paramExecTypes == NIL)
684  return true;
685  /* Else use max_parallel_hazard's search logic, but stop on RESTRICTED */
686  context.max_hazard = PROPARALLEL_SAFE;
687  context.max_interesting = PROPARALLEL_RESTRICTED;
688  context.safe_param_ids = NIL;
689 
690  /*
691  * The params that refer to the same or parent query level are considered
692  * parallel-safe. The idea is that we compute such params at Gather or
693  * Gather Merge node and pass their value to workers.
694  */
695  for (proot = root; proot != NULL; proot = proot->parent_root)
696  {
697  foreach(l, proot->init_plans)
698  {
699  SubPlan *initsubplan = (SubPlan *) lfirst(l);
700 
701  context.safe_param_ids = list_concat(context.safe_param_ids,
702  initsubplan->setParam);
703  }
704  }
705 
706  return !max_parallel_hazard_walker(node, &context);
707 }
static bool max_parallel_hazard_walker(Node *node, max_parallel_hazard_context *context)
Definition: clauses.c:746
List * list_concat(List *list1, const List *list2)
Definition: list.c:560
char maxParallelHazard
Definition: pathnodes.h:159
List * paramExecTypes
Definition: pathnodes.h:135
List * init_plans
Definition: pathnodes.h:296
List * setParam
Definition: primnodes.h:1015

References PlannerInfo::glob, PlannerInfo::init_plans, lfirst, list_concat(), max_parallel_hazard_context::max_hazard, max_parallel_hazard_context::max_interesting, max_parallel_hazard_walker(), PlannerGlobal::maxParallelHazard, NIL, PlannerGlobal::paramExecTypes, max_parallel_hazard_context::safe_param_ids, and SubPlan::setParam.

Referenced by apply_projection_to_path(), build_join_rel(), create_minmaxagg_path(), create_projection_path(), create_set_projection_path(), create_window_paths(), find_computable_ec_member(), grouping_planner(), make_grouping_rel(), plan_create_index_workers(), query_planner(), relation_can_be_sorted_early(), and set_rel_consider_parallel().

◆ is_pseudo_constant_clause()

bool is_pseudo_constant_clause ( Node clause)

Definition at line 2005 of file clauses.c.

2006 {
2007  /*
2008  * We could implement this check in one recursive scan. But since the
2009  * check for volatile functions is both moderately expensive and unlikely
2010  * to fail, it seems better to look for Vars first and only check for
2011  * volatile functions if we find no Vars.
2012  */
2013  if (!contain_var_clause(clause) &&
2014  !contain_volatile_functions(clause))
2015  return true;
2016  return false;
2017 }

References contain_var_clause(), and contain_volatile_functions().

Referenced by clauselist_selectivity_ext(), dependency_is_compatible_clause(), dependency_is_compatible_expression(), and find_window_run_conditions().

◆ is_pseudo_constant_clause_relids()

bool is_pseudo_constant_clause_relids ( Node clause,
Relids  relids 
)

Definition at line 2025 of file clauses.c.

2026 {
2027  if (bms_is_empty(relids) &&
2028  !contain_volatile_functions(clause))
2029  return true;
2030  return false;
2031 }

References bms_is_empty, and contain_volatile_functions().

Referenced by clauselist_selectivity_ext().

◆ is_strict_saop()

static bool is_strict_saop ( ScalarArrayOpExpr expr,
bool  falseOK 
)
static

Definition at line 1943 of file clauses.c.

1944 {
1945  Node *rightop;
1946 
1947  /* The contained operator must be strict. */
1948  set_sa_opfuncid(expr);
1949  if (!func_strict(expr->opfuncid))
1950  return false;
1951  /* If ANY and falseOK, that's all we need to check. */
1952  if (expr->useOr && falseOK)
1953  return true;
1954  /* Else, we have to see if the array is provably non-empty. */
1955  Assert(list_length(expr->args) == 2);
1956  rightop = (Node *) lsecond(expr->args);
1957  if (rightop && IsA(rightop, Const))
1958  {
1959  Datum arraydatum = ((Const *) rightop)->constvalue;
1960  bool arrayisnull = ((Const *) rightop)->constisnull;
1961  ArrayType *arrayval;
1962  int nitems;
1963 
1964  if (arrayisnull)
1965  return false;
1966  arrayval = DatumGetArrayTypeP(arraydatum);
1967  nitems = ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
1968  if (nitems > 0)
1969  return true;
1970  }
1971  else if (rightop && IsA(rightop, ArrayExpr))
1972  {
1973  ArrayExpr *arrayexpr = (ArrayExpr *) rightop;
1974 
1975  if (arrayexpr->elements != NIL && !arrayexpr->multidims)
1976  return true;
1977  }
1978  return false;
1979 }
List * elements
Definition: primnodes.h:1307

References ScalarArrayOpExpr::args, ARR_DIMS, ARR_NDIM, ArrayGetNItems(), Assert(), DatumGetArrayTypeP, ArrayExpr::elements, func_strict(), IsA, list_length(), lsecond, NIL, nitems, set_sa_opfuncid(), and ScalarArrayOpExpr::useOr.

Referenced by find_nonnullable_rels_walker(), and find_nonnullable_vars_walker().

◆ max_parallel_hazard()

char max_parallel_hazard ( Query parse)

Definition at line 651 of file clauses.c.

652 {
654 
655  context.max_hazard = PROPARALLEL_SAFE;
656  context.max_interesting = PROPARALLEL_UNSAFE;
657  context.safe_param_ids = NIL;
658  (void) max_parallel_hazard_walker((Node *) parse, &context);
659  return context.max_hazard;
660 }
static struct subre * parse(struct vars *v, int stopper, int type, struct state *init, struct state *final)
Definition: regcomp.c:715

References max_parallel_hazard_context::max_hazard, max_parallel_hazard_context::max_interesting, max_parallel_hazard_walker(), NIL, parse(), and max_parallel_hazard_context::safe_param_ids.

Referenced by standard_planner().

◆ max_parallel_hazard_checker()

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

Definition at line 739 of file clauses.c.

740 {
741  return max_parallel_hazard_test(func_parallel(func_id),
742  (max_parallel_hazard_context *) context);
743 }
static bool max_parallel_hazard_test(char proparallel, max_parallel_hazard_context *context)
Definition: clauses.c:711
char func_parallel(Oid funcid)
Definition: lsyscache.c:1803

References func_parallel(), and max_parallel_hazard_test().

Referenced by max_parallel_hazard_walker().

◆ max_parallel_hazard_test()

static bool max_parallel_hazard_test ( char  proparallel,
max_parallel_hazard_context context 
)
static

Definition at line 711 of file clauses.c.

712 {
713  switch (proparallel)
714  {
715  case PROPARALLEL_SAFE:
716  /* nothing to see here, move along */
717  break;
718  case PROPARALLEL_RESTRICTED:
719  /* increase max_hazard to RESTRICTED */
720  Assert(context->max_hazard != PROPARALLEL_UNSAFE);
721  context->max_hazard = proparallel;
722  /* done if we are not expecting any unsafe functions */
723  if (context->max_interesting == proparallel)
724  return true;
725  break;
726  case PROPARALLEL_UNSAFE:
727  context->max_hazard = proparallel;
728  /* we're always done at the first unsafe construct */
729  return true;
730  default:
731  elog(ERROR, "unrecognized proparallel value \"%c\"", proparallel);
732  break;
733  }
734  return false;
735 }

References Assert(), elog(), ERROR, max_parallel_hazard_context::max_hazard, and max_parallel_hazard_context::max_interesting.

Referenced by max_parallel_hazard_checker(), and max_parallel_hazard_walker().

◆ max_parallel_hazard_walker()

static bool max_parallel_hazard_walker ( Node node,
max_parallel_hazard_context context 
)
static

Definition at line 746 of file clauses.c.

747 {
748  if (node == NULL)
749  return false;
750 
751  /* Check for hazardous functions in node itself */
753  context))
754  return true;
755 
756  /*
757  * It should be OK to treat MinMaxExpr as parallel-safe, since btree
758  * opclass support functions are generally parallel-safe. XmlExpr is a
759  * bit more dubious but we can probably get away with it. We err on the
760  * side of caution by treating CoerceToDomain as parallel-restricted.
761  * (Note: in principle that's wrong because a domain constraint could
762  * contain a parallel-unsafe function; but useful constraints probably
763  * never would have such, and assuming they do would cripple use of
764  * parallel query in the presence of domain types.) SQLValueFunction
765  * should be safe in all cases. NextValueExpr is parallel-unsafe.
766  */
767  if (IsA(node, CoerceToDomain))
768  {
769  if (max_parallel_hazard_test(PROPARALLEL_RESTRICTED, context))
770  return true;
771  }
772 
773  else if (IsA(node, NextValueExpr))
774  {
775  if (max_parallel_hazard_test(PROPARALLEL_UNSAFE, context))
776  return true;
777  }
778 
779  /*
780  * Treat window functions as parallel-restricted because we aren't sure
781  * whether the input row ordering is fully deterministic, and the output
782  * of window functions might vary across workers if not. (In some cases,
783  * like where the window frame orders by a primary key, we could relax
784  * this restriction. But it doesn't currently seem worth expending extra
785  * effort to do so.)
786  */
787  else if (IsA(node, WindowFunc))
788  {
789  if (max_parallel_hazard_test(PROPARALLEL_RESTRICTED, context))
790  return true;
791  }
792 
793  /*
794  * As a notational convenience for callers, look through RestrictInfo.
795  */
796  else if (IsA(node, RestrictInfo))
797  {
798  RestrictInfo *rinfo = (RestrictInfo *) node;
799 
800  return max_parallel_hazard_walker((Node *) rinfo->clause, context);
801  }
802 
803  /*
804  * Really we should not see SubLink during a max_interesting == restricted
805  * scan, but if we do, return true.
806  */
807  else if (IsA(node, SubLink))
808  {
809  if (max_parallel_hazard_test(PROPARALLEL_RESTRICTED, context))
810  return true;
811  }
812 
813  /*
814  * Only parallel-safe SubPlans can be sent to workers. Within the
815  * testexpr of the SubPlan, Params representing the output columns of the
816  * subplan can be treated as parallel-safe, so temporarily add their IDs
817  * to the safe_param_ids list while examining the testexpr.
818  */
819  else if (IsA(node, SubPlan))
820  {
821  SubPlan *subplan = (SubPlan *) node;
822  List *save_safe_param_ids;
823 
824  if (!subplan->parallel_safe &&
825  max_parallel_hazard_test(PROPARALLEL_RESTRICTED, context))
826  return true;
827  save_safe_param_ids = context->safe_param_ids;
828  context->safe_param_ids = list_concat_copy(context->safe_param_ids,
829  subplan->paramIds);
830  if (max_parallel_hazard_walker(subplan->testexpr, context))
831  return true; /* no need to restore safe_param_ids */
832  list_free(context->safe_param_ids);
833  context->safe_param_ids = save_safe_param_ids;
834  /* we must also check args, but no special Param treatment there */
835  if (max_parallel_hazard_walker((Node *) subplan->args, context))
836  return true;
837  /* don't want to recurse normally, so we're done */
838  return false;
839  }
840 
841  /*
842  * We can't pass Params to workers at the moment either, so they are also
843  * parallel-restricted, unless they are PARAM_EXTERN Params or are
844  * PARAM_EXEC Params listed in safe_param_ids, meaning they could be
845  * either generated within workers or can be computed by the leader and
846  * then their value can be passed to workers.
847  */
848  else if (IsA(node, Param))
849  {
850  Param *param = (Param *) node;
851 
852  if (param->paramkind == PARAM_EXTERN)
853  return false;
854 
855  if (param->paramkind != PARAM_EXEC ||
856  !list_member_int(context->safe_param_ids, param->paramid))
857  {
858  if (max_parallel_hazard_test(PROPARALLEL_RESTRICTED, context))
859  return true;
860  }
861  return false; /* nothing to recurse to */
862  }
863 
864  /*
865  * When we're first invoked on a completely unplanned tree, we must
866  * recurse into subqueries so to as to locate parallel-unsafe constructs
867  * anywhere in the tree.
868  */
869  else if (IsA(node, Query))
870  {
871  Query *query = (Query *) node;
872 
873  /* SELECT FOR UPDATE/SHARE must be treated as unsafe */
874  if (query->rowMarks != NULL)
875  {
876  context->max_hazard = PROPARALLEL_UNSAFE;
877  return true;
878  }
879 
880  /* Recurse into subselects */
881  return query_tree_walker(query,
883  context, 0);
884  }
885 
886  /* Recurse to check arguments */
887  return expression_tree_walker(node,
889  context);
890 }
static bool max_parallel_hazard_checker(Oid func_id, void *context)
Definition: clauses.c:739
void list_free(List *list)
Definition: list.c:1545
List * rowMarks
Definition: parsenodes.h:214
List * args
Definition: primnodes.h:1018
List * paramIds
Definition: primnodes.h:995
Node * testexpr
Definition: primnodes.h:994
bool parallel_safe
Definition: primnodes.h:1011

References SubPlan::args, check_functions_in_node(), RestrictInfo::clause, expression_tree_walker, IsA, list_concat_copy(), list_free(), list_member_int(), max_parallel_hazard_context::max_hazard, max_parallel_hazard_checker(), max_parallel_hazard_test(), SubPlan::parallel_safe, PARAM_EXEC, PARAM_EXTERN, Param::paramid, SubPlan::paramIds, Param::paramkind, query_tree_walker, Query::rowMarks, max_parallel_hazard_context::safe_param_ids, and SubPlan::testexpr.

Referenced by is_parallel_safe(), and max_parallel_hazard().

◆ NumRelids()

int NumRelids ( PlannerInfo root,
Node clause 
)

Definition at line 2047 of file clauses.c.

2048 {
2049  int result;
2050  Relids varnos = pull_varnos(root, clause);
2051 
2052  varnos = bms_del_members(varnos, root->outer_join_rels);
2053  result = bms_num_members(varnos);
2054  bms_free(varnos);
2055  return result;
2056 }
void bms_free(Bitmapset *a)
Definition: bitmapset.c:194
int bms_num_members(const Bitmapset *a)
Definition: bitmapset.c:685
Bitmapset * bms_del_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:993
Relids outer_join_rels
Definition: pathnodes.h:258
Relids pull_varnos(PlannerInfo *root, Node *node)
Definition: var.c:108

References bms_del_members(), bms_free(), bms_num_members(), PlannerInfo::outer_join_rels, and pull_varnos().

Referenced by clauselist_selectivity_ext(), rowcomparesel(), and treat_as_join_clause().

◆ pull_paramids()

Bitmapset* pull_paramids ( Expr expr)

Definition at line 5306 of file clauses.c.

5307 {
5308  Bitmapset *result = NULL;
5309 
5310  (void) pull_paramids_walker((Node *) expr, &result);
5311 
5312  return result;
5313 }
static bool pull_paramids_walker(Node *node, Bitmapset **context)
Definition: clauses.c:5316

References pull_paramids_walker().

Referenced by create_memoize_plan().

◆ pull_paramids_walker()

static bool pull_paramids_walker ( Node node,
Bitmapset **  context 
)
static

Definition at line 5316 of file clauses.c.

5317 {
5318  if (node == NULL)
5319  return false;
5320  if (IsA(node, Param))
5321  {
5322  Param *param = (Param *) node;
5323 
5324  *context = bms_add_member(*context, param->paramid);
5325  return false;
5326  }
5328  (void *) context);
5329 }
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:753

References bms_add_member(), expression_tree_walker, IsA, and Param::paramid.

Referenced by pull_paramids().

◆ recheck_cast_function_args()

static void recheck_cast_function_args ( List args,
Oid  result_type,
Oid proargtypes,
int  pronargs,
HeapTuple  func_tuple 
)
static

Definition at line 4273 of file clauses.c.

4276 {
4277  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4278  int nargs;
4279  Oid actual_arg_types[FUNC_MAX_ARGS];
4280  Oid declared_arg_types[FUNC_MAX_ARGS];
4281  Oid rettype;
4282  ListCell *lc;
4283