PostgreSQL Source Code  git master
clauses.c File Reference
#include "postgres.h"
#include "access/htup_details.h"
#include "catalog/pg_aggregate.h"
#include "catalog/pg_class.h"
#include "catalog/pg_language.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "executor/executor.h"
#include "executor/functions.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "nodes/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/rewriteManip.h"
#include "tcop/tcopprot.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/datum.h"
#include "utils/fmgroids.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
Include dependency graph for clauses.c:

Go to the source code of this file.

Data Structures

struct  get_agg_clause_costs_context
 
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 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 get_agg_clause_costs_walker (Node *node, get_agg_clause_costs_context *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_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 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, HeapTuple func_tuple)
 
static Listadd_function_defaults (List *args, HeapTuple func_tuple)
 
static Listfetch_function_defaults (HeapTuple func_tuple)
 
static void recheck_cast_function_args (List *args, Oid result_type, HeapTuple func_tuple)
 
static Exprevaluate_function (Oid funcid, Oid result_type, int32 result_typmod, Oid result_collid, Oid input_collid, List *args, bool funcvariadic, HeapTuple func_tuple, eval_const_expressions_context *context)
 
static Exprinline_function (Oid funcid, Oid result_type, Oid result_collid, Oid input_collid, List *args, bool funcvariadic, HeapTuple func_tuple, eval_const_expressions_context *context)
 
static Nodesubstitute_actual_parameters (Node *expr, int nargs, List *args, int *usecounts)
 
static Nodesubstitute_actual_parameters_mutator (Node *node, substitute_actual_parameters_context *context)
 
static void sql_inline_error_callback (void *arg)
 
static Querysubstitute_actual_srf_parameters (Query *expr, int nargs, List *args)
 
static Nodesubstitute_actual_srf_parameters_mutator (Node *node, substitute_actual_srf_parameters_context *context)
 
bool contain_agg_clause (Node *clause)
 
void get_agg_clause_costs (PlannerInfo *root, Node *clause, AggSplit aggsplit, AggClauseCosts *costs)
 
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_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 (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)
 
Nodeestimate_expression_value (PlannerInfo *root, Node *node)
 
Listexpand_function_arguments (List *args, Oid result_type, HeapTuple func_tuple)
 
Exprevaluate_expr (Expr *expr, Oid result_type, int32 result_typmod, Oid result_collation)
 
Queryinline_set_returning_function (PlannerInfo *root, RangeTblEntry *rte)
 

Macro Definition Documentation

◆ CCDN_CASETESTEXPR_OK

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

Definition at line 1249 of file clauses.c.

Referenced by contain_context_dependent_node_walker().

◆ ece_all_arguments_const

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

Definition at line 2316 of file clauses.c.

Referenced by eval_const_expressions_mutator().

◆ ece_evaluate_expr

#define ece_evaluate_expr (   node)
Value:
((Node *) evaluate_expr((Expr *) (node), \
exprType((Node *) (node)), \
exprTypmod((Node *) (node)), \
exprCollation((Node *) (node))))
Expr * evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod, Oid result_collation)
Definition: clauses.c:4788
Definition: nodes.h:525
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41

Definition at line 2320 of file clauses.c.

Referenced by eval_const_expressions_mutator().

◆ ece_generic_processing

#define ece_generic_processing (   node)
Value:
(void *) context)
Node * expression_tree_mutator(Node *node, Node *(*mutator)(), void *context)
Definition: nodeFuncs.c:2516
Definition: nodes.h:525
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2330

Definition at line 2307 of file clauses.c.

Referenced by eval_const_expressions_mutator().

Function Documentation

◆ add_function_defaults()

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

Definition at line 4160 of file clauses.c.

References elog, ERROR, fetch_function_defaults(), GETSTRUCT, list_concat_copy(), list_copy_tail(), and list_length().

Referenced by expand_function_arguments().

4161 {
4162  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4163  int nargsprovided = list_length(args);
4164  List *defaults;
4165  int ndelete;
4166 
4167  /* Get all the default expressions from the pg_proc tuple */
4168  defaults = fetch_function_defaults(func_tuple);
4169 
4170  /* Delete any unused defaults from the list */
4171  ndelete = nargsprovided + list_length(defaults) - funcform->pronargs;
4172  if (ndelete < 0)
4173  elog(ERROR, "not enough default arguments");
4174  if (ndelete > 0)
4175  defaults = list_copy_tail(defaults, ndelete);
4176 
4177  /* And form the combined argument list, not modifying the input list */
4178  return list_concat_copy(args, defaults);
4179 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
List * list_copy_tail(const List *oldlist, int nskip)
Definition: list.c:1423
#define ERROR
Definition: elog.h:43
List * list_concat_copy(const List *list1, const List *list2)
Definition: list.c:553
static List * fetch_function_defaults(HeapTuple func_tuple)
Definition: clauses.c:4185
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:133
static int list_length(const List *l)
Definition: pg_list.h:169
#define elog(elevel,...)
Definition: elog.h:228
Definition: pg_list.h:50

◆ CommuteOpExpr()

void CommuteOpExpr ( OpExpr clause)

Definition at line 2145 of file clauses.c.

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

Referenced by get_switched_clauses().

2146 {
2147  Oid opoid;
2148  Node *temp;
2149 
2150  /* Sanity checks: caller is at fault if these fail */
2151  if (!is_opclause(clause) ||
2152  list_length(clause->args) != 2)
2153  elog(ERROR, "cannot commute non-binary-operator clause");
2154 
2155  opoid = get_commutator(clause->opno);
2156 
2157  if (!OidIsValid(opoid))
2158  elog(ERROR, "could not find commutator for operator %u",
2159  clause->opno);
2160 
2161  /*
2162  * modify the clause in-place!
2163  */
2164  clause->opno = opoid;
2165  clause->opfuncid = InvalidOid;
2166  /* opresulttype, opretset, opcollid, inputcollid need not change */
2167 
2168  temp = linitial(clause->args);
2169  linitial(clause->args) = lsecond(clause->args);
2170  lsecond(clause->args) = temp;
2171 }
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1311
Definition: nodes.h:525
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:645
#define lsecond(l)
Definition: pg_list.h:200
#define linitial(l)
Definition: pg_list.h:195
#define ERROR
Definition: elog.h:43
Oid opfuncid
Definition: primnodes.h:517
#define InvalidOid
Definition: postgres_ext.h:36
static int list_length(const List *l)
Definition: pg_list.h:169
#define elog(elevel,...)
Definition: elog.h:228
Oid opno
Definition: primnodes.h:516
static bool is_opclause(const void *clause)
Definition: nodeFuncs.h:63
List * args
Definition: primnodes.h:522

◆ contain_agg_clause()

bool contain_agg_clause ( Node clause)

Definition at line 178 of file clauses.c.

References contain_agg_clause_walker().

Referenced by get_eclass_for_sort_expr(), and subquery_planner().

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

◆ contain_agg_clause_walker()

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

Definition at line 184 of file clauses.c.

References Assert, expression_tree_walker(), and IsA.

Referenced by contain_agg_clause().

185 {
186  if (node == NULL)
187  return false;
188  if (IsA(node, Aggref))
189  {
190  Assert(((Aggref *) node)->agglevelsup == 0);
191  return true; /* abort the tree traversal and return true */
192  }
193  if (IsA(node, GroupingFunc))
194  {
195  Assert(((GroupingFunc *) node)->agglevelsup == 0);
196  return true; /* abort the tree traversal and return true */
197  }
198  Assert(!IsA(node, SubLink));
199  return expression_tree_walker(node, contain_agg_clause_walker, context);
200 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
static bool contain_agg_clause_walker(Node *node, void *context)
Definition: clauses.c:184
#define Assert(condition)
Definition: c.h:739
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1839

◆ contain_context_dependent_node()

static bool contain_context_dependent_node ( Node clause)
static

Definition at line 1242 of file clauses.c.

References contain_context_dependent_node_walker().

Referenced by inline_function().

1243 {
1244  int flags = 0;
1245 
1246  return contain_context_dependent_node_walker(clause, &flags);
1247 }
static bool contain_context_dependent_node_walker(Node *node, int *flags)
Definition: clauses.c:1252

◆ contain_context_dependent_node_walker()

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

Definition at line 1252 of file clauses.c.

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

Referenced by contain_context_dependent_node().

1253 {
1254  if (node == NULL)
1255  return false;
1256  if (IsA(node, CaseTestExpr))
1257  return !(*flags & CCDN_CASETESTEXPR_OK);
1258  else if (IsA(node, CaseExpr))
1259  {
1260  CaseExpr *caseexpr = (CaseExpr *) node;
1261 
1262  /*
1263  * If this CASE doesn't have a test expression, then it doesn't create
1264  * a context in which CaseTestExprs should appear, so just fall
1265  * through and treat it as a generic expression node.
1266  */
1267  if (caseexpr->arg)
1268  {
1269  int save_flags = *flags;
1270  bool res;
1271 
1272  /*
1273  * Note: in principle, we could distinguish the various sub-parts
1274  * of a CASE construct and set the flag bit only for some of them,
1275  * since we are only expecting CaseTestExprs to appear in the
1276  * "expr" subtree of the CaseWhen nodes. But it doesn't really
1277  * seem worth any extra code. If there are any bare CaseTestExprs
1278  * elsewhere in the CASE, something's wrong already.
1279  */
1280  *flags |= CCDN_CASETESTEXPR_OK;
1281  res = expression_tree_walker(node,
1283  (void *) flags);
1284  *flags = save_flags;
1285  return res;
1286  }
1287  }
1288  else if (IsA(node, ArrayCoerceExpr))
1289  {
1290  ArrayCoerceExpr *ac = (ArrayCoerceExpr *) node;
1291  int save_flags;
1292  bool res;
1293 
1294  /* Check the array expression */
1295  if (contain_context_dependent_node_walker((Node *) ac->arg, flags))
1296  return true;
1297 
1298  /* Check the elemexpr, which is allowed to contain CaseTestExpr */
1299  save_flags = *flags;
1300  *flags |= CCDN_CASETESTEXPR_OK;
1302  flags);
1303  *flags = save_flags;
1304  return res;
1305  }
1307  (void *) flags);
1308 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
Definition: nodes.h:525
#define CCDN_CASETESTEXPR_OK
Definition: clauses.c:1249
Expr * elemexpr
Definition: primnodes.h:859
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1839
Expr * arg
Definition: primnodes.h:932
static bool contain_context_dependent_node_walker(Node *node, int *flags)
Definition: clauses.c:1252

◆ contain_leaked_vars()

bool contain_leaked_vars ( Node clause)

Definition at line 1326 of file clauses.c.

References contain_leaked_vars_walker().

Referenced by make_restrictinfo_internal(), and qual_is_pushdown_safe().

1327 {
1328  return contain_leaked_vars_walker(clause, NULL);
1329 }
static bool contain_leaked_vars_walker(Node *node, void *context)
Definition: clauses.c:1338

◆ contain_leaked_vars_checker()

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

Definition at line 1332 of file clauses.c.

References get_func_leakproof().

Referenced by contain_leaked_vars_walker().

1333 {
1334  return !get_func_leakproof(func_id);
1335 }
bool get_func_leakproof(Oid funcid)
Definition: lsyscache.c:1639

◆ contain_leaked_vars_walker()

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

Definition at line 1338 of file clauses.c.

References MinMaxExpr::args, check_functions_in_node(), TypeCacheEntry::cmp_proc, contain_leaked_vars_checker(), contain_var_clause(), expression_tree_walker(), forthree, get_func_leakproof(), get_opcode(), RowCompareExpr::largs, lfirst, lfirst_oid, lookup_type_cache(), MinMaxExpr::minmaxtype, nodeTag, OidIsValid, RowCompareExpr::opnos, RowCompareExpr::rargs, 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().

1339 {
1340  if (node == NULL)
1341  return false;
1342 
1343  switch (nodeTag(node))
1344  {
1345  case T_Var:
1346  case T_Const:
1347  case T_Param:
1348  case T_ArrayExpr:
1349  case T_FieldSelect:
1350  case T_FieldStore:
1351  case T_NamedArgExpr:
1352  case T_BoolExpr:
1353  case T_RelabelType:
1354  case T_CollateExpr:
1355  case T_CaseExpr:
1356  case T_CaseTestExpr:
1357  case T_RowExpr:
1358  case T_SQLValueFunction:
1359  case T_NullTest:
1360  case T_BooleanTest:
1361  case T_NextValueExpr:
1362  case T_List:
1363 
1364  /*
1365  * We know these node types don't contain function calls; but
1366  * something further down in the node tree might.
1367  */
1368  break;
1369 
1370  case T_FuncExpr:
1371  case T_OpExpr:
1372  case T_DistinctExpr:
1373  case T_NullIfExpr:
1374  case T_ScalarArrayOpExpr:
1375  case T_CoerceViaIO:
1376  case T_ArrayCoerceExpr:
1377  case T_SubscriptingRef:
1378 
1379  /*
1380  * If node contains a leaky function call, and there's any Var
1381  * underneath it, reject.
1382  */
1384  context) &&
1385  contain_var_clause(node))
1386  return true;
1387  break;
1388 
1389  case T_RowCompareExpr:
1390  {
1391  /*
1392  * It's worth special-casing this because a leaky comparison
1393  * function only compromises one pair of row elements, which
1394  * might not contain Vars while others do.
1395  */
1396  RowCompareExpr *rcexpr = (RowCompareExpr *) node;
1397  ListCell *opid;
1398  ListCell *larg;
1399  ListCell *rarg;
1400 
1401  forthree(opid, rcexpr->opnos,
1402  larg, rcexpr->largs,
1403  rarg, rcexpr->rargs)
1404  {
1405  Oid funcid = get_opcode(lfirst_oid(opid));
1406 
1407  if (!get_func_leakproof(funcid) &&
1408  (contain_var_clause((Node *) lfirst(larg)) ||
1409  contain_var_clause((Node *) lfirst(rarg))))
1410  return true;
1411  }
1412  }
1413  break;
1414 
1415  case T_MinMaxExpr:
1416  {
1417  /*
1418  * MinMaxExpr is leakproof if the comparison function it calls
1419  * is leakproof.
1420  */
1421  MinMaxExpr *minmaxexpr = (MinMaxExpr *) node;
1422  TypeCacheEntry *typentry;
1423  bool leakproof;
1424 
1425  /* Look up the btree comparison function for the datatype */
1426  typentry = lookup_type_cache(minmaxexpr->minmaxtype,
1428  if (OidIsValid(typentry->cmp_proc))
1429  leakproof = get_func_leakproof(typentry->cmp_proc);
1430  else
1431  {
1432  /*
1433  * The executor will throw an error, but here we just
1434  * treat the missing function as leaky.
1435  */
1436  leakproof = false;
1437  }
1438 
1439  if (!leakproof &&
1440  contain_var_clause((Node *) minmaxexpr->args))
1441  return true;
1442  }
1443  break;
1444 
1445  case T_CurrentOfExpr:
1446 
1447  /*
1448  * WHERE CURRENT OF doesn't contain leaky function calls.
1449  * Moreover, it is essential that this is considered non-leaky,
1450  * since the planner must always generate a TID scan when CURRENT
1451  * OF is present -- cf. cost_tidscan.
1452  */
1453  return false;
1454 
1455  default:
1456 
1457  /*
1458  * If we don't recognize the node tag, assume it might be leaky.
1459  * This prevents an unexpected security hole if someone adds a new
1460  * node type that can call a function.
1461  */
1462  return true;
1463  }
1465  context);
1466 }
Oid minmaxtype
Definition: primnodes.h:1102
bool get_func_leakproof(Oid funcid)
Definition: lsyscache.c:1639
List * args
Definition: primnodes.h:1106
#define forthree(cell1, list1, cell2, list2, cell3, list3)
Definition: pg_list.h:464
Definition: nodes.h:525
bool contain_var_clause(Node *node)
Definition: var.c:331
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:645
bool check_functions_in_node(Node *node, check_function_callback checker, void *context)
Definition: nodeFuncs.c:1656
Definition: nodes.h:297
Definition: nodes.h:152
Definition: nodes.h:151
TypeCacheEntry * lookup_type_cache(Oid type_id, int flags)
Definition: typcache.c:322
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1092
#define TYPECACHE_CMP_PROC
Definition: typcache.h:131
#define lfirst(lc)
Definition: pg_list.h:190
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1839
#define nodeTag(nodeptr)
Definition: nodes.h:530
static bool contain_leaked_vars_checker(Oid func_id, void *context)
Definition: clauses.c:1332
static bool contain_leaked_vars_walker(Node *node, void *context)
Definition: clauses.c:1338
#define lfirst_oid(lc)
Definition: pg_list.h:192
Definition: nodes.h:153

◆ contain_mutable_functions()

◆ contain_mutable_functions_checker()

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

Definition at line 650 of file clauses.c.

References func_volatile().

Referenced by contain_mutable_functions_walker().

651 {
652  return (func_volatile(func_id) != PROVOLATILE_IMMUTABLE);
653 }
char func_volatile(Oid funcid)
Definition: lsyscache.c:1582

◆ contain_mutable_functions_walker()

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

Definition at line 656 of file clauses.c.

References check_functions_in_node(), contain_mutable_functions_checker(), expression_tree_walker(), IsA, and query_tree_walker().

Referenced by contain_mutable_functions().

657 {
658  if (node == NULL)
659  return false;
660  /* Check for mutable functions in node itself */
662  context))
663  return true;
664 
665  if (IsA(node, SQLValueFunction))
666  {
667  /* all variants of SQLValueFunction are stable */
668  return true;
669  }
670 
671  if (IsA(node, NextValueExpr))
672  {
673  /* NextValueExpr is volatile */
674  return true;
675  }
676 
677  /*
678  * It should be safe to treat MinMaxExpr as immutable, because it will
679  * depend on a non-cross-type btree comparison function, and those should
680  * always be immutable. Treating XmlExpr as immutable is more dubious,
681  * and treating CoerceToDomain as immutable is outright dangerous. But we
682  * have done so historically, and changing this would probably cause more
683  * problems than it would fix. In practice, if you have a non-immutable
684  * domain constraint you are in for pain anyhow.
685  */
686 
687  /* Recurse to check arguments */
688  if (IsA(node, Query))
689  {
690  /* Recurse into subselects */
691  return query_tree_walker((Query *) node,
693  context, 0);
694  }
696  context);
697 }
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2273
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
static bool contain_mutable_functions_walker(Node *node, void *context)
Definition: clauses.c:656
static bool contain_mutable_functions_checker(Oid func_id, void *context)
Definition: clauses.c:650
bool check_functions_in_node(Node *node, check_function_callback checker, void *context)
Definition: nodeFuncs.c:1656
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1839

◆ contain_non_const_walker()

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

Definition at line 3617 of file clauses.c.

References expression_tree_walker(), and IsA.

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 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1839
Definition: pg_list.h:50
static bool contain_non_const_walker(Node *node, void *context)
Definition: clauses.c:3617

◆ contain_nonstrict_functions()

bool contain_nonstrict_functions ( Node clause)

Definition at line 1093 of file clauses.c.

References contain_nonstrict_functions_walker().

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

1094 {
1095  return contain_nonstrict_functions_walker(clause, NULL);
1096 }
static bool contain_nonstrict_functions_walker(Node *node, void *context)
Definition: clauses.c:1105

◆ contain_nonstrict_functions_checker()

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

Definition at line 1099 of file clauses.c.

References func_strict().

Referenced by contain_nonstrict_functions_walker().

1100 {
1101  return !func_strict(func_id);
1102 }
bool func_strict(Oid funcid)
Definition: lsyscache.c:1563

◆ contain_nonstrict_functions_walker()

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

Definition at line 1105 of file clauses.c.

References AND_EXPR, arg, BoolExpr::boolop, check_functions_in_node(), contain_nonstrict_functions_checker(), expression_tree_walker(), IsA, and OR_EXPR.

Referenced by contain_nonstrict_functions().

1106 {
1107  if (node == NULL)
1108  return false;
1109  if (IsA(node, Aggref))
1110  {
1111  /* an aggregate could return non-null with null input */
1112  return true;
1113  }
1114  if (IsA(node, GroupingFunc))
1115  {
1116  /*
1117  * A GroupingFunc doesn't evaluate its arguments, and therefore must
1118  * be treated as nonstrict.
1119  */
1120  return true;
1121  }
1122  if (IsA(node, WindowFunc))
1123  {
1124  /* a window function could return non-null with null input */
1125  return true;
1126  }
1127  if (IsA(node, SubscriptingRef))
1128  {
1129  /*
1130  * subscripting assignment is nonstrict, but subscripting itself is
1131  * strict
1132  */
1133  if (((SubscriptingRef *) node)->refassgnexpr != NULL)
1134  return true;
1135 
1136  /* else fall through to check args */
1137  }
1138  if (IsA(node, DistinctExpr))
1139  {
1140  /* IS DISTINCT FROM is inherently non-strict */
1141  return true;
1142  }
1143  if (IsA(node, NullIfExpr))
1144  {
1145  /* NULLIF is inherently non-strict */
1146  return true;
1147  }
1148  if (IsA(node, BoolExpr))
1149  {
1150  BoolExpr *expr = (BoolExpr *) node;
1151 
1152  switch (expr->boolop)
1153  {
1154  case AND_EXPR:
1155  case OR_EXPR:
1156  /* AND, OR are inherently non-strict */
1157  return true;
1158  default:
1159  break;
1160  }
1161  }
1162  if (IsA(node, SubLink))
1163  {
1164  /* In some cases a sublink might be strict, but in general not */
1165  return true;
1166  }
1167  if (IsA(node, SubPlan))
1168  return true;
1169  if (IsA(node, AlternativeSubPlan))
1170  return true;
1171  if (IsA(node, FieldStore))
1172  return true;
1173  if (IsA(node, CoerceViaIO))
1174  {
1175  /*
1176  * CoerceViaIO is strict regardless of whether the I/O functions are,
1177  * so just go look at its argument; asking check_functions_in_node is
1178  * useless expense and could deliver the wrong answer.
1179  */
1180  return contain_nonstrict_functions_walker((Node *) ((CoerceViaIO *) node)->arg,
1181  context);
1182  }
1183  if (IsA(node, ArrayCoerceExpr))
1184  {
1185  /*
1186  * ArrayCoerceExpr is strict at the array level, regardless of what
1187  * the per-element expression is; so we should ignore elemexpr and
1188  * recurse only into the arg.
1189  */
1191  context);
1192  }
1193  if (IsA(node, CaseExpr))
1194  return true;
1195  if (IsA(node, ArrayExpr))
1196  return true;
1197  if (IsA(node, RowExpr))
1198  return true;
1199  if (IsA(node, RowCompareExpr))
1200  return true;
1201  if (IsA(node, CoalesceExpr))
1202  return true;
1203  if (IsA(node, MinMaxExpr))
1204  return true;
1205  if (IsA(node, XmlExpr))
1206  return true;
1207  if (IsA(node, NullTest))
1208  return true;
1209  if (IsA(node, BooleanTest))
1210  return true;
1211 
1212  /* Check other function-containing nodes */
1214  context))
1215  return true;
1216 
1218  context);
1219 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
Definition: nodes.h:525
static bool contain_nonstrict_functions_walker(Node *node, void *context)
Definition: clauses.c:1105
bool check_functions_in_node(Node *node, check_function_callback checker, void *context)
Definition: nodeFuncs.c:1656
BoolExprType boolop
Definition: primnodes.h:582
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1839
void * arg
static bool contain_nonstrict_functions_checker(Oid func_id, void *context)
Definition: clauses.c:1099

◆ contain_subplans()

bool contain_subplans ( Node clause)

Definition at line 609 of file clauses.c.

References contain_subplans_walker().

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

610 {
611  return contain_subplans_walker(clause, NULL);
612 }
static bool contain_subplans_walker(Node *node, void *context)
Definition: clauses.c:615

◆ contain_subplans_walker()

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

Definition at line 615 of file clauses.c.

References expression_tree_walker(), and IsA.

Referenced by contain_subplans().

616 {
617  if (node == NULL)
618  return false;
619  if (IsA(node, SubPlan) ||
620  IsA(node, AlternativeSubPlan) ||
621  IsA(node, SubLink))
622  return true; /* abort the tree traversal and return true */
623  return expression_tree_walker(node, contain_subplans_walker, context);
624 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1839
static bool contain_subplans_walker(Node *node, void *context)
Definition: clauses.c:615

◆ contain_volatile_functions()

◆ contain_volatile_functions_checker()

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

Definition at line 729 of file clauses.c.

References func_volatile().

Referenced by contain_volatile_functions_walker().

730 {
731  return (func_volatile(func_id) == PROVOLATILE_VOLATILE);
732 }
char func_volatile(Oid funcid)
Definition: lsyscache.c:1582

◆ contain_volatile_functions_not_nextval()

bool contain_volatile_functions_not_nextval ( Node clause)

Definition at line 773 of file clauses.c.

References contain_volatile_functions_not_nextval_walker().

Referenced by BeginCopyFrom().

774 {
776 }
static bool contain_volatile_functions_not_nextval_walker(Node *node, void *context)
Definition: clauses.c:786

◆ contain_volatile_functions_not_nextval_checker()

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

Definition at line 779 of file clauses.c.

References func_volatile().

Referenced by contain_volatile_functions_not_nextval_walker().

780 {
781  return (func_id != F_NEXTVAL_OID &&
782  func_volatile(func_id) == PROVOLATILE_VOLATILE);
783 }
char func_volatile(Oid funcid)
Definition: lsyscache.c:1582

◆ contain_volatile_functions_not_nextval_walker()

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

Definition at line 786 of file clauses.c.

References check_functions_in_node(), contain_volatile_functions_not_nextval_checker(), expression_tree_walker(), IsA, and query_tree_walker().

Referenced by contain_volatile_functions_not_nextval().

787 {
788  if (node == NULL)
789  return false;
790  /* Check for volatile functions in node itself */
791  if (check_functions_in_node(node,
793  context))
794  return true;
795 
796  /*
797  * See notes in contain_mutable_functions_walker about why we treat
798  * MinMaxExpr, XmlExpr, and CoerceToDomain as immutable, while
799  * SQLValueFunction is stable. Hence, none of them are of interest here.
800  * Also, since we're intentionally ignoring nextval(), presumably we
801  * should ignore NextValueExpr.
802  */
803 
804  /* Recurse to check arguments */
805  if (IsA(node, Query))
806  {
807  /* Recurse into subselects */
808  return query_tree_walker((Query *) node,
810  context, 0);
811  }
812  return expression_tree_walker(node,
814  context);
815 }
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2273
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
static bool contain_volatile_functions_not_nextval_walker(Node *node, void *context)
Definition: clauses.c:786
bool check_functions_in_node(Node *node, check_function_callback checker, void *context)
Definition: nodeFuncs.c:1656
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1839
static bool contain_volatile_functions_not_nextval_checker(Oid func_id, void *context)
Definition: clauses.c:779

◆ contain_volatile_functions_walker()

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

Definition at line 735 of file clauses.c.

References check_functions_in_node(), contain_volatile_functions_checker(), expression_tree_walker(), IsA, and query_tree_walker().

Referenced by contain_volatile_functions().

736 {
737  if (node == NULL)
738  return false;
739  /* Check for volatile functions in node itself */
741  context))
742  return true;
743 
744  if (IsA(node, NextValueExpr))
745  {
746  /* NextValueExpr is volatile */
747  return true;
748  }
749 
750  /*
751  * See notes in contain_mutable_functions_walker about why we treat
752  * MinMaxExpr, XmlExpr, and CoerceToDomain as immutable, while
753  * SQLValueFunction is stable. Hence, none of them are of interest here.
754  */
755 
756  /* Recurse to check arguments */
757  if (IsA(node, Query))
758  {
759  /* Recurse into subselects */
760  return query_tree_walker((Query *) node,
762  context, 0);
763  }
765  context);
766 }
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2273
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
bool check_functions_in_node(Node *node, check_function_callback checker, void *context)
Definition: nodeFuncs.c:1656
static bool contain_volatile_functions_walker(Node *node, void *context)
Definition: clauses.c:735
static bool contain_volatile_functions_checker(Oid func_id, void *context)
Definition: clauses.c:729
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1839

◆ contain_window_function()

bool contain_window_function ( Node clause)

Definition at line 493 of file clauses.c.

References contain_windowfuncs().

Referenced by get_eclass_for_sort_expr(), and qual_is_pushdown_safe().

494 {
495  return contain_windowfuncs(clause);
496 }
bool contain_windowfuncs(Node *node)
Definition: rewriteManip.c:197

◆ 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.

References eval_const_expressions_context::estimate, and func_volatile().

Referenced by eval_const_expressions_mutator().

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 }
char func_volatile(Oid funcid)
Definition: lsyscache.c:1582

◆ estimate_expression_value()

Node* estimate_expression_value ( PlannerInfo root,
Node node 
)

Definition at line 2285 of file clauses.c.

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

Referenced by array_unnest_support(), bernoulli_samplescangetsamplesize(), clause_selectivity(), 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().

2286 {
2288 
2289  context.boundParams = root->glob->boundParams; /* bound Params */
2290  /* we do not need to mark the plan as depending on inlined functions */
2291  context.root = NULL;
2292  context.active_fns = NIL; /* nothing being recursively simplified */
2293  context.case_val = NULL; /* no CASE being examined */
2294  context.estimate = true; /* unsafe transformations OK */
2295  return eval_const_expressions_mutator(node, &context);
2296 }
#define NIL
Definition: pg_list.h:65
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2330
ParamListInfo boundParams
Definition: clauses.c:66
PlannerGlobal * glob
Definition: pathnodes.h:181
ParamListInfo boundParams
Definition: pathnodes.h:109

◆ eval_const_expressions()

Node* eval_const_expressions ( PlannerInfo root,
Node node 
)

Definition at line 2252 of file clauses.c.

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

Referenced by apply_child_basequals(), ATExecAttachPartition(), ConstraintImpliedByRelConstraint(), convert_EXISTS_to_ANY(), DoCopy(), expression_planner(), expression_planner_with_deps(), get_proposed_default_constraint(), get_relation_constraints(), preprocess_expression(), preprocess_function_rtes(), process_implied_equality(), RelationBuildPartitionKey(), RelationGetIndexExpressions(), RelationGetIndexPredicate(), and simplify_EXISTS_query().

2253 {
2255 
2256  if (root)
2257  context.boundParams = root->glob->boundParams; /* bound Params */
2258  else
2259  context.boundParams = NULL;
2260  context.root = root; /* for inlined-function dependencies */
2261  context.active_fns = NIL; /* nothing being recursively simplified */
2262  context.case_val = NULL; /* no CASE being examined */
2263  context.estimate = false; /* safe transformations only */
2264  return eval_const_expressions_mutator(node, &context);
2265 }
#define NIL
Definition: pg_list.h:65
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2330
ParamListInfo boundParams
Definition: clauses.c:66
PlannerGlobal * glob
Definition: pathnodes.h:181
ParamListInfo boundParams
Definition: pathnodes.h:109

◆ eval_const_expressions_mutator()

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

Definition at line 2330 of file clauses.c.

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

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

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

◆ evaluate_expr()

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

Definition at line 4788 of file clauses.c.

References CreateExecutorState(), datumCopy(), EState::es_query_cxt, ExecEvalExprSwitchContext(), ExecInitExpr(), fix_opfuncids(), FreeExecutorState(), get_typlenbyval(), GetPerTupleExprContext, makeConst(), MemoryContextSwitchTo(), PG_DETOAST_DATUM_COPY, and PointerGetDatum.

Referenced by eval_const_expressions_mutator(), evaluate_function(), and transformPartitionBoundValue().

4790 {
4791  EState *estate;
4792  ExprState *exprstate;
4793  MemoryContext oldcontext;
4794  Datum const_val;
4795  bool const_is_null;
4796  int16 resultTypLen;
4797  bool resultTypByVal;
4798 
4799  /*
4800  * To use the executor, we need an EState.
4801  */
4802  estate = CreateExecutorState();
4803 
4804  /* We can use the estate's working context to avoid memory leaks. */
4805  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
4806 
4807  /* Make sure any opfuncids are filled in. */
4808  fix_opfuncids((Node *) expr);
4809 
4810  /*
4811  * Prepare expr for execution. (Note: we can't use ExecPrepareExpr
4812  * because it'd result in recursively invoking eval_const_expressions.)
4813  */
4814  exprstate = ExecInitExpr(expr, NULL);
4815 
4816  /*
4817  * And evaluate it.
4818  *
4819  * It is OK to use a default econtext because none of the ExecEvalExpr()
4820  * code used in this situation will use econtext. That might seem
4821  * fortuitous, but it's not so unreasonable --- a constant expression does
4822  * not depend on context, by definition, n'est ce pas?
4823  */
4824  const_val = ExecEvalExprSwitchContext(exprstate,
4825  GetPerTupleExprContext(estate),
4826  &const_is_null);
4827 
4828  /* Get info needed about result datatype */
4829  get_typlenbyval(result_type, &resultTypLen, &resultTypByVal);
4830 
4831  /* Get back to outer memory context */
4832  MemoryContextSwitchTo(oldcontext);
4833 
4834  /*
4835  * Must copy result out of sub-context used by expression eval.
4836  *
4837  * Also, if it's varlena, forcibly detoast it. This protects us against
4838  * storing TOAST pointers into plans that might outlive the referenced
4839  * data. (makeConst would handle detoasting anyway, but it's worth a few
4840  * extra lines here so that we can do the copy and detoast in one step.)
4841  */
4842  if (!const_is_null)
4843  {
4844  if (resultTypLen == -1)
4845  const_val = PointerGetDatum(PG_DETOAST_DATUM_COPY(const_val));
4846  else
4847  const_val = datumCopy(const_val, resultTypByVal, resultTypLen);
4848  }
4849 
4850  /* Release all the junk we just created */
4851  FreeExecutorState(estate);
4852 
4853  /*
4854  * Make the constant result node.
4855  */
4856  return (Expr *) makeConst(result_type, result_typmod, result_collation,
4857  resultTypLen,
4858  const_val, const_is_null,
4859  resultTypByVal);
4860 }
signed short int16
Definition: c.h:346
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:300
#define PG_DETOAST_DATUM_COPY(datum)
Definition: fmgr.h:237
#define PointerGetDatum(X)
Definition: postgres.h:556
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1587
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Definition: nodes.h:525
Const * makeConst(Oid consttype, int32 consttypmod, Oid constcollid, int constlen, Datum constvalue, bool constisnull, bool constbyval)
Definition: makefuncs.c:297
void FreeExecutorState(EState *estate)
Definition: execUtils.c:190
#define GetPerTupleExprContext(estate)
Definition: executor.h:501
MemoryContext es_query_cxt
Definition: execnodes.h:549
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:130
EState * CreateExecutorState(void)
Definition: execUtils.c:88
uintptr_t Datum
Definition: postgres.h:367
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2029
ExprState * ExecInitExpr(Expr *node, PlanState *parent)
Definition: execExpr.c:121

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

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

Referenced by simplify_function().

4269 {
4270  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4271  bool has_nonconst_input = false;
4272  bool has_null_input = false;
4273  ListCell *arg;
4274  FuncExpr *newexpr;
4275 
4276  /*
4277  * Can't simplify if it returns a set.
4278  */
4279  if (funcform->proretset)
4280  return NULL;
4281 
4282  /*
4283  * Can't simplify if it returns RECORD. The immediate problem is that it
4284  * will be needing an expected tupdesc which we can't supply here.
4285  *
4286  * In the case where it has OUT parameters, it could get by without an
4287  * expected tupdesc, but we still have issues: get_expr_result_type()
4288  * doesn't know how to extract type info from a RECORD constant, and in
4289  * the case of a NULL function result there doesn't seem to be any clean
4290  * way to fix that. In view of the likelihood of there being still other
4291  * gotchas, seems best to leave the function call unreduced.
4292  */
4293  if (funcform->prorettype == RECORDOID)
4294  return NULL;
4295 
4296  /*
4297  * Check for constant inputs and especially constant-NULL inputs.
4298  */
4299  foreach(arg, args)
4300  {
4301  if (IsA(lfirst(arg), Const))
4302  has_null_input |= ((Const *) lfirst(arg))->constisnull;
4303  else
4304  has_nonconst_input = true;
4305  }
4306 
4307  /*
4308  * If the function is strict and has a constant-NULL input, it will never
4309  * be called at all, so we can replace the call by a NULL constant, even
4310  * if there are other inputs that aren't constant, and even if the
4311  * function is not otherwise immutable.
4312  */
4313  if (funcform->proisstrict && has_null_input)
4314  return (Expr *) makeNullConst(result_type, result_typmod,
4315  result_collid);
4316 
4317  /*
4318  * Otherwise, can simplify only if all inputs are constants. (For a
4319  * non-strict function, constant NULL inputs are treated the same as
4320  * constant non-NULL inputs.)
4321  */
4322  if (has_nonconst_input)
4323  return NULL;
4324 
4325  /*
4326  * Ordinarily we are only allowed to simplify immutable functions. But for
4327  * purposes of estimation, we consider it okay to simplify functions that
4328  * are merely stable; the risk that the result might change from planning
4329  * time to execution time is worth taking in preference to not being able
4330  * to estimate the value at all.
4331  */
4332  if (funcform->provolatile == PROVOLATILE_IMMUTABLE)
4333  /* okay */ ;
4334  else if (context->estimate && funcform->provolatile == PROVOLATILE_STABLE)
4335  /* okay */ ;
4336  else
4337  return NULL;
4338 
4339  /*
4340  * OK, looks like we can simplify this operator/function.
4341  *
4342  * Build a new FuncExpr node containing the already-simplified arguments.
4343  */
4344  newexpr = makeNode(FuncExpr);
4345  newexpr->funcid = funcid;
4346  newexpr->funcresulttype = result_type;
4347  newexpr->funcretset = false;
4348  newexpr->funcvariadic = funcvariadic;
4349  newexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
4350  newexpr->funccollid = result_collid; /* doesn't matter */
4351  newexpr->inputcollid = input_collid;
4352  newexpr->args = args;
4353  newexpr->location = -1;
4354 
4355  return evaluate_expr((Expr *) newexpr, result_type, result_typmod,
4356  result_collid);
4357 }
Expr * evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod, Oid result_collation)
Definition: clauses.c:4788
Oid funcresulttype
Definition: primnodes.h:470
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
List * args
Definition: primnodes.h:477
Oid funccollid
Definition: primnodes.h:475
bool funcretset
Definition: primnodes.h:471
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:335
CoercionForm funcformat
Definition: primnodes.h:474
Oid funcid
Definition: primnodes.h:469
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:133
#define makeNode(_type_)
Definition: nodes.h:573
Oid inputcollid
Definition: primnodes.h:476
#define lfirst(lc)
Definition: pg_list.h:190
void * arg
int location
Definition: primnodes.h:478
bool funcvariadic
Definition: primnodes.h:472

◆ expand_function_arguments()

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

Definition at line 4047 of file clauses.c.

References add_function_defaults(), arg, generate_unaccent_rules::args, GETSTRUCT, IsA, lfirst, list_length(), recheck_cast_function_args(), and reorder_function_arguments().

Referenced by eval_const_expressions_mutator(), exec_stmt_call(), ExecuteCallStmt(), and simplify_function().

4048 {
4049  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4050  bool has_named_args = false;
4051  ListCell *lc;
4052 
4053  /* Do we have any named arguments? */
4054  foreach(lc, args)
4055  {
4056  Node *arg = (Node *) lfirst(lc);
4057 
4058  if (IsA(arg, NamedArgExpr))
4059  {
4060  has_named_args = true;
4061  break;
4062  }
4063  }
4064 
4065  /* If so, we must apply reorder_function_arguments */
4066  if (has_named_args)
4067  {
4068  args = reorder_function_arguments(args, func_tuple);
4069  /* Recheck argument types and add casts if needed */
4070  recheck_cast_function_args(args, result_type, func_tuple);
4071  }
4072  else if (list_length(args) < funcform->pronargs)
4073  {
4074  /* No named args, but we seem to be short some defaults */
4075  args = add_function_defaults(args, func_tuple);
4076  /* Recheck argument types and add casts if needed */
4077  recheck_cast_function_args(args, result_type, func_tuple);
4078  }
4079 
4080  return args;
4081 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Definition: nodes.h:525
static void recheck_cast_function_args(List *args, Oid result_type, HeapTuple func_tuple)
Definition: clauses.c:4220
static List * add_function_defaults(List *args, HeapTuple func_tuple)
Definition: clauses.c:4160
static List * reorder_function_arguments(List *args, HeapTuple func_tuple)
Definition: clauses.c:4090
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:133
#define lfirst(lc)
Definition: pg_list.h:190
static int list_length(const List *l)
Definition: pg_list.h:169
void * arg

◆ expression_returns_set_rows()

double expression_returns_set_rows ( PlannerInfo root,
Node clause 
)

Definition at line 568 of file clauses.c.

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

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

569 {
570  if (clause == NULL)
571  return 1.0;
572  if (IsA(clause, FuncExpr))
573  {
574  FuncExpr *expr = (FuncExpr *) clause;
575 
576  if (expr->funcretset)
577  return clamp_row_est(get_function_rows(root, expr->funcid, clause));
578  }
579  if (IsA(clause, OpExpr))
580  {
581  OpExpr *expr = (OpExpr *) clause;
582 
583  if (expr->opretset)
584  {
585  set_opfuncid(expr);
586  return clamp_row_est(get_function_rows(root, expr->opfuncid, clause));
587  }
588  }
589  return 1.0;
590 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
bool funcretset
Definition: primnodes.h:471
Oid funcid
Definition: primnodes.h:469
Oid opfuncid
Definition: primnodes.h:517
void set_opfuncid(OpExpr *opexpr)
Definition: nodeFuncs.c:1618
double clamp_row_est(double nrows)
Definition: costsize.c:187
bool opretset
Definition: primnodes.h:519
double get_function_rows(PlannerInfo *root, Oid funcid, Node *node)
Definition: plancat.c:1966

◆ fetch_function_defaults()

static List * fetch_function_defaults ( HeapTuple  func_tuple)
static

Definition at line 4185 of file clauses.c.

References castNode, elog, ERROR, pfree(), PROCOID, generate_unaccent_rules::str, stringToNode(), SysCacheGetAttr(), and TextDatumGetCString.

Referenced by add_function_defaults(), and reorder_function_arguments().

4186 {
4187  List *defaults;
4188  Datum proargdefaults;
4189  bool isnull;
4190  char *str;
4191 
4192  /* The error cases here shouldn't happen, but check anyway */
4193  proargdefaults = SysCacheGetAttr(PROCOID, func_tuple,
4194  Anum_pg_proc_proargdefaults,
4195  &isnull);
4196  if (isnull)
4197  elog(ERROR, "not enough default arguments");
4198  str = TextDatumGetCString(proargdefaults);
4199  defaults = castNode(List, stringToNode(str));
4200  pfree(str);
4201  return defaults;
4202 }
#define castNode(_type_, nodeptr)
Definition: nodes.h:594
void * stringToNode(const char *str)
Definition: read.c:89
void pfree(void *pointer)
Definition: mcxt.c:1056
#define ERROR
Definition: elog.h:43
#define TextDatumGetCString(d)
Definition: builtins.h:84
uintptr_t Datum
Definition: postgres.h:367
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1377
#define elog(elevel,...)
Definition: elog.h:228
Definition: pg_list.h:50

◆ find_forced_null_var()

Var* find_forced_null_var ( Node node)

Definition at line 1977 of file clauses.c.

References NullTest::arg, BooleanTest::arg, NullTest::argisrow, BooleanTest::booltesttype, IS_NULL, IS_UNKNOWN, IsA, NullTest::nulltesttype, and Var::varlevelsup.

Referenced by check_redundant_nullability_qual(), and find_forced_null_vars().

1978 {
1979  if (node == NULL)
1980  return NULL;
1981  if (IsA(node, NullTest))
1982  {
1983  /* check for var IS NULL */
1984  NullTest *expr = (NullTest *) node;
1985 
1986  if (expr->nulltesttype == IS_NULL && !expr->argisrow)
1987  {
1988  Var *var = (Var *) expr->arg;
1989 
1990  if (var && IsA(var, Var) &&
1991  var->varlevelsup == 0)
1992  return var;
1993  }
1994  }
1995  else if (IsA(node, BooleanTest))
1996  {
1997  /* var IS UNKNOWN is equivalent to var IS NULL */
1998  BooleanTest *expr = (BooleanTest *) node;
1999 
2000  if (expr->booltesttype == IS_UNKNOWN)
2001  {
2002  Var *var = (Var *) expr->arg;
2003 
2004  if (var && IsA(var, Var) &&
2005  var->varlevelsup == 0)
2006  return var;
2007  }
2008  }
2009  return NULL;
2010 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
Index varlevelsup
Definition: primnodes.h:191
Definition: primnodes.h:181
Expr * arg
Definition: primnodes.h:1219
Expr * arg
Definition: primnodes.h:1242
BoolTestType booltesttype
Definition: primnodes.h:1243
NullTestType nulltesttype
Definition: primnodes.h:1220
bool argisrow
Definition: primnodes.h:1221

◆ find_forced_null_vars()

List* find_forced_null_vars ( Node node)

Definition at line 1918 of file clauses.c.

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

Referenced by find_forced_null_vars(), and reduce_outer_joins_pass2().

1919 {
1920  List *result = NIL;
1921  Var *var;
1922  ListCell *l;
1923 
1924  if (node == NULL)
1925  return NIL;
1926  /* Check single-clause cases using subroutine */
1927  var = find_forced_null_var(node);
1928  if (var)
1929  {
1930  result = list_make1(var);
1931  }
1932  /* Otherwise, handle AND-conditions */
1933  else if (IsA(node, List))
1934  {
1935  /*
1936  * At top level, we are examining an implicit-AND list: if any of the
1937  * arms produces FALSE-or-NULL then the result is FALSE-or-NULL.
1938  */
1939  foreach(l, (List *) node)
1940  {
1941  result = list_concat(result,
1943  }
1944  }
1945  else if (IsA(node, BoolExpr))
1946  {
1947  BoolExpr *expr = (BoolExpr *) node;
1948 
1949  /*
1950  * We don't bother considering the OR case, because it's fairly
1951  * unlikely anyone would write "v1 IS NULL OR v1 IS NULL". Likewise,
1952  * the NOT case isn't worth expending code on.
1953  */
1954  if (expr->boolop == AND_EXPR)
1955  {
1956  /* At top level we can just recurse (to the List case) */
1957  result = find_forced_null_vars((Node *) expr->args);
1958  }
1959  }
1960  return result;
1961 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
Definition: nodes.h:525
List * list_concat(List *list1, const List *list2)
Definition: list.c:516
Definition: primnodes.h:181
List * find_forced_null_vars(Node *node)
Definition: clauses.c:1918
#define list_make1(x1)
Definition: pg_list.h:227
BoolExprType boolop
Definition: primnodes.h:582
#define lfirst(lc)
Definition: pg_list.h:190
List * args
Definition: primnodes.h:583
Definition: pg_list.h:50
Var * find_forced_null_var(Node *node)
Definition: clauses.c:1977

◆ find_nonnullable_rels()

Relids find_nonnullable_rels ( Node clause)

Definition at line 1500 of file clauses.c.

References find_nonnullable_rels_walker().

Referenced by make_outerjoininfo(), and reduce_outer_joins_pass2().

1501 {
1502  return find_nonnullable_rels_walker(clause, true);
1503 }
static Relids find_nonnullable_rels_walker(Node *node, bool top_level)
Definition: clauses.c:1506

◆ find_nonnullable_rels_walker()

static Relids find_nonnullable_rels_walker ( Node node,
bool  top_level 
)
static

Definition at line 1506 of file clauses.c.

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

Referenced by find_nonnullable_rels().

1507 {
1508  Relids result = NULL;
1509  ListCell *l;
1510 
1511  if (node == NULL)
1512  return NULL;
1513  if (IsA(node, Var))
1514  {
1515  Var *var = (Var *) node;
1516 
1517  if (var->varlevelsup == 0)
1518  result = bms_make_singleton(var->varno);
1519  }
1520  else if (IsA(node, List))
1521  {
1522  /*
1523  * At top level, we are examining an implicit-AND list: if any of the
1524  * arms produces FALSE-or-NULL then the result is FALSE-or-NULL. If
1525  * not at top level, we are examining the arguments of a strict
1526  * function: if any of them produce NULL then the result of the
1527  * function must be NULL. So in both cases, the set of nonnullable
1528  * rels is the union of those found in the arms, and we pass down the
1529  * top_level flag unmodified.
1530  */
1531  foreach(l, (List *) node)
1532  {
1533  result = bms_join(result,
1535  top_level));
1536  }
1537  }
1538  else if (IsA(node, FuncExpr))
1539  {
1540  FuncExpr *expr = (FuncExpr *) node;
1541 
1542  if (func_strict(expr->funcid))
1543  result = find_nonnullable_rels_walker((Node *) expr->args, false);
1544  }
1545  else if (IsA(node, OpExpr))
1546  {
1547  OpExpr *expr = (OpExpr *) node;
1548 
1549  set_opfuncid(expr);
1550  if (func_strict(expr->opfuncid))
1551  result = find_nonnullable_rels_walker((Node *) expr->args, false);
1552  }
1553  else if (IsA(node, ScalarArrayOpExpr))
1554  {
1555  ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1556 
1557  if (is_strict_saop(expr, true))
1558  result = find_nonnullable_rels_walker((Node *) expr->args, false);
1559  }
1560  else if (IsA(node, BoolExpr))
1561  {
1562  BoolExpr *expr = (BoolExpr *) node;
1563 
1564  switch (expr->boolop)
1565  {
1566  case AND_EXPR:
1567  /* At top level we can just recurse (to the List case) */
1568  if (top_level)
1569  {
1570  result = find_nonnullable_rels_walker((Node *) expr->args,
1571  top_level);
1572  break;
1573  }
1574 
1575  /*
1576  * Below top level, even if one arm produces NULL, the result
1577  * could be FALSE (hence not NULL). However, if *all* the
1578  * arms produce NULL then the result is NULL, so we can take
1579  * the intersection of the sets of nonnullable rels, just as
1580  * for OR. Fall through to share code.
1581  */
1582  /* FALL THRU */
1583  case OR_EXPR:
1584 
1585  /*
1586  * OR is strict if all of its arms are, so we can take the
1587  * intersection of the sets of nonnullable rels for each arm.
1588  * This works for both values of top_level.
1589  */
1590  foreach(l, expr->args)
1591  {
1592  Relids subresult;
1593 
1594  subresult = find_nonnullable_rels_walker(lfirst(l),
1595  top_level);
1596  if (result == NULL) /* first subresult? */
1597  result = subresult;
1598  else
1599  result = bms_int_members(result, subresult);
1600 
1601  /*
1602  * If the intersection is empty, we can stop looking. This
1603  * also justifies the test for first-subresult above.
1604  */
1605  if (bms_is_empty(result))
1606  break;
1607  }
1608  break;
1609  case NOT_EXPR:
1610  /* NOT will return null if its arg is null */
1611  result = find_nonnullable_rels_walker((Node *) expr->args,
1612  false);
1613  break;
1614  default:
1615  elog(ERROR, "unrecognized boolop: %d", (int) expr->boolop);
1616  break;
1617  }
1618  }
1619  else if (IsA(node, RelabelType))
1620  {
1621  RelabelType *expr = (RelabelType *) node;
1622 
1623  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1624  }
1625  else if (IsA(node, CoerceViaIO))
1626  {
1627  /* not clear this is useful, but it can't hurt */
1628  CoerceViaIO *expr = (CoerceViaIO *) node;
1629 
1630  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1631  }
1632  else if (IsA(node, ArrayCoerceExpr))
1633  {
1634  /* ArrayCoerceExpr is strict at the array level; ignore elemexpr */
1635  ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
1636 
1637  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1638  }
1639  else if (IsA(node, ConvertRowtypeExpr))
1640  {
1641  /* not clear this is useful, but it can't hurt */
1642  ConvertRowtypeExpr *expr = (ConvertRowtypeExpr *) node;
1643 
1644  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1645  }
1646  else if (IsA(node, CollateExpr))
1647  {
1648  CollateExpr *expr = (CollateExpr *) node;
1649 
1650  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1651  }
1652  else if (IsA(node, NullTest))
1653  {
1654  /* IS NOT NULL can be considered strict, but only at top level */
1655  NullTest *expr = (NullTest *) node;
1656 
1657  if (top_level && expr->nulltesttype == IS_NOT_NULL && !expr->argisrow)
1658  result = find_nonnullable_rels_walker((Node *) expr->arg, false);
1659  }
1660  else if (IsA(node, BooleanTest))
1661  {
1662  /* Boolean tests that reject NULL are strict at top level */
1663  BooleanTest *expr = (BooleanTest *) node;
1664 
1665  if (top_level &&
1666  (expr->booltesttype == IS_TRUE ||
1667  expr->booltesttype == IS_FALSE ||
1668  expr->booltesttype == IS_NOT_UNKNOWN))
1669  result = find_nonnullable_rels_walker((Node *) expr->arg, false);
1670  }
1671  else if (IsA(node, PlaceHolderVar))
1672  {
1673  PlaceHolderVar *phv = (PlaceHolderVar *) node;
1674 
1675  /*
1676  * If the contained expression forces any rels non-nullable, so does
1677  * the PHV.
1678  */
1679  result = find_nonnullable_rels_walker((Node *) phv->phexpr, top_level);
1680 
1681  /*
1682  * If the PHV's syntactic scope is exactly one rel, it will be forced
1683  * to be evaluated at that rel, and so it will behave like a Var of
1684  * that rel: if the rel's entire output goes to null, so will the PHV.
1685  * (If the syntactic scope is a join, we know that the PHV will go to
1686  * null if the whole join does; but that is AND semantics while we
1687  * need OR semantics for find_nonnullable_rels' result, so we can't do
1688  * anything with the knowledge.)
1689  */
1690  if (phv->phlevelsup == 0 &&
1692  result = bms_add_members(result, phv->phrels);
1693  }
1694  return result;
1695 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
Index varlevelsup
Definition: primnodes.h:191
List * args
Definition: primnodes.h:477
Expr * arg
Definition: primnodes.h:814
Definition: nodes.h:525
Definition: primnodes.h:181
Oid funcid
Definition: primnodes.h:469
#define ERROR
Definition: elog.h:43
Bitmapset * bms_join(Bitmapset *a, Bitmapset *b)
Definition: bitmapset.c:949
BoolExprType boolop
Definition: primnodes.h:582
Expr * arg
Definition: primnodes.h:1219
Bitmapset * bms_make_singleton(int x)
Definition: bitmapset.c:186
Expr * arg
Definition: primnodes.h:1242
Expr * arg
Definition: primnodes.h:834
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:701
Index varno
Definition: primnodes.h:184
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:672
BoolTestType booltesttype
Definition: primnodes.h:1243
Oid opfuncid
Definition: primnodes.h:517
static Relids find_nonnullable_rels_walker(Node *node, bool top_level)
Definition: clauses.c:1506
NullTestType nulltesttype
Definition: primnodes.h:1220
static bool is_strict_saop(ScalarArrayOpExpr *expr, bool falseOK)
Definition: clauses.c:2026
#define lfirst(lc)
Definition: pg_list.h:190
Expr * arg
Definition: primnodes.h:900
List * args
Definition: primnodes.h:583
bool func_strict(Oid funcid)
Definition: lsyscache.c:1563
Index phlevelsup
Definition: pathnodes.h:2067
void set_opfuncid(OpExpr *opexpr)
Definition: nodeFuncs.c:1618
#define elog(elevel,...)
Definition: elog.h:228
bool argisrow
Definition: primnodes.h:1221
List * args
Definition: primnodes.h:522
Bitmapset * bms_int_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:902
Definition: pg_list.h:50
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:793

◆ find_nonnullable_vars()

List* find_nonnullable_vars ( Node clause)

Definition at line 1725 of file clauses.c.

References find_nonnullable_vars_walker().

Referenced by reduce_outer_joins_pass2().

1726 {
1727  return find_nonnullable_vars_walker(clause, true);
1728 }
static List * find_nonnullable_vars_walker(Node *node, bool top_level)
Definition: clauses.c:1731

◆ find_nonnullable_vars_walker()

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

Definition at line 1731 of file clauses.c.

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

Referenced by find_nonnullable_vars().

1732 {
1733  List *result = NIL;
1734  ListCell *l;
1735 
1736  if (node == NULL)
1737  return NIL;
1738  if (IsA(node, Var))
1739  {
1740  Var *var = (Var *) node;
1741 
1742  if (var->varlevelsup == 0)
1743  result = list_make1(var);
1744  }
1745  else if (IsA(node, List))
1746  {
1747  /*
1748  * At top level, we are examining an implicit-AND list: if any of the
1749  * arms produces FALSE-or-NULL then the result is FALSE-or-NULL. If
1750  * not at top level, we are examining the arguments of a strict
1751  * function: if any of them produce NULL then the result of the
1752  * function must be NULL. So in both cases, the set of nonnullable
1753  * vars is the union of those found in the arms, and we pass down the
1754  * top_level flag unmodified.
1755  */
1756  foreach(l, (List *) node)
1757  {
1758  result = list_concat(result,
1760  top_level));
1761  }
1762  }
1763  else if (IsA(node, FuncExpr))
1764  {
1765  FuncExpr *expr = (FuncExpr *) node;
1766 
1767  if (func_strict(expr->funcid))
1768  result = find_nonnullable_vars_walker((Node *) expr->args, false);
1769  }
1770  else if (IsA(node, OpExpr))
1771  {
1772  OpExpr *expr = (OpExpr *) node;
1773 
1774  set_opfuncid(expr);
1775  if (func_strict(expr->opfuncid))
1776  result = find_nonnullable_vars_walker((Node *) expr->args, false);
1777  }
1778  else if (IsA(node, ScalarArrayOpExpr))
1779  {
1780  ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1781 
1782  if (is_strict_saop(expr, true))
1783  result = find_nonnullable_vars_walker((Node *) expr->args, false);
1784  }
1785  else if (IsA(node, BoolExpr))
1786  {
1787  BoolExpr *expr = (BoolExpr *) node;
1788 
1789  switch (expr->boolop)
1790  {
1791  case AND_EXPR:
1792  /* At top level we can just recurse (to the List case) */
1793  if (top_level)
1794  {
1795  result = find_nonnullable_vars_walker((Node *) expr->args,
1796  top_level);
1797  break;
1798  }
1799 
1800  /*
1801  * Below top level, even if one arm produces NULL, the result
1802  * could be FALSE (hence not NULL). However, if *all* the
1803  * arms produce NULL then the result is NULL, so we can take
1804  * the intersection of the sets of nonnullable vars, just as
1805  * for OR. Fall through to share code.
1806  */
1807  /* FALL THRU */
1808  case OR_EXPR:
1809 
1810  /*
1811  * OR is strict if all of its arms are, so we can take the
1812  * intersection of the sets of nonnullable vars for each arm.
1813  * This works for both values of top_level.
1814  */
1815  foreach(l, expr->args)
1816  {
1817  List *subresult;
1818 
1819  subresult = find_nonnullable_vars_walker(lfirst(l),
1820  top_level);
1821  if (result == NIL) /* first subresult? */
1822  result = subresult;
1823  else
1824  result = list_intersection(result, subresult);
1825 
1826  /*
1827  * If the intersection is empty, we can stop looking. This
1828  * also justifies the test for first-subresult above.
1829  */
1830  if (result == NIL)
1831  break;
1832  }
1833  break;
1834  case NOT_EXPR:
1835  /* NOT will return null if its arg is null */
1836  result = find_nonnullable_vars_walker((Node *) expr->args,
1837  false);
1838  break;
1839  default:
1840  elog(ERROR, "unrecognized boolop: %d", (int) expr->boolop);
1841  break;
1842  }
1843  }
1844  else if (IsA(node, RelabelType))
1845  {
1846  RelabelType *expr = (RelabelType *) node;
1847 
1848  result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1849  }
1850  else if (IsA(node, CoerceViaIO))
1851  {
1852  /* not clear this is useful, but it can't hurt */
1853  CoerceViaIO *expr = (CoerceViaIO *) node;
1854 
1855  result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1856  }
1857  else if (IsA(node, ArrayCoerceExpr))
1858  {
1859  /* ArrayCoerceExpr is strict at the array level; ignore elemexpr */
1860  ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
1861 
1862  result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1863  }
1864  else if (IsA(node, ConvertRowtypeExpr))
1865  {
1866  /* not clear this is useful, but it can't hurt */
1867  ConvertRowtypeExpr *expr = (ConvertRowtypeExpr *) node;
1868 
1869  result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1870  }
1871  else if (IsA(node, CollateExpr))
1872  {
1873  CollateExpr *expr = (CollateExpr *) node;
1874 
1875  result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1876  }
1877  else if (IsA(node, NullTest))
1878  {
1879  /* IS NOT NULL can be considered strict, but only at top level */
1880  NullTest *expr = (NullTest *) node;
1881 
1882  if (top_level && expr->nulltesttype == IS_NOT_NULL && !expr->argisrow)
1883  result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1884  }
1885  else if (IsA(node, BooleanTest))
1886  {
1887  /* Boolean tests that reject NULL are strict at top level */
1888  BooleanTest *expr = (BooleanTest *) node;
1889 
1890  if (top_level &&
1891  (expr->booltesttype == IS_TRUE ||
1892  expr->booltesttype == IS_FALSE ||
1893  expr->booltesttype == IS_NOT_UNKNOWN))
1894  result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1895  }
1896  else if (IsA(node, PlaceHolderVar))
1897  {
1898  PlaceHolderVar *phv = (PlaceHolderVar *) node;
1899 
1900  result = find_nonnullable_vars_walker((Node *) phv->phexpr, top_level);
1901  }
1902  return result;
1903 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
Index varlevelsup
Definition: primnodes.h:191
List * args
Definition: primnodes.h:477
Expr * arg
Definition: primnodes.h:814
Definition: nodes.h:525
List * list_concat(List *list1, const List *list2)
Definition: list.c:516
Definition: primnodes.h:181
#define list_make1(x1)
Definition: pg_list.h:227
Oid funcid
Definition: primnodes.h:469
#define ERROR
Definition: elog.h:43
BoolExprType boolop
Definition: primnodes.h:582
Expr * arg
Definition: primnodes.h:1219
Expr * arg
Definition: primnodes.h:1242
List * list_intersection(const List *list1, const List *list2)
Definition: list.c:1019
static List * find_nonnullable_vars_walker(Node *node, bool top_level)
Definition: clauses.c:1731
Expr * arg
Definition: primnodes.h:834
BoolTestType booltesttype
Definition: primnodes.h:1243
Oid opfuncid
Definition: primnodes.h:517
NullTestType nulltesttype
Definition: primnodes.h:1220
static bool is_strict_saop(ScalarArrayOpExpr *expr, bool falseOK)
Definition: clauses.c:2026
#define lfirst(lc)
Definition: pg_list.h:190
Expr * arg
Definition: primnodes.h:900
List * args
Definition: primnodes.h:583
bool func_strict(Oid funcid)
Definition: lsyscache.c:1563
void set_opfuncid(OpExpr *opexpr)
Definition: nodeFuncs.c:1618
#define elog(elevel,...)
Definition: elog.h:228
bool argisrow
Definition: primnodes.h:1221
List * args
Definition: primnodes.h:522
Definition: pg_list.h:50

◆ find_window_functions()

WindowFuncLists* find_window_functions ( Node clause,
Index  maxWinRef 
)

Definition at line 506 of file clauses.c.

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

Referenced by grouping_planner().

507 {
508  WindowFuncLists *lists = palloc(sizeof(WindowFuncLists));
509 
510  lists->numWindowFuncs = 0;
511  lists->maxWinRef = maxWinRef;
512  lists->windowFuncs = (List **) palloc0((maxWinRef + 1) * sizeof(List *));
513  (void) find_window_functions_walker(clause, lists);
514  return lists;
515 }
Index maxWinRef
Definition: clauses.h:23
int numWindowFuncs
Definition: clauses.h:22
void * palloc0(Size size)
Definition: mcxt.c:980
void * palloc(Size size)
Definition: mcxt.c:949
static bool find_window_functions_walker(Node *node, WindowFuncLists *lists)
Definition: clauses.c:518
Definition: pg_list.h:50
List ** windowFuncs
Definition: clauses.h:24

◆ find_window_functions_walker()

static bool find_window_functions_walker ( Node node,
WindowFuncLists lists 
)
static

Definition at line 518 of file clauses.c.

References Assert, elog, ERROR, expression_tree_walker(), IsA, lappend(), list_member(), WindowFuncLists::maxWinRef, WindowFuncLists::numWindowFuncs, WindowFuncLists::windowFuncs, and WindowFunc::winref.

Referenced by find_window_functions().

519 {
520  if (node == NULL)
521  return false;
522  if (IsA(node, WindowFunc))
523  {
524  WindowFunc *wfunc = (WindowFunc *) node;
525 
526  /* winref is unsigned, so one-sided test is OK */
527  if (wfunc->winref > lists->maxWinRef)
528  elog(ERROR, "WindowFunc contains out-of-range winref %u",
529  wfunc->winref);
530  /* eliminate duplicates, so that we avoid repeated computation */
531  if (!list_member(lists->windowFuncs[wfunc->winref], wfunc))
532  {
533  lists->windowFuncs[wfunc->winref] =
534  lappend(lists->windowFuncs[wfunc->winref], wfunc);
535  lists->numWindowFuncs++;
536  }
537 
538  /*
539  * We assume that the parser checked that there are no window
540  * functions in the arguments or filter clause. Hence, we need not
541  * recurse into them. (If either the parser or the planner screws up
542  * on this point, the executor will still catch it; see ExecInitExpr.)
543  */
544  return false;
545  }
546  Assert(!IsA(node, SubLink));
548  (void *) lists);
549 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
Index maxWinRef
Definition: clauses.h:23
int numWindowFuncs
Definition: clauses.h:22
Index winref
Definition: primnodes.h:379
#define ERROR
Definition: elog.h:43
bool list_member(const List *list, const void *datum)
Definition: list.c:614
List * lappend(List *list, void *datum)
Definition: list.c:322
#define Assert(condition)
Definition: c.h:739
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1839
#define elog(elevel,...)
Definition: elog.h:228
static bool find_window_functions_walker(Node *node, WindowFuncLists *lists)
Definition: clauses.c:518
List ** windowFuncs
Definition: clauses.h:24

◆ get_agg_clause_costs()

void get_agg_clause_costs ( PlannerInfo root,
Node clause,
AggSplit  aggsplit,
AggClauseCosts costs 
)

Definition at line 228 of file clauses.c.

References get_agg_clause_costs_context::aggsplit, get_agg_clause_costs_context::costs, get_agg_clause_costs_walker(), and get_agg_clause_costs_context::root.

Referenced by create_partial_grouping_paths(), estimate_path_cost_size(), and grouping_planner().

230 {
232 
233  context.root = root;
234  context.aggsplit = aggsplit;
235  context.costs = costs;
236  (void) get_agg_clause_costs_walker(clause, &context);
237 }
AggClauseCosts * costs
Definition: clauses.c:61
static bool get_agg_clause_costs_walker(Node *node, get_agg_clause_costs_context *context)
Definition: clauses.c:240

◆ get_agg_clause_costs_walker()

static bool get_agg_clause_costs_walker ( Node node,
get_agg_clause_costs_context context 
)
static

Definition at line 240 of file clauses.c.

References add_function_cost(), Aggref::aggdirectargs, Aggref::aggdistinct, Aggref::aggfilter, AGGFNOID, Aggref::aggfnoid, Aggref::agglevelsup, Aggref::aggorder, get_agg_clause_costs_context::aggsplit, Aggref::aggtranstype, ALLOCSET_DEFAULT_INITSIZE, ALLOCSET_SMALL_INITSIZE, Aggref::args, Assert, cost_qual_eval_node(), get_agg_clause_costs_context::costs, DO_AGGSPLIT_COMBINE, DO_AGGSPLIT_DESERIALIZE, DO_AGGSPLIT_SERIALIZE, DO_AGGSPLIT_SKIPFINAL, elog, ERROR, TargetEntry::expr, expression_tree_walker(), exprType(), exprTypmod(), AggClauseCosts::finalCost, FUNC_MAX_ARGS, get_aggregate_argtypes(), get_typavgwidth(), get_typbyval(), GETSTRUCT, AggClauseCosts::hasNonPartial, AggClauseCosts::hasNonSerial, HeapTupleIsValid, IsA, linitial, MAXALIGN, NIL, AggClauseCosts::numAggs, AggClauseCosts::numOrderedAggs, ObjectIdGetDatum, OidIsValid, QualCost::per_tuple, ReleaseSysCache(), resolve_aggregate_transtype(), get_agg_clause_costs_context::root, SearchSysCache1(), QualCost::startup, AggClauseCosts::transCost, and AggClauseCosts::transitionSpace.

Referenced by get_agg_clause_costs().

241 {
242  if (node == NULL)
243  return false;
244  if (IsA(node, Aggref))
245  {
246  Aggref *aggref = (Aggref *) node;
247  AggClauseCosts *costs = context->costs;
248  HeapTuple aggTuple;
249  Form_pg_aggregate aggform;
250  Oid aggtransfn;
251  Oid aggfinalfn;
252  Oid aggcombinefn;
253  Oid aggserialfn;
254  Oid aggdeserialfn;
255  Oid aggtranstype;
256  int32 aggtransspace;
257  QualCost argcosts;
258 
259  Assert(aggref->agglevelsup == 0);
260 
261  /*
262  * Fetch info about aggregate from pg_aggregate. Note it's correct to
263  * ignore the moving-aggregate variant, since what we're concerned
264  * with here is aggregates not window functions.
265  */
266  aggTuple = SearchSysCache1(AGGFNOID,
267  ObjectIdGetDatum(aggref->aggfnoid));
268  if (!HeapTupleIsValid(aggTuple))
269  elog(ERROR, "cache lookup failed for aggregate %u",
270  aggref->aggfnoid);
271  aggform = (Form_pg_aggregate) GETSTRUCT(aggTuple);
272  aggtransfn = aggform->aggtransfn;
273  aggfinalfn = aggform->aggfinalfn;
274  aggcombinefn = aggform->aggcombinefn;
275  aggserialfn = aggform->aggserialfn;
276  aggdeserialfn = aggform->aggdeserialfn;
277  aggtranstype = aggform->aggtranstype;
278  aggtransspace = aggform->aggtransspace;
279  ReleaseSysCache(aggTuple);
280 
281  /*
282  * Resolve the possibly-polymorphic aggregate transition type, unless
283  * already done in a previous pass over the expression.
284  */
285  if (OidIsValid(aggref->aggtranstype))
286  aggtranstype = aggref->aggtranstype;
287  else
288  {
289  Oid inputTypes[FUNC_MAX_ARGS];
290  int numArguments;
291 
292  /* extract argument types (ignoring any ORDER BY expressions) */
293  numArguments = get_aggregate_argtypes(aggref, inputTypes);
294 
295  /* resolve actual type of transition state, if polymorphic */
296  aggtranstype = resolve_aggregate_transtype(aggref->aggfnoid,
297  aggtranstype,
298  inputTypes,
299  numArguments);
300  aggref->aggtranstype = aggtranstype;
301  }
302 
303  /*
304  * Count it, and check for cases requiring ordered input. Note that
305  * ordered-set aggs always have nonempty aggorder. Any ordered-input
306  * case also defeats partial aggregation.
307  */
308  costs->numAggs++;
309  if (aggref->aggorder != NIL || aggref->aggdistinct != NIL)
310  {
311  costs->numOrderedAggs++;
312  costs->hasNonPartial = true;
313  }
314 
315  /*
316  * Check whether partial aggregation is feasible, unless we already
317  * found out that we can't do it.
318  */
319  if (!costs->hasNonPartial)
320  {
321  /*
322  * If there is no combine function, then partial aggregation is
323  * not possible.
324  */
325  if (!OidIsValid(aggcombinefn))
326  costs->hasNonPartial = true;
327 
328  /*
329  * If we have any aggs with transtype INTERNAL then we must check
330  * whether they have serialization/deserialization functions; if
331  * not, we can't serialize partial-aggregation results.
332  */
333  else if (aggtranstype == INTERNALOID &&
334  (!OidIsValid(aggserialfn) || !OidIsValid(aggdeserialfn)))
335  costs->hasNonSerial = true;
336  }
337 
338  /*
339  * Add the appropriate component function execution costs to
340  * appropriate totals.
341  */
342  if (DO_AGGSPLIT_COMBINE(context->aggsplit))
343  {
344  /* charge for combining previously aggregated states */
345  add_function_cost(context->root, aggcombinefn, NULL,
346  &costs->transCost);
347  }
348  else
349  add_function_cost(context->root, aggtransfn, NULL,
350  &costs->transCost);
351  if (DO_AGGSPLIT_DESERIALIZE(context->aggsplit) &&
352  OidIsValid(aggdeserialfn))
353  add_function_cost(context->root, aggdeserialfn, NULL,
354  &costs->transCost);
355  if (DO_AGGSPLIT_SERIALIZE(context->aggsplit) &&
356  OidIsValid(aggserialfn))
357  add_function_cost(context->root, aggserialfn, NULL,
358  &costs->finalCost);
359  if (!DO_AGGSPLIT_SKIPFINAL(context->aggsplit) &&
360  OidIsValid(aggfinalfn))
361  add_function_cost(context->root, aggfinalfn, NULL,
362  &costs->finalCost);
363 
364  /*
365  * These costs are incurred only by the initial aggregate node, so we
366  * mustn't include them again at upper levels.
367  */
368  if (!DO_AGGSPLIT_COMBINE(context->aggsplit))
369  {
370  /* add the input expressions' cost to per-input-row costs */
371  cost_qual_eval_node(&argcosts, (Node *) aggref->args, context->root);
372  costs->transCost.startup += argcosts.startup;
373  costs->transCost.per_tuple += argcosts.per_tuple;
374 
375  /*
376  * Add any filter's cost to per-input-row costs.
377  *
378  * XXX Ideally we should reduce input expression costs according
379  * to filter selectivity, but it's not clear it's worth the
380  * trouble.
381  */
382  if (aggref->aggfilter)
383  {
384  cost_qual_eval_node(&argcosts, (Node *) aggref->aggfilter,
385  context->root);
386  costs->transCost.startup += argcosts.startup;
387  costs->transCost.per_tuple += argcosts.per_tuple;
388  }
389  }
390 
391  /*
392  * If there are direct arguments, treat their evaluation cost like the
393  * cost of the finalfn.
394  */
395  if (aggref->aggdirectargs)
396  {
397  cost_qual_eval_node(&argcosts, (Node *) aggref->aggdirectargs,
398  context->root);
399  costs->finalCost.startup += argcosts.startup;
400  costs->finalCost.per_tuple += argcosts.per_tuple;
401  }
402 
403  /*
404  * If the transition type is pass-by-value then it doesn't add
405  * anything to the required size of the hashtable. If it is
406  * pass-by-reference then we have to add the estimated size of the
407  * value itself, plus palloc overhead.
408  */
409  if (!get_typbyval(aggtranstype))
410  {
411  int32 avgwidth;
412 
413  /* Use average width if aggregate definition gave one */
414  if (aggtransspace > 0)
415  avgwidth = aggtransspace;
416  else if (aggtransfn == F_ARRAY_APPEND)
417  {
418  /*
419  * If the transition function is array_append(), it'll use an
420  * expanded array as transvalue, which will occupy at least
421  * ALLOCSET_SMALL_INITSIZE and possibly more. Use that as the
422  * estimate for lack of a better idea.
423  */
424  avgwidth = ALLOCSET_SMALL_INITSIZE;
425  }
426  else
427  {
428  /*
429  * If transition state is of same type as first aggregated
430  * input, assume it's the same typmod (same width) as well.
431  * This works for cases like MAX/MIN and is probably somewhat
432  * reasonable otherwise.
433  */
434  int32 aggtranstypmod = -1;
435 
436  if (aggref->args)
437  {
438  TargetEntry *tle = (TargetEntry *) linitial(aggref->args);
439 
440  if (aggtranstype == exprType((Node *) tle->expr))
441  aggtranstypmod = exprTypmod((Node *) tle->expr);
442  }
443 
444  avgwidth = get_typavgwidth(aggtranstype, aggtranstypmod);
445  }
446 
447  avgwidth = MAXALIGN(avgwidth);
448  costs->transitionSpace += avgwidth + 2 * sizeof(void *);
449  }
450  else if (aggtranstype == INTERNALOID)
451  {
452  /*
453  * INTERNAL transition type is a special case: although INTERNAL
454  * is pass-by-value, it's almost certainly being used as a pointer
455  * to some large data structure. The aggregate definition can
456  * provide an estimate of the size. If it doesn't, then we assume
457  * ALLOCSET_DEFAULT_INITSIZE, which is a good guess if the data is
458  * being kept in a private memory context, as is done by
459  * array_agg() for instance.
460  */
461  if (aggtransspace > 0)
462  costs->transitionSpace += aggtransspace;
463  else
465  }
466 
467  /*
468  * We assume that the parser checked that there are no aggregates (of
469  * this level anyway) in the aggregated arguments, direct arguments,
470  * or filter clause. Hence, we need not recurse into any of them.
471  */
472  return false;
473  }
474  Assert(!IsA(node, SubLink));
476  (void *) context);
477 }
List * aggdistinct
Definition: primnodes.h:321
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:3845
#define NIL
Definition: pg_list.h:65
AggClauseCosts * costs
Definition: clauses.c:61
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:275
QualCost finalCost
Definition: pathnodes.h:63
Definition: nodes.h:525
List * args
Definition: primnodes.h:319
bool hasNonSerial
Definition: pathnodes.h:61
void add_function_cost(PlannerInfo *root, Oid funcid, Node *node, QualCost *cost)
Definition: plancat.c:1905
bool hasNonPartial
Definition: pathnodes.h:60
QualCost transCost
Definition: pathnodes.h:62
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:645
#define DO_AGGSPLIT_COMBINE(as)
Definition: nodes.h:787
Cost startup
Definition: pathnodes.h:45
static bool get_agg_clause_costs_walker(Node *node, get_agg_clause_costs_context *context)
Definition: clauses.c:240
signed int int32
Definition: c.h:347
#define FUNC_MAX_ARGS
bool get_typbyval(Oid typid)
Definition: lsyscache.c:2000
Cost per_tuple
Definition: pathnodes.h:46
#define DO_AGGSPLIT_SERIALIZE(as)
Definition: nodes.h:789
#define linitial(l)
Definition: pg_list.h:195
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
List * aggorder
Definition: primnodes.h:320
Index agglevelsup
Definition: primnodes.h:327
List * aggdirectargs
Definition: primnodes.h:318
int numOrderedAggs
Definition: pathnodes.h:59
#define ALLOCSET_SMALL_INITSIZE
Definition: memutils.h:200
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition: lsyscache.c:2356
Oid aggfnoid
Definition: primnodes.h:312
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:739
FormData_pg_aggregate * Form_pg_aggregate
Definition: pg_aggregate.h:109
Expr * expr
Definition: primnodes.h:1407
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1839
#define DO_AGGSPLIT_SKIPFINAL(as)
Definition: nodes.h:788
Expr * aggfilter
Definition: primnodes.h:322
#define MAXALIGN(LEN)
Definition: c.h:692
#define DO_AGGSPLIT_DESERIALIZE(as)
Definition: nodes.h:790
#define elog(elevel,...)
Definition: elog.h:228
#define ALLOCSET_DEFAULT_INITSIZE
Definition: memutils.h:190
Oid aggtranstype
Definition: primnodes.h:316
Size transitionSpace
Definition: pathnodes.h:64
int get_aggregate_argtypes(Aggref *aggref, Oid *inputTypes)
Definition: parse_agg.c:1819
Oid resolve_aggregate_transtype(Oid aggfuncid, Oid aggtranstype, Oid *inputTypes, int numArguments)
Definition: parse_agg.c:1845

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

References ACL_EXECUTE, ACLCHECK_OK, eval_const_expressions_context::active_fns, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, arg, ErrorContextCallback::arg, CollateExpr::arg, generate_unaccent_rules::args, FuncExpr::args, ErrorContextCallback::callback, check_sql_fn_retval(), CMD_SELECT, COERCE_EXPLICIT_CALL, CollateExpr::collOid, Query::commandType, contain_context_dependent_node(), contain_mutable_functions(), contain_nonstrict_functions(), contain_subplans(), contain_volatile_functions(), copyObject, cost_qual_eval(), cpu_operator_cost, Query::cteList, CurrentMemoryContext, Query::distinctClause, elog, ERROR, error_context_stack, eval_const_expressions_mutator(), exprCollation(), exprType(), FmgrHookIsNeeded, free_parsestate(), FromExpr::fromlist, FuncExpr::funccollid, FuncExpr::funcformat, FuncExpr::funcid, FuncExpr::funcresulttype, FuncExpr::funcretset, FuncExpr::funcvariadic, get_expr_result_type(), GETSTRUCT, GetUserId(), Query::groupClause, Query::groupingSets, Query::hasAggs, Query::hasSubLinks, Query::hasTargetSRFs, Query::hasWindowFuncs, Query::havingQual, heap_attisnull(), i, FuncExpr::inputcollid, IsA, Query::jointree, lappend_oid(), lfirst, Query::limitCount, Query::limitOffset, linitial, list_delete_last(), list_length(), list_make1, list_member_oid(), FuncExpr::location, CollateExpr::location, make_parsestate(), makeNode, MemoryContextDelete(), MemoryContextSwitchTo(), NameStr, OidIsValid, ParseState::p_sourcetext, palloc0(), QualCost::per_tuple, pg_parse_query(), pg_proc_aclcheck(), prepare_sql_fn_parse_info(), ErrorContextCallback::previous, PROCOID, inline_error_callback_arg::proname, inline_error_callback_arg::prosrc, FromExpr::quals, querytree(), record_plan_function_dependency(), eval_const_expressions_context::root, Query::rtable, Query::setOperations, Query::sortClause, sql_fn_parser_setup(), sql_inline_error_callback(), QualCost::startup, substitute_actual_parameters(), SysCacheGetAttr(), Query::targetList, TextDatumGetCString, transformTopLevelStmt(), and Query::windowClause.

Referenced by simplify_function().

4396 {
4397  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4398  char *src;
4399  Datum tmp;
4400  bool isNull;
4401  MemoryContext oldcxt;
4402  MemoryContext mycxt;
4403  inline_error_callback_arg callback_arg;
4404  ErrorContextCallback sqlerrcontext;
4405  FuncExpr *fexpr;
4407  TupleDesc rettupdesc;
4408  ParseState *pstate;
4409  List *raw_parsetree_list;
4410  List *querytree_list;
4411  Query *querytree;
4412  Node *newexpr;
4413  int *usecounts;
4414  ListCell *arg;
4415  int i;
4416 
4417  /*
4418  * Forget it if the function is not SQL-language or has other showstopper
4419  * properties. (The prokind and nargs checks are just paranoia.)
4420  */
4421  if (funcform->prolang != SQLlanguageId ||
4422  funcform->prokind != PROKIND_FUNCTION ||
4423  funcform->prosecdef ||
4424  funcform->proretset ||
4425  funcform->prorettype == RECORDOID ||
4426  !heap_attisnull(func_tuple, Anum_pg_proc_proconfig, NULL) ||
4427  funcform->pronargs != list_length(args))
4428  return NULL;
4429 
4430  /* Check for recursive function, and give up trying to expand if so */
4431  if (list_member_oid(context->active_fns, funcid))
4432  return NULL;
4433 
4434  /* Check permission to call function (fail later, if not) */
4436  return NULL;
4437 
4438  /* Check whether a plugin wants to hook function entry/exit */
4439  if (FmgrHookIsNeeded(funcid))
4440  return NULL;
4441 
4442  /*
4443  * Make a temporary memory context, so that we don't leak all the stuff
4444  * that parsing might create.
4445  */
4447  "inline_function",
4449  oldcxt = MemoryContextSwitchTo(mycxt);
4450 
4451  /* Fetch the function body */
4452  tmp = SysCacheGetAttr(PROCOID,
4453  func_tuple,
4454  Anum_pg_proc_prosrc,
4455  &isNull);
4456  if (isNull)
4457  elog(ERROR, "null prosrc for function %u", funcid);
4458  src = TextDatumGetCString(tmp);
4459 
4460  /*
4461  * Setup error traceback support for ereport(). This is so that we can
4462  * finger the function that bad information came from.
4463  */
4464  callback_arg.proname = NameStr(funcform->proname);
4465  callback_arg.prosrc = src;
4466 
4467  sqlerrcontext.callback = sql_inline_error_callback;
4468  sqlerrcontext.arg = (void *) &callback_arg;
4469  sqlerrcontext.previous = error_context_stack;
4470  error_context_stack = &sqlerrcontext;
4471 
4472  /*
4473  * Set up to handle parameters while parsing the function body. We need a
4474  * dummy FuncExpr node containing the already-simplified arguments to pass
4475  * to prepare_sql_fn_parse_info. (In some cases we don't really need
4476  * that, but for simplicity we always build it.)
4477  */
4478  fexpr = makeNode(FuncExpr);
4479  fexpr->funcid = funcid;
4480  fexpr->funcresulttype = result_type;
4481  fexpr->funcretset = false;
4482  fexpr->funcvariadic = funcvariadic;
4483  fexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
4484  fexpr->funccollid = result_collid; /* doesn't matter */
4485  fexpr->inputcollid = input_collid;
4486  fexpr->args = args;
4487  fexpr->location = -1;
4488 
4489  pinfo = prepare_sql_fn_parse_info(func_tuple,
4490  (Node *) fexpr,
4491  input_collid);
4492 
4493  /* fexpr also provides a convenient way to resolve a composite result */
4494  (void) get_expr_result_type((Node *) fexpr,
4495  NULL,
4496  &rettupdesc);
4497 
4498  /*
4499  * We just do parsing and parse analysis, not rewriting, because rewriting
4500  * will not affect table-free-SELECT-only queries, which is all that we
4501  * care about. Also, we can punt as soon as we detect more than one
4502  * command in the function body.
4503  */
4504  raw_parsetree_list = pg_parse_query(src);
4505  if (list_length(raw_parsetree_list) != 1)
4506  goto fail;
4507 
4508  pstate = make_parsestate(NULL);
4509  pstate->p_sourcetext = src;
4510  sql_fn_parser_setup(pstate, pinfo);
4511 
4512  querytree = transformTopLevelStmt(pstate, linitial(raw_parsetree_list));
4513 
4514  free_parsestate(pstate);
4515 
4516  /*
4517  * The single command must be a simple "SELECT expression".
4518  *
4519  * Note: if you change the tests involved in this, see also plpgsql's
4520  * exec_simple_check_plan(). That generally needs to have the same idea
4521  * of what's a "simple expression", so that inlining a function that
4522  * previously wasn't inlined won't change plpgsql's conclusion.
4523  */
4524  if (!IsA(querytree, Query) ||
4525  querytree->commandType != CMD_SELECT ||
4526  querytree->hasAggs ||
4527  querytree->hasWindowFuncs ||
4528  querytree->hasTargetSRFs ||
4529  querytree->hasSubLinks ||
4530  querytree->cteList ||
4531  querytree->rtable ||
4532  querytree->jointree->fromlist ||
4533  querytree->jointree->quals ||
4534  querytree->groupClause ||
4535  querytree->groupingSets ||
4536  querytree->havingQual ||
4537  querytree->windowClause ||
4538  querytree->distinctClause ||
4539  querytree->sortClause ||
4540  querytree->limitOffset ||
4541  querytree->limitCount ||
4542  querytree->setOperations ||
4543  list_length(querytree->targetList) != 1)
4544  goto fail;
4545 
4546  /*
4547  * Make sure the function (still) returns what it's declared to. This
4548  * will raise an error if wrong, but that's okay since the function would
4549  * fail at runtime anyway. Note that check_sql_fn_retval will also insert
4550  * a coercion if needed to make the tlist expression match the declared
4551  * type of the function.
4552  *
4553  * Note: we do not try this until we have verified that no rewriting was
4554  * needed; that's probably not important, but let's be careful.
4555  */
4556  querytree_list = list_make1(querytree);
4557  if (check_sql_fn_retval(querytree_list, result_type, rettupdesc,
4558  false, NULL))
4559  goto fail; /* reject whole-tuple-result cases */
4560 
4561  /*
4562  * Given the tests above, check_sql_fn_retval shouldn't have decided to
4563  * inject a projection step, but let's just make sure.
4564  */
4565  if (querytree != linitial(querytree_list))
4566  goto fail;
4567 
4568  /* Now we can grab the tlist expression */
4569  newexpr = (Node *) ((TargetEntry *) linitial(querytree->targetList))->expr;
4570 
4571  /*
4572  * If the SQL function returns VOID, we can only inline it if it is a
4573  * SELECT of an expression returning VOID (ie, it's just a redirection to
4574  * another VOID-returning function). In all non-VOID-returning cases,
4575  * check_sql_fn_retval should ensure that newexpr returns the function's
4576  * declared result type, so this test shouldn't fail otherwise; but we may
4577  * as well cope gracefully if it does.
4578  */
4579  if (exprType(newexpr) != result_type)
4580  goto fail;
4581 
4582  /*
4583  * Additional validity checks on the expression. It mustn't be more
4584  * volatile than the surrounding function (this is to avoid breaking hacks
4585  * that involve pretending a function is immutable when it really ain't).
4586  * If the surrounding function is declared strict, then the expression
4587  * must contain only strict constructs and must use all of the function
4588  * parameters (this is overkill, but an exact analysis is hard).
4589  */
4590  if (funcform->provolatile == PROVOLATILE_IMMUTABLE &&
4591  contain_mutable_functions(newexpr))
4592  goto fail;
4593  else if (funcform->provolatile == PROVOLATILE_STABLE &&
4594  contain_volatile_functions(newexpr))
4595  goto fail;
4596 
4597  if (funcform->proisstrict &&
4598  contain_nonstrict_functions(newexpr))
4599  goto fail;
4600 
4601  /*
4602  * If any parameter expression contains a context-dependent node, we can't
4603  * inline, for fear of putting such a node into the wrong context.
4604  */
4605  if (contain_context_dependent_node((Node *) args))
4606  goto fail;
4607 
4608  /*
4609  * We may be able to do it; there are still checks on parameter usage to
4610  * make, but those are most easily done in combination with the actual
4611  * substitution of the inputs. So start building expression with inputs
4612  * substituted.
4613  */
4614  usecounts = (int *) palloc0(funcform->pronargs * sizeof(int));
4615  newexpr = substitute_actual_parameters(newexpr, funcform->pronargs,
4616  args, usecounts);
4617 
4618  /* Now check for parameter usage */
4619  i = 0;
4620  foreach(arg, args)
4621  {
4622  Node *param = lfirst(arg);
4623 
4624  if (usecounts[i] == 0)
4625  {
4626  /* Param not used at all: uncool if func is strict */
4627  if (funcform->proisstrict)
4628  goto fail;
4629  }
4630  else if (usecounts[i] != 1)
4631  {
4632  /* Param used multiple times: uncool if expensive or volatile */
4633  QualCost eval_cost;
4634 
4635  /*
4636  * We define "expensive" as "contains any subplan or more than 10
4637  * operators". Note that the subplan search has to be done
4638  * explicitly, since cost_qual_eval() will barf on unplanned
4639  * subselects.
4640  */
4641  if (contain_subplans(param))
4642  goto fail;
4643  cost_qual_eval(&eval_cost, list_make1(param), NULL);
4644  if (eval_cost.startup + eval_cost.per_tuple >
4645  10 * cpu_operator_cost)
4646  goto fail;
4647 
4648  /*
4649  * Check volatility last since this is more expensive than the
4650  * above tests
4651  */
4652  if (contain_volatile_functions(param))
4653  goto fail;
4654  }
4655  i++;
4656  }
4657 
4658  /*
4659  * Whew --- we can make the substitution. Copy the modified expression
4660  * out of the temporary memory context, and clean up.
4661  */
4662  MemoryContextSwitchTo(oldcxt);
4663 
4664  newexpr = copyObject(newexpr);
4665 
4666  MemoryContextDelete(mycxt);
4667 
4668  /*
4669  * If the result is of a collatable type, force the result to expose the
4670  * correct collation. In most cases this does not matter, but it's
4671  * possible that the function result is used directly as a sort key or in
4672  * other places where we expect exprCollation() to tell the truth.
4673  */
4674  if (OidIsValid(result_collid))
4675  {
4676  Oid exprcoll = exprCollation(newexpr);
4677 
4678  if (OidIsValid(exprcoll) && exprcoll != result_collid)
4679  {
4680  CollateExpr *newnode = makeNode(CollateExpr);
4681 
4682  newnode->arg = (Expr *) newexpr;
4683  newnode->collOid = result_collid;
4684  newnode->location = -1;
4685 
4686  newexpr = (Node *) newnode;
4687  }
4688  }
4689 
4690  /*
4691  * Since there is now no trace of the function in the plan tree, we must
4692  * explicitly record the plan's dependency on the function.
4693  */
4694  if (context->root)
4695  record_plan_function_dependency(context->root, funcid);
4696 
4697  /*
4698  * Recursively try to simplify the modified expression. Here we must add
4699  * the current function to the context list of active functions.
4700  */
4701  context->active_fns = lappend_oid(context->active_fns, funcid);
4702  newexpr = eval_const_expressions_mutator(newexpr, context);
4703  context->active_fns = list_delete_last(context->active_fns);
4704 
4705  error_context_stack = sqlerrcontext.previous;
4706 
4707  return (Expr *) newexpr;
4708 
4709  /* Here if func is not inlinable: release temp memory and return NULL */
4710 fail:
4711  MemoryContextSwitchTo(oldcxt);
4712  MemoryContextDelete(mycxt);
4713  error_context_stack = sqlerrcontext.previous;
4714 
4715  return NULL;
4716 }
Node * limitOffset
Definition: parsenodes.h:160
Oid funcresulttype
Definition: primnodes.h:470
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
#define AllocSetContextCreate
Definition: memutils.h:170
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
List * sortClause
Definition: parsenodes.h:158
List * args
Definition: primnodes.h:477
FromExpr * jointree
Definition: parsenodes.h:138
Oid GetUserId(void)
Definition: miscinit.c:380
Oid funccollid
Definition: primnodes.h:475
void sql_fn_parser_setup(struct ParseState *pstate, SQLFunctionParseInfoPtr pinfo)
Definition: functions.c:278
bool check_sql_fn_retval(List *queryTreeList, Oid rettype, TupleDesc rettupdesc, bool insertDroppedCols, List **resultTargetList)
Definition: functions.c:1589
bool hasAggs
Definition: parsenodes.h:125
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
List * groupingSets
Definition: parsenodes.h:150
Definition: nodes.h:525
bool heap_attisnull(HeapTuple tup, int attnum, TupleDesc tupleDesc)
Definition: heaptuple.c:359
bool funcretset
Definition: primnodes.h:471
List * fromlist
Definition: primnodes.h:1510
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:723
unsigned int Oid
Definition: postgres_ext.h:31
void(* callback)(void *arg)
Definition: elog.h:256
TypeFuncClass get_expr_result_type(Node *expr, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:212
List * lappend_oid(List *list, Oid datum)
Definition: list.c:358
struct ErrorContextCallback * previous
Definition: elog.h:255
#define OidIsValid(objectId)
Definition: c.h:645
#define FmgrHookIsNeeded(fn_oid)
Definition: fmgr.h:760
Node * quals
Definition: primnodes.h:1511
Cost startup
Definition: pathnodes.h:45
List * windowClause
Definition: parsenodes.h:154
List * targetList
Definition: parsenodes.h:140
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:43
ErrorContextCallback * error_context_stack
Definition: elog.c:91
#define list_make1(x1)
Definition: pg_list.h:227
bool contain_subplans(Node *clause)
Definition: clauses.c:609
CoercionForm funcformat
Definition: primnodes.h:474
Cost per_tuple
Definition: pathnodes.h:46
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2330
#define linitial(l)
Definition: pg_list.h:195
List * rtable
Definition: parsenodes.h:137
List * distinctClause
Definition: parsenodes.h:156
Oid funcid
Definition: primnodes.h:469
#define ERROR
Definition: elog.h:43
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3819
List * pg_parse_query(const char *query_string)
Definition: postgres.c:628
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
Node * limitCount
Definition: parsenodes.h:161
List * list_delete_last(List *list)
Definition: list.c:878
double cpu_operator_cost
Definition: costsize.c:114
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
const char * p_sourcetext
Definition: parse_node.h:179
static Node * substitute_actual_parameters(Node *expr, int nargs, List *args, int *usecounts)
Definition: clauses.c:4722
static void sql_inline_error_callback(void *arg)
Definition: clauses.c:4764
#define TextDatumGetCString(d)
Definition: builtins.h:84
void * palloc0(Size size)
Definition: mcxt.c:980
uintptr_t Datum
Definition: postgres.h:367
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1377
void record_plan_function_dependency(PlannerInfo *root, Oid funcid)
Definition: setrefs.c:2709
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:133
CmdType commandType
Definition: parsenodes.h:112
bool hasTargetSRFs
Definition: parsenodes.h:127
#define makeNode(_type_)
Definition: nodes.h:573
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:675
Oid inputcollid
Definition: primnodes.h:476
#define lfirst(lc)
Definition: pg_list.h:190
bool hasWindowFuncs
Definition: parsenodes.h:126
Query * transformTopLevelStmt(ParseState *pstate, RawStmt *parseTree)
Definition: analyze.c:191
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
static int list_length(const List *l)
Definition: pg_list.h:169
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:719
Expr * arg
Definition: primnodes.h:900
Datum querytree(PG_FUNCTION_ARGS)
Definition: _int_bool.c:664
static bool contain_context_dependent_node(Node *clause)
Definition: clauses.c:1242
List * cteList
Definition: parsenodes.h:135
Node * setOperations
Definition: parsenodes.h:165
List * groupClause
Definition: parsenodes.h:148