PostgreSQL Source Code  git master
clauses.c File Reference
#include "postgres.h"
#include "access/htup_details.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_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_mutable_functions_after_planning (Expr *expr)
 
bool contain_volatile_functions (Node *clause)
 
static bool contain_volatile_functions_checker (Oid func_id, void *context)
 
bool contain_volatile_functions_after_planning (Expr *expr)
 
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 1166 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 2406 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:4941
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
Definition: nodes.h:129

Definition at line 2410 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:2420
#define expression_tree_mutator(n, m, c)
Definition: nodeFuncs.h:153

Definition at line 2397 of file clauses.c.

◆ MIN_ARRAY_SIZE_FOR_HASHED_SAOP

#define MIN_ARRAY_SIZE_FOR_HASHED_SAOP   9

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

4294 {
4295  int nargsprovided = list_length(args);
4296  List *defaults;
4297  int ndelete;
4298 
4299  /* Get all the default expressions from the pg_proc tuple */
4300  defaults = fetch_function_defaults(func_tuple);
4301 
4302  /* Delete any unused defaults from the list */
4303  ndelete = nargsprovided + list_length(defaults) - pronargs;
4304  if (ndelete < 0)
4305  elog(ERROR, "not enough default arguments");
4306  if (ndelete > 0)
4307  defaults = list_delete_first_n(defaults, ndelete);
4308 
4309  /* And form the combined argument list, not modifying the input list */
4310  return list_concat_copy(args, defaults);
4311 }
static List * fetch_function_defaults(HeapTuple func_tuple)
Definition: clauses.c:4317
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:224
List * list_delete_first_n(List *list, int n)
Definition: list.c:983
List * list_concat_copy(const List *list1, const List *list2)
Definition: list.c:598
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 2127 of file clauses.c.

2128 {
2129  Oid opoid;
2130  Node *temp;
2131 
2132  /* Sanity checks: caller is at fault if these fail */
2133  if (!is_opclause(clause) ||
2134  list_length(clause->args) != 2)
2135  elog(ERROR, "cannot commute non-binary-operator clause");
2136 
2137  opoid = get_commutator(clause->opno);
2138 
2139  if (!OidIsValid(opoid))
2140  elog(ERROR, "could not find commutator for operator %u",
2141  clause->opno);
2142 
2143  /*
2144  * modify the clause in-place!
2145  */
2146  clause->opno = opoid;
2147  clause->opfuncid = InvalidOid;
2148  /* opresulttype, opretset, opcollid, inputcollid need not change */
2149 
2150  temp = linitial(clause->args);
2151  linitial(clause->args) = lsecond(clause->args);
2152  lsecond(clause->args) = temp;
2153 }
#define OidIsValid(objectId)
Definition: c.h:762
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1487
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:774
List * args
Definition: primnodes.h:792

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

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

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

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

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

1160 {
1161  int flags = 0;
1162 
1163  return contain_context_dependent_node_walker(clause, &flags);
1164 }
static bool contain_context_dependent_node_walker(Node *node, int *flags)
Definition: clauses.c:1169

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

1170 {
1171  if (node == NULL)
1172  return false;
1173  if (IsA(node, CaseTestExpr))
1174  return !(*flags & CCDN_CASETESTEXPR_OK);
1175  else if (IsA(node, CaseExpr))
1176  {
1177  CaseExpr *caseexpr = (CaseExpr *) node;
1178 
1179  /*
1180  * If this CASE doesn't have a test expression, then it doesn't create
1181  * a context in which CaseTestExprs should appear, so just fall
1182  * through and treat it as a generic expression node.
1183  */
1184  if (caseexpr->arg)
1185  {
1186  int save_flags = *flags;
1187  bool res;
1188 
1189  /*
1190  * Note: in principle, we could distinguish the various sub-parts
1191  * of a CASE construct and set the flag bit only for some of them,
1192  * since we are only expecting CaseTestExprs to appear in the
1193  * "expr" subtree of the CaseWhen nodes. But it doesn't really
1194  * seem worth any extra code. If there are any bare CaseTestExprs
1195  * elsewhere in the CASE, something's wrong already.
1196  */
1197  *flags |= CCDN_CASETESTEXPR_OK;
1198  res = expression_tree_walker(node,
1200  (void *) flags);
1201  *flags = save_flags;
1202  return res;
1203  }
1204  }
1205  else if (IsA(node, ArrayCoerceExpr))
1206  {
1207  ArrayCoerceExpr *ac = (ArrayCoerceExpr *) node;
1208  int save_flags;
1209  bool res;
1210 
1211  /* Check the array expression */
1212  if (contain_context_dependent_node_walker((Node *) ac->arg, flags))
1213  return true;
1214 
1215  /* Check the elemexpr, which is allowed to contain CaseTestExpr */
1216  save_flags = *flags;
1217  *flags |= CCDN_CASETESTEXPR_OK;
1219  flags);
1220  *flags = save_flags;
1221  return res;
1222  }
1224  (void *) flags);
1225 }
#define CCDN_CASETESTEXPR_OK
Definition: clauses.c:1166
Expr * arg
Definition: primnodes.h:1269

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

1118 {
1119  return contain_exec_param_walker(clause, param_ids);
1120 }
static bool contain_exec_param_walker(Node *node, List *param_ids)
Definition: clauses.c:1123

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

1124 {
1125  if (node == NULL)
1126  return false;
1127  if (IsA(node, Param))
1128  {
1129  Param *p = (Param *) node;
1130 
1131  if (p->paramkind == PARAM_EXEC &&
1132  list_member_int(param_ids, p->paramid))
1133  return true;
1134  }
1135  return expression_tree_walker(node, contain_exec_param_walker, param_ids);
1136 }
bool list_member_int(const List *list, int datum)
Definition: list.c:702
@ PARAM_EXEC
Definition: primnodes.h:354
int paramid
Definition: primnodes.h:363
ParamKind paramkind
Definition: primnodes.h:362

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

1244 {
1245  return contain_leaked_vars_walker(clause, NULL);
1246 }
static bool contain_leaked_vars_walker(Node *node, void *context)
Definition: clauses.c:1255

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

1250 {
1251  return !get_func_leakproof(func_id);
1252 }
bool get_func_leakproof(Oid funcid)
Definition: lsyscache.c:1815

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

1256 {
1257  if (node == NULL)
1258  return false;
1259 
1260  switch (nodeTag(node))
1261  {
1262  case T_Var:
1263  case T_Const:
1264  case T_Param:
1265  case T_ArrayExpr:
1266  case T_FieldSelect:
1267  case T_FieldStore:
1268  case T_NamedArgExpr:
1269  case T_BoolExpr:
1270  case T_RelabelType:
1271  case T_CollateExpr:
1272  case T_CaseExpr:
1273  case T_CaseTestExpr:
1274  case T_RowExpr:
1275  case T_SQLValueFunction:
1276  case T_NullTest:
1277  case T_BooleanTest:
1278  case T_NextValueExpr:
1279  case T_List:
1280 
1281  /*
1282  * We know these node types don't contain function calls; but
1283  * something further down in the node tree might.
1284  */
1285  break;
1286 
1287  case T_FuncExpr:
1288  case T_OpExpr:
1289  case T_DistinctExpr:
1290  case T_NullIfExpr:
1291  case T_ScalarArrayOpExpr:
1292  case T_CoerceViaIO:
1293  case T_ArrayCoerceExpr:
1294 
1295  /*
1296  * If node contains a leaky function call, and there's any Var
1297  * underneath it, reject.
1298  */
1300  context) &&
1301  contain_var_clause(node))
1302  return true;
1303  break;
1304 
1305  case T_SubscriptingRef:
1306  {
1307  SubscriptingRef *sbsref = (SubscriptingRef *) node;
1308  const SubscriptRoutines *sbsroutines;
1309 
1310  /* Consult the subscripting support method info */
1311  sbsroutines = getSubscriptingRoutines(sbsref->refcontainertype,
1312  NULL);
1313  if (!sbsroutines ||
1314  !(sbsref->refassgnexpr != NULL ?
1315  sbsroutines->store_leakproof :
1316  sbsroutines->fetch_leakproof))
1317  {
1318  /* Node is leaky, so reject if it contains Vars */
1319  if (contain_var_clause(node))
1320  return true;
1321  }
1322  }
1323  break;
1324 
1325  case T_RowCompareExpr:
1326  {
1327  /*
1328  * It's worth special-casing this because a leaky comparison
1329  * function only compromises one pair of row elements, which
1330  * might not contain Vars while others do.
1331  */
1332  RowCompareExpr *rcexpr = (RowCompareExpr *) node;
1333  ListCell *opid;
1334  ListCell *larg;
1335  ListCell *rarg;
1336 
1337  forthree(opid, rcexpr->opnos,
1338  larg, rcexpr->largs,
1339  rarg, rcexpr->rargs)
1340  {
1341  Oid funcid = get_opcode(lfirst_oid(opid));
1342 
1343  if (!get_func_leakproof(funcid) &&
1344  (contain_var_clause((Node *) lfirst(larg)) ||
1345  contain_var_clause((Node *) lfirst(rarg))))
1346  return true;
1347  }
1348  }
1349  break;
1350 
1351  case T_MinMaxExpr:
1352  {
1353  /*
1354  * MinMaxExpr is leakproof if the comparison function it calls
1355  * is leakproof.
1356  */
1357  MinMaxExpr *minmaxexpr = (MinMaxExpr *) node;
1358  TypeCacheEntry *typentry;
1359  bool leakproof;
1360 
1361  /* Look up the btree comparison function for the datatype */
1362  typentry = lookup_type_cache(minmaxexpr->minmaxtype,
1364  if (OidIsValid(typentry->cmp_proc))
1365  leakproof = get_func_leakproof(typentry->cmp_proc);
1366  else
1367  {
1368  /*
1369  * The executor will throw an error, but here we just
1370  * treat the missing function as leaky.
1371  */
1372  leakproof = false;
1373  }
1374 
1375  if (!leakproof &&
1376  contain_var_clause((Node *) minmaxexpr->args))
1377  return true;
1378  }
1379  break;
1380 
1381  case T_CurrentOfExpr:
1382 
1383  /*
1384  * WHERE CURRENT OF doesn't contain leaky function calls.
1385  * Moreover, it is essential that this is considered non-leaky,
1386  * since the planner must always generate a TID scan when CURRENT
1387  * OF is present -- cf. cost_tidscan.
1388  */
1389  return false;
1390 
1391  default:
1392 
1393  /*
1394  * If we don't recognize the node tag, assume it might be leaky.
1395  * This prevents an unexpected security hole if someone adds a new
1396  * node type that can call a function.
1397  */
1398  return true;
1399  }
1401  context);
1402 }
static bool contain_leaked_vars_checker(Oid func_id, void *context)
Definition: clauses.c:1249
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1263
const struct SubscriptRoutines * getSubscriptingRoutines(Oid typid, Oid *typelemp)
Definition: lsyscache.c:3086
bool check_functions_in_node(Node *node, check_function_callback checker, void *context)
Definition: nodeFuncs.c:1828
#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:563
#define lfirst_oid(lc)
Definition: pg_list.h:174
List * args
Definition: primnodes.h:1474
Expr * refassgnexpr
Definition: primnodes.h:659
TypeCacheEntry * lookup_type_cache(Oid type_id, int flags)
Definition: typcache.c:346
#define TYPECACHE_CMP_PROC
Definition: typcache.h:140
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_after_planning()

bool contain_mutable_functions_after_planning ( Expr expr)

Definition at line 470 of file clauses.c.

471 {
472  /* We assume here that expression_planner() won't scribble on its input */
473  expr = expression_planner(expr);
474 
475  /* Now we can search for non-immutable functions */
476  return contain_mutable_functions((Node *) expr);
477 }
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:369
Expr * expression_planner(Expr *expr)
Definition: planner.c:6400

References contain_mutable_functions(), and expression_planner().

Referenced by CheckPredicate(), ComputeIndexAttrs(), and cookDefault().

◆ contain_mutable_functions_checker()

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

Definition at line 375 of file clauses.c.

376 {
377  return (func_volatile(func_id) != PROVOLATILE_IMMUTABLE);
378 }
char func_volatile(Oid funcid)
Definition: lsyscache.c:1758

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

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

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

3704 {
3705  if (node == NULL)
3706  return false;
3707  if (IsA(node, Const))
3708  return false;
3709  if (IsA(node, List))
3710  return expression_tree_walker(node, contain_non_const_walker, context);
3711  /* Otherwise, abort the tree traversal and return true */
3712  return true;
3713 }
static bool contain_non_const_walker(Node *node, void *context)
Definition: clauses.c:3703

References expression_tree_walker, and IsA.

◆ contain_nonstrict_functions()

bool contain_nonstrict_functions ( Node clause)

Definition at line 973 of file clauses.c.

974 {
975  return contain_nonstrict_functions_walker(clause, NULL);
976 }
static bool contain_nonstrict_functions_walker(Node *node, void *context)
Definition: clauses.c:985

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

980 {
981  return !func_strict(func_id);
982 }
bool func_strict(Oid funcid)
Definition: lsyscache.c:1739

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

986 {
987  if (node == NULL)
988  return false;
989  if (IsA(node, Aggref))
990  {
991  /* an aggregate could return non-null with null input */
992  return true;
993  }
994  if (IsA(node, GroupingFunc))
995  {
996  /*
997  * A GroupingFunc doesn't evaluate its arguments, and therefore must
998  * be treated as nonstrict.
999  */
1000  return true;
1001  }
1002  if (IsA(node, WindowFunc))
1003  {
1004  /* a window function could return non-null with null input */
1005  return true;
1006  }
1007  if (IsA(node, SubscriptingRef))
1008  {
1009  SubscriptingRef *sbsref = (SubscriptingRef *) node;
1010  const SubscriptRoutines *sbsroutines;
1011 
1012  /* Subscripting assignment is always presumed nonstrict */
1013  if (sbsref->refassgnexpr != NULL)
1014  return true;
1015  /* Otherwise we must look up the subscripting support methods */
1016  sbsroutines = getSubscriptingRoutines(sbsref->refcontainertype, NULL);
1017  if (!(sbsroutines && sbsroutines->fetch_strict))
1018  return true;
1019  /* else fall through to check args */
1020  }
1021  if (IsA(node, DistinctExpr))
1022  {
1023  /* IS DISTINCT FROM is inherently non-strict */
1024  return true;
1025  }
1026  if (IsA(node, NullIfExpr))
1027  {
1028  /* NULLIF is inherently non-strict */
1029  return true;
1030  }
1031  if (IsA(node, BoolExpr))
1032  {
1033  BoolExpr *expr = (BoolExpr *) node;
1034 
1035  switch (expr->boolop)
1036  {
1037  case AND_EXPR:
1038  case OR_EXPR:
1039  /* AND, OR are inherently non-strict */
1040  return true;
1041  default:
1042  break;
1043  }
1044  }
1045  if (IsA(node, SubLink))
1046  {
1047  /* In some cases a sublink might be strict, but in general not */
1048  return true;
1049  }
1050  if (IsA(node, SubPlan))
1051  return true;
1052  if (IsA(node, AlternativeSubPlan))
1053  return true;
1054  if (IsA(node, FieldStore))
1055  return true;
1056  if (IsA(node, CoerceViaIO))
1057  {
1058  /*
1059  * CoerceViaIO is strict regardless of whether the I/O functions are,
1060  * so just go look at its argument; asking check_functions_in_node is
1061  * useless expense and could deliver the wrong answer.
1062  */
1063  return contain_nonstrict_functions_walker((Node *) ((CoerceViaIO *) node)->arg,
1064  context);
1065  }
1066  if (IsA(node, ArrayCoerceExpr))
1067  {
1068  /*
1069  * ArrayCoerceExpr is strict at the array level, regardless of what
1070  * the per-element expression is; so we should ignore elemexpr and
1071  * recurse only into the arg.
1072  */
1074  context);
1075  }
1076  if (IsA(node, CaseExpr))
1077  return true;
1078  if (IsA(node, ArrayExpr))
1079  return true;
1080  if (IsA(node, RowExpr))
1081  return true;
1082  if (IsA(node, RowCompareExpr))
1083  return true;
1084  if (IsA(node, CoalesceExpr))
1085  return true;
1086  if (IsA(node, MinMaxExpr))
1087  return true;
1088  if (IsA(node, XmlExpr))
1089  return true;
1090  if (IsA(node, NullTest))
1091  return true;
1092  if (IsA(node, BooleanTest))
1093  return true;
1094 
1095  /* Check other function-containing nodes */
1097  context))
1098  return true;
1099 
1101  context);
1102 }
static bool contain_nonstrict_functions_checker(Oid func_id, void *context)
Definition: clauses.c:979
void * arg
@ AND_EXPR
Definition: primnodes.h:887
@ OR_EXPR
Definition: primnodes.h:887
BoolExprType boolop
Definition: primnodes.h:895

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)

◆ contain_subplans_walker()

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

Definition at line 335 of file clauses.c.

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

References expression_tree_walker, and IsA.

Referenced by contain_subplans().

◆ contain_volatile_functions()

◆ contain_volatile_functions_after_planning()

bool contain_volatile_functions_after_planning ( Expr expr)

Definition at line 639 of file clauses.c.

640 {
641  /* We assume here that expression_planner() won't scribble on its input */
642  expr = expression_planner(expr);
643 
644  /* Now we can search for volatile functions */
645  return contain_volatile_functions((Node *) expr);
646 }
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:518

References contain_volatile_functions(), and expression_planner().

Referenced by AddRelationNewConstraints().

◆ contain_volatile_functions_checker()

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

Definition at line 524 of file clauses.c.

525 {
526  return (func_volatile(func_id) == PROVOLATILE_VOLATILE);
527 }

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

654 {
656 }
static bool contain_volatile_functions_not_nextval_walker(Node *node, void *context)
Definition: clauses.c:666

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

660 {
661  return (func_id != F_NEXTVAL &&
662  func_volatile(func_id) == PROVOLATILE_VOLATILE);
663 }

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

667 {
668  if (node == NULL)
669  return false;
670  /* Check for volatile functions in node itself */
671  if (check_functions_in_node(node,
673  context))
674  return true;
675 
676  /*
677  * See notes in contain_mutable_functions_walker about why we treat
678  * MinMaxExpr, XmlExpr, and CoerceToDomain as immutable, while
679  * SQLValueFunction is stable. Hence, none of them are of interest here.
680  * Also, since we're intentionally ignoring nextval(), presumably we
681  * should ignore NextValueExpr.
682  */
683 
684  /* Recurse to check arguments */
685  if (IsA(node, Query))
686  {
687  /* Recurse into subselects */
688  return query_tree_walker((Query *) node,
690  context, 0);
691  }
692  return expression_tree_walker(node,
694  context);
695 }
static bool contain_volatile_functions_not_nextval_checker(Oid func_id, void *context)
Definition: clauses.c:659

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

531 {
532  if (node == NULL)
533  return false;
534  /* Check for volatile functions in node itself */
536  context))
537  return true;
538 
539  if (IsA(node, NextValueExpr))
540  {
541  /* NextValueExpr is volatile */
542  return true;
543  }
544 
545  if (IsA(node, RestrictInfo))
546  {
547  RestrictInfo *rinfo = (RestrictInfo *) node;
548 
549  /*
550  * For RestrictInfo, check if we've checked the volatility of it
551  * before. If so, we can just use the cached value and not bother
552  * checking it again. Otherwise, check it and cache if whether we
553  * found any volatile functions.
554  */
555  if (rinfo->has_volatile == VOLATILITY_NOVOLATILE)
556  return false;
557  else if (rinfo->has_volatile == VOLATILITY_VOLATILE)
558  return true;
559  else
560  {
561  bool hasvolatile;
562 
563  hasvolatile = contain_volatile_functions_walker((Node *) rinfo->clause,
564  context);
565  if (hasvolatile)
566  rinfo->has_volatile = VOLATILITY_VOLATILE;
567  else
568  rinfo->has_volatile = VOLATILITY_NOVOLATILE;
569 
570  return hasvolatile;
571  }
572  }
573 
574  if (IsA(node, PathTarget))
575  {
576  PathTarget *target = (PathTarget *) node;
577 
578  /*
579  * We also do caching for PathTarget the same as we do above for
580  * RestrictInfos.
581  */
583  return false;
584  else if (target->has_volatile_expr == VOLATILITY_VOLATILE)
585  return true;
586  else
587  {
588  bool hasvolatile;
589 
590  hasvolatile = contain_volatile_functions_walker((Node *) target->exprs,
591  context);
592 
593  if (hasvolatile)
595  else
597 
598  return hasvolatile;
599  }
600  }
601 
602  /*
603  * See notes in contain_mutable_functions_walker about why we treat
604  * MinMaxExpr, XmlExpr, and CoerceToDomain as immutable, while
605  * SQLValueFunction is stable. Hence, none of them are of interest here.
606  */
607 
608  /* Recurse to check arguments */
609  if (IsA(node, Query))
610  {
611  /* Recurse into subselects */
612  return query_tree_walker((Query *) node,
614  context, 0);
615  }
617  context);
618 }
static bool contain_volatile_functions_checker(Oid func_id, void *context)
Definition: clauses.c:524
@ VOLATILITY_NOVOLATILE
Definition: pathnodes.h:1480
@ VOLATILITY_VOLATILE
Definition: pathnodes.h:1479
VolatileFunctionStatus has_volatile_expr
Definition: pathnodes.h:1525
List * exprs
Definition: pathnodes.h:1513
Expr * clause
Definition: pathnodes.h:2541

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

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

2268 {
2269  (void) convert_saop_to_hashed_saop_walker(node, NULL);
2270 }
static bool convert_saop_to_hashed_saop_walker(Node *node, void *context)
Definition: clauses.c:2273

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

2274 {
2275  if (node == NULL)
2276  return false;
2277 
2278  if (IsA(node, ScalarArrayOpExpr))
2279  {
2280  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
2281  Expr *arrayarg = (Expr *) lsecond(saop->args);
2282  Oid lefthashfunc;
2283  Oid righthashfunc;
2284 
2285  if (arrayarg && IsA(arrayarg, Const) &&
2286  !((Const *) arrayarg)->constisnull)
2287  {
2288  if (saop->useOr)
2289  {
2290  if (get_op_hash_functions(saop->opno, &lefthashfunc, &righthashfunc) &&
2291  lefthashfunc == righthashfunc)
2292  {
2293  Datum arrdatum = ((Const *) arrayarg)->constvalue;
2294  ArrayType *arr = (ArrayType *) DatumGetPointer(arrdatum);
2295  int nitems;
2296 
2297  /*
2298  * Only fill in the hash functions if the array looks
2299  * large enough for it to be worth hashing instead of
2300  * doing a linear search.
2301  */
2302  nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr));
2303 
2305  {
2306  /* Looks good. Fill in the hash functions */
2307  saop->hashfuncid = lefthashfunc;
2308  }
2309  return true;
2310  }
2311  }
2312  else /* !saop->useOr */
2313  {
2314  Oid negator = get_negator(saop->opno);
2315 
2316  /*
2317  * Check if this is a NOT IN using an operator whose negator
2318  * is hashable. If so we can still build a hash table and
2319  * just ensure the lookup items are not in the hash table.
2320  */
2321  if (OidIsValid(negator) &&
2322  get_op_hash_functions(negator, &lefthashfunc, &righthashfunc) &&
2323  lefthashfunc == righthashfunc)
2324  {
2325  Datum arrdatum = ((Const *) arrayarg)->constvalue;
2326  ArrayType *arr = (ArrayType *) DatumGetPointer(arrdatum);
2327  int nitems;
2328 
2329  /*
2330  * Only fill in the hash functions if the array looks
2331  * large enough for it to be worth hashing instead of
2332  * doing a linear search.
2333  */
2334  nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr));
2335 
2337  {
2338  /* Looks good. Fill in the hash functions */
2339  saop->hashfuncid = lefthashfunc;
2340 
2341  /*
2342  * Also set the negfuncid. The executor will need
2343  * that to perform hashtable lookups.
2344  */
2345  saop->negfuncid = get_opcode(negator);
2346  }
2347  return true;
2348  }
2349  }
2350  }
2351  }
2352 
2354 }
#define ARR_NDIM(a)
Definition: array.h:290
#define ARR_DIMS(a)
Definition: array.h:294
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:57
#define MIN_ARRAY_SIZE_FOR_HASHED_SAOP
Definition: clauses.c:2249
#define nitems(x)
Definition: indent.h:31
bool get_op_hash_functions(Oid opno, RegProcedure *lhs_procno, RegProcedure *rhs_procno)
Definition: lsyscache.c:510
Oid get_negator(Oid opno)
Definition: lsyscache.c:1511
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 3719 of file clauses.c.

3720 {
3721  char provolatile = func_volatile(funcid);
3722 
3723  /*
3724  * Ordinarily we are only allowed to simplify immutable functions. But for
3725  * purposes of estimation, we consider it okay to simplify functions that
3726  * are merely stable; the risk that the result might change from planning
3727  * time to execution time is worth taking in preference to not being able
3728  * to estimate the value at all.
3729  */
3730  if (provolatile == PROVOLATILE_IMMUTABLE)
3731  return true;
3732  if (context->estimate && provolatile == PROVOLATILE_STABLE)
3733  return true;
3734  return false;
3735 }

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

2376 {
2378 
2379  context.boundParams = root->glob->boundParams; /* bound Params */
2380  /* we do not need to mark the plan as depending on inlined functions */
2381  context.root = NULL;
2382  context.active_fns = NIL; /* nothing being recursively simplified */
2383  context.case_val = NULL; /* no CASE being examined */
2384  context.estimate = true; /* unsafe transformations OK */
2385  return eval_const_expressions_mutator(node, &context);
2386 }
#define NIL
Definition: pg_list.h:68
PlannerGlobal * glob
Definition: pathnodes.h:202
ParamListInfo boundParams
Definition: clauses.c:60

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

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

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, check_stack_depth(), 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, 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 4941 of file clauses.c.

4943 {
4944  EState *estate;
4945  ExprState *exprstate;
4946  MemoryContext oldcontext;
4947  Datum const_val;
4948  bool const_is_null;
4949  int16 resultTypLen;
4950  bool resultTypByVal;
4951 
4952  /*
4953  * To use the executor, we need an EState.
4954  */
4955  estate = CreateExecutorState();
4956 
4957  /* We can use the estate's working context to avoid memory leaks. */
4958  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
4959 
4960  /* Make sure any opfuncids are filled in. */
4961  fix_opfuncids((Node *) expr);
4962 
4963  /*
4964  * Prepare expr for execution. (Note: we can't use ExecPrepareExpr
4965  * because it'd result in recursively invoking eval_const_expressions.)
4966  */
4967  exprstate = ExecInitExpr(expr, NULL);
4968 
4969  /*
4970  * And evaluate it.
4971  *
4972  * It is OK to use a default econtext because none of the ExecEvalExpr()
4973  * code used in this situation will use econtext. That might seem
4974  * fortuitous, but it's not so unreasonable --- a constant expression does
4975  * not depend on context, by definition, n'est ce pas?
4976  */
4977  const_val = ExecEvalExprSwitchContext(exprstate,
4978  GetPerTupleExprContext(estate),
4979  &const_is_null);
4980 
4981  /* Get info needed about result datatype */
4982  get_typlenbyval(result_type, &resultTypLen, &resultTypByVal);
4983 
4984  /* Get back to outer memory context */
4985  MemoryContextSwitchTo(oldcontext);
4986 
4987  /*
4988  * Must copy result out of sub-context used by expression eval.
4989  *
4990  * Also, if it's varlena, forcibly detoast it. This protects us against
4991  * storing TOAST pointers into plans that might outlive the referenced
4992  * data. (makeConst would handle detoasting anyway, but it's worth a few
4993  * extra lines here so that we can do the copy and detoast in one step.)
4994  */
4995  if (!const_is_null)
4996  {
4997  if (resultTypLen == -1)
4998  const_val = PointerGetDatum(PG_DETOAST_DATUM_COPY(const_val));
4999  else
5000  const_val = datumCopy(const_val, resultTypByVal, resultTypLen);
5001  }
5002 
5003  /* Release all the junk we just created */
5004  FreeExecutorState(estate);
5005 
5006  /*
5007  * Make the constant result node.
5008  */
5009  return (Expr *) makeConst(result_type, result_typmod, result_collation,
5010  resultTypLen,
5011  const_val, const_is_null,
5012  resultTypByVal);
5013 }
ExprState * ExecInitExpr(Expr *node, PlanState *parent)
Definition: execExpr.c:127
EState * CreateExecutorState(void)
Definition: execUtils.c:88
void FreeExecutorState(EState *estate)
Definition: execUtils.c:189
#define GetPerTupleExprContext(estate)
Definition: executor.h:550
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:348
#define PG_DETOAST_DATUM_COPY(datum)
Definition: fmgr.h:242
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1759
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:322
MemoryContext es_query_cxt
Definition: execnodes.h:665

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

4397 {
4398  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4399  bool has_nonconst_input = false;
4400  bool has_null_input = false;
4401  ListCell *arg;
4402  FuncExpr *newexpr;
4403 
4404  /*
4405  * Can't simplify if it returns a set.
4406  */
4407  if (funcform->proretset)
4408  return NULL;
4409 
4410  /*
4411  * Can't simplify if it returns RECORD. The immediate problem is that it
4412  * will be needing an expected tupdesc which we can't supply here.
4413  *
4414  * In the case where it has OUT parameters, it could get by without an
4415  * expected tupdesc, but we still have issues: get_expr_result_type()
4416  * doesn't know how to extract type info from a RECORD constant, and in
4417  * the case of a NULL function result there doesn't seem to be any clean
4418  * way to fix that. In view of the likelihood of there being still other
4419  * gotchas, seems best to leave the function call unreduced.
4420  */
4421  if (funcform->prorettype == RECORDOID)
4422  return NULL;
4423 
4424  /*
4425  * Check for constant inputs and especially constant-NULL inputs.
4426  */
4427  foreach(arg, args)
4428  {
4429  if (IsA(lfirst(arg), Const))
4430  has_null_input |= ((Const *) lfirst(arg))->constisnull;
4431  else
4432  has_nonconst_input = true;
4433  }
4434 
4435  /*
4436  * If the function is strict and has a constant-NULL input, it will never
4437  * be called at all, so we can replace the call by a NULL constant, even
4438  * if there are other inputs that aren't constant, and even if the
4439  * function is not otherwise immutable.
4440  */
4441  if (funcform->proisstrict && has_null_input)
4442  return (Expr *) makeNullConst(result_type, result_typmod,
4443  result_collid);
4444 
4445  /*
4446  * Otherwise, can simplify only if all inputs are constants. (For a
4447  * non-strict function, constant NULL inputs are treated the same as
4448  * constant non-NULL inputs.)
4449  */
4450  if (has_nonconst_input)
4451  return NULL;
4452 
4453  /*
4454  * Ordinarily we are only allowed to simplify immutable functions. But for
4455  * purposes of estimation, we consider it okay to simplify functions that
4456  * are merely stable; the risk that the result might change from planning
4457  * time to execution time is worth taking in preference to not being able
4458  * to estimate the value at all.
4459  */
4460  if (funcform->provolatile == PROVOLATILE_IMMUTABLE)
4461  /* okay */ ;
4462  else if (context->estimate && funcform->provolatile == PROVOLATILE_STABLE)
4463  /* okay */ ;
4464  else
4465  return NULL;
4466 
4467  /*
4468  * OK, looks like we can simplify this operator/function.
4469  *
4470  * Build a new FuncExpr node containing the already-simplified arguments.
4471  */
4472  newexpr = makeNode(FuncExpr);
4473  newexpr->funcid = funcid;
4474  newexpr->funcresulttype = result_type;
4475  newexpr->funcretset = false;
4476  newexpr->funcvariadic = funcvariadic;
4477  newexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
4478  newexpr->funccollid = result_collid; /* doesn't matter */
4479  newexpr->inputcollid = input_collid;
4480  newexpr->args = args;
4481  newexpr->location = -1;
4482 
4483  return evaluate_expr((Expr *) newexpr, result_type, result_typmod,
4484  result_collid);
4485 }
#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:690

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

4144 {
4145  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4146  Oid *proargtypes = funcform->proargtypes.values;
4147  int pronargs = funcform->pronargs;
4148  bool has_named_args = false;
4149  ListCell *lc;
4150 
4151  /*
4152  * If we are asked to match to OUT arguments, then use the proallargtypes
4153  * array (which includes those); otherwise use proargtypes (which
4154  * doesn't). Of course, if proallargtypes is null, we always use
4155  * proargtypes. (Fetching proallargtypes is annoyingly expensive
4156  * considering that we may have nothing to do here, but fortunately the
4157  * common case is include_out_arguments == false.)
4158  */
4159  if (include_out_arguments)
4160  {
4161  Datum proallargtypes;
4162  bool isNull;
4163 
4164  proallargtypes = SysCacheGetAttr(PROCOID, func_tuple,
4165  Anum_pg_proc_proallargtypes,
4166  &isNull);
4167  if (!isNull)
4168  {
4169  ArrayType *arr = DatumGetArrayTypeP(proallargtypes);
4170 
4171  pronargs = ARR_DIMS(arr)[0];
4172  if (ARR_NDIM(arr) != 1 ||
4173  pronargs < 0 ||
4174  ARR_HASNULL(arr) ||
4175  ARR_ELEMTYPE(arr) != OIDOID)
4176  elog(ERROR, "proallargtypes is not a 1-D Oid array or it contains nulls");
4177  Assert(pronargs >= funcform->pronargs);
4178  proargtypes = (Oid *) ARR_DATA_PTR(arr);
4179  }
4180  }
4181 
4182  /* Do we have any named arguments? */
4183  foreach(lc, args)
4184  {
4185  Node *arg = (Node *) lfirst(lc);
4186 
4187  if (IsA(arg, NamedArgExpr))
4188  {
4189  has_named_args = true;
4190  break;
4191  }
4192  }
4193 
4194  /* If so, we must apply reorder_function_arguments */
4195  if (has_named_args)
4196  {
4197  args = reorder_function_arguments(args, pronargs, func_tuple);
4198  /* Recheck argument types and add casts if needed */
4199  recheck_cast_function_args(args, result_type,
4200  proargtypes, pronargs,
4201  func_tuple);
4202  }
4203  else if (list_length(args) < pronargs)
4204  {
4205  /* No named args, but we seem to be short some defaults */
4206  args = add_function_defaults(args, pronargs, func_tuple);
4207  /* Recheck argument types and add casts if needed */
4208  recheck_cast_function_args(args, result_type,
4209  proargtypes, pronargs,
4210  func_tuple);
4211  }
4212 
4213  return args;
4214 }
#define ARR_DATA_PTR(a)
Definition: array.h:322
#define DatumGetArrayTypeP(X)
Definition: array.h:261
#define ARR_ELEMTYPE(a)
Definition: array.h:292
#define ARR_HASNULL(a)
Definition: array.h:291
static List * add_function_defaults(List *args, int pronargs, HeapTuple func_tuple)
Definition: clauses.c:4293
static List * reorder_function_arguments(List *args, int pronargs, HeapTuple func_tuple)
Definition: clauses.c:4223
static void recheck_cast_function_args(List *args, Oid result_type, Oid *proargtypes, int pronargs, HeapTuple func_tuple)
Definition: clauses.c:4347
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:479

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(), 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 288 of file clauses.c.

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

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

4318 {
4319  List *defaults;
4320  Datum proargdefaults;
4321  char *str;
4322 
4323  proargdefaults = SysCacheGetAttrNotNull(PROCOID, func_tuple,
4324  Anum_pg_proc_proargdefaults);
4325  str = TextDatumGetCString(proargdefaults);
4326  defaults = castNode(List, stringToNode(str));
4327  pfree(str);
4328  return defaults;
4329 }
#define TextDatumGetCString(d)
Definition: builtins.h:98
void pfree(void *pointer)
Definition: mcxt.c:1508
void * stringToNode(const char *str)
Definition: read.c:90
Datum SysCacheGetAttrNotNull(int cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition: syscache.c:510

References castNode, pfree(), 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 1957 of file clauses.c.

1958 {
1959  if (node == NULL)
1960  return NULL;
1961  if (IsA(node, NullTest))
1962  {
1963  /* check for var IS NULL */
1964  NullTest *expr = (NullTest *) node;
1965 
1966  if (expr->nulltesttype == IS_NULL && !expr->argisrow)
1967  {
1968  Var *var = (Var *) expr->arg;
1969 
1970  if (var && IsA(var, Var) &&
1971  var->varlevelsup == 0)
1972  return var;
1973  }
1974  }
1975  else if (IsA(node, BooleanTest))
1976  {
1977  /* var IS UNKNOWN is equivalent to var IS NULL */
1978  BooleanTest *expr = (BooleanTest *) node;
1979 
1980  if (expr->booltesttype == IS_UNKNOWN)
1981  {
1982  Var *var = (Var *) expr->arg;
1983 
1984  if (var && IsA(var, Var) &&
1985  var->varlevelsup == 0)
1986  return var;
1987  }
1988  }
1989  return NULL;
1990 }
Index varlevelsup
Definition: primnodes.h:266

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

1897 {
1898  List *result = NIL;
1899  Var *var;
1900  ListCell *l;
1901 
1902  if (node == NULL)
1903  return NIL;
1904  /* Check single-clause cases using subroutine */
1905  var = find_forced_null_var(node);
1906  if (var)
1907  {
1908  result = mbms_add_member(result,
1909  var->varno,
1911  }
1912  /* Otherwise, handle AND-conditions */
1913  else if (IsA(node, List))
1914  {
1915  /*
1916  * At top level, we are examining an implicit-AND list: if any of the
1917  * arms produces FALSE-or-NULL then the result is FALSE-or-NULL.
1918  */
1919  foreach(l, (List *) node)
1920  {
1921  result = mbms_add_members(result,
1923  }
1924  }
1925  else if (IsA(node, BoolExpr))
1926  {
1927  BoolExpr *expr = (BoolExpr *) node;
1928 
1929  /*
1930  * We don't bother considering the OR case, because it's fairly
1931  * unlikely anyone would write "v1 IS NULL OR v1 IS NULL". Likewise,
1932  * the NOT case isn't worth expending code on.
1933  */
1934  if (expr->boolop == AND_EXPR)
1935  {
1936  /* At top level we can just recurse (to the List case) */
1937  result = find_forced_null_vars((Node *) expr->args);
1938  }
1939  }
1940  return result;
1941 }
Var * find_forced_null_var(Node *node)
Definition: clauses.c:1957
List * find_forced_null_vars(Node *node)
Definition: clauses.c:1896
List * mbms_add_member(List *a, int listidx, int bitidx)
List * mbms_add_members(List *a, const List *b)
AttrNumber varattno
Definition: primnodes.h:246
int varno
Definition: primnodes.h:241
#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 1436 of file clauses.c.

1437 {
1438  return find_nonnullable_rels_walker(clause, true);
1439 }
static Relids find_nonnullable_rels_walker(Node *node, bool top_level)
Definition: clauses.c:1442

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

1443 {
1444  Relids result = NULL;
1445  ListCell *l;
1446 
1447  if (node == NULL)
1448  return NULL;
1449  if (IsA(node, Var))
1450  {
1451  Var *var = (Var *) node;
1452 
1453  if (var->varlevelsup == 0)
1454  result = bms_make_singleton(var->varno);
1455  }
1456  else if (IsA(node, List))
1457  {
1458  /*
1459  * At top level, we are examining an implicit-AND list: if any of the
1460  * arms produces FALSE-or-NULL then the result is FALSE-or-NULL. If
1461  * not at top level, we are examining the arguments of a strict
1462  * function: if any of them produce NULL then the result of the
1463  * function must be NULL. So in both cases, the set of nonnullable
1464  * rels is the union of those found in the arms, and we pass down the
1465  * top_level flag unmodified.
1466  */
1467  foreach(l, (List *) node)
1468  {
1469  result = bms_join(result,
1471  top_level));
1472  }
1473  }
1474  else if (IsA(node, FuncExpr))
1475  {
1476  FuncExpr *expr = (FuncExpr *) node;
1477 
1478  if (func_strict(expr->funcid))
1479  result = find_nonnullable_rels_walker((Node *) expr->args, false);
1480  }
1481  else if (IsA(node, OpExpr))
1482  {
1483  OpExpr *expr = (OpExpr *) node;
1484 
1485  set_opfuncid(expr);
1486  if (func_strict(expr->opfuncid))
1487  result = find_nonnullable_rels_walker((Node *) expr->args, false);
1488  }
1489  else if (IsA(node, ScalarArrayOpExpr))
1490  {
1491  ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1492 
1493  if (is_strict_saop(expr, true))
1494  result = find_nonnullable_rels_walker((Node *) expr->args, false);
1495  }
1496  else if (IsA(node, BoolExpr))
1497  {
1498  BoolExpr *expr = (BoolExpr *) node;
1499 
1500  switch (expr->boolop)
1501  {
1502  case AND_EXPR:
1503  /* At top level we can just recurse (to the List case) */
1504  if (top_level)
1505  {
1506  result = find_nonnullable_rels_walker((Node *) expr->args,
1507  top_level);
1508  break;
1509  }
1510 
1511  /*
1512  * Below top level, even if one arm produces NULL, the result
1513  * could be FALSE (hence not NULL). However, if *all* the
1514  * arms produce NULL then the result is NULL, so we can take
1515  * the intersection of the sets of nonnullable rels, just as
1516  * for OR. Fall through to share code.
1517  */
1518  /* FALL THRU */
1519  case OR_EXPR:
1520 
1521  /*
1522  * OR is strict if all of its arms are, so we can take the
1523  * intersection of the sets of nonnullable rels for each arm.
1524  * This works for both values of top_level.
1525  */
1526  foreach(l, expr->args)
1527  {
1528  Relids subresult;
1529 
1530  subresult = find_nonnullable_rels_walker(lfirst(l),
1531  top_level);
1532  if (result == NULL) /* first subresult? */
1533  result = subresult;
1534  else
1535  result = bms_int_members(result, subresult);
1536 
1537  /*
1538  * If the intersection is empty, we can stop looking. This
1539  * also justifies the test for first-subresult above.
1540  */
1541  if (bms_is_empty(result))
1542  break;
1543  }
1544  break;
1545  case NOT_EXPR:
1546  /* NOT will return null if its arg is null */
1547  result = find_nonnullable_rels_walker((Node *) expr->args,
1548  false);
1549  break;
1550  default:
1551  elog(ERROR, "unrecognized boolop: %d", (int) expr->boolop);
1552  break;
1553  }
1554  }
1555  else if (IsA(node, RelabelType))
1556  {
1557  RelabelType *expr = (RelabelType *) node;
1558 
1559  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1560  }
1561  else if (IsA(node, CoerceViaIO))
1562  {
1563  /* not clear this is useful, but it can't hurt */
1564  CoerceViaIO *expr = (CoerceViaIO *) node;
1565 
1566  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1567  }
1568  else if (IsA(node, ArrayCoerceExpr))
1569  {
1570  /* ArrayCoerceExpr is strict at the array level; ignore elemexpr */
1571  ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
1572 
1573  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1574  }
1575  else if (IsA(node, ConvertRowtypeExpr))
1576  {
1577  /* not clear this is useful, but it can't hurt */
1578  ConvertRowtypeExpr *expr = (ConvertRowtypeExpr *) node;
1579 
1580  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1581  }
1582  else if (IsA(node, CollateExpr))
1583  {
1584  CollateExpr *expr = (CollateExpr *) node;
1585 
1586  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1587  }
1588  else if (IsA(node, NullTest))
1589  {
1590  /* IS NOT NULL can be considered strict, but only at top level */
1591  NullTest *expr = (NullTest *) node;
1592 
1593  if (top_level && expr->nulltesttype == IS_NOT_NULL && !expr->argisrow)
1594  result = find_nonnullable_rels_walker((Node *) expr->arg, false);
1595  }
1596  else if (IsA(node, BooleanTest))
1597  {
1598  /* Boolean tests that reject NULL are strict at top level */
1599  BooleanTest *expr = (BooleanTest *) node;
1600 
1601  if (top_level &&
1602  (expr->booltesttype == IS_TRUE ||
1603  expr->booltesttype == IS_FALSE ||
1604  expr->booltesttype == IS_NOT_UNKNOWN))
1605  result = find_nonnullable_rels_walker((Node *) expr->arg, false);
1606  }
1607  else if (IsA(node, SubPlan))
1608  {
1609  SubPlan *splan = (SubPlan *) node;
1610 
1611  /*
1612  * For some types of SubPlan, we can infer strictness from Vars in the
1613  * testexpr (the LHS of the original SubLink).
1614  *
1615  * For ANY_SUBLINK, if the subquery produces zero rows, the result is
1616  * always FALSE. If the subquery produces more than one row, the
1617  * per-row results of the testexpr are combined using OR semantics.
1618  * Hence ANY_SUBLINK can be strict only at top level, but there it's
1619  * as strict as the testexpr is.
1620  *
1621  * For ROWCOMPARE_SUBLINK, if the subquery produces zero rows, the
1622  * result is always NULL. Otherwise, the result is as strict as the
1623  * testexpr is. So we can check regardless of top_level.
1624  *
1625  * We can't prove anything for other sublink types (in particular,
1626  * note that ALL_SUBLINK will return TRUE if the subquery is empty).
1627  */
1628  if ((top_level && splan->subLinkType == ANY_SUBLINK) ||
1629  splan->subLinkType == ROWCOMPARE_SUBLINK)
1630  result = find_nonnullable_rels_walker(splan->testexpr, top_level);
1631  }
1632  else if (IsA(node, PlaceHolderVar))
1633  {
1634  PlaceHolderVar *phv = (PlaceHolderVar *) node;
1635 
1636  /*
1637  * If the contained expression forces any rels non-nullable, so does
1638  * the PHV.
1639  */
1640  result = find_nonnullable_rels_walker((Node *) phv->phexpr, top_level);
1641 
1642  /*
1643  * If the PHV's syntactic scope is exactly one rel, it will be forced
1644  * to be evaluated at that rel, and so it will behave like a Var of
1645  * that rel: if the rel's entire output goes to null, so will the PHV.
1646  * (If the syntactic scope is a join, we know that the PHV will go to
1647  * null if the whole join does; but that is AND semantics while we
1648  * need OR semantics for find_nonnullable_rels' result, so we can't do
1649  * anything with the knowledge.)
1650  */
1651  if (phv->phlevelsup == 0 &&
1652  bms_membership(phv->phrels) == BMS_SINGLETON)
1653  result = bms_add_members(result, phv->phrels);
1654  }
1655  return result;
1656 }
Bitmapset * bms_join(Bitmapset *a, Bitmapset *b)
Definition: bitmapset.c:1230
Bitmapset * bms_make_singleton(int x)
Definition: bitmapset.c:216
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:917
Bitmapset * bms_int_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:1109
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:781
#define bms_is_empty(a)
Definition: bitmapset.h:118
@ BMS_SINGLETON
Definition: bitmapset.h:72
static bool is_strict_saop(ScalarArrayOpExpr *expr, bool falseOK)
Definition: clauses.c:2006
@ ANY_SUBLINK
Definition: primnodes.h:955
@ ROWCOMPARE_SUBLINK
Definition: primnodes.h:956
static SPIPlanPtr splan
Definition: regress.c:269
Index phlevelsup
Definition: pathnodes.h:2774

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

1688 {
1689  return find_nonnullable_vars_walker(clause, true);
1690 }
static List * find_nonnullable_vars_walker(Node *node, bool top_level)
Definition: clauses.c:1693

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

1694 {
1695  List *result = NIL;
1696  ListCell *l;
1697 
1698  if (node == NULL)
1699  return NIL;
1700  if (IsA(node, Var))
1701  {
1702  Var *var = (Var *) node;
1703 
1704  if (var->varlevelsup == 0)
1705  result = mbms_add_member(result,
1706  var->varno,
1708  }
1709  else if (IsA(node, List))
1710  {
1711  /*
1712  * At top level, we are examining an implicit-AND list: if any of the
1713  * arms produces FALSE-or-NULL then the result is FALSE-or-NULL. If
1714  * not at top level, we are examining the arguments of a strict
1715  * function: if any of them produce NULL then the result of the
1716  * function must be NULL. So in both cases, the set of nonnullable
1717  * vars is the union of those found in the arms, and we pass down the
1718  * top_level flag unmodified.
1719  */
1720  foreach(l, (List *) node)
1721  {
1722  result = mbms_add_members(result,
1724  top_level));
1725  }
1726  }
1727  else if (IsA(node, FuncExpr))
1728  {
1729  FuncExpr *expr = (FuncExpr *) node;
1730 
1731  if (func_strict(expr->funcid))
1732  result = find_nonnullable_vars_walker((Node *) expr->args, false);
1733  }
1734  else if (IsA(node, OpExpr))
1735  {
1736  OpExpr *expr = (OpExpr *) node;
1737 
1738  set_opfuncid(expr);
1739  if (func_strict(expr->opfuncid))
1740  result = find_nonnullable_vars_walker((Node *) expr->args, false);
1741  }
1742  else if (IsA(node, ScalarArrayOpExpr))
1743  {
1744  ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1745 
1746  if (is_strict_saop(expr, true))
1747  result = find_nonnullable_vars_walker((Node *) expr->args, false);
1748  }
1749  else if (IsA(node, BoolExpr))
1750  {
1751  BoolExpr *expr = (BoolExpr *) node;
1752 
1753  switch (expr->boolop)
1754  {
1755  case AND_EXPR:
1756 
1757  /*
1758  * At top level we can just recurse (to the List case), since
1759  * the result should be the union of what we can prove in each
1760  * arm.
1761  */
1762  if (top_level)
1763  {
1764  result = find_nonnullable_vars_walker((Node *) expr->args,
1765  top_level);
1766  break;
1767  }
1768 
1769  /*
1770  * Below top level, even if one arm produces NULL, the result
1771  * could be FALSE (hence not NULL). However, if *all* the
1772  * arms produce NULL then the result is NULL, so we can take
1773  * the intersection of the sets of nonnullable vars, just as
1774  * for OR. Fall through to share code.
1775  */
1776  /* FALL THRU */
1777  case OR_EXPR:
1778 
1779  /*
1780  * OR is strict if all of its arms are, so we can take the
1781  * intersection of the sets of nonnullable vars for each arm.
1782  * This works for both values of top_level.
1783  */
1784  foreach(l, expr->args)
1785  {
1786  List *subresult;
1787 
1788  subresult = find_nonnullable_vars_walker(lfirst(l),
1789  top_level);
1790  if (result == NIL) /* first subresult? */
1791  result = subresult;
1792  else
1793  result = mbms_int_members(result, subresult);
1794 
1795  /*
1796  * If the intersection is empty, we can stop looking. This
1797  * also justifies the test for first-subresult above.
1798  */
1799  if (result == NIL)
1800  break;
1801  }
1802  break;
1803  case NOT_EXPR:
1804  /* NOT will return null if its arg is null */
1805  result = find_nonnullable_vars_walker((Node *) expr->args,
1806  false);
1807  break;
1808  default:
1809  elog(ERROR, "unrecognized boolop: %d", (int) expr->boolop);
1810  break;
1811  }
1812  }
1813  else if (IsA(node, RelabelType))
1814  {
1815  RelabelType *expr = (RelabelType *) node;
1816 
1817  result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1818  }
1819  else if (IsA(node, CoerceViaIO))
1820  {
1821  /* not clear this is useful, but it can't hurt */
1822  CoerceViaIO *expr = (CoerceViaIO *) node;
1823 
1824  result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1825  }
1826  else if (IsA(node, ArrayCoerceExpr))
1827  {
1828  /* ArrayCoerceExpr is strict at the array level; ignore elemexpr */
1829  ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
1830 
1831  result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1832  }
1833  else if (IsA(node, ConvertRowtypeExpr))
1834  {
1835  /* not clear this is useful, but it can't hurt */
1836  ConvertRowtypeExpr *expr = (ConvertRowtypeExpr *) node;
1837 
1838  result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1839  }
1840  else if (IsA(node, CollateExpr))
1841  {
1842  CollateExpr *expr = (CollateExpr *) node;
1843 
1844  result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1845  }
1846  else if (IsA(node, NullTest))
1847  {
1848  /* IS NOT NULL can be considered strict, but only at top level */
1849  NullTest *expr = (NullTest *) node;
1850 
1851  if (top_level && expr->nulltesttype == IS_NOT_NULL && !expr->argisrow)
1852  result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1853  }
1854  else if (IsA(node, BooleanTest))
1855  {
1856  /* Boolean tests that reject NULL are strict at top level */
1857  BooleanTest *expr = (BooleanTest *) node;
1858 
1859  if (top_level &&
1860  (expr->booltesttype == IS_TRUE ||
1861  expr->booltesttype == IS_FALSE ||
1862  expr->booltesttype == IS_NOT_UNKNOWN))
1863  result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1864  }
1865  else if (IsA(node, SubPlan))
1866  {
1867  SubPlan *splan = (SubPlan *) node;
1868 
1869  /* See analysis in find_nonnullable_rels_walker */
1870  if ((top_level && splan->subLinkType == ANY_SUBLINK) ||
1871  splan->subLinkType == ROWCOMPARE_SUBLINK)
1872  result = find_nonnullable_vars_walker(splan->testexpr, top_level);
1873  }
1874  else if (IsA(node, PlaceHolderVar))
1875  {
1876  PlaceHolderVar *phv = (PlaceHolderVar *) node;
1877 
1878  result = find_nonnullable_vars_walker((Node *) phv->phexpr, top_level);
1879  }
1880  return result;
1881 }
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 226 of file clauses.c.

227 {
228  WindowFuncLists *lists = palloc(sizeof(WindowFuncLists));
229 
230  lists->numWindowFuncs = 0;
231  lists->maxWinRef = maxWinRef;
232  lists->windowFuncs = (List **) palloc0((maxWinRef + 1) * sizeof(List *));
233  (void) find_window_functions_walker(clause, lists);
234  return lists;
235 }
static bool find_window_functions_walker(Node *node, WindowFuncLists *lists)
Definition: clauses.c:238
void * palloc0(Size size)
Definition: mcxt.c:1334
void * palloc(Size size)
Definition: mcxt.c:1304
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 238 of file clauses.c.

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

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

4524 {
4525  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4526  char *src;
4527  Datum tmp;
4528  bool isNull;
4529  MemoryContext oldcxt;
4530  MemoryContext mycxt;
4531  inline_error_callback_arg callback_arg;
4532  ErrorContextCallback sqlerrcontext;
4533  FuncExpr *fexpr;
4535  TupleDesc rettupdesc;
4536  ParseState *pstate;
4537  List *raw_parsetree_list;
4538  List *querytree_list;
4539  Query *querytree;
4540  Node *newexpr;
4541  int *usecounts;
4542  ListCell *arg;
4543  int i;
4544 
4545  /*
4546  * Forget it if the function is not SQL-language or has other showstopper
4547  * properties. (The prokind and nargs checks are just paranoia.)
4548  */
4549  if (funcform->prolang != SQLlanguageId ||
4550  funcform->prokind != PROKIND_FUNCTION ||
4551  funcform->prosecdef ||
4552  funcform->proretset ||
4553  funcform->prorettype == RECORDOID ||
4554  !heap_attisnull(func_tuple, Anum_pg_proc_proconfig, NULL) ||
4555  funcform->pronargs != list_length(args))
4556  return NULL;
4557 
4558  /* Check for recursive function, and give up trying to expand if so */
4559  if (list_member_oid(context->active_fns, funcid))
4560  return NULL;
4561 
4562  /* Check permission to call function (fail later, if not) */
4563  if (object_aclcheck(ProcedureRelationId, funcid, GetUserId(), ACL_EXECUTE) != ACLCHECK_OK)
4564  return NULL;
4565 
4566  /* Check whether a plugin wants to hook function entry/exit */
4567  if (FmgrHookIsNeeded(funcid))
4568  return NULL;
4569 
4570  /*
4571  * Make a temporary memory context, so that we don't leak all the stuff
4572  * that parsing might create.
4573  */
4575  "inline_function",
4577  oldcxt = MemoryContextSwitchTo(mycxt);
4578 
4579  /*
4580  * We need a dummy FuncExpr node containing the already-simplified
4581  * arguments. (In some cases we don't really need it, but building it is
4582  * cheap enough that it's not worth contortions to avoid.)
4583  */
4584  fexpr = makeNode(FuncExpr);
4585  fexpr->funcid = funcid;
4586  fexpr->funcresulttype = result_type;
4587  fexpr->funcretset = false;
4588  fexpr->funcvariadic = funcvariadic;
4589  fexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
4590  fexpr->funccollid = result_collid; /* doesn't matter */
4591  fexpr->inputcollid = input_collid;
4592  fexpr->args = args;
4593  fexpr->location = -1;
4594 
4595  /* Fetch the function body */
4596  tmp = SysCacheGetAttrNotNull(PROCOID, func_tuple, Anum_pg_proc_prosrc);
4597  src = TextDatumGetCString(tmp);
4598 
4599  /*
4600  * Setup error traceback support for ereport(). This is so that we can
4601  * finger the function that bad information came from.
4602  */
4603  callback_arg.proname = NameStr(funcform->proname);
4604  callback_arg.prosrc = src;
4605 
4606  sqlerrcontext.callback = sql_inline_error_callback;
4607  sqlerrcontext.arg = (void *) &callback_arg;
4608  sqlerrcontext.previous = error_context_stack;
4609  error_context_stack = &sqlerrcontext;
4610 
4611  /* If we have prosqlbody, pay attention to that not prosrc */
4612  tmp = SysCacheGetAttr(PROCOID,
4613  func_tuple,
4614  Anum_pg_proc_prosqlbody,
4615  &isNull);
4616  if (!isNull)
4617  {
4618  Node *n;
4619  List *query_list;
4620 
4622  if (IsA(n, List))
4623  query_list = linitial_node(List, castNode(List, n));
4624  else
4625  query_list = list_make1(n);
4626  if (list_length(query_list) != 1)
4627  goto fail;
4628  querytree = linitial(query_list);
4629 
4630  /*
4631  * Because we'll insist below that the querytree have an empty rtable
4632  * and no sublinks, it cannot have any relation references that need
4633  * to be locked or rewritten. So we can omit those steps.
4634  */
4635  }
4636  else
4637  {
4638  /* Set up to handle parameters while parsing the function body. */
4639  pinfo = prepare_sql_fn_parse_info(func_tuple,
4640  (Node *) fexpr,
4641  input_collid);
4642 
4643  /*
4644  * We just do parsing and parse analysis, not rewriting, because
4645  * rewriting will not affect table-free-SELECT-only queries, which is
4646  * all that we care about. Also, we can punt as soon as we detect
4647  * more than one command in the function body.
4648  */
4649  raw_parsetree_list = pg_parse_query(src);
4650  if (list_length(raw_parsetree_list) != 1)
4651  goto fail;
4652 
4653  pstate = make_parsestate(NULL);
4654  pstate->p_sourcetext = src;
4655  sql_fn_parser_setup(pstate, pinfo);
4656 
4657  querytree = transformTopLevelStmt(pstate, linitial(raw_parsetree_list));
4658 
4659  free_parsestate(pstate);
4660  }
4661 
4662  /*
4663  * The single command must be a simple "SELECT expression".
4664  *
4665  * Note: if you change the tests involved in this, see also plpgsql's
4666  * exec_simple_check_plan(). That generally needs to have the same idea
4667  * of what's a "simple expression", so that inlining a function that
4668  * previously wasn't inlined won't change plpgsql's conclusion.
4669  */
4670  if (!IsA(querytree, Query) ||
4671  querytree->commandType != CMD_SELECT ||
4672  querytree->hasAggs ||
4673  querytree->hasWindowFuncs ||
4674  querytree->hasTargetSRFs ||
4675  querytree->hasSubLinks ||
4676  querytree->cteList ||
4677  querytree->rtable ||
4678  querytree->jointree->fromlist ||
4679  querytree->jointree->quals ||
4680  querytree->groupClause ||
4681  querytree->groupingSets ||
4682  querytree->havingQual ||
4683  querytree->windowClause ||
4684  querytree->distinctClause ||
4685  querytree->sortClause ||
4686  querytree->limitOffset ||
4687  querytree->limitCount ||
4688  querytree->setOperations ||
4689  list_length(querytree->targetList) != 1)
4690  goto fail;
4691 
4692  /* If the function result is composite, resolve it */
4693  (void) get_expr_result_type((Node *) fexpr,
4694  NULL,
4695  &rettupdesc);
4696 
4697  /*
4698  * Make sure the function (still) returns what it's declared to. This
4699  * will raise an error if wrong, but that's okay since the function would
4700  * fail at runtime anyway. Note that check_sql_fn_retval will also insert
4701  * a coercion if needed to make the tlist expression match the declared
4702  * type of the function.
4703  *
4704  * Note: we do not try this until we have verified that no rewriting was
4705  * needed; that's probably not important, but let's be careful.
4706  */
4707  querytree_list = list_make1(querytree);
4708  if (check_sql_fn_retval(list_make1(querytree_list),
4709  result_type, rettupdesc,
4710  funcform->prokind,
4711  false, NULL))
4712  goto fail; /* reject whole-tuple-result cases */
4713 
4714  /*
4715  * Given the tests above, check_sql_fn_retval shouldn't have decided to
4716  * inject a projection step, but let's just make sure.
4717  */
4718  if (querytree != linitial(querytree_list))
4719  goto fail;
4720 
4721  /* Now we can grab the tlist expression */
4722  newexpr = (Node *) ((TargetEntry *) linitial(querytree->targetList))->expr;
4723 
4724  /*
4725  * If the SQL function returns VOID, we can only inline it if it is a
4726  * SELECT of an expression returning VOID (ie, it's just a redirection to
4727  * another VOID-returning function). In all non-VOID-returning cases,
4728  * check_sql_fn_retval should ensure that newexpr returns the function's
4729  * declared result type, so this test shouldn't fail otherwise; but we may
4730  * as well cope gracefully if it does.
4731  */
4732  if (exprType(newexpr) != result_type)
4733  goto fail;
4734 
4735  /*
4736  * Additional validity checks on the expression. It mustn't be more
4737  * volatile than the surrounding function (this is to avoid breaking hacks
4738  * that involve pretending a function is immutable when it really ain't).
4739  * If the surrounding function is declared strict, then the expression
4740  * must contain only strict constructs and must use all of the function
4741  * parameters (this is overkill, but an exact analysis is hard).
4742  */
4743  if (funcform->provolatile == PROVOLATILE_IMMUTABLE &&
4744  contain_mutable_functions(newexpr))
4745  goto fail;
4746  else if (funcform->provolatile == PROVOLATILE_STABLE &&
4747  contain_volatile_functions(newexpr))
4748  goto fail;
4749 
4750  if (funcform->proisstrict &&
4751  contain_nonstrict_functions(newexpr))
4752  goto fail;
4753 
4754  /*
4755  * If any parameter expression contains a context-dependent node, we can't
4756  * inline, for fear of putting such a node into the wrong context.
4757  */
4759  goto fail;
4760 
4761  /*
4762  * We may be able to do it; there are still checks on parameter usage to
4763  * make, but those are most easily done in combination with the actual
4764  * substitution of the inputs. So start building expression with inputs
4765  * substituted.
4766  */
4767  usecounts = (int *) palloc0(funcform->pronargs * sizeof(int));
4768  newexpr = substitute_actual_parameters(newexpr, funcform->pronargs,
4769  args, usecounts);
4770 
4771  /* Now check for parameter usage */
4772  i = 0;
4773  foreach(arg, args)
4774  {
4775  Node *param = lfirst(arg);
4776 
4777  if (usecounts[i] == 0)
4778  {
4779  /* Param not used at all: uncool if func is strict */
4780  if (funcform->proisstrict)
4781  goto fail;
4782  }
4783  else if (usecounts[i] != 1)
4784  {
4785  /* Param used multiple times: uncool if expensive or volatile */
4786  QualCost eval_cost;
4787 
4788  /*
4789  * We define "expensive" as "contains any subplan or more than 10
4790  * operators". Note that the subplan search has to be done
4791  * explicitly, since cost_qual_eval() will barf on unplanned
4792  * subselects.
4793  */
4794  if (contain_subplans(param))
4795  goto fail;
4796  cost_qual_eval(&eval_cost, list_make1(param), NULL);
4797  if (eval_cost.startup + eval_cost.per_tuple >
4798  10 * cpu_operator_cost)
4799  goto fail;
4800 
4801  /*
4802  * Check volatility last since this is more expensive than the
4803  * above tests
4804  */
4805  if (contain_volatile_functions(param))
4806  goto fail;
4807  }
4808  i++;
4809  }
4810 
4811  /*
4812  * Whew --- we can make the substitution. Copy the modified expression
4813  * out of the temporary memory context, and clean up.
4814  */
4815  MemoryContextSwitchTo(oldcxt);
4816 
4817  newexpr = copyObject(newexpr);
4818 
4819  MemoryContextDelete(mycxt);
4820 
4821  /*
4822  * If the result is of a collatable type, force the result to expose the
4823  * correct collation. In most cases this does not matter, but it's
4824  * possible that the function result is used directly as a sort key or in
4825  * other places where we expect exprCollation() to tell the truth.
4826  */
4827  if (OidIsValid(result_collid))
4828  {
4829  Oid exprcoll = exprCollation(newexpr);
4830 
4831  if (OidIsValid(exprcoll) && exprcoll != result_collid)
4832  {
4833  CollateExpr *newnode = makeNode(CollateExpr);
4834 
4835  newnode->arg = (Expr *) newexpr;
4836  newnode->collOid = result_collid;
4837  newnode->location = -1;
4838 
4839  newexpr = (Node *) newnode;
4840  }
4841  }
4842 
4843  /*
4844  * Since there is now no trace of the function in the plan tree, we must
4845  * explicitly record the plan's dependency on the function.
4846  */
4847  if (context->root)
4848  record_plan_function_dependency(context->root, funcid);
4849 
4850  /*
4851  * Recursively try to simplify the modified expression. Here we must add
4852  * the current function to the context list of active functions.
4853  */
4854  context->active_fns = lappend_oid(context->active_fns, funcid);
4855  newexpr = eval_const_expressions_mutator(newexpr, context);
4856  context->active_fns = list_delete_last(context->active_fns);
4857 
4858  error_context_stack = sqlerrcontext.previous;
4859 
4860  return (Expr *) newexpr;
4861 
4862  /* Here if func is not inlinable: release temp memory and return NULL */
4863 fail:
4864  MemoryContextSwitchTo(oldcxt);
4865  MemoryContextDelete(mycxt);
4866  error_context_stack = sqlerrcontext.previous;
4867 
4868  return NULL;
4869 }
Datum querytree(PG_FUNCTION_ARGS)
Definition: _int_bool.c:666
@ ACLCHECK_OK
Definition: acl.h:183
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition: aclchk.c:3876
#define NameStr(name)
Definition: c.h:733
static Node * substitute_actual_parameters(Node *expr, int nargs, List *args, int *usecounts)
Definition: clauses.c:4875
static void sql_inline_error_callback(void *arg)
Definition: clauses.c:4917
static bool contain_context_dependent_node(Node *clause)
Definition: clauses.c:1159
bool contain_nonstrict_functions(Node *clause)
Definition: clauses.c:973
bool contain_subplans(Node *clause)
Definition: clauses.c:329
double cpu_operator_cost
Definition: costsize.c:123
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:4640
ErrorContextCallback * error_context_stack
Definition: elog.c:94
#define FmgrHookIsNeeded(fn_oid)
Definition: fmgr.h:797
TypeFuncClass get_expr_result_type(Node *expr, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:292
void sql_fn_parser_setup(struct ParseState *pstate, SQLFunctionParseInfoPtr pinfo)
Definition: functions.c:265
bool check_sql_fn_retval(List *queryTreeLists, Oid rettype, TupleDesc rettupdesc, char prokind, bool insertDroppedCols, List **resultTargetList)
Definition: functions.c:1608
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:455
int i
Definition: isn.c:73
List * lappend_oid(List *list, Oid datum)
Definition: list.c:375
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:722
List * list_delete_last(List *list)
Definition: list.c:957
MemoryContext CurrentMemoryContext
Definition: mcxt.c:131
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:442
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:153
Oid GetUserId(void)
Definition: miscinit.c:514
@ CMD_SELECT
Definition: nodes.h:255
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:72
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:39
#define ACL_EXECUTE
Definition: parsenodes.h:83
Query * transformTopLevelStmt(ParseState *pstate, RawStmt *parseTree)
Definition: analyze.c:248
#define linitial_node(type, l)
Definition: pg_list.h:181
List * pg_parse_query(const char *query_string)
Definition: postgres.c:611
void record_plan_function_dependency(PlannerInfo *root, Oid funcid)
Definition: setrefs.c:3444
struct ErrorContextCallback * previous
Definition: elog.h:295
void(* callback)(void *arg)
Definition: elog.h:296
const char * p_sourcetext
Definition: parse_node.h:193
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, 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 5033 of file clauses.c.

5034 {
5035  RangeTblFunction *rtfunc;
5036  FuncExpr *fexpr;
5037  Oid func_oid;
5038  HeapTuple func_tuple;
5039  Form_pg_proc funcform;
5040  char *src;
5041  Datum tmp;
5042  bool isNull;
5043  MemoryContext oldcxt;
5044  MemoryContext mycxt;
5045  inline_error_callback_arg callback_arg;
5046  ErrorContextCallback sqlerrcontext;
5048  TypeFuncClass functypclass;
5049  TupleDesc rettupdesc;
5050  List *raw_parsetree_list;
5051  List *querytree_list;
5052  Query *querytree;
5053 
5054  Assert(rte->rtekind == RTE_FUNCTION);
5055 
5056  /*
5057  * It doesn't make a lot of sense for a SQL SRF to refer to itself in its
5058  * own FROM clause, since that must cause infinite recursion at runtime.
5059  * It will cause this code to recurse too, so check for stack overflow.
5060  * (There's no need to do more.)
5061  */
5063 
5064  /* Fail if the RTE has ORDINALITY - we don't implement that here. */
5065  if (rte->funcordinality)
5066  return NULL;
5067 
5068  /* Fail if RTE isn't a single, simple FuncExpr */
5069  if (list_length(rte->functions) != 1)
5070  return NULL;
5071  rtfunc = (RangeTblFunction *) linitial(rte->functions);
5072 
5073  if (!IsA(rtfunc->funcexpr, FuncExpr))
5074  return NULL;
5075  fexpr = (FuncExpr *) rtfunc->funcexpr;
5076 
5077  func_oid = fexpr->funcid;
5078 
5079  /*
5080  * The function must be declared to return a set, else inlining would
5081  * change the results if the contained SELECT didn't return exactly one
5082  * row.
5083  */
5084  if (!fexpr->funcretset)
5085  return NULL;
5086 
5087  /*
5088  * Refuse to inline if the arguments contain any volatile functions or
5089  * sub-selects. Volatile functions are rejected because inlining may
5090  * result in the arguments being evaluated multiple times, risking a
5091  * change in behavior. Sub-selects are rejected partly for implementation
5092  * reasons (pushing them down another level might change their behavior)
5093  * and partly because they're likely to be expensive and so multiple
5094  * evaluation would be bad.
5095  */
5096  if (contain_volatile_functions((Node *) fexpr->args) ||
5097  contain_subplans((Node *) fexpr->args))
5098  return NULL;
5099 
5100  /* Check permission to call function (fail later, if not) */
5101  if (object_aclcheck(ProcedureRelationId, func_oid, GetUserId(), ACL_EXECUTE) != ACLCHECK_OK)
5102  return NULL;
5103 
5104  /* Check whether a plugin wants to hook function entry/exit */
5105  if (FmgrHookIsNeeded(func_oid))
5106  return NULL;
5107 
5108  /*
5109  * OK, let's take a look at the function's pg_proc entry.
5110  */
5111  func_tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(func_oid));
5112  if (!HeapTupleIsValid(func_tuple))
5113  elog(ERROR, "cache lookup failed for function %u", func_oid);
5114  funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
5115 
5116  /*
5117  * Forget it if the function is not SQL-language or has other showstopper
5118  * properties. In particular it mustn't be declared STRICT, since we
5119  * couldn't enforce that. It also mustn't be VOLATILE, because that is
5120  * supposed to cause it to be executed with its own snapshot, rather than
5121  * sharing the snapshot of the calling query. We also disallow returning
5122  * SETOF VOID, because inlining would result in exposing the actual result
5123  * of the function's last SELECT, which should not happen in that case.
5124  * (Rechecking prokind, proretset, and pronargs is just paranoia.)
5125  */
5126  if (funcform->prolang != SQLlanguageId ||
5127  funcform->prokind != PROKIND_FUNCTION ||
5128  funcform->proisstrict ||
5129  funcform->provolatile == PROVOLATILE_VOLATILE ||
5130  funcform->prorettype == VOIDOID ||
5131  funcform->prosecdef ||
5132  !funcform->proretset ||
5133  list_length(fexpr->args) != funcform->pronargs ||
5134  !heap_attisnull(func_tuple, Anum_pg_proc_proconfig, NULL))
5135  {
5136  ReleaseSysCache(func_tuple);
5137  return NULL;
5138  }
5139 
5140  /*
5141  * Make a temporary memory context, so that we don't leak all the stuff
5142  * that parsing might create.
5143  */
5145  "inline_set_returning_function",
5147  oldcxt = MemoryContextSwitchTo(mycxt);
5148 
5149  /* Fetch the function body */
5150  tmp = SysCacheGetAttrNotNull(PROCOID, func_tuple, Anum_pg_proc_prosrc);
5151  src = TextDatumGetCString(tmp);
5152 
5153  /*
5154  * Setup error traceback support for ereport(). This is so that we can
5155  * finger the function that bad information came from.
5156  */
5157  callback_arg.proname = NameStr(funcform->proname);
5158  callback_arg.prosrc = src;
5159 
5160  sqlerrcontext.callback = sql_inline_error_callback;
5161  sqlerrcontext.arg = (void *) &callback_arg;
5162  sqlerrcontext.previous = error_context_stack;
5163  error_context_stack = &sqlerrcontext;
5164 
5165  /* If we have prosqlbody, pay attention to that not prosrc */
5166  tmp = SysCacheGetAttr(PROCOID,
5167  func_tuple,
5168  Anum_pg_proc_prosqlbody,
5169  &isNull);
5170  if (!isNull)
5171  {
5172  Node *n;
5173 
5175  if (IsA(n, List))
5176  querytree_list = linitial_node(List, castNode(List, n));
5177  else
5178  querytree_list = list_make1(n);
5179  if (list_length(querytree_list) != 1)
5180  goto fail;
5181  querytree = linitial(querytree_list);
5182 
5183  /* Acquire necessary locks, then apply rewriter. */
5184  AcquireRewriteLocks(querytree, true, false);
5185  querytree_list = pg_rewrite_query(querytree);
5186  if (list_length(querytree_list) != 1)
5187  goto fail;
5188  querytree = linitial(querytree_list);
5189  }
5190  else
5191  {
5192  /*
5193  * Set up to handle parameters while parsing the function body. We
5194  * can use the FuncExpr just created as the input for
5195  * prepare_sql_fn_parse_info.
5196  */
5197  pinfo = prepare_sql_fn_parse_info(func_tuple,
5198  (Node *) fexpr,
5199  fexpr->inputcollid);
5200 
5201  /*
5202  * Parse, analyze, and rewrite (unlike inline_function(), we can't
5203  * skip rewriting here). We can fail as soon as we find more than one
5204  * query, though.
5205  */
5206  raw_parsetree_list = pg_parse_query(src);
5207  if (list_length(raw_parsetree_list) != 1)
5208  goto fail;
5209 
5210  querytree_list = pg_analyze_and_rewrite_withcb(linitial(raw_parsetree_list),
5211  src,
5213  pinfo, NULL);
5214  if (list_length(querytree_list) != 1)
5215  goto fail;
5216  querytree = linitial(querytree_list);
5217  }
5218 
5219  /*
5220  * Also resolve the actual function result tupdesc, if composite. If we
5221  * have a coldeflist, believe that; otherwise use get_expr_result_type.
5222  * (This logic should match ExecInitFunctionScan.)
5223  */
5224  if (rtfunc->funccolnames != NIL)
5225  {
5226  functypclass = TYPEFUNC_RECORD;
5227  rettupdesc = BuildDescFromLists(rtfunc->funccolnames,
5228  rtfunc->funccoltypes,
5229  rtfunc->funccoltypmods,
5230  rtfunc->funccolcollations);
5231  }
5232  else
5233  functypclass = get_expr_result_type((Node *) fexpr, NULL, &rettupdesc);
5234 
5235  /*
5236  * The single command must be a plain SELECT.
5237  */
5238  if (!IsA(querytree, Query) ||
5239  querytree->commandType != CMD_SELECT)
5240  goto fail;
5241 
5242  /*
5243  * Make sure the function (still) returns what it's declared to. This
5244  * will raise an error if wrong, but that's okay since the function would
5245  * fail at runtime anyway. Note that check_sql_fn_retval will also insert
5246  * coercions if needed to make the tlist expression(s) match the declared
5247  * type of the function. We also ask it to insert dummy NULL columns for
5248  * any dropped columns in rettupdesc, so that the elements of the modified
5249  * tlist match up to the attribute numbers.
5250  *
5251  * If the function returns a composite type, don't inline unless the check
5252  * shows it's returning a whole tuple result; otherwise what it's
5253  * returning is a single composite column which is not what we need.
5254  */
5255  if (!check_sql_fn_retval(list_make1(querytree_list),
5256  fexpr->funcresulttype, rettupdesc,
5257  funcform->prokind,
5258  true, NULL) &&
5259  (functypclass == TYPEFUNC_COMPOSITE ||
5260  functypclass == TYPEFUNC_COMPOSITE_DOMAIN ||
5261  functypclass == TYPEFUNC_RECORD))
5262  goto fail; /* reject not-whole-tuple-result cases */
5263 
5264  /*
5265  * check_sql_fn_retval might've inserted a projection step, but that's
5266  * fine; just make sure we use the upper Query.
5267  */
5268  querytree = linitial_node(Query, querytree_list);
5269 
5270  /*
5271  * Looks good --- substitute parameters into the query.
5272  */
5274  funcform->pronargs,
5275  fexpr->args);
5276 
5277  /*
5278  * Copy the modified query out of the temporary memory context, and clean
5279  * up.
5280  */
5281  MemoryContextSwitchTo(oldcxt);
5282 
5284 
5285  MemoryContextDelete(mycxt);
5286  error_context_stack = sqlerrcontext.previous;
5287  ReleaseSysCache(func_tuple);
5288 
5289  /*
5290  * We don't have to fix collations here because the upper query is already
5291  * parsed, ie, the collations in the RTE are what count.
5292  */
5293 
5294  /*
5295  * Since there is now no trace of the function in the plan tree, we must
5296  * explicitly record the plan's dependency on the function.
5297  */
5298  record_plan_function_dependency(root, func_oid);
5299 
5300  /*
5301  * We must also notice if the inserted query adds a dependency on the
5302  * calling role due to RLS quals.
5303  */
5304  if (querytree->hasRowSecurity)
5305  root->glob->dependsOnRole = true;
5306 
5307  return querytree;
5308 
5309  /* Here if func is not inlinable: release temp memory and return NULL */
5310 fail:
5311  MemoryContextSwitchTo(oldcxt);
5312  MemoryContextDelete(mycxt);
5313  error_context_stack = sqlerrcontext.previous;
5314  ReleaseSysCache(func_tuple);
5315 
5316  return NULL;
5317 }
static Query * substitute_actual_srf_parameters(Query *expr, int nargs, List *args)
Definition: clauses.c:5326
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:1014
List * pg_analyze_and_rewrite_withcb(RawStmt *parsetree, const char *query_string, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
Definition: postgres.c:764
List * pg_rewrite_query(Query *query)
Definition: postgres.c:804
void AcquireRewriteLocks(Query *parsetree, bool forExecute, bool forUpdatePushedDown)
bool dependsOnRole
Definition: pathnodes.h:150
bool funcordinality
Definition: parsenodes.h:1154
List * functions
Definition: parsenodes.h:1153
RTEKind rtekind
Definition: parsenodes.h:1030
TupleDesc BuildDescFromLists(const List *names, const List *types, const List *typmods, const List *collations)
Definition: tupdesc.c:858

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, NIL, object_aclcheck(), ObjectIdGetDatum(), pg_analyze_and_rewrite_withcb(), pg_parse_query(), pg_rewrite_query(), prepare_sql_fn_parse_info(), ErrorContextCallback::previous, 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 733 of file clauses.c.

734 {
736  PlannerInfo *proot;
737  ListCell *l;
738 
739  /*
740  * Even if the original querytree contained nothing unsafe, we need to
741  * search the expression if we have generated any PARAM_EXEC Params while
742  * planning, because those are parallel-restricted and there might be one
743  * in this expression. But otherwise we don't need to look.
744  */
745  if (root->glob->maxParallelHazard == PROPARALLEL_SAFE &&
746  root->glob->paramExecTypes == NIL)
747  return true;
748  /* Else use max_parallel_hazard's search logic, but stop on RESTRICTED */
749  context.max_hazard = PROPARALLEL_SAFE;
750  context.max_interesting = PROPARALLEL_RESTRICTED;
751  context.safe_param_ids = NIL;
752 
753  /*
754  * The params that refer to the same or parent query level are considered
755  * parallel-safe. The idea is that we compute such params at Gather or
756  * Gather Merge node and pass their value to workers.
757  */
758  for (proot = root; proot != NULL; proot = proot->parent_root)
759  {
760  foreach(l, proot->init_plans)
761  {
762  SubPlan *initsubplan = (SubPlan *) lfirst(l);
763 
764  context.safe_param_ids = list_concat(context.safe_param_ids,
765  initsubplan->setParam);
766  }
767  }
768 
769  return !max_parallel_hazard_walker(node, &context);
770 }
static bool max_parallel_hazard_walker(Node *node, max_parallel_hazard_context *context)
Definition: clauses.c:809
List * list_concat(List *list1, const List *list2)
Definition: list.c:561
char maxParallelHazard
Definition: pathnodes.h:159
List * paramExecTypes
Definition: pathnodes.h:135
List * init_plans
Definition: pathnodes.h:296
List * setParam
Definition: primnodes.h:1044

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

2069 {
2070  /*
2071  * We could implement this check in one recursive scan. But since the
2072  * check for volatile functions is both moderately expensive and unlikely
2073  * to fail, it seems better to look for Vars first and only check for
2074  * volatile functions if we find no Vars.
2075  */
2076  if (!contain_var_clause(clause) &&
2077  !contain_volatile_functions(clause))
2078  return true;
2079  return false;
2080 }

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

2089 {
2090  if (bms_is_empty(relids) &&
2091  !contain_volatile_functions(clause))
2092  return true;
2093  return false;
2094 }

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

2007 {
2008  Node *rightop;
2009 
2010  /* The contained operator must be strict. */
2011  set_sa_opfuncid(expr);
2012  if (!func_strict(expr->opfuncid))
2013  return false;
2014  /* If ANY and falseOK, that's all we need to check. */
2015  if (expr->useOr && falseOK)
2016  return true;
2017  /* Else, we have to see if the array is provably non-empty. */
2018  Assert(list_length(expr->args) == 2);
2019  rightop = (Node *) lsecond(expr->args);
2020  if (rightop && IsA(rightop, Const))
2021  {
2022  Datum arraydatum = ((Const *) rightop)->constvalue;
2023  bool arrayisnull = ((Const *) rightop)->constisnull;
2024  ArrayType *arrayval;
2025  int nitems;
2026 
2027  if (arrayisnull)
2028  return false;
2029  arrayval = DatumGetArrayTypeP(arraydatum);
2030  nitems = ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
2031  if (nitems > 0)
2032  return true;
2033  }
2034  else if (rightop && IsA(rightop, ArrayExpr))
2035  {
2036  ArrayExpr *arrayexpr = (ArrayExpr *) rightop;
2037 
2038  if (arrayexpr->elements != NIL && !arrayexpr->multidims)
2039  return true;
2040  }
2041  return false;
2042 }
List * elements
Definition: primnodes.h:1336

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

715 {
717 
718  context.max_hazard = PROPARALLEL_SAFE;
719  context.max_interesting = PROPARALLEL_UNSAFE;
720  context.safe_param_ids = NIL;
721  (void) max_parallel_hazard_walker((Node *) parse, &context);
722  return context.max_hazard;
723 }
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 802 of file clauses.c.

803 {
804  return max_parallel_hazard_test(func_parallel(func_id),
805  (max_parallel_hazard_context *) context);
806 }
static bool max_parallel_hazard_test(char proparallel, max_parallel_hazard_context *context)
Definition: clauses.c:774
char func_parallel(Oid funcid)
Definition: lsyscache.c:1777

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

775 {
776  switch (proparallel)
777  {
778  case PROPARALLEL_SAFE:
779  /* nothing to see here, move along */
780  break;
781  case PROPARALLEL_RESTRICTED:
782  /* increase max_hazard to RESTRICTED */
783  Assert(context->max_hazard != PROPARALLEL_UNSAFE);
784  context->max_hazard = proparallel;
785  /* done if we are not expecting any unsafe functions */
786  if (context->max_interesting == proparallel)
787  return true;
788  break;
789  case PROPARALLEL_UNSAFE:
790  context->max_hazard = proparallel;
791  /* we're always done at the first unsafe construct */
792  return true;
793  default:
794  elog(ERROR, "unrecognized proparallel value \"%c\"", proparallel);
795  break;
796  }
797  return false;
798 }

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

810 {
811  if (node == NULL)
812  return false;
813 
814  /* Check for hazardous functions in node itself */
816  context))
817  return true;
818 
819  /*
820  * It should be OK to treat MinMaxExpr as parallel-safe, since btree
821  * opclass support functions are generally parallel-safe. XmlExpr is a
822  * bit more dubious but we can probably get away with it. We err on the
823  * side of caution by treating CoerceToDomain as parallel-restricted.
824  * (Note: in principle that's wrong because a domain constraint could
825  * contain a parallel-unsafe function; but useful constraints probably
826  * never would have such, and assuming they do would cripple use of
827  * parallel query in the presence of domain types.) SQLValueFunction
828  * should be safe in all cases. NextValueExpr is parallel-unsafe.
829  */
830  if (IsA(node, CoerceToDomain))
831  {
832  if (max_parallel_hazard_test(PROPARALLEL_RESTRICTED, context))
833  return true;
834  }
835 
836  else if (IsA(node, NextValueExpr))
837  {
838  if (max_parallel_hazard_test(PROPARALLEL_UNSAFE, context))
839  return true;
840  }
841 
842  /*
843  * Treat window functions as parallel-restricted because we aren't sure
844  * whether the input row ordering is fully deterministic, and the output
845  * of window functions might vary across workers if not. (In some cases,
846  * like where the window frame orders by a primary key, we could relax
847  * this restriction. But it doesn't currently seem worth expending extra
848  * effort to do so.)
849  */
850  else if (IsA(node, WindowFunc))
851  {
852  if (max_parallel_hazard_test(PROPARALLEL_RESTRICTED, context))
853  return true;
854  }
855 
856  /*
857  * As a notational convenience for callers, look through RestrictInfo.
858  */
859  else if (IsA(node, RestrictInfo))
860  {
861  RestrictInfo *rinfo = (RestrictInfo *) node;
862 
863  return max_parallel_hazard_walker((Node *) rinfo->clause, context);
864  }
865 
866  /*
867  * Really we should not see SubLink during a max_interesting == restricted
868  * scan, but if we do, return true.
869  */
870  else if (IsA(node, SubLink))
871  {
872  if (max_parallel_hazard_test(PROPARALLEL_RESTRICTED, context))
873  return true;
874  }
875 
876  /*
877  * Only parallel-safe SubPlans can be sent to workers. Within the
878  * testexpr of the SubPlan, Params representing the output columns of the
879  * subplan can be treated as parallel-safe, so temporarily add their IDs
880  * to the safe_param_ids list while examining the testexpr.
881  */
882  else if (IsA(node, SubPlan))
883  {
884  SubPlan *subplan = (SubPlan *) node;
885  List *save_safe_param_ids;
886 
887  if (!subplan->parallel_safe &&
888  max_parallel_hazard_test(PROPARALLEL_RESTRICTED, context))
889  return true;
890  save_safe_param_ids = context->safe_param_ids;
891  context->safe_param_ids = list_concat_copy(context->safe_param_ids,
892  subplan->paramIds);
893  if (max_parallel_hazard_walker(subplan->testexpr, context))
894  return true; /* no need to restore safe_param_ids */
895  list_free(context->safe_param_ids);
896  context->safe_param_ids = save_safe_param_ids;
897  /* we must also check args, but no special Param treatment there */
898  if (max_parallel_hazard_walker((Node *) subplan->args, context))
899  return true;
900  /* don't want to recurse normally, so we're done */
901  return false;
902  }
903 
904  /*
905  * We can't pass Params to workers at the moment either, so they are also
906  * parallel-restricted, unless they are PARAM_EXTERN Params or are
907  * PARAM_EXEC Params listed in safe_param_ids, meaning they could be
908  * either generated within workers or can be computed by the leader and
909  * then their value can be passed to workers.
910  */
911  else if (IsA(node, Param))
912  {
913  Param *param = (Param *) node;
914 
915  if (param->paramkind == PARAM_EXTERN)
916  return false;
917 
918  if (param->paramkind != PARAM_EXEC ||
919  !list_member_int(context->safe_param_ids, param->paramid))
920  {
921  if (max_parallel_hazard_test(PROPARALLEL_RESTRICTED, context))
922  return true;
923  }
924  return false; /* nothing to recurse to */
925  }
926 
927  /*
928  * When we're first invoked on a completely unplanned tree, we must
929  * recurse into subqueries so to as to locate parallel-unsafe constructs
930  * anywhere in the tree.
931  */
932  else if (IsA(node, Query))
933  {
934  Query *query = (Query *) node;
935 
936  /* SELECT FOR UPDATE/SHARE must be treated as unsafe */
937  if (query->rowMarks != NULL)
938  {
939  context->max_hazard = PROPARALLEL_UNSAFE;
940  return true;
941  }
942 
943  /* Recurse into subselects */
944  return query_tree_walker(query,
946  context, 0);
947  }
948 
949  /* Recurse to check arguments */
950  return expression_tree_walker(node,
952  context);
953 }
static bool max_parallel_hazard_checker(Oid func_id, void *context)
Definition: clauses.c:802
void list_free(List *list)
Definition: list.c:1546
List * rowMarks
Definition: parsenodes.h:216
List * args
Definition: primnodes.h:1047
List * paramIds
Definition: primnodes.h:1024
Node * testexpr
Definition: primnodes.h:1023
bool parallel_safe
Definition: primnodes.h:1040

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

2111 {
2112  int result;
2113  Relids varnos = pull_varnos(root, clause);
2114 
2115  varnos = bms_del_members(varnos, root->outer_join_rels);
2116  result = bms_num_members(varnos);
2117  bms_free(varnos);
2118  return result;
2119 }
void bms_free(Bitmapset *a)
Definition: bitmapset.c:239
int bms_num_members(const Bitmapset *a)
Definition: bitmapset.c:751
Bitmapset * bms_del_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:1161
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 5386 of file clauses.c.

5387 {
5388  Bitmapset *result = NULL;
5389 
5390  (void) pull_paramids_walker((Node *) expr, &result);
5391 
5392  return result;
5393 }
static bool pull_paramids_walker(Node *node, Bitmapset **context)
Definition: clauses.c:5396

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

5397 {
5398  if (node == NULL)
5399  return false;
5400  if (IsA(node, Param))
5401  {
5402  Param *param = (Param *) node;
5403 
5404  *context = bms_add_member(*context, param->paramid);
5405  return false;
5406  }
5408  (void *) context);
5409 }
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815

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

4350 {
4351  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4352  int nargs;
4353  Oid actual_arg_types[FUNC_MAX_ARGS];
4354  Oid declared_arg_types[FUNC_MAX_ARGS];
4355  Oid rettype;
4356  ListCell *lc;
4357 
4359  elog(ERROR, "too many function arguments");
4360  nargs = 0;
4361  foreach(lc, args)
4362  {
4363  actual_arg_types[nargs++] = exprType((Node *) lfirst(lc));
4364  }
4365  Assert(nargs == pronargs);
4366  memcpy(declared_arg_types, proargtypes, pronargs * sizeof(Oid));
4367  rettype = enforce_generic_type_consistency(actual_arg_types,
4368  declared_arg_types,
4369  nargs,
4370  funcform->prorettype,
4371  false);
4372  /* let's just check we got the same answer as the parser did ... */
4373  if (rettype != result_type)
4374  elog(ERROR, "function's resolved result type changed during planning");
4375 
4376  /* perform any necessary typecasting of arguments */
4377  make_fn_arguments(NULL, args, actual_arg_types, declared_arg_types);
4378 }
Oid enforce_generic_type_consistency(const Oid *actual_arg_types, Oid *declared_arg_types, int nargs, Oid rettype, bool allow_poly)
void make_fn_arguments(ParseState *pstate, List *fargs, Oid *actual_arg_types, Oid *declared_arg_types)
Definition: parse_func.c:1824
#define FUNC_MAX_ARGS

References generate_unaccent_rules::args, Assert(), elog, enforce_generic_type_consistency(), ERROR, exprType(), FUNC_MAX_ARGS, GETSTRUCT, lfirst, list_length(), make_fn_arguments(), and pronargs.

Referenced by expand_function_arguments().

◆ reorder_function_arguments()

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

Definition at line 4223 of file clauses.c.

4224 {
4225  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4226  int nargsprovided = list_length(args);
4227  Node *argarray[FUNC_MAX_ARGS];
4228  ListCell *lc;
4229  int i;
4230 
4231  Assert(nargsprovided <= pronargs);
4232  if (pronargs < 0 || pronargs > FUNC_MAX_ARGS)
4233  elog(ERROR, "too many function arguments");
4234  memset(argarray, 0, pronargs * sizeof(Node *));
4235 
4236  /* Deconstruct the argument list into an array indexed by argnumber */
4237  i = 0;
4238  foreach(lc, args)
4239  {
4240  Node *arg = (Node *) lfirst(lc);
4241 
4242  if (!IsA(arg, NamedArgExpr))
4243  {
4244  /* positional argument, assumed to precede all named args */
4245  Assert(argarray[i] == NULL);
4246  argarray[i++] = arg;
4247  }
4248  else
4249  {
4250  NamedArgExpr *na = (NamedArgExpr *) arg;
4251 
4252  Assert(na->argnumber >= 0 && na->argnumber < pronargs);
4253  Assert(argarray[na->argnumber] == NULL);
4254  argarray[na->argnumber] = (Node *) na->arg;
4255  }
4256  }
4257 
4258  /*
4259  * Fetch default expressions, if needed, and insert into array at proper
4260  * locations (they aren't necessarily consecutive or all used)
4261  */
4262  if (nargsprovided < pronargs)
4263  {
4264  List *defaults = fetch_function_defaults(func_tuple);
4265 
4266  i = pronargs - funcform->pronargdefaults;
4267  foreach(lc, defaults)
4268  {
4269  if (argarray[i] == NULL)
4270  argarray[i] = (Node *) lfirst(lc);
4271  i++;
4272  }
4273  }
4274 
4275  /* Now reconstruct the args list in proper order */
4276  args = NIL;
4277  for (i = 0; i < pronargs; i++)
4278  {
4279  Assert(argarray[i] != NULL);
4280  args = lappend(args, argarray[i]);
4281  }
4282 
4283  return args;
4284 }
Expr * arg
Definition: primnodes.h:747

References arg, NamedArgExpr::arg, NamedArgExpr::argnumber, generate_unaccent_rules::args, Assert(), elog, ERROR, fetch_function_defaults(), FUNC_MAX_ARGS, GETSTRUCT, i, IsA, lappend(), lfirst, list_length(), NIL, and pronargs.

Referenced by expand_function_arguments().

◆ rowtype_field_matches()

static bool rowtype_field_matches ( Oid  rowtypeid,
int  fieldnum,
Oid  expectedtype,
int32  expectedtypmod,
Oid  expectedcollation 
)
static

Definition at line 2166 of file clauses.c.

2169 {
2170  TupleDesc tupdesc;
2171  Form_pg_attribute attr;
2172 
2173  /* No issue for RECORD, since there is no way to ALTER such a type */
2174  if (rowtypeid == RECORDOID)
2175  return true;
2176  tupdesc = lookup_rowtype_tupdesc_domain(rowtypeid, -1, false);
2177  if (fieldnum <= 0 || fieldnum > tupdesc->natts)
2178  {
2179  ReleaseTupleDesc(tupdesc);
2180  return false;
2181  }
2182  attr = TupleDescAttr(tupdesc, fieldnum - 1);
2183  if (attr->attisdropped ||
2184  attr->atttypid != expectedtype ||
2185  attr->atttypmod != expectedtypmod ||
2186  attr->attcollation != expectedcollation)
2187  {
2188  ReleaseTupleDesc(tupdesc);
2189  return false;
2190  }
2191  ReleaseTupleDesc(tupdesc);
2192  return true;
2193 }
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:209
#define ReleaseTupleDesc(tupdesc)
Definition: tupdesc.h:122
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
TupleDesc lookup_rowtype_tupdesc_domain(Oid type_id, int32 typmod, bool noError)
Definition: typcache.c:1889

References lookup_rowtype_tupdesc_domain(), TupleDescData::natts, ReleaseTupleDesc, and TupleDescAttr.

Referenced by eval_const_expressions_mutator().

◆ simplify_and_arguments()

static List * simplify_and_arguments ( List args,
eval_const_expressions_context context,
bool haveNull,
bool forceFalse 
)
static

Definition at line 3863 of file clauses.c.

3866 {
3867  List *newargs = NIL;
3868  List *unprocessed_args;
3869 
3870  /* See comments in simplify_or_arguments */
3871  unprocessed_args = list_copy(args);
3872  while (unprocessed_args)
3873  {
3874  Node *arg = (Node *) linitial(unprocessed_args);
3875 
3876  unprocessed_args = list_delete_first(unprocessed_args);
3877 
3878  /* flatten nested ANDs as per above comment */
3879  if (is_andclause(arg))
3880  {
3881  List *subargs = ((BoolExpr *) arg)->args;
3882  List *oldlist = unprocessed_args;
3883 
3884  unprocessed_args = list_concat_copy(subargs, unprocessed_args);
3885  /* perhaps-overly-tense code to avoid leaking old lists */
3886  list_free(oldlist);
3887  continue;
3888  }
3889 
3890  /* If it's not an AND, simplify it */
3892 
3893  /*
3894  * It is unlikely but not impossible for simplification of a non-AND
3895  * clause to produce an AND. Recheck, but don't be too tense about it
3896  * since it's not a mainstream case. In particular we don't worry
3897  * about const-simplifying the input twice, nor about list leakage.
3898  */
3899  if (is_andclause(arg))
3900  {
3901  List *subargs = ((BoolExpr *) arg)->args;
3902 
3903  unprocessed_args = list_concat_copy(subargs, unprocessed_args);
3904  continue;
3905  }
3906 
3907  /*
3908  * OK, we have a const-simplified non-AND argument. Process it per
3909  * comments above.
3910  */
3911  if (IsA(arg, Const))
3912  {
3913  Const *const_input = (Const *) arg;
3914 
3915  if (const_input->constisnull)
3916  *haveNull = true;
3917  else if (!DatumGetBool(const_input->constvalue))
3918  {
3919  *forceFalse = true;
3920 
3921  /*
3922  * Once we detect a FALSE result we can just exit the loop
3923  * immediately. However, if we ever add a notion of
3924  * non-removable functions, we'd need to keep scanning.
3925  */
3926  return NIL;
3927  }
3928  /* otherwise, we can drop the constant-true input */
3929  continue;
3930  }
3931 
3932  /* else emit the simplified arg into the result list */
3933  newargs = lappend(newargs, arg);
3934  }
3935 
3936  return newargs;
3937 }
List * list_copy(const List *oldlist)
Definition: list.c:1573
List * list_delete_first(List *list)
Definition: list.c:943
static bool is_andclause(const void *clause)
Definition: nodeFuncs.h:105

References arg, generate_unaccent_rules::args, DatumGetBool(), eval_const_expressions_mutator(), is_andclause(), IsA, lappend(), linitial, list_concat_copy(), list_copy(), list_delete_first(), list_free(), and NIL.

Referenced by eval_const_expressions_mutator().

◆ simplify_boolean_equality()

static Node * simplify_boolean_equality ( Oid  opno,
List args 
)
static

Definition at line 3957 of file clauses.c.

3958 {
3959  Node *leftop;
3960  Node *rightop;
3961 
3962  Assert(list_length(args) == 2);
3963  leftop = linitial(args);
3964  rightop = lsecond(args);
3965  if (leftop && IsA(leftop, Const))
3966  {
3967  Assert(!((Const *) leftop)->constisnull);
3968  if (opno == BooleanEqualOperator)
3969  {
3970  if (DatumGetBool(((Const *) leftop)->constvalue))
3971  return rightop; /* true = foo */
3972  else
3973  return negate_clause(rightop); /* false = foo */
3974  }
3975  else
3976  {
3977  if (DatumGetBool(((Const *) leftop)->constvalue))
3978  return negate_clause(rightop); /* true <> foo */
3979  else
3980  return rightop; /* false <> foo */
3981  }
3982  }
3983  if (rightop && IsA(rightop, Const))
3984  {
3985  Assert(!((Const *) rightop)->constisnull);
3986  if (opno == BooleanEqualOperator)
3987  {
3988  if (DatumGetBool(((Const *) rightop)->constvalue))
3989  return leftop; /* foo = true */
3990  else
3991  return negate_clause(leftop); /* foo = false */
3992  }
3993  else
3994  {
3995  if (DatumGetBool(((Const *) rightop)->constvalue))
3996  return negate_clause(leftop); /* foo <> true */
3997  else
3998  return leftop; /* foo <> false */
3999  }
4000  }
4001  return NULL;
4002 }

References generate_unaccent_rules::args, Assert(), DatumGetBool(), IsA, linitial, list_length(), lsecond, and negate_clause().

Referenced by eval_const_expressions_mutator().

◆ simplify_function()

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

Definition at line 4026 of file clauses.c.

4030 {
4031  List *args = *args_p;
4032  HeapTuple func_tuple;
4033  Form_pg_proc func_form;
4034  Expr *newexpr;
4035 
4036  /*
4037  * We have three strategies for simplification: execute the function to
4038  * deliver a constant result, use a transform function to generate a
4039  * substitute node tree, or expand in-line the body of the function
4040  * definition (which only works for simple SQL-language functions, but
4041  * that is a common case). Each case needs access to the function's
4042  * pg_proc tuple, so fetch it just once.
4043  *
4044  * Note: the allow_non_const flag suppresses both the second and third
4045  * strategies; so if !allow_non_const, simplify_function can only return a
4046  * Const or NULL. Argument-list rewriting happens anyway, though.
4047  */
4048  func_tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
4049  if (!HeapTupleIsValid(func_tuple))
4050  elog(ERROR, "cache lookup failed for function %u", funcid);
4051  func_form = (Form_pg_proc) GETSTRUCT(func_tuple);
4052 
4053  /*
4054  * Process the function arguments, unless the caller did it already.
4055  *
4056  * Here we must deal with named or defaulted arguments, and then
4057  * recursively apply eval_const_expressions to the whole argument list.
4058  */
4059  if (process_args)
4060  {
4061  args = expand_function_arguments(args, false, result_type, func_tuple);
4064  (void *) context);
4065  /* Argument processing done, give it back to the caller */
4066  *args_p = args;
4067  }
4068 
4069  /* Now attempt simplification of the function call proper. */
4070 
4071  newexpr = evaluate_function(funcid, result_type, result_typmod,
4072  result_collid, input_collid,
4073  args, funcvariadic,
4074  func_tuple, context);
4075 
4076  if (!newexpr && allow_non_const && OidIsValid(func_form->prosupport))
4077  {
4078  /*
4079  * Build a SupportRequestSimplify node to pass to the support
4080  * function, pointing to a dummy FuncExpr node containing the
4081  * simplified arg list. We use this approach to present a uniform
4082  * interface to the support function regardless of how the target
4083  * function is actually being invoked.
4084  */
4086  FuncExpr fexpr;
4087 
4088  fexpr.xpr.type = T_FuncExpr;
4089  fexpr.funcid = funcid;
4090  fexpr.funcresulttype = result_type;
4091  fexpr.funcretset = func_form->proretset;
4092  fexpr.funcvariadic = funcvariadic;
4093  fexpr.funcformat = COERCE_EXPLICIT_CALL;
4094  fexpr.funccollid = result_collid;
4095  fexpr.inputcollid = input_collid;
4096  fexpr.args = args;
4097  fexpr.location = -1;
4098 
4099  req.type = T_SupportRequestSimplify;
4100  req.root = context->root;
4101  req.fcall = &fexpr;
4102 
4103  newexpr = (Expr *)
4104  DatumGetPointer(OidFunctionCall1(func_form->prosupport,
4105  PointerGetDatum(&req)));
4106 
4107  /* catch a possible API misunderstanding */
4108  Assert(newexpr != (Expr *) &fexpr);
4109  }
4110 
4111  if (!newexpr && allow_non_const)
4112  newexpr = inline_function(funcid, result_type, result_collid,
4113  input_collid, args, funcvariadic,
4114  func_tuple, context);
4115 
4116  ReleaseSysCache(func_tuple);
4117 
4118  return newexpr;
4119 }
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)
Definition: clauses.c:4392
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)
Definition: clauses.c:4519
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:680
Expr xpr
Definition: primnodes.h:704
struct PlannerInfo * root
Definition: supportnodes.h:68

References generate_unaccent_rules::args, FuncExpr::args, Assert(), COERCE_EXPLICIT_CALL, DatumGetPointer(), elog, ERROR, eval_const_expressions_mutator(), evaluate_function(), expand_function_arguments(), expression_tree_mutator, SupportRequestSimplify::fcall, FuncExpr::funcid, GETSTRUCT, HeapTupleIsValid, inline_function(), FuncExpr::location, ObjectIdGetDatum(), OidFunctionCall1, OidIsValid, PointerGetDatum(), ReleaseSysCache(), eval_const_expressions_context::root, SupportRequestSimplify::root, SearchSysCache1(), SupportRequestSimplify::type, and FuncExpr::xpr.

Referenced by eval_const_expressions_mutator().

◆ simplify_or_arguments()

static List * simplify_or_arguments ( List args,
eval_const_expressions_context context,
bool haveNull,
bool forceTrue 
)
static

Definition at line 3757 of file clauses.c.

3760 {
3761  List *newargs = NIL;
3762  List *unprocessed_args;
3763 
3764  /*
3765  * We want to ensure that any OR immediately beneath another OR gets
3766  * flattened into a single OR-list, so as to simplify later reasoning.
3767  *
3768  * To avoid stack overflow from recursion of eval_const_expressions, we
3769  * resort to some tenseness here: we keep a list of not-yet-processed
3770  * inputs, and handle flattening of nested ORs by prepending to the to-do
3771  * list instead of recursing. Now that the parser generates N-argument
3772  * ORs from simple lists, this complexity is probably less necessary than
3773  * it once was, but we might as well keep the logic.
3774  */
3775  unprocessed_args = list_copy(args);
3776  while (unprocessed_args)
3777  {
3778  Node *arg = (Node *) linitial(unprocessed_args);
3779 
3780  unprocessed_args = list_delete_first(unprocessed_args);
3781 
3782  /* flatten nested ORs as per above comment */
3783  if (is_orclause(arg))
3784  {
3785  List *subargs = ((BoolExpr *) arg)->args;
3786  List *oldlist = unprocessed_args;
3787 
3788  unprocessed_args = list_concat_copy(subargs, unprocessed_args);
3789  /* perhaps-overly-tense code to avoid leaking old lists */
3790  list_free(oldlist);
3791  continue;
3792  }
3793 
3794  /* If it's not an OR, simplify it */
3796 
3797  /*
3798  * It is unlikely but not impossible for simplification of a non-OR
3799  * clause to produce an OR. Recheck, but don't be too tense about it
3800  * since it's not a mainstream case. In particular we don't worry
3801  * about const-simplifying the input twice, nor about list leakage.
3802  */
3803  if (is_orclause(arg))
3804  {
3805  List *subargs = ((BoolExpr *) arg)->args;
3806 
3807  unprocessed_args = list_concat_copy(subargs, unprocessed_args);
3808  continue;
3809  }
3810 
3811  /*
3812  * OK, we have a const-simplified non-OR argument. Process it per
3813  * comments above.
3814  */
3815  if (IsA(arg, Const))
3816  {
3817  Const *const_input = (Const *) arg;
3818 
3819  if (const_input->constisnull)
3820  *haveNull = true;
3821  else if (DatumGetBool(const_input->constvalue))
3822  {
3823  *forceTrue = true;
3824 
3825  /*
3826  * Once we detect a TRUE result we can just exit the loop
3827  * immediately. However, if we ever add a notion of
3828  * non-removable functions, we'd need to keep scanning.
3829  */
3830  return NIL;
3831  }
3832  /* otherwise, we can drop the constant-false input */
3833  continue;
3834  }
3835 
3836  /* else emit the simplified arg into the result list */
3837  newargs = lappend(newargs, arg);
3838  }
3839 
3840  return newargs;
3841 }
static bool is_orclause(const void *clause)
Definition: nodeFuncs.h:114

References arg, generate_unaccent_rules::args, DatumGetBool(), eval_const_expressions_mutator(), is_orclause(), IsA, lappend(), linitial, list_concat_copy(), list_copy(), list_delete_first(), list_free(), and NIL.

Referenced by eval_const_expressions_mutator().

◆ sql_inline_error_callback()

static void sql_inline_error_callback ( void *  arg)
static

Definition at line 4917 of file clauses.c.

4918 {
4920  int syntaxerrposition;
4921 
4922  /* If it's a syntax error, convert to internal syntax error report */
4923  syntaxerrposition = geterrposition();
4924  if (syntaxerrposition > 0)
4925  {
4926  errposition(0);
4927  internalerrposition(syntaxerrposition);
4928  internalerrquery(callback_arg->prosrc);
4929  }
4930 
4931  errcontext("SQL function \"%s\" during inlining", callback_arg->proname);
4932 }
int internalerrquery(const char *query)
Definition: elog.c:1484
int internalerrposition(int cursorpos)
Definition: elog.c:1464
int geterrposition(void)
Definition: elog.c:1580
int errposition(int cursorpos)
Definition: elog.c:1448
#define errcontext
Definition: elog.h:196

References arg, errcontext, errposition(), geterrposition(), internalerrposition(), internalerrquery(), inline_error_callback_arg::proname, and inline_error_callback_arg::prosrc.

Referenced by inline_function(), and inline_set_returning_function().

◆ substitute_actual_parameters()

static Node * substitute_actual_parameters ( Node expr,
int  nargs,
List args,
int *  usecounts 
)
static

Definition at line 4875 of file clauses.c.

4877 {
4879 
4880  context.nargs = nargs;
4881  context.args = args;
4882  context.usecounts = usecounts;
4883 
4884  return substitute_actual_parameters_mutator(expr, &context);
4885 }
static Node * substitute_actual_parameters_mutator(Node *node, substitute_actual_parameters_context *context)
Definition: clauses.c:4888

References generate_unaccent_rules::args, substitute_actual_parameters_context::args, substitute_actual_parameters_context::nargs, substitute_actual_parameters_mutator(), and substitute_actual_parameters_context::usecounts.

Referenced by inline_function().

◆ substitute_actual_parameters_mutator()

static Node * substitute_actual_parameters_mutator ( Node node,
substitute_actual_parameters_context context 
)
static

Definition at line 4888 of file clauses.c.

4890 {
4891  if (node == NULL)
4892  return NULL;
4893  if (IsA(node, Param))
4894  {
4895  Param *param = (Param *) node;
4896 
4897  if (param->paramkind != PARAM_EXTERN)
4898  elog(ERROR, "unexpected paramkind: %d", (int) param->paramkind);
4899  if (param->paramid <= 0 || param->paramid > context->nargs)
4900  elog(ERROR, "invalid paramid: %d", param->paramid);
4901 
4902  /* Count usage of parameter */
4903  context->usecounts[param->paramid - 1]++;
4904 
4905  /* Select the appropriate actual arg and replace the Param with it */
4906  /* We don't need to copy at this time (it'll get done later) */
4907  return list_nth(context->args, param->paramid - 1);
4908  }
4910  (void *) context);
4911 }

References substitute_actual_parameters_context::args, elog, ERROR, expression_tree_mutator, IsA, list_nth(), substitute_actual_parameters_context::nargs, PARAM_EXTERN, Param::paramid, Param::paramkind, and substitute_actual_parameters_context::usecounts.

Referenced by substitute_actual_parameters().

◆ substitute_actual_srf_parameters()

static Query * substitute_actual_srf_parameters ( Query expr,
int  nargs,
List args 
)
static

Definition at line 5326 of file clauses.c.

5327 {
5329 
5330  context.nargs = nargs;
5331  context.args = args;
5332  context.sublevels_up = 1;
5333 
5334  return query_tree_mutator(expr,
5336  &context,
5337  0);
5338 }
static Node * substitute_actual_srf_parameters_mutator(Node *node, substitute_actual_srf_parameters_context *context)
Definition: clauses.c:5341
#define query_tree_mutator(q, m, c, f)
Definition: nodeFuncs.h:158

References generate_unaccent_rules::args, substitute_actual_srf_parameters_context::args, substitute_actual_srf_parameters_context::nargs, query_tree_mutator, substitute_actual_srf_parameters_context::sublevels_up, and substitute_actual_srf_parameters_mutator().

Referenced by inline_set_returning_function().

◆ substitute_actual_srf_parameters_mutator()

static Node * substitute_actual_srf_parameters_mutator ( Node node,
substitute_actual_srf_parameters_context context 
)
static

Definition at line 5341 of file clauses.c.

5343 {
5344  Node *result;
5345 
5346  if (node == NULL)
5347  return NULL;
5348  if (IsA(node, Query))
5349  {
5350  context->sublevels_up++;
5351  result = (Node *) query_tree_mutator((Query *) node,
5353  (void *) context,
5354  0);
5355  context->sublevels_up--;
5356  return result;
5357  }
5358  if (IsA(node, Param))
5359  {
5360  Param *param = (Param *) node;
5361 
5362  if (param->paramkind == PARAM_EXTERN)
5363  {
5364  if (param->paramid <= 0 || param->paramid > context->nargs)
5365  elog(ERROR, "invalid paramid: %d", param->paramid);
5366 
5367  /*
5368  * Since the parameter is being inserted into a subquery, we must
5369  * adjust levels.
5370  */
5371  result = copyObject(list_nth(context->args, param->paramid - 1));
5372  IncrementVarSublevelsUp(result, context->sublevels_up, 0);
5373  return result;
5374  }
5375  }
5376  return expression_tree_mutator(node,
5378  (void *) context);
5379 }
void IncrementVarSublevelsUp(Node *node, int delta_sublevels_up, int min_sublevels_up)
Definition: rewriteManip.c:849

References substitute_actual_srf_parameters_context::args, copyObject, elog, ERROR, expression_tree_mutator, IncrementVarSublevelsUp(), IsA, list_nth(), substitute_actual_srf_parameters_context::nargs, PARAM_EXTERN, Param::paramid, Param::paramkind, query_tree_mutator, and substitute_actual_srf_parameters_context::sublevels_up.

Referenced by substitute_actual_srf_parameters().