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 "executor/execExpr.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "nodes/subscripting.h"
#include "nodes/supportnodes.h"
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
#include "optimizer/optimizer.h"
#include "optimizer/plancat.h"
#include "optimizer/planmain.h"
#include "parser/analyze.h"
#include "parser/parse_agg.h"
#include "parser/parse_coerce.h"
#include "parser/parse_func.h"
#include "rewrite/rewriteHandler.h"
#include "rewrite/rewriteManip.h"
#include "tcop/tcopprot.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/datum.h"
#include "utils/fmgroids.h"
#include "utils/json.h"
#include "utils/jsonb.h"
#include "utils/jsonpath.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
Include dependency graph for clauses.c:

Go to the source code of this file.

Data Structures

struct  eval_const_expressions_context
 
struct  substitute_actual_parameters_context
 
struct  substitute_actual_srf_parameters_context
 
struct  inline_error_callback_arg
 
struct  max_parallel_hazard_context
 

Macros

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

Functions

static bool contain_agg_clause_walker (Node *node, void *context)
 
static bool find_window_functions_walker (Node *node, WindowFuncLists *lists)
 
static bool contain_subplans_walker (Node *node, void *context)
 
static bool contain_mutable_functions_walker (Node *node, void *context)
 
static bool contain_volatile_functions_walker (Node *node, void *context)
 
static bool contain_volatile_functions_not_nextval_walker (Node *node, void *context)
 
static bool max_parallel_hazard_walker (Node *node, max_parallel_hazard_context *context)
 
static bool contain_nonstrict_functions_walker (Node *node, void *context)
 
static bool contain_exec_param_walker (Node *node, List *param_ids)
 
static bool contain_context_dependent_node (Node *clause)
 
static bool contain_context_dependent_node_walker (Node *node, int *flags)
 
static bool contain_leaked_vars_walker (Node *node, void *context)
 
static Relids find_nonnullable_rels_walker (Node *node, bool top_level)
 
static Listfind_nonnullable_vars_walker (Node *node, bool top_level)
 
static bool is_strict_saop (ScalarArrayOpExpr *expr, bool falseOK)
 
static bool convert_saop_to_hashed_saop_walker (Node *node, void *context)
 
static Nodeeval_const_expressions_mutator (Node *node, eval_const_expressions_context *context)
 
static bool contain_non_const_walker (Node *node, void *context)
 
static bool ece_function_is_safe (Oid funcid, eval_const_expressions_context *context)
 
static Listsimplify_or_arguments (List *args, eval_const_expressions_context *context, bool *haveNull, bool *forceTrue)
 
static Listsimplify_and_arguments (List *args, eval_const_expressions_context *context, bool *haveNull, bool *forceFalse)
 
static Nodesimplify_boolean_equality (Oid opno, List *args)
 
static Exprsimplify_function (Oid funcid, Oid result_type, int32 result_typmod, Oid result_collid, Oid input_collid, List **args_p, bool funcvariadic, bool process_args, bool allow_non_const, eval_const_expressions_context *context)
 
static Listreorder_function_arguments (List *args, int pronargs, HeapTuple func_tuple)
 
static Listadd_function_defaults (List *args, int pronargs, HeapTuple func_tuple)
 
static Listfetch_function_defaults (HeapTuple func_tuple)
 
static void recheck_cast_function_args (List *args, Oid result_type, Oid *proargtypes, int pronargs, HeapTuple func_tuple)
 
static Exprevaluate_function (Oid funcid, Oid result_type, int32 result_typmod, Oid result_collid, Oid input_collid, List *args, bool funcvariadic, HeapTuple func_tuple, eval_const_expressions_context *context)
 
static Exprinline_function (Oid funcid, Oid result_type, Oid result_collid, Oid input_collid, List *args, bool funcvariadic, HeapTuple func_tuple, eval_const_expressions_context *context)
 
static Nodesubstitute_actual_parameters (Node *expr, int nargs, List *args, int *usecounts)
 
static Nodesubstitute_actual_parameters_mutator (Node *node, substitute_actual_parameters_context *context)
 
static void sql_inline_error_callback (void *arg)
 
static Querysubstitute_actual_srf_parameters (Query *expr, int nargs, List *args)
 
static Nodesubstitute_actual_srf_parameters_mutator (Node *node, substitute_actual_srf_parameters_context *context)
 
static bool pull_paramids_walker (Node *node, Bitmapset **context)
 
bool contain_agg_clause (Node *clause)
 
bool contain_window_function (Node *clause)
 
WindowFuncListsfind_window_functions (Node *clause, Index maxWinRef)
 
double expression_returns_set_rows (PlannerInfo *root, Node *clause)
 
bool contain_subplans (Node *clause)
 
bool contain_mutable_functions (Node *clause)
 
static bool contain_mutable_functions_checker (Oid func_id, void *context)
 
bool contain_volatile_functions (Node *clause)
 
static bool contain_volatile_functions_checker (Oid func_id, void *context)
 
bool contain_volatile_functions_not_nextval (Node *clause)
 
static bool contain_volatile_functions_not_nextval_checker (Oid func_id, void *context)
 
char max_parallel_hazard (Query *parse)
 
bool is_parallel_safe (PlannerInfo *root, Node *node)
 
static bool max_parallel_hazard_test (char proparallel, max_parallel_hazard_context *context)
 
static bool max_parallel_hazard_checker (Oid func_id, void *context)
 
bool contain_nonstrict_functions (Node *clause)
 
static bool contain_nonstrict_functions_checker (Oid func_id, void *context)
 
bool contain_exec_param (Node *clause, List *param_ids)
 
bool contain_leaked_vars (Node *clause)
 
static bool contain_leaked_vars_checker (Oid func_id, void *context)
 
Relids find_nonnullable_rels (Node *clause)
 
Listfind_nonnullable_vars (Node *clause)
 
Listfind_forced_null_vars (Node *node)
 
Varfind_forced_null_var (Node *node)
 
bool is_pseudo_constant_clause (Node *clause)
 
bool is_pseudo_constant_clause_relids (Node *clause, Relids relids)
 
int NumRelids (PlannerInfo *root, Node *clause)
 
void CommuteOpExpr (OpExpr *clause)
 
static bool rowtype_field_matches (Oid rowtypeid, int fieldnum, Oid expectedtype, int32 expectedtypmod, Oid expectedcollation)
 
Nodeeval_const_expressions (PlannerInfo *root, Node *node)
 
void convert_saop_to_hashed_saop (Node *node)
 
Nodeestimate_expression_value (PlannerInfo *root, Node *node)
 
Listexpand_function_arguments (List *args, bool include_out_arguments, Oid result_type, HeapTuple func_tuple)
 
Exprevaluate_expr (Expr *expr, Oid result_type, int32 result_typmod, Oid result_collation)
 
Queryinline_set_returning_function (PlannerInfo *root, RangeTblEntry *rte)
 
Bitmapsetpull_paramids (Expr *expr)
 

Macro Definition Documentation

◆ CCDN_CASETESTEXPR_OK

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

Definition at line 1128 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 2321 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:4864
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
Definition: nodes.h:574

Definition at line 2325 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:2335
Node * expression_tree_mutator(Node *node, Node *(*mutator)(), void *context)
Definition: nodeFuncs.c:2815

Definition at line 2312 of file clauses.c.

◆ MIN_ARRAY_SIZE_FOR_HASHED_SAOP

#define MIN_ARRAY_SIZE_FOR_HASHED_SAOP   9

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

4208 {
4209  int nargsprovided = list_length(args);
4210  List *defaults;
4211  int ndelete;
4212 
4213  /* Get all the default expressions from the pg_proc tuple */
4214  defaults = fetch_function_defaults(func_tuple);
4215 
4216  /* Delete any unused defaults from the list */
4217  ndelete = nargsprovided + list_length(defaults) - pronargs;
4218  if (ndelete < 0)
4219  elog(ERROR, "not enough default arguments");
4220  if (ndelete > 0)
4221  defaults = list_delete_first_n(defaults, ndelete);
4222 
4223  /* And form the combined argument list, not modifying the input list */
4224  return list_concat_copy(args, defaults);
4225 }
static List * fetch_function_defaults(HeapTuple func_tuple)
Definition: clauses.c:4231
#define ERROR
Definition: elog.h:33
#define elog(elevel,...)
Definition: elog.h:218
List * list_delete_first_n(List *list, int n)
Definition: list.c:942
List * list_concat_copy(const List *list1, const List *list2)
Definition: list.c:577
static int list_length(const List *l)
Definition: pg_list.h:149
int16 pronargs
Definition: pg_proc.h:81
Definition: pg_list.h:51

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

2044 {
2045  Oid opoid;
2046  Node *temp;
2047 
2048  /* Sanity checks: caller is at fault if these fail */
2049  if (!is_opclause(clause) ||
2050  list_length(clause->args) != 2)
2051  elog(ERROR, "cannot commute non-binary-operator clause");
2052 
2053  opoid = get_commutator(clause->opno);
2054 
2055  if (!OidIsValid(opoid))
2056  elog(ERROR, "could not find commutator for operator %u",
2057  clause->opno);
2058 
2059  /*
2060  * modify the clause in-place!
2061  */
2062  clause->opno = opoid;
2063  clause->opfuncid = InvalidOid;
2064  /* opresulttype, opretset, opcollid, inputcollid need not change */
2065 
2066  temp = linitial(clause->args);
2067  linitial(clause->args) = lsecond(clause->args);
2068  lsecond(clause->args) = temp;
2069 }
#define OidIsValid(objectId)
Definition: c.h:710
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1490
static bool is_opclause(const void *clause)
Definition: nodeFuncs.h:64
#define linitial(l)
Definition: pg_list.h:174
#define lsecond(l)
Definition: pg_list.h:179
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
Oid opno
Definition: primnodes.h:551
List * args
Definition: primnodes.h:557
Oid opfuncid
Definition: primnodes.h:552

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

Referenced by get_switched_clauses().

◆ contain_agg_clause()

bool contain_agg_clause ( Node clause)

Definition at line 180 of file clauses.c.

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

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

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

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

1122 {
1123  int flags = 0;
1124 
1125  return contain_context_dependent_node_walker(clause, &flags);
1126 }
static bool contain_context_dependent_node_walker(Node *node, int *flags)
Definition: clauses.c:1131

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

1132 {
1133  if (node == NULL)
1134  return false;
1135  if (IsA(node, CaseTestExpr))
1136  return !(*flags & CCDN_CASETESTEXPR_OK);
1137  else if (IsA(node, CaseExpr))
1138  {
1139  CaseExpr *caseexpr = (CaseExpr *) node;
1140 
1141  /*
1142  * If this CASE doesn't have a test expression, then it doesn't create
1143  * a context in which CaseTestExprs should appear, so just fall
1144  * through and treat it as a generic expression node.
1145  */
1146  if (caseexpr->arg)
1147  {
1148  int save_flags = *flags;
1149  bool res;
1150 
1151  /*
1152  * Note: in principle, we could distinguish the various sub-parts
1153  * of a CASE construct and set the flag bit only for some of them,
1154  * since we are only expecting CaseTestExprs to appear in the
1155  * "expr" subtree of the CaseWhen nodes. But it doesn't really
1156  * seem worth any extra code. If there are any bare CaseTestExprs
1157  * elsewhere in the CASE, something's wrong already.
1158  */
1159  *flags |= CCDN_CASETESTEXPR_OK;
1160  res = expression_tree_walker(node,
1162  (void *) flags);
1163  *flags = save_flags;
1164  return res;
1165  }
1166  }
1167  else if (IsA(node, ArrayCoerceExpr))
1168  {
1169  ArrayCoerceExpr *ac = (ArrayCoerceExpr *) node;
1170  int save_flags;
1171  bool res;
1172 
1173  /* Check the array expression */
1174  if (contain_context_dependent_node_walker((Node *) ac->arg, flags))
1175  return true;
1176 
1177  /* Check the elemexpr, which is allowed to contain CaseTestExpr */
1178  save_flags = *flags;
1179  *flags |= CCDN_CASETESTEXPR_OK;
1181  flags);
1182  *flags = save_flags;
1183  return res;
1184  }
1186  (void *) flags);
1187 }
#define CCDN_CASETESTEXPR_OK
Definition: clauses.c:1128
Expr * elemexpr
Definition: primnodes.h:914
Expr * arg
Definition: primnodes.h:987

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

1080 {
1081  return contain_exec_param_walker(clause, param_ids);
1082 }
static bool contain_exec_param_walker(Node *node, List *param_ids)
Definition: clauses.c:1085

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

1086 {
1087  if (node == NULL)
1088  return false;
1089  if (IsA(node, Param))
1090  {
1091  Param *p = (Param *) node;
1092 
1093  if (p->paramkind == PARAM_EXEC &&
1094  list_member_int(param_ids, p->paramid))
1095  return true;
1096  }
1097  return expression_tree_walker(node, contain_exec_param_walker, param_ids);
1098 }
bool list_member_int(const List *list, int datum)
Definition: list.c:681
@ PARAM_EXEC
Definition: primnodes.h:268
int paramid
Definition: primnodes.h:277
ParamKind paramkind
Definition: primnodes.h:276

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

1206 {
1207  return contain_leaked_vars_walker(clause, NULL);
1208 }
static bool contain_leaked_vars_walker(Node *node, void *context)
Definition: clauses.c:1217

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

1212 {
1213  return !get_func_leakproof(func_id);
1214 }
bool get_func_leakproof(Oid funcid)
Definition: lsyscache.c:1818

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

1218 {
1219  if (node == NULL)
1220  return false;
1221 
1222  switch (nodeTag(node))
1223  {
1224  case T_Var:
1225  case T_Const:
1226  case T_Param:
1227  case T_ArrayExpr:
1228  case T_FieldSelect:
1229  case T_FieldStore:
1230  case T_NamedArgExpr:
1231  case T_BoolExpr:
1232  case T_RelabelType:
1233  case T_CollateExpr:
1234  case T_CaseExpr:
1235  case T_CaseTestExpr:
1236  case T_RowExpr:
1237  case T_SQLValueFunction:
1238  case T_NullTest:
1239  case T_BooleanTest:
1240  case T_NextValueExpr:
1241  case T_List:
1242 
1243  /*
1244  * We know these node types don't contain function calls; but
1245  * something further down in the node tree might.
1246  */
1247  break;
1248 
1249  case T_FuncExpr:
1250  case T_OpExpr:
1251  case T_DistinctExpr:
1252  case T_NullIfExpr:
1253  case T_ScalarArrayOpExpr:
1254  case T_CoerceViaIO:
1255  case T_ArrayCoerceExpr:
1256 
1257  /*
1258  * If node contains a leaky function call, and there's any Var
1259  * underneath it, reject.
1260  */
1262  context) &&
1263  contain_var_clause(node))
1264  return true;
1265  break;
1266 
1267  case T_SubscriptingRef:
1268  {
1269  SubscriptingRef *sbsref = (SubscriptingRef *) node;
1270  const SubscriptRoutines *sbsroutines;
1271 
1272  /* Consult the subscripting support method info */
1273  sbsroutines = getSubscriptingRoutines(sbsref->refcontainertype,
1274  NULL);
1275  if (!sbsroutines ||
1276  !(sbsref->refassgnexpr != NULL ?
1277  sbsroutines->store_leakproof :
1278  sbsroutines->fetch_leakproof))
1279  {
1280  /* Node is leaky, so reject if it contains Vars */
1281  if (contain_var_clause(node))
1282  return true;
1283  }
1284  }
1285  break;
1286 
1287  case T_RowCompareExpr:
1288  {
1289  /*
1290  * It's worth special-casing this because a leaky comparison
1291  * function only compromises one pair of row elements, which
1292  * might not contain Vars while others do.
1293  */
1294  RowCompareExpr *rcexpr = (RowCompareExpr *) node;
1295  ListCell *opid;
1296  ListCell *larg;
1297  ListCell *rarg;
1298 
1299  forthree(opid, rcexpr->opnos,
1300  larg, rcexpr->largs,
1301  rarg, rcexpr->rargs)
1302  {
1303  Oid funcid = get_opcode(lfirst_oid(opid));
1304 
1305  if (!get_func_leakproof(funcid) &&
1306  (contain_var_clause((Node *) lfirst(larg)) ||
1307  contain_var_clause((Node *) lfirst(rarg))))
1308  return true;
1309  }
1310  }
1311  break;
1312 
1313  case T_MinMaxExpr:
1314  {
1315  /*
1316  * MinMaxExpr is leakproof if the comparison function it calls
1317  * is leakproof.
1318  */
1319  MinMaxExpr *minmaxexpr = (MinMaxExpr *) node;
1320  TypeCacheEntry *typentry;
1321  bool leakproof;
1322 
1323  /* Look up the btree comparison function for the datatype */
1324  typentry = lookup_type_cache(minmaxexpr->minmaxtype,
1326  if (OidIsValid(typentry->cmp_proc))
1327  leakproof = get_func_leakproof(typentry->cmp_proc);
1328  else
1329  {
1330  /*
1331  * The executor will throw an error, but here we just
1332  * treat the missing function as leaky.
1333  */
1334  leakproof = false;
1335  }
1336 
1337  if (!leakproof &&
1338  contain_var_clause((Node *) minmaxexpr->args))
1339  return true;
1340  }
1341  break;
1342 
1343  case T_CurrentOfExpr:
1344 
1345  /*
1346  * WHERE CURRENT OF doesn't contain leaky function calls.
1347  * Moreover, it is essential that this is considered non-leaky,
1348  * since the planner must always generate a TID scan when CURRENT
1349  * OF is present -- cf. cost_tidscan.
1350  */
1351  return false;
1352 
1353  default:
1354 
1355  /*
1356  * If we don't recognize the node tag, assume it might be leaky.
1357  * This prevents an unexpected security hole if someone adds a new
1358  * node type that can call a function.
1359  */
1360  return true;
1361  }
1363  context);
1364 }
static bool contain_leaked_vars_checker(Oid func_id, void *context)
Definition: clauses.c:1211
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1266
const struct SubscriptRoutines * getSubscriptingRoutines(Oid typid, Oid *typelemp)
Definition: lsyscache.c:3087
bool check_functions_in_node(Node *node, check_function_callback checker, void *context)
Definition: nodeFuncs.c:1832
#define nodeTag(nodeptr)
Definition: nodes.h:578
@ T_FieldStore
Definition: nodes.h:175
@ T_List
Definition: nodes.h:317
@ T_FieldSelect
Definition: nodes.h:174
@ T_ArrayExpr
Definition: nodes.h:184
@ T_CollateExpr
Definition: nodes.h:180
@ T_BoolExpr
Definition: nodes.h:170
@ T_OpExpr
Definition: nodes.h:166
@ T_ScalarArrayOpExpr
Definition: nodes.h:169
@ T_CaseExpr
Definition: nodes.h:181
@ T_RelabelType
Definition: nodes.h:176
@ T_RowExpr
Definition: nodes.h:185
@ T_ArrayCoerceExpr
Definition: nodes.h:178
@ T_MinMaxExpr
Definition: nodes.h:188
@ T_CurrentOfExpr
Definition: nodes.h:196
@ T_BooleanTest
Definition: nodes.h:192
@ T_SQLValueFunction
Definition: nodes.h:189
@ T_NamedArgExpr
Definition: nodes.h:165
@ T_Const
Definition: nodes.h:158
@ T_CoerceViaIO
Definition: nodes.h:177
@ T_NextValueExpr
Definition: nodes.h:197
@ T_Param
Definition: nodes.h:159
@ T_DistinctExpr
Definition: nodes.h:167
@ T_FuncExpr
Definition: nodes.h:164
@ T_Var
Definition: nodes.h:157
@ T_RowCompareExpr
Definition: nodes.h:186
@ T_CaseTestExpr
Definition: nodes.h:183
@ T_NullTest
Definition: nodes.h:191
@ T_SubscriptingRef
Definition: nodes.h:163
@ T_NullIfExpr
Definition: nodes.h:168
#define lfirst(lc)
Definition: pg_list.h:169
#define forthree(cell1, list1, cell2, list2, cell3, list3)
Definition: pg_list.h:491
#define lfirst_oid(lc)
Definition: pg_list.h:171
List * args
Definition: primnodes.h:1159
Oid minmaxtype
Definition: primnodes.h:1155
Expr * refassgnexpr
Definition: primnodes.h:460
Oid refcontainertype
Definition: primnodes.h:448
TypeCacheEntry * lookup_type_cache(Oid type_id, int flags)
Definition: typcache.c:339
#define TYPECACHE_CMP_PROC
Definition: typcache.h:139
bool contain_var_clause(Node *node)
Definition: var.c:400

References MinMaxExpr::args, check_functions_in_node(), TypeCacheEntry::cmp_proc, contain_leaked_vars_checker(), contain_var_clause(), expression_tree_walker(), SubscriptRoutines::fetch_leakproof, forthree, get_func_leakproof(), get_opcode(), getSubscriptingRoutines(), RowCompareExpr::largs, lfirst, lfirst_oid, lookup_type_cache(), MinMaxExpr::minmaxtype, nodeTag, OidIsValid, RowCompareExpr::opnos, RowCompareExpr::rargs, SubscriptingRef::refassgnexpr, SubscriptingRef::refcontainertype, SubscriptRoutines::store_leakproof, T_ArrayCoerceExpr, T_ArrayExpr, T_BooleanTest, T_BoolExpr, T_CaseExpr, T_CaseTestExpr, T_CoerceViaIO, T_CollateExpr, T_Const, T_CurrentOfExpr, T_DistinctExpr, T_FieldSelect, T_FieldStore, T_FuncExpr, T_List, T_MinMaxExpr, T_NamedArgExpr, T_NextValueExpr, T_NullIfExpr, T_NullTest, T_OpExpr, T_Param, T_RelabelType, T_RowCompareExpr, T_RowExpr, T_ScalarArrayOpExpr, T_SQLValueFunction, T_SubscriptingRef, T_Var, and TYPECACHE_CMP_PROC.

Referenced by contain_leaked_vars().

◆ contain_mutable_functions()

◆ contain_mutable_functions_checker()

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

Definition at line 374 of file clauses.c.

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

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

381 {
382  if (node == NULL)
383  return false;
384  /* Check for mutable functions in node itself */
386  context))
387  return true;
388 
389  if (IsA(node, JsonConstructorExpr))
390  {
391  const JsonConstructorExpr *ctor = (JsonConstructorExpr *) node;
392  ListCell *lc;
393  bool is_jsonb =
395 
396  /* Check argument_type => json[b] conversions */
397  foreach(lc, ctor->args)
398  {
399  Oid typid = exprType(lfirst(lc));
400 
401  if (is_jsonb ?
402  !to_jsonb_is_immutable(typid) :
403  !to_json_is_immutable(typid))
404  return true;
405  }
406 
407  /* Check all subnodes */
408  }
409 
410  if (IsA(node, JsonExpr))
411  {
412  JsonExpr *jexpr = castNode(JsonExpr, node);
413  Const *cnst;
414 
415  if (!IsA(jexpr->path_spec, Const))
416  return true;
417 
418  cnst = castNode(Const, jexpr->path_spec);
419 
420  Assert(cnst->consttype == JSONPATHOID);
421  if (cnst->constisnull)
422  return false;
423 
425  jexpr->passing_names, jexpr->passing_values);
426  }
427 
428  if (IsA(node, SQLValueFunction))
429  {
430  /* all variants of SQLValueFunction are stable */
431  return true;
432  }
433 
434  if (IsA(node, NextValueExpr))
435  {
436  /* NextValueExpr is volatile */
437  return true;
438  }
439 
440  /*
441  * It should be safe to treat MinMaxExpr as immutable, because it will
442  * depend on a non-cross-type btree comparison function, and those should
443  * always be immutable. Treating XmlExpr as immutable is more dubious,
444  * and treating CoerceToDomain as immutable is outright dangerous. But we
445  * have done so historically, and changing this would probably cause more
446  * problems than it would fix. In practice, if you have a non-immutable
447  * domain constraint you are in for pain anyhow.
448  */
449 
450  /* Recurse to check arguments */
451  if (IsA(node, Query))
452  {
453  /* Recurse into subselects */
454  return query_tree_walker((Query *) node,
456  context, 0);
457  }
459  context);
460 }
static bool contain_mutable_functions_checker(Oid func_id, void *context)
Definition: clauses.c:374
bool to_json_is_immutable(Oid typoid)
Definition: json.c:758
bool to_jsonb_is_immutable(Oid typoid)
Definition: jsonb.c:1131
bool jspIsMutable(JsonPath *path, List *varnames, List *varexprs)
Definition: jsonpath.c:1321
#define DatumGetJsonPathP(d)
Definition: jsonpath.h:35
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2570
#define castNode(_type_, nodeptr)
Definition: nodes.h:642
@ JS_FORMAT_JSONB
Definition: primnodes.h:1277
Oid consttype
Definition: primnodes.h:224
Datum constvalue
Definition: primnodes.h:228
bool constisnull
Definition: primnodes.h:229
JsonReturning * returning
Definition: primnodes.h:1370
List * passing_values
Definition: primnodes.h:1459
List * passing_names
Definition: primnodes.h:1458
Node * path_spec
Definition: primnodes.h:1457
JsonFormatType format_type
Definition: primnodes.h:1319
JsonFormat * format
Definition: primnodes.h:1331

References JsonConstructorExpr::args, Assert(), castNode, check_functions_in_node(), Const::constisnull, Const::consttype, Const::constvalue, contain_mutable_functions_checker(), DatumGetJsonPathP, expression_tree_walker(), exprType(), JsonReturning::format, JsonFormat::format_type, IsA, JS_FORMAT_JSONB, jspIsMutable(), lfirst, JsonExpr::passing_names, JsonExpr::passing_values, JsonExpr::path_spec, 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 3617 of file clauses.c.

3618 {
3619  if (node == NULL)
3620  return false;
3621  if (IsA(node, Const))
3622  return false;
3623  if (IsA(node, List))
3624  return expression_tree_walker(node, contain_non_const_walker, context);
3625  /* Otherwise, abort the tree traversal and return true */
3626  return true;
3627 }
static bool contain_non_const_walker(Node *node, void *context)
Definition: clauses.c:3617

References expression_tree_walker(), and IsA.

◆ contain_nonstrict_functions()

bool contain_nonstrict_functions ( Node clause)

Definition at line 935 of file clauses.c.

936 {
937  return contain_nonstrict_functions_walker(clause, NULL);
938 }
static bool contain_nonstrict_functions_walker(Node *node, void *context)
Definition: clauses.c:947

References contain_nonstrict_functions_walker().

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

◆ contain_nonstrict_functions_checker()

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

Definition at line 941 of file clauses.c.

942 {
943  return !func_strict(func_id);
944 }
bool func_strict(Oid funcid)
Definition: lsyscache.c:1742

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

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

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

Referenced by contain_nonstrict_functions().

◆ contain_subplans()

bool contain_subplans ( Node clause)

Definition at line 333 of file clauses.c.

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

References contain_subplans_walker().

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

◆ contain_subplans_walker()

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

Definition at line 339 of file clauses.c.

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

References expression_tree_walker(), and IsA.

Referenced by contain_subplans().

◆ contain_volatile_functions()

◆ contain_volatile_functions_checker()

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

Definition at line 502 of file clauses.c.

503 {
504  return (func_volatile(func_id) == PROVOLATILE_VOLATILE);
505 }

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

604 {
606 }
static bool contain_volatile_functions_not_nextval_walker(Node *node, void *context)
Definition: clauses.c:616

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

610 {
611  return (func_id != F_NEXTVAL &&
612  func_volatile(func_id) == PROVOLATILE_VOLATILE);
613 }

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

617 {
618  if (node == NULL)
619  return false;
620  /* Check for volatile functions in node itself */
621  if (check_functions_in_node(node,
623  context))
624  return true;
625 
626  /*
627  * See notes in contain_mutable_functions_walker about why we treat
628  * MinMaxExpr, XmlExpr, and CoerceToDomain as immutable, while
629  * SQLValueFunction is stable. Hence, none of them are of interest here.
630  * Also, since we're intentionally ignoring nextval(), presumably we
631  * should ignore NextValueExpr.
632  */
633 
634  /* Recurse to check arguments */
635  if (IsA(node, Query))
636  {
637  /* Recurse into subselects */
638  return query_tree_walker((Query *) node,
640  context, 0);
641  }
642  return expression_tree_walker(node,
644  context);
645 }
static bool contain_volatile_functions_not_nextval_checker(Oid func_id, void *context)
Definition: clauses.c:609

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

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

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

Referenced by contain_volatile_functions().

◆ contain_window_function()

bool contain_window_function ( Node clause)

Definition at line 217 of file clauses.c.

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

References contain_windowfuncs().

Referenced by get_eclass_for_sort_expr(), and qual_is_pushdown_safe().

◆ convert_saop_to_hashed_saop()

void convert_saop_to_hashed_saop ( Node node)

Definition at line 2182 of file clauses.c.

2183 {
2184  (void) convert_saop_to_hashed_saop_walker(node, NULL);
2185 }
static bool convert_saop_to_hashed_saop_walker(Node *node, void *context)
Definition: clauses.c:2188

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

2189 {
2190  if (node == NULL)
2191  return false;
2192 
2193  if (IsA(node, ScalarArrayOpExpr))
2194  {
2195  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
2196  Expr *arrayarg = (Expr *) lsecond(saop->args);
2197  Oid lefthashfunc;
2198  Oid righthashfunc;
2199 
2200  if (arrayarg && IsA(arrayarg, Const) &&
2201  !((Const *) arrayarg)->constisnull)
2202  {
2203  if (saop->useOr)
2204  {
2205  if (get_op_hash_functions(saop->opno, &lefthashfunc, &righthashfunc) &&
2206  lefthashfunc == righthashfunc)
2207  {
2208  Datum arrdatum = ((Const *) arrayarg)->constvalue;
2209  ArrayType *arr = (ArrayType *) DatumGetPointer(arrdatum);
2210  int nitems;
2211 
2212  /*
2213  * Only fill in the hash functions if the array looks
2214  * large enough for it to be worth hashing instead of
2215  * doing a linear search.
2216  */
2217  nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr));
2218 
2219  if (nitems >= MIN_ARRAY_SIZE_FOR_HASHED_SAOP)
2220  {
2221  /* Looks good. Fill in the hash functions */
2222  saop->hashfuncid = lefthashfunc;
2223  }
2224  return true;
2225  }
2226  }
2227  else /* !saop->useOr */
2228  {
2229  Oid negator = get_negator(saop->opno);
2230 
2231  /*
2232  * Check if this is a NOT IN using an operator whose negator
2233  * is hashable. If so we can still build a hash table and
2234  * just ensure the lookup items are not in the hash table.
2235  */
2236  if (OidIsValid(negator) &&
2237  get_op_hash_functions(negator, &lefthashfunc, &righthashfunc) &&
2238  lefthashfunc == righthashfunc)
2239  {
2240  Datum arrdatum = ((Const *) arrayarg)->constvalue;
2241  ArrayType *arr = (ArrayType *) DatumGetPointer(arrdatum);
2242  int nitems;
2243 
2244  /*
2245  * Only fill in the hash functions if the array looks
2246  * large enough for it to be worth hashing instead of
2247  * doing a linear search.
2248  */
2249  nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr));
2250 
2251  if (nitems >= MIN_ARRAY_SIZE_FOR_HASHED_SAOP)
2252  {
2253  /* Looks good. Fill in the hash functions */
2254  saop->hashfuncid = lefthashfunc;
2255 
2256  /*
2257  * Also set the negfuncid. The executor will need
2258  * that to perform hashtable lookups.
2259  */
2260  saop->negfuncid = get_opcode(negator);
2261  }
2262  return true;
2263  }
2264  }
2265  }
2266  }
2267 
2269 }
#define ARR_NDIM(a)
Definition: array.h:283
#define ARR_DIMS(a)
Definition: array.h:287
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:76
#define MIN_ARRAY_SIZE_FOR_HASHED_SAOP
Definition: clauses.c:2165
bool get_op_hash_functions(Oid opno, RegProcedure *lhs_procno, RegProcedure *rhs_procno)
Definition: lsyscache.c:508
Oid get_negator(Oid opno)
Definition: lsyscache.c:1514
uintptr_t Datum
Definition: postgres.h:411
#define DatumGetPointer(X)
Definition: postgres.h:593

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

Referenced by convert_saop_to_hashed_saop().

◆ ece_function_is_safe()

static bool ece_function_is_safe ( Oid  funcid,
eval_const_expressions_context context 
)
static

Definition at line 3633 of file clauses.c.

3634 {
3635  char provolatile = func_volatile(funcid);
3636 
3637  /*
3638  * Ordinarily we are only allowed to simplify immutable functions. But for
3639  * purposes of estimation, we consider it okay to simplify functions that
3640  * are merely stable; the risk that the result might change from planning
3641  * time to execution time is worth taking in preference to not being able
3642  * to estimate the value at all.
3643  */
3644  if (provolatile == PROVOLATILE_IMMUTABLE)
3645  return true;
3646  if (context->estimate && provolatile == PROVOLATILE_STABLE)
3647  return true;
3648  return false;
3649 }

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

2291 {
2293 
2294  context.boundParams = root->glob->boundParams; /* bound Params */
2295  /* we do not need to mark the plan as depending on inlined functions */
2296  context.root = NULL;
2297  context.active_fns = NIL; /* nothing being recursively simplified */
2298  context.case_val = NULL; /* no CASE being examined */
2299  context.estimate = true; /* unsafe transformations OK */
2300  return eval_const_expressions_mutator(node, &context);
2301 }
#define NIL
Definition: pg_list.h:65
ParamListInfo boundParams
Definition: pathnodes.h:94
PlannerGlobal * glob
Definition: pathnodes.h:164
ParamListInfo boundParams
Definition: clauses.c:64

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

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

◆ eval_const_expressions()

Node* eval_const_expressions ( PlannerInfo root,
Node node 
)

◆ eval_const_expressions_mutator()

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

Definition at line 2335 of file clauses.c.

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

References WindowFunc::aggfilter, AND_EXPR, applyRelabelType(), arg, FieldSelect::arg, RelabelType::arg, CoerceViaIO::arg, ArrayCoerceExpr::arg, ConvertRowtypeExpr::arg, CollateExpr::arg, CaseExpr::arg, NullTest::arg, BooleanTest::arg, CoerceToDomain::arg, NullTest::argisrow, generate_unaccent_rules::args, WindowFunc::args, FuncExpr::args, OpExpr::args, BoolExpr::args, CaseExpr::args, RowExpr::args, CoalesceExpr::args, Assert(), BoolGetDatum, BoolExpr::boolop, BooleanTest::booltesttype, eval_const_expressions_context::boundParams, eval_const_expressions_context::case_val, CaseExpr::casecollid, CaseExpr::casetype, castNode, CoalesceExpr::coalescecollid, CoalesceExpr::coalescetype, COERCE_IMPLICIT_CAST, CoerceViaIO::coerceformat, CoerceToDomain::coercionformat, CollateExpr::collOid, Const::constisnull, Const::consttype, Const::constvalue, contain_mutable_functions(), ConvertRowtypeExpr::convertformat, copyObject, datumCopy(), DatumGetBool, CaseExpr::defresult, DomainHasConstraints(), ece_all_arguments_const, ece_evaluate_expr, ece_function_is_safe(), ece_generic_processing, ArrayCoerceExpr::elemexpr, elog, ERROR, eval_const_expressions_context::estimate, evaluate_expr(), expand_function_arguments(), CaseWhen::expr, exprCollation(), expression_tree_mutator(), exprType(), exprTypmod(), FieldSelect::fieldnum, JsonValueExpr::formatted_expr, FuncExpr::funccollid, FuncExpr::funcformat, FuncExpr::funcid, FuncExpr::funcresulttype, FuncExpr::funcretset, FuncExpr::funcvariadic, get_typlenbyval(), getTypeInputInfo(), getTypeOutputInfo(), HeapTupleIsValid, if(), WindowFunc::inputcollid, FuncExpr::inputcollid, OpExpr::inputcollid, Int32GetDatum, InvalidAttrNumber, InvalidOid, IS_FALSE, IS_NOT_FALSE, IS_NOT_NULL, IS_NOT_TRUE, IS_NOT_UNKNOWN, IS_NULL, IS_TRUE, IS_UNKNOWN, IsA, ParamExternData::isnull, lappend(), lfirst, lfirst_node, linitial, list_length(), list_make1, list_make3, list_nth(), Const::location, Param::location, WindowFunc::location, FuncExpr::location, OpExpr::location, RelabelType::location, CoerceViaIO::location, ConvertRowtypeExpr::location, CollateExpr::location, CaseExpr::location, CaseWhen::location, CoalesceExpr::location, NullTest::location, BooleanTest::location, CoerceToDomain::location, make_andclause(), make_orclause(), makeBoolConst(), makeConst(), makeNode, makeNullConst(), makeVar(), negate_clause(), NIL, nodeTag, NOT_EXPR, NullTest::nulltesttype, ParamListInfoData::numParams, ObjectIdGetDatum, OidIsValid, OpExpr::opcollid, OpExpr::opfuncid, ScalarArrayOpExpr::opfuncid, OpExpr::opno, OpExpr::opresulttype, OpExpr::opretset, OR_EXPR, PARAM_EXTERN, PARAM_FLAG_CONST, Param::paramcollid, ParamListInfoData::paramFetch, Param::paramid, Param::paramkind, ParamListInfoData::params, Param::paramtype, Param::paramtypmod, ParamExternData::pflags, PlaceHolderVar::phexpr, PROCOID, ParamExternData::ptype, JsonValueExpr::raw_expr, record_plan_type_dependency(), RelabelType::relabelformat, ReleaseSysCache(), CaseWhen::result, FieldSelect::resultcollid, RelabelType::resultcollid, CoerceViaIO::resultcollid, CoerceToDomain::resultcollid, FieldSelect::resulttype, RelabelType::resulttype, CoerceViaIO::resulttype, ConvertRowtypeExpr::resulttype, CoerceToDomain::resulttype, FieldSelect::resulttypmod, RelabelType::resulttypmod, CoerceToDomain::resulttypmod, eval_const_expressions_context::root, RowExpr::row_typeid, rowtype_field_matches(), SearchSysCache1(), set_opfuncid(), set_sa_opfuncid(), simplify_and_arguments(), simplify_boolean_equality(), simplify_function(), simplify_or_arguments(), T_AlternativeSubPlan, T_ArrayCoerceExpr, T_ArrayExpr, T_BooleanTest, T_BoolExpr, T_CaseExpr, T_CaseTestExpr, T_CoalesceExpr, T_CoerceToDomain, T_CoerceViaIO, T_CollateExpr, T_ConvertRowtypeExpr, T_DistinctExpr, T_FieldSelect, T_FuncExpr, T_JsonValueExpr, T_MinMaxExpr, T_NullIfExpr, T_NullTest, T_OpExpr, T_Param, T_PlaceHolderVar, T_RelabelType, T_RowExpr, T_ScalarArrayOpExpr, T_SQLValueFunction, T_SubPlan, T_SubscriptingRef, T_WindowFunc, SQLValueFunction::type, SQLValueFunction::typmod, ParamExternData::value, WindowFunc::winagg, WindowFunc::wincollid, WindowFunc::winfnoid, WindowFunc::winref, WindowFunc::winstar, and WindowFunc::wintype.

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

◆ evaluate_expr()

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

Definition at line 4864 of file clauses.c.

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

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

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

References arg, generate_unaccent_rules::args, FuncExpr::args, COERCE_EXPLICIT_CALL, eval_const_expressions_context::estimate, evaluate_expr(), FuncExpr::funccollid, FuncExpr::funcformat, FuncExpr::funcid, FuncExpr::funcresulttype, FuncExpr::funcretset, FuncExpr::funcvariadic, GETSTRUCT, FuncExpr::inputcollid, IsA, lfirst, FuncExpr::location, makeNode, and makeNullConst().

Referenced by simplify_function().

◆ expand_function_arguments()

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

Definition at line 4056 of file clauses.c.

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

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

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

◆ expression_returns_set_rows()

double expression_returns_set_rows ( PlannerInfo root,
Node clause 
)

Definition at line 292 of file clauses.c.

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

References clamp_row_est(), FuncExpr::funcid, FuncExpr::funcretset, get_function_rows(), IsA, OpExpr::opfuncid, OpExpr::opretset, and set_opfuncid().

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

◆ fetch_function_defaults()

static List * fetch_function_defaults ( HeapTuple  func_tuple)
static

Definition at line 4231 of file clauses.c.

4232 {
4233  List *defaults;
4234  Datum proargdefaults;
4235  bool isnull;
4236  char *str;
4237 
4238  /* The error cases here shouldn't happen, but check anyway */
4239  proargdefaults = SysCacheGetAttr(PROCOID, func_tuple,
4240  Anum_pg_proc_proargdefaults,
4241  &isnull);
4242  if (isnull)
4243  elog(ERROR, "not enough default arguments");
4244  str = TextDatumGetCString(proargdefaults);
4245  defaults = castNode(List, stringToNode(str));
4246  pfree(str);
4247  return defaults;
4248 }
#define TextDatumGetCString(d)
Definition: builtins.h:86
void pfree(void *pointer)
Definition: mcxt.c:1175
void * stringToNode(const char *str)
Definition: read.c:89

References castNode, elog, ERROR, pfree(), PROCOID, generate_unaccent_rules::str, stringToNode(), SysCacheGetAttr(), 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 1875 of file clauses.c.

1876 {
1877  if (node == NULL)
1878  return NULL;
1879  if (IsA(node, NullTest))
1880  {
1881  /* check for var IS NULL */
1882  NullTest *expr = (NullTest *) node;
1883 
1884  if (expr->nulltesttype == IS_NULL && !expr->argisrow)
1885  {
1886  Var *var = (Var *) expr->arg;
1887 
1888  if (var && IsA(var, Var) &&
1889  var->varlevelsup == 0)
1890  return var;
1891  }
1892  }
1893  else if (IsA(node, BooleanTest))
1894  {
1895  /* var IS UNKNOWN is equivalent to var IS NULL */
1896  BooleanTest *expr = (BooleanTest *) node;
1897 
1898  if (expr->booltesttype == IS_UNKNOWN)
1899  {
1900  Var *var = (Var *) expr->arg;
1901 
1902  if (var && IsA(var, Var) &&
1903  var->varlevelsup == 0)
1904  return var;
1905  }
1906  }
1907  return NULL;
1908 }
Index varlevelsup
Definition: primnodes.h:205

References NullTest::arg, BooleanTest::arg, NullTest::argisrow, 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 1816 of file clauses.c.

1817 {
1818  List *result = NIL;
1819  Var *var;
1820  ListCell *l;
1821 
1822  if (node == NULL)
1823  return NIL;
1824  /* Check single-clause cases using subroutine */
1825  var = find_forced_null_var(node);
1826  if (var)
1827  {
1828  result = list_make1(var);
1829  }
1830  /* Otherwise, handle AND-conditions */
1831  else if (IsA(node, List))
1832  {
1833  /*
1834  * At top level, we are examining an implicit-AND list: if any of the
1835  * arms produces FALSE-or-NULL then the result is FALSE-or-NULL.
1836  */
1837  foreach(l, (List *) node)
1838  {
1839  result = list_concat(result,
1841  }
1842  }
1843  else if (IsA(node, BoolExpr))
1844  {
1845  BoolExpr *expr = (BoolExpr *) node;
1846 
1847  /*
1848  * We don't bother considering the OR case, because it's fairly
1849  * unlikely anyone would write "v1 IS NULL OR v1 IS NULL". Likewise,
1850  * the NOT case isn't worth expending code on.
1851  */
1852  if (expr->boolop == AND_EXPR)
1853  {
1854  /* At top level we can just recurse (to the List case) */
1855  result = find_forced_null_vars((Node *) expr->args);
1856  }
1857  }
1858  return result;
1859 }
Var * find_forced_null_var(Node *node)
Definition: clauses.c:1875
List * find_forced_null_vars(Node *node)
Definition: clauses.c:1816
List * list_concat(List *list1, const List *list2)
Definition: list.c:540

References AND_EXPR, BoolExpr::args, BoolExpr::boolop, find_forced_null_var(), IsA, lfirst, list_concat(), list_make1, and NIL.

Referenced by reduce_outer_joins_pass2().

◆ find_nonnullable_rels()

Relids find_nonnullable_rels ( Node clause)

Definition at line 1398 of file clauses.c.

1399 {
1400  return find_nonnullable_rels_walker(clause, true);
1401 }
static Relids find_nonnullable_rels_walker(Node *node, bool top_level)
Definition: clauses.c:1404

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

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

References AND_EXPR, RelabelType::arg, CoerceViaIO::arg, ArrayCoerceExpr::arg, ConvertRowtypeExpr::arg, CollateExpr::arg, NullTest::arg, BooleanTest::arg, NullTest::argisrow, FuncExpr::args, OpExpr::args, ScalarArrayOpExpr::args, BoolExpr::args, bms_add_members(), bms_int_members(), bms_is_empty(), bms_join(), bms_make_singleton(), bms_membership(), BMS_SINGLETON, BoolExpr::boolop, BooleanTest::booltesttype, elog, ERROR, func_strict(), FuncExpr::funcid, IS_FALSE, IS_NOT_NULL, IS_NOT_UNKNOWN, is_strict_saop(), IS_TRUE, IsA, lfirst, NOT_EXPR, NullTest::nulltesttype, OpExpr::opfuncid, OR_EXPR, PlaceHolderVar::phexpr, PlaceHolderVar::phlevelsup, PlaceHolderVar::phrels, set_opfuncid(), Var::varlevelsup, and Var::varno.

Referenced by find_nonnullable_rels().

◆ find_nonnullable_vars()

List* find_nonnullable_vars ( Node clause)

Definition at line 1623 of file clauses.c.

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

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

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

References AND_EXPR, RelabelType::arg, CoerceViaIO::arg, ArrayCoerceExpr::arg, ConvertRowtypeExpr::arg, CollateExpr::arg, NullTest::arg, BooleanTest::arg, NullTest::argisrow, FuncExpr::args, OpExpr::args, ScalarArrayOpExpr::args, BoolExpr::args, BoolExpr::boolop, BooleanTest::booltesttype, elog, ERROR, func_strict(), FuncExpr::funcid, IS_FALSE, IS_NOT_NULL, IS_NOT_UNKNOWN, is_strict_saop(), IS_TRUE, IsA, lfirst, list_concat(), list_intersection(), list_make1, NIL, NOT_EXPR, NullTest::nulltesttype, OpExpr::opfuncid, OR_EXPR, PlaceHolderVar::phexpr, set_opfuncid(), and Var::varlevelsup.

Referenced by find_nonnullable_vars().

◆ find_window_functions()

WindowFuncLists* find_window_functions ( Node clause,
Index  maxWinRef 
)

Definition at line 230 of file clauses.c.

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

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

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

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

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, elog, ERROR, error_context_stack, eval_const_expressions_mutator(), exprCollation(), exprType(), FmgrHookIsNeeded, free_parsestate(), FuncExpr::funccollid, FuncExpr::funcformat, FuncExpr::funcid, FuncExpr::funcresulttype, FuncExpr::funcretset, FuncExpr::funcvariadic, get_expr_result_type(), GETSTRUCT, GetUserId(), heap_attisnull(), i, FuncExpr::inputcollid, 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, OidIsValid, ParseState::p_sourcetext, palloc0(), QualCost::per_tuple, pg_parse_query(), pg_proc_aclcheck(), prepare_sql_fn_parse_info(), ErrorContextCallback::previous, PROCOID, inline_error_callback_arg::proname, inline_error_callback_arg::prosrc, 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(), TextDatumGetCString, and transformTopLevelStmt().

Referenced by simplify_function().

◆ inline_set_returning_function()

Query* inline_set_returning_function ( PlannerInfo root,
RangeTblEntry rte 
)

Definition at line 4956 of file clauses.c.

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

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, elog, ERROR, error_context_stack, FmgrHookIsNeeded, RangeTblFunction::funccolcollations, RangeTblFunction::funccolnames, RangeTblFunction::funccoltypes, RangeTblFunction::funccoltypmods, RangeTblFunction::funcexpr, FuncExpr::funcid, RangeTblEntry::funcordinality, FuncExpr::funcresulttype, FuncExpr::funcretset, RangeTblEntry::functions, get_expr_result_type(), GETSTRUCT, GetUserId(), heap_attisnull(), HeapTupleIsValid, if(), IsA, linitial, linitial_node, list_length(), list_make1, MemoryContextDelete(), MemoryContextSwitchTo(), NameStr, ObjectIdGetDatum, pg_analyze_and_rewrite_withcb(), pg_parse_query(), pg_proc_aclcheck(), pg_rewrite_query(), prepare_sql_fn_parse_info(), ErrorContextCallback::previous, PROCOID, inline_error_callback_arg::proname, inline_error_callback_arg::prosrc, querytree(), record_plan_function_dependency(), ReleaseSysCache(), RTE_FUNCTION, RangeTblEntry::rtekind, SearchSysCache1(), sql_fn_parser_setup(), sql_inline_error_callback(), stringToNode(), substitute_actual_srf_parameters(), SysCacheGetAttr(), 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 683 of file clauses.c.

684 {
686  PlannerInfo *proot;
687  ListCell *l;
688 
689  /*
690  * Even if the original querytree contained nothing unsafe, we need to
691  * search the expression if we have generated any PARAM_EXEC Params while
692  * planning, because those are parallel-restricted and there might be one
693  * in this expression. But otherwise we don't need to look.
694  */
695  if (root->glob->maxParallelHazard == PROPARALLEL_SAFE &&
696  root->glob->paramExecTypes == NIL)
697  return true;
698  /* Else use max_parallel_hazard's search logic, but stop on RESTRICTED */
699  context.max_hazard = PROPARALLEL_SAFE;
700  context.max_interesting = PROPARALLEL_RESTRICTED;
701  context.safe_param_ids = NIL;
702 
703  /*
704  * The params that refer to the same or parent query level are considered
705  * parallel-safe. The idea is that we compute such params at Gather or
706  * Gather Merge node and pass their value to workers.
707  */
708  for (proot = root; proot != NULL; proot = proot->parent_root)
709  {
710  foreach(l, proot->init_plans)
711  {
712  SubPlan *initsubplan = (SubPlan *) lfirst(l);
713 
714  context.safe_param_ids = list_concat(context.safe_param_ids,
715  initsubplan->setParam);
716  }
717  }
718 
719  return !max_parallel_hazard_walker(node, &context);
720 }
static bool max_parallel_hazard_walker(Node *node, max_parallel_hazard_context *context)
Definition: clauses.c:759
char maxParallelHazard
Definition: pathnodes.h:130
List * paramExecTypes
Definition: pathnodes.h:114
List * init_plans
Definition: pathnodes.h:242
PlannerInfo * parent_root
Definition: pathnodes.h:168
List * setParam
Definition: primnodes.h:779

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, PlannerInfo::parent_root, max_parallel_hazard_context::safe_param_ids, and SubPlan::setParam.

Referenced by apply_projection_to_path(), build_join_rel(), 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 1986 of file clauses.c.

1987 {
1988  /*
1989  * We could implement this check in one recursive scan. But since the
1990  * check for volatile functions is both moderately expensive and unlikely
1991  * to fail, it seems better to look for Vars first and only check for
1992  * volatile functions if we find no Vars.
1993  */
1994  if (!contain_var_clause(clause) &&
1995  !contain_volatile_functions(clause))
1996  return true;
1997  return false;
1998 }

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

2007 {
2008  if (bms_is_empty(relids) &&
2009  !contain_volatile_functions(clause))
2010  return true;
2011  return false;
2012 }

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

1925 {
1926  Node *rightop;
1927 
1928  /* The contained operator must be strict. */
1929  set_sa_opfuncid(expr);
1930  if (!func_strict(expr->opfuncid))
1931  return false;
1932  /* If ANY and falseOK, that's all we need to check. */
1933  if (expr->useOr && falseOK)
1934  return true;
1935  /* Else, we have to see if the array is provably non-empty. */
1936  Assert(list_length(expr->args) == 2);
1937  rightop = (Node *) lsecond(expr->args);
1938  if (rightop && IsA(rightop, Const))
1939  {
1940  Datum arraydatum = ((Const *) rightop)->constvalue;
1941  bool arrayisnull = ((Const *) rightop)->constisnull;
1942  ArrayType *arrayval;
1943  int nitems;
1944 
1945  if (arrayisnull)
1946  return false;
1947  arrayval = DatumGetArrayTypeP(arraydatum);
1948  nitems = ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
1949  if (nitems > 0)
1950  return true;
1951  }
1952  else if (rightop && IsA(rightop, ArrayExpr))
1953  {
1954  ArrayExpr *arrayexpr = (ArrayExpr *) rightop;
1955 
1956  if (arrayexpr->elements != NIL && !arrayexpr->multidims)
1957  return true;
1958  }
1959  return false;
1960 }
bool multidims
Definition: primnodes.h:1047
List * elements
Definition: primnodes.h:1046

References ScalarArrayOpExpr::args, ARR_DIMS, ARR_NDIM, ArrayGetNItems(),