PostgreSQL Source Code  git master
clauses.c File Reference
#include "postgres.h"
#include "access/htup_details.h"
#include "catalog/pg_aggregate.h"
#include "catalog/pg_class.h"
#include "catalog/pg_language.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "executor/executor.h"
#include "executor/functions.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/multibitmapset.h"
#include "nodes/nodeFuncs.h"
#include "nodes/subscripting.h"
#include "nodes/supportnodes.h"
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
#include "optimizer/optimizer.h"
#include "optimizer/plancat.h"
#include "optimizer/planmain.h"
#include "parser/analyze.h"
#include "parser/parse_agg.h"
#include "parser/parse_coerce.h"
#include "parser/parse_func.h"
#include "rewrite/rewriteHandler.h"
#include "rewrite/rewriteManip.h"
#include "tcop/tcopprot.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/datum.h"
#include "utils/fmgroids.h"
#include "utils/json.h"
#include "utils/jsonb.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
Include dependency graph for clauses.c:

Go to the source code of this file.

Data Structures

struct  eval_const_expressions_context
 
struct  substitute_actual_parameters_context
 
struct  substitute_actual_srf_parameters_context
 
struct  inline_error_callback_arg
 
struct  max_parallel_hazard_context
 

Macros

#define CCDN_CASETESTEXPR_OK   0x0001 /* CaseTestExpr okay here? */
 
#define MIN_ARRAY_SIZE_FOR_HASHED_SAOP   9
 
#define ece_generic_processing(node)
 
#define ece_all_arguments_const(node)    (!expression_tree_walker((Node *) (node), contain_non_const_walker, NULL))
 
#define ece_evaluate_expr(node)
 

Functions

static bool contain_agg_clause_walker (Node *node, void *context)
 
static bool find_window_functions_walker (Node *node, WindowFuncLists *lists)
 
static bool contain_subplans_walker (Node *node, void *context)
 
static bool contain_mutable_functions_walker (Node *node, void *context)
 
static bool contain_volatile_functions_walker (Node *node, void *context)
 
static bool contain_volatile_functions_not_nextval_walker (Node *node, void *context)
 
static bool max_parallel_hazard_walker (Node *node, max_parallel_hazard_context *context)
 
static bool contain_nonstrict_functions_walker (Node *node, void *context)
 
static bool contain_exec_param_walker (Node *node, List *param_ids)
 
static bool contain_context_dependent_node (Node *clause)
 
static bool contain_context_dependent_node_walker (Node *node, int *flags)
 
static bool contain_leaked_vars_walker (Node *node, void *context)
 
static Relids find_nonnullable_rels_walker (Node *node, bool top_level)
 
static Listfind_nonnullable_vars_walker (Node *node, bool top_level)
 
static bool is_strict_saop (ScalarArrayOpExpr *expr, bool falseOK)
 
static bool convert_saop_to_hashed_saop_walker (Node *node, void *context)
 
static Nodeeval_const_expressions_mutator (Node *node, eval_const_expressions_context *context)
 
static bool contain_non_const_walker (Node *node, void *context)
 
static bool ece_function_is_safe (Oid funcid, eval_const_expressions_context *context)
 
static Listsimplify_or_arguments (List *args, eval_const_expressions_context *context, bool *haveNull, bool *forceTrue)
 
static Listsimplify_and_arguments (List *args, eval_const_expressions_context *context, bool *haveNull, bool *forceFalse)
 
static Nodesimplify_boolean_equality (Oid opno, List *args)
 
static Exprsimplify_function (Oid funcid, Oid result_type, int32 result_typmod, Oid result_collid, Oid input_collid, List **args_p, bool funcvariadic, bool process_args, bool allow_non_const, eval_const_expressions_context *context)
 
static Listreorder_function_arguments (List *args, int pronargs, HeapTuple func_tuple)
 
static Listadd_function_defaults (List *args, int pronargs, HeapTuple func_tuple)
 
static Listfetch_function_defaults (HeapTuple func_tuple)
 
static void recheck_cast_function_args (List *args, Oid result_type, Oid *proargtypes, int pronargs, HeapTuple func_tuple)
 
static Exprevaluate_function (Oid funcid, Oid result_type, int32 result_typmod, Oid result_collid, Oid input_collid, List *args, bool funcvariadic, HeapTuple func_tuple, eval_const_expressions_context *context)
 
static Exprinline_function (Oid funcid, Oid result_type, Oid result_collid, Oid input_collid, List *args, bool funcvariadic, HeapTuple func_tuple, eval_const_expressions_context *context)
 
static Nodesubstitute_actual_parameters (Node *expr, int nargs, List *args, int *usecounts)
 
static Nodesubstitute_actual_parameters_mutator (Node *node, substitute_actual_parameters_context *context)
 
static void sql_inline_error_callback (void *arg)
 
static Querysubstitute_actual_srf_parameters (Query *expr, int nargs, List *args)
 
static Nodesubstitute_actual_srf_parameters_mutator (Node *node, substitute_actual_srf_parameters_context *context)
 
static bool pull_paramids_walker (Node *node, Bitmapset **context)
 
bool contain_agg_clause (Node *clause)
 
bool contain_window_function (Node *clause)
 
WindowFuncListsfind_window_functions (Node *clause, Index maxWinRef)
 
double expression_returns_set_rows (PlannerInfo *root, Node *clause)
 
bool contain_subplans (Node *clause)
 
bool contain_mutable_functions (Node *clause)
 
static bool contain_mutable_functions_checker (Oid func_id, void *context)
 
bool contain_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 1169 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 2409 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:4943
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:43
Definition: nodes.h:129

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

Definition at line 2400 of file clauses.c.

◆ MIN_ARRAY_SIZE_FOR_HASHED_SAOP

#define MIN_ARRAY_SIZE_FOR_HASHED_SAOP   9

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

4297 {
4298  int nargsprovided = list_length(args);
4299  List *defaults;
4300  int ndelete;
4301 
4302  /* Get all the default expressions from the pg_proc tuple */
4303  defaults = fetch_function_defaults(func_tuple);
4304 
4305  /* Delete any unused defaults from the list */
4306  ndelete = nargsprovided + list_length(defaults) - pronargs;
4307  if (ndelete < 0)
4308  elog(ERROR, "not enough default arguments");
4309  if (ndelete > 0)
4310  defaults = list_delete_first_n(defaults, ndelete);
4311 
4312  /* And form the combined argument list, not modifying the input list */
4313  return list_concat_copy(args, defaults);
4314 }
static List * fetch_function_defaults(HeapTuple func_tuple)
Definition: clauses.c:4320
#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 2130 of file clauses.c.

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

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

Referenced by get_switched_clauses().

◆ contain_agg_clause()

bool contain_agg_clause ( Node clause)

Definition at line 179 of file clauses.c.

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

References contain_agg_clause_walker().

Referenced by get_eclass_for_sort_expr(), and subquery_planner().

◆ contain_agg_clause_walker()

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

Definition at line 185 of file clauses.c.

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

1163 {
1164  int flags = 0;
1165 
1166  return contain_context_dependent_node_walker(clause, &flags);
1167 }
static bool contain_context_dependent_node_walker(Node *node, int *flags)
Definition: clauses.c:1172

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

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

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

1121 {
1122  return contain_exec_param_walker(clause, param_ids);
1123 }
static bool contain_exec_param_walker(Node *node, List *param_ids)
Definition: clauses.c:1126

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

1127 {
1128  if (node == NULL)
1129  return false;
1130  if (IsA(node, Param))
1131  {
1132  Param *p = (Param *) node;
1133 
1134  if (p->paramkind == PARAM_EXEC &&
1135  list_member_int(param_ids, p->paramid))
1136  return true;
1137  }
1138  return expression_tree_walker(node, contain_exec_param_walker, param_ids);
1139 }
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 1246 of file clauses.c.

1247 {
1248  return contain_leaked_vars_walker(clause, NULL);
1249 }
static bool contain_leaked_vars_walker(Node *node, void *context)
Definition: clauses.c:1258

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

1253 {
1254  return !get_func_leakproof(func_id);
1255 }
bool get_func_leakproof(Oid funcid)
Definition: lsyscache.c:1814

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

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

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

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

379 {
380  return (func_volatile(func_id) != PROVOLATILE_IMMUTABLE);
381 }
char func_volatile(Oid funcid)
Definition: lsyscache.c:1757

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

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

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

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

References expression_tree_walker, and IsA.

◆ contain_nonstrict_functions()

bool contain_nonstrict_functions ( Node clause)

Definition at line 976 of file clauses.c.

977 {
978  return contain_nonstrict_functions_walker(clause, NULL);
979 }
static bool contain_nonstrict_functions_walker(Node *node, void *context)
Definition: clauses.c:988

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

983 {
984  return !func_strict(func_id);
985 }
bool func_strict(Oid funcid)
Definition: lsyscache.c:1738

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

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

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

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

References expression_tree_walker, and IsA.

Referenced by contain_subplans().

◆ contain_volatile_functions()

◆ contain_volatile_functions_after_planning()

bool contain_volatile_functions_after_planning ( Expr expr)

Definition at line 642 of file clauses.c.

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

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

528 {
529  return (func_volatile(func_id) == PROVOLATILE_VOLATILE);
530 }

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

657 {
659 }
static bool contain_volatile_functions_not_nextval_walker(Node *node, void *context)
Definition: clauses.c:669

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

663 {
664  return (func_id != F_NEXTVAL &&
665  func_volatile(func_id) == PROVOLATILE_VOLATILE);
666 }

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

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

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

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

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

References contain_windowfuncs().

Referenced by get_eclass_for_sort_expr().

◆ convert_saop_to_hashed_saop()

void convert_saop_to_hashed_saop ( Node node)

Definition at line 2270 of file clauses.c.

2271 {
2272  (void) convert_saop_to_hashed_saop_walker(node, NULL);
2273 }
static bool convert_saop_to_hashed_saop_walker(Node *node, void *context)
Definition: clauses.c:2276

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

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

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

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

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

References eval_const_expressions_context::active_fns, eval_const_expressions_context::boundParams, eval_const_expressions_context::case_val, eval_const_expressions_context::estimate, eval_const_expressions_mutator(), PlannerInfo::glob, NIL, and eval_const_expressions_context::root.

Referenced by array_unnest_support(), bernoulli_samplescangetsamplesize(), clause_selectivity_ext(), generate_series_int4_support(), generate_series_int8_support(), get_restriction_variable(), gincost_opexpr(), gincost_scalararrayopexpr(), preprocess_limit(), scalararraysel(), system_rows_samplescangetsamplesize(), system_samplescangetsamplesize(), and system_time_samplescangetsamplesize().

◆ eval_const_expressions()

◆ eval_const_expressions_mutator()

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

Definition at line 2423 of file clauses.c.

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

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

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

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

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

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

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

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

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

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

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

1961 {
1962  if (node == NULL)
1963  return NULL;
1964  if (IsA(node, NullTest))
1965  {
1966  /* check for var IS NULL */
1967  NullTest *expr = (NullTest *) node;
1968 
1969  if (expr->nulltesttype == IS_NULL && !expr->argisrow)
1970  {
1971  Var *var = (Var *) expr->arg;
1972 
1973  if (var && IsA(var, Var) &&
1974  var->varlevelsup == 0)
1975  return var;
1976  }
1977  }
1978  else if (IsA(node, BooleanTest))
1979  {
1980  /* var IS UNKNOWN is equivalent to var IS NULL */
1981  BooleanTest *expr = (BooleanTest *) node;
1982 
1983  if (expr->booltesttype == IS_UNKNOWN)
1984  {
1985  Var *var = (Var *) expr->arg;
1986 
1987  if (var && IsA(var, Var) &&
1988  var->varlevelsup == 0)
1989  return var;
1990  }
1991  }
1992  return NULL;
1993 }
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 1899 of file clauses.c.

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

1440 {
1441  return find_nonnullable_rels_walker(clause, true);
1442 }
static Relids find_nonnullable_rels_walker(Node *node, bool top_level)
Definition: clauses.c:1445

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

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

1691 {
1692  return find_nonnullable_vars_walker(clause, true);
1693 }
static List * find_nonnullable_vars_walker(Node *node, bool top_level)
Definition: clauses.c:1696

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

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

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

Referenced by find_nonnullable_vars().

◆ find_window_functions()

WindowFuncLists* find_window_functions ( Node clause,
Index  maxWinRef 
)

Definition at line 229 of file clauses.c.

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

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

Referenced by grouping_planner().

◆ find_window_functions_walker()

static bool find_window_functions_walker ( Node node,
WindowFuncLists lists 
)
static

Definition at line 241 of file clauses.c.

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

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

References ACL_EXECUTE, ACLCHECK_OK, eval_const_expressions_context::active_fns, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, arg, CollateExpr::arg, ErrorContextCallback::arg, generate_unaccent_rules::args, FuncExpr::args, ErrorContextCallback::callback, castNode, check_sql_fn_retval(), CMD_SELECT, COERCE_EXPLICIT_CALL, CollateExpr::collOid, contain_context_dependent_node(), contain_mutable_functions(), contain_nonstrict_functions(), contain_subplans(), contain_volatile_functions(), copyObject, cost_qual_eval(), cpu_operator_cost, CurrentMemoryContext, error_context_stack, eval_const_expressions_mutator(), exprCollation(), exprType(), FmgrHookIsNeeded, free_parsestate(), FuncExpr::funcid, get_expr_result_type(), GETSTRUCT, GetUserId(), heap_attisnull(), i, IsA, lappend_oid(), lfirst, linitial, linitial_node, list_delete_last(), list_length(), list_make1, list_member_oid(), FuncExpr::location, CollateExpr::location, make_parsestate(), makeNode, MemoryContextDelete(), MemoryContextSwitchTo(), NameStr, object_aclcheck(), OidIsValid, ParseState::p_sourcetext, palloc0(), QualCost::per_tuple, pg_parse_query(), prepare_sql_fn_parse_info(), ErrorContextCallback::previous, 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 5035 of file clauses.c.

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

References ACL_EXECUTE, ACLCHECK_OK, AcquireRewriteLocks(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, ErrorContextCallback::arg, FuncExpr::args, Assert(), BuildDescFromLists(), ErrorContextCallback::callback, castNode, check_sql_fn_retval(), check_stack_depth(), CMD_SELECT, contain_subplans(), contain_volatile_functions(), copyObject, CurrentMemoryContext, PlannerGlobal::dependsOnRole, elog, ERROR, error_context_stack, FmgrHookIsNeeded, RangeTblFunction::funcexpr, FuncExpr::funcid, RangeTblEntry::funcordinality, RangeTblEntry::functions, get_expr_result_type(), GETSTRUCT, GetUserId(), PlannerInfo::glob, heap_attisnull(), HeapTupleIsValid, if(), IsA, linitial, linitial_node, list_length(), list_make1, MemoryContextDelete(), MemoryContextSwitchTo(), NameStr, object_aclcheck(), ObjectIdGetDatum(), pg_analyze_and_rewrite_withcb(), pg_parse_query(), pg_rewrite_query(), prepare_sql_fn_parse_info(), ErrorContextCallback::previous, 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 736 of file clauses.c.

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

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

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

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

2092 {
2093  if (bms_is_empty(relids) &&
2094  !contain_volatile_functions(clause))
2095  return true;
2096  return false;
2097 }

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

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

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

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

806 {
807  return max_parallel_hazard_test(func_parallel(func_id),
808  (max_parallel_hazard_context *) context);
809 }
static bool max_parallel_hazard_test(char proparallel, max_parallel_hazard_context *context)
Definition: clauses.c:777
char func_parallel(Oid funcid)
Definition: lsyscache.c:1776

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

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

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

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

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

2114 {
2115  int result;
2116  Relids varnos = pull_varnos(root, clause);
2117 
2118  varnos = bms_del_members(varnos, root->outer_join_rels);
2119  result = bms_num_members(varnos);
2120  bms_free(varnos);
2121  return result;
2122 }
void bms_free(Bitmapset *a)
Definition: bitmapset.c:252
int bms_num_members(const Bitmapset *a)
Definition: bitmapset.c:764
Bitmapset * bms_del_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:1174
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 5383 of file clauses.c.

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

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

5394 {
5395  if (node == NULL)
5396  return false;
5397  if (IsA(node, Param))
5398  {
5399  Param *param = (Param *) node;