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 Nodeapply_const_relabel (Node *arg, Oid rtype, int32 rtypmod, Oid rcollid, CoercionForm rformat, int rlocation)
 
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 1252 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 2319 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:4773
Definition: nodes.h:529
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41

Definition at line 2323 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:529
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2333

Definition at line 2310 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 4145 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().

4146 {
4147  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4148  int nargsprovided = list_length(args);
4149  List *defaults;
4150  int ndelete;
4151 
4152  /* Get all the default expressions from the pg_proc tuple */
4153  defaults = fetch_function_defaults(func_tuple);
4154 
4155  /* Delete any unused defaults from the list */
4156  ndelete = nargsprovided + list_length(defaults) - funcform->pronargs;
4157  if (ndelete < 0)
4158  elog(ERROR, "not enough default arguments");
4159  if (ndelete > 0)
4160  defaults = list_copy_tail(defaults, ndelete);
4161 
4162  /* And form the combined argument list, not modifying the input list */
4163  return list_concat_copy(args, defaults);
4164 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
List * list_copy_tail(const List *oldlist, int nskip)
Definition: list.c:1422
#define ERROR
Definition: elog.h:43
List * list_concat_copy(const List *list1, const List *list2)
Definition: list.c:552
static List * fetch_function_defaults(HeapTuple func_tuple)
Definition: clauses.c:4170
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:214
Definition: pg_list.h:50

◆ apply_const_relabel()

static Node * apply_const_relabel ( Node arg,
Oid  rtype,
int32  rtypmod,
Oid  rcollid,
CoercionForm  rformat,
int  rlocation 
)
static

Definition at line 3588 of file clauses.c.

References arg, RelabelType::arg, Const::constcollid, Const::consttype, Const::consttypmod, exprCollation(), exprType(), exprTypmod(), IsA, RelabelType::location, makeNode, RelabelType::relabelformat, RelabelType::resultcollid, RelabelType::resulttype, and RelabelType::resulttypmod.

Referenced by eval_const_expressions_mutator().

3590 {
3591  /*
3592  * If we find stacked RelabelTypes (eg, from foo::int::oid) we can discard
3593  * all but the top one, and must do so to ensure that semantically
3594  * equivalent expressions are equal().
3595  */
3596  while (arg && IsA(arg, RelabelType))
3597  arg = (Node *) ((RelabelType *) arg)->arg;
3598 
3599  if (arg && IsA(arg, Const))
3600  {
3601  /*
3602  * If it's a Const, just modify it in-place; since this is part of
3603  * eval_const_expressions, we want to end up with a simple Const not
3604  * an expression tree. We assume the Const is newly generated and
3605  * hence safe to modify.
3606  */
3607  Const *con = (Const *) arg;
3608 
3609  con->consttype = rtype;
3610  con->consttypmod = rtypmod;
3611  con->constcollid = rcollid;
3612  return (Node *) con;
3613  }
3614  else if (exprType(arg) == rtype &&
3615  exprTypmod(arg) == rtypmod &&
3616  exprCollation(arg) == rcollid)
3617  {
3618  /* Sometimes we find a nest of relabels that net out to nothing. */
3619  return arg;
3620  }
3621  else
3622  {
3623  /* Nope, gotta have a RelabelType. */
3624  RelabelType *newrelabel = makeNode(RelabelType);
3625 
3626  newrelabel->arg = (Expr *) arg;
3627  newrelabel->resulttype = rtype;
3628  newrelabel->resulttypmod = rtypmod;
3629  newrelabel->resultcollid = rcollid;
3630  newrelabel->relabelformat = rformat;
3631  newrelabel->location = rlocation;
3632  return (Node *) newrelabel;
3633  }
3634 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:275
Expr * arg
Definition: primnodes.h:814
Definition: nodes.h:529
Oid consttype
Definition: primnodes.h:210
Oid constcollid
Definition: primnodes.h:212
Oid resulttype
Definition: primnodes.h:815
Oid resultcollid
Definition: primnodes.h:817
#define makeNode(_type_)
Definition: nodes.h:577
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:719
int32 consttypmod
Definition: primnodes.h:211
void * arg
int32 resulttypmod
Definition: primnodes.h:816
CoercionForm relabelformat
Definition: primnodes.h:818
int location
Definition: primnodes.h:819

◆ CommuteOpExpr()

void CommuteOpExpr ( OpExpr clause)

Definition at line 2148 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().

2149 {
2150  Oid opoid;
2151  Node *temp;
2152 
2153  /* Sanity checks: caller is at fault if these fail */
2154  if (!is_opclause(clause) ||
2155  list_length(clause->args) != 2)
2156  elog(ERROR, "cannot commute non-binary-operator clause");
2157 
2158  opoid = get_commutator(clause->opno);
2159 
2160  if (!OidIsValid(opoid))
2161  elog(ERROR, "could not find commutator for operator %u",
2162  clause->opno);
2163 
2164  /*
2165  * modify the clause in-place!
2166  */
2167  clause->opno = opoid;
2168  clause->opfuncid = InvalidOid;
2169  /* opresulttype, opretset, opcollid, inputcollid need not change */
2170 
2171  temp = linitial(clause->args);
2172  linitial(clause->args) = lsecond(clause->args);
2173  lsecond(clause->args) = temp;
2174 }
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1421
Definition: nodes.h:529
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:644
#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:214
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 181 of file clauses.c.

References contain_agg_clause_walker().

Referenced by get_eclass_for_sort_expr(), and subquery_planner().

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

◆ contain_agg_clause_walker()

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

Definition at line 187 of file clauses.c.

References Assert, expression_tree_walker(), and IsA.

Referenced by contain_agg_clause().

188 {
189  if (node == NULL)
190  return false;
191  if (IsA(node, Aggref))
192  {
193  Assert(((Aggref *) node)->agglevelsup == 0);
194  return true; /* abort the tree traversal and return true */
195  }
196  if (IsA(node, GroupingFunc))
197  {
198  Assert(((GroupingFunc *) node)->agglevelsup == 0);
199  return true; /* abort the tree traversal and return true */
200  }
201  Assert(!IsA(node, SubLink));
202  return expression_tree_walker(node, contain_agg_clause_walker, context);
203 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
static bool contain_agg_clause_walker(Node *node, void *context)
Definition: clauses.c:187
#define Assert(condition)
Definition: c.h:738
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 1245 of file clauses.c.

References contain_context_dependent_node_walker().

Referenced by inline_function().

1246 {
1247  int flags = 0;
1248 
1249  return contain_context_dependent_node_walker(clause, &flags);
1250 }
static bool contain_context_dependent_node_walker(Node *node, int *flags)
Definition: clauses.c:1255

◆ contain_context_dependent_node_walker()

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

Definition at line 1255 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().

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

◆ contain_leaked_vars()

bool contain_leaked_vars ( Node clause)

Definition at line 1329 of file clauses.c.

References contain_leaked_vars_walker().

Referenced by make_restrictinfo_internal(), and qual_is_pushdown_safe().

1330 {
1331  return contain_leaked_vars_walker(clause, NULL);
1332 }
static bool contain_leaked_vars_walker(Node *node, void *context)
Definition: clauses.c:1341

◆ contain_leaked_vars_checker()

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

Definition at line 1335 of file clauses.c.

References get_func_leakproof().

Referenced by contain_leaked_vars_walker().

1336 {
1337  return !get_func_leakproof(func_id);
1338 }
bool get_func_leakproof(Oid funcid)
Definition: lsyscache.c:1749

◆ contain_leaked_vars_walker()

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

Definition at line 1341 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().

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

◆ contain_mutable_functions()

◆ contain_mutable_functions_checker()

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

Definition at line 653 of file clauses.c.

References func_volatile().

Referenced by contain_mutable_functions_walker().

654 {
655  return (func_volatile(func_id) != PROVOLATILE_IMMUTABLE);
656 }
char func_volatile(Oid funcid)
Definition: lsyscache.c:1692

◆ contain_mutable_functions_walker()

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

Definition at line 659 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().

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

References expression_tree_walker(), and IsA.

3551 {
3552  if (node == NULL)
3553  return false;
3554  if (IsA(node, Const))
3555  return false;
3556  if (IsA(node, List))
3557  return expression_tree_walker(node, contain_non_const_walker, context);
3558  /* Otherwise, abort the tree traversal and return true */
3559  return true;
3560 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
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:3550

◆ contain_nonstrict_functions()

bool contain_nonstrict_functions ( Node clause)

Definition at line 1096 of file clauses.c.

References contain_nonstrict_functions_walker().

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

1097 {
1098  return contain_nonstrict_functions_walker(clause, NULL);
1099 }
static bool contain_nonstrict_functions_walker(Node *node, void *context)
Definition: clauses.c:1108

◆ contain_nonstrict_functions_checker()

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

Definition at line 1102 of file clauses.c.

References func_strict().

Referenced by contain_nonstrict_functions_walker().

1103 {
1104  return !func_strict(func_id);
1105 }
bool func_strict(Oid funcid)
Definition: lsyscache.c:1673

◆ contain_nonstrict_functions_walker()

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

Definition at line 1108 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().

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

◆ contain_subplans()

bool contain_subplans ( Node clause)

Definition at line 612 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().

613 {
614  return contain_subplans_walker(clause, NULL);
615 }
static bool contain_subplans_walker(Node *node, void *context)
Definition: clauses.c:618

◆ contain_subplans_walker()

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

Definition at line 618 of file clauses.c.

References expression_tree_walker(), and IsA.

Referenced by contain_subplans().

619 {
620  if (node == NULL)
621  return false;
622  if (IsA(node, SubPlan) ||
623  IsA(node, AlternativeSubPlan) ||
624  IsA(node, SubLink))
625  return true; /* abort the tree traversal and return true */
626  return expression_tree_walker(node, contain_subplans_walker, context);
627 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
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:618

◆ contain_volatile_functions()

◆ contain_volatile_functions_checker()

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

Definition at line 732 of file clauses.c.

References func_volatile().

Referenced by contain_volatile_functions_walker().

733 {
734  return (func_volatile(func_id) == PROVOLATILE_VOLATILE);
735 }
char func_volatile(Oid funcid)
Definition: lsyscache.c:1692

◆ contain_volatile_functions_not_nextval()

bool contain_volatile_functions_not_nextval ( Node clause)

Definition at line 776 of file clauses.c.

References contain_volatile_functions_not_nextval_walker().

Referenced by BeginCopyFrom().

777 {
779 }
static bool contain_volatile_functions_not_nextval_walker(Node *node, void *context)
Definition: clauses.c:789

◆ contain_volatile_functions_not_nextval_checker()

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

Definition at line 782 of file clauses.c.

References func_volatile().

Referenced by contain_volatile_functions_not_nextval_walker().

783 {
784  return (func_id != F_NEXTVAL_OID &&
785  func_volatile(func_id) == PROVOLATILE_VOLATILE);
786 }
char func_volatile(Oid funcid)
Definition: lsyscache.c:1692

◆ contain_volatile_functions_not_nextval_walker()

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

Definition at line 789 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().

790 {
791  if (node == NULL)
792  return false;
793  /* Check for volatile functions in node itself */
794  if (check_functions_in_node(node,
796  context))
797  return true;
798 
799  /*
800  * See notes in contain_mutable_functions_walker about why we treat
801  * MinMaxExpr, XmlExpr, and CoerceToDomain as immutable, while
802  * SQLValueFunction is stable. Hence, none of them are of interest here.
803  * Also, since we're intentionally ignoring nextval(), presumably we
804  * should ignore NextValueExpr.
805  */
806 
807  /* Recurse to check arguments */
808  if (IsA(node, Query))
809  {
810  /* Recurse into subselects */
811  return query_tree_walker((Query *) node,
813  context, 0);
814  }
815  return expression_tree_walker(node,
817  context);
818 }
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2273
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
static bool contain_volatile_functions_not_nextval_walker(Node *node, void *context)
Definition: clauses.c:789
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:782

◆ contain_volatile_functions_walker()

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

Definition at line 738 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().

739 {
740  if (node == NULL)
741  return false;
742  /* Check for volatile functions in node itself */
744  context))
745  return true;
746 
747  if (IsA(node, NextValueExpr))
748  {
749  /* NextValueExpr is volatile */
750  return true;
751  }
752 
753  /*
754  * See notes in contain_mutable_functions_walker about why we treat
755  * MinMaxExpr, XmlExpr, and CoerceToDomain as immutable, while
756  * SQLValueFunction is stable. Hence, none of them are of interest here.
757  */
758 
759  /* Recurse to check arguments */
760  if (IsA(node, Query))
761  {
762  /* Recurse into subselects */
763  return query_tree_walker((Query *) node,
765  context, 0);
766  }
768  context);
769 }
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2273
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
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:738
static bool contain_volatile_functions_checker(Oid func_id, void *context)
Definition: clauses.c:732
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 496 of file clauses.c.

References contain_windowfuncs().

Referenced by get_eclass_for_sort_expr(), and qual_is_pushdown_safe().

497 {
498  return contain_windowfuncs(clause);
499 }
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 3566 of file clauses.c.

References eval_const_expressions_context::estimate, and func_volatile().

Referenced by eval_const_expressions_mutator().

3567 {
3568  char provolatile = func_volatile(funcid);
3569 
3570  /*
3571  * Ordinarily we are only allowed to simplify immutable functions. But for
3572  * purposes of estimation, we consider it okay to simplify functions that
3573  * are merely stable; the risk that the result might change from planning
3574  * time to execution time is worth taking in preference to not being able
3575  * to estimate the value at all.
3576  */
3577  if (provolatile == PROVOLATILE_IMMUTABLE)
3578  return true;
3579  if (context->estimate && provolatile == PROVOLATILE_STABLE)
3580  return true;
3581  return false;
3582 }
char func_volatile(Oid funcid)
Definition: lsyscache.c:1692

◆ estimate_expression_value()

Node* estimate_expression_value ( PlannerInfo root,
Node node 
)

Definition at line 2288 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().

2289 {
2291 
2292  context.boundParams = root->glob->boundParams; /* bound Params */
2293  /* we do not need to mark the plan as depending on inlined functions */
2294  context.root = NULL;
2295  context.active_fns = NIL; /* nothing being recursively simplified */
2296  context.case_val = NULL; /* no CASE being examined */
2297  context.estimate = true; /* unsafe transformations OK */
2298  return eval_const_expressions_mutator(node, &context);
2299 }
#define NIL
Definition: pg_list.h:65
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2333
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 2255 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().

2256 {
2258 
2259  if (root)
2260  context.boundParams = root->glob->boundParams; /* bound Params */
2261  else
2262  context.boundParams = NULL;
2263  context.root = root; /* for inlined-function dependencies */
2264  context.active_fns = NIL; /* nothing being recursively simplified */
2265  context.case_val = NULL; /* no CASE being examined */
2266  context.estimate = false; /* safe transformations only */
2267  return eval_const_expressions_mutator(node, &context);
2268 }
#define NIL
Definition: pg_list.h:65
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2333
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 2333 of file clauses.c.

References WindowFunc::aggfilter, AND_EXPR, apply_const_relabel(), arg, FieldSelect::arg, RelabelType::arg, CoerceViaIO::arg, ArrayCoerceExpr::arg, ConvertRowtypeExpr::arg, CollateExpr::arg, CaseExpr::arg, NullTest::arg, BooleanTest::arg, CoerceToDomain::arg, NullTest::argisrow, generate_unaccent_rules::args, WindowFunc::args, FuncExpr::args, OpExpr::args, BoolExpr::args, CaseExpr::args, RowExpr::args, CoalesceExpr::args, Assert, BoolGetDatum, BoolExpr::boolop, BooleanTest::booltesttype, eval_const_expressions_context::boundParams, eval_const_expressions_context::case_val, CaseExpr::casecollid, CaseExpr::casetype, castNode, CoalesceExpr::coalescecollid, CoalesceExpr::coalescetype, COERCE_IMPLICIT_CAST, CoerceViaIO::coerceformat, CoerceToDomain::coercionformat, CollateExpr::collOid, Const::constisnull, Const::consttype, Const::constvalue, contain_mutable_functions(), ConvertRowtypeExpr::convertformat, copyObject, datumCopy(), DatumGetBool, CaseExpr::defresult, DomainHasConstraints(), ece_all_arguments_const, ece_evaluate_expr, ece_function_is_safe(), ece_generic_processing, ArrayCoerceExpr::elemexpr, elog, ERROR, eval_const_expressions_context::estimate, evaluate_expr(), expand_function_arguments(), CaseWhen::expr, exprCollation(), expression_tree_mutator(), exprType(), exprTypmod(), FieldSelect::fieldnum, 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().

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

◆ evaluate_expr()

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

Definition at line 4773 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().

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

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

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

4033 {
4034  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4035  bool has_named_args = false;
4036  ListCell *lc;
4037 
4038  /* Do we have any named arguments? */
4039  foreach(lc, args)
4040  {
4041  Node *arg = (Node *) lfirst(lc);
4042 
4043  if (IsA(arg, NamedArgExpr))
4044  {
4045  has_named_args = true;
4046  break;
4047  }
4048  }
4049 
4050  /* If so, we must apply reorder_function_arguments */
4051  if (has_named_args)
4052  {
4053  args = reorder_function_arguments(args, func_tuple);
4054  /* Recheck argument types and add casts if needed */
4055  recheck_cast_function_args(args, result_type, func_tuple);
4056  }
4057  else if (list_length(args) < funcform->pronargs)
4058  {
4059  /* No named args, but we seem to be short some defaults */
4060  args = add_function_defaults(args, func_tuple);
4061  /* Recheck argument types and add casts if needed */
4062  recheck_cast_function_args(args, result_type, func_tuple);
4063  }
4064 
4065  return args;
4066 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Definition: nodes.h:529
static void recheck_cast_function_args(List *args, Oid result_type, HeapTuple func_tuple)
Definition: clauses.c:4205
static List * add_function_defaults(List *args, HeapTuple func_tuple)
Definition: clauses.c:4145
static List * reorder_function_arguments(List *args, HeapTuple func_tuple)
Definition: clauses.c:4075
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 571 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().

572 {
573  if (clause == NULL)
574  return 1.0;
575  if (IsA(clause, FuncExpr))
576  {
577  FuncExpr *expr = (FuncExpr *) clause;
578 
579  if (expr->funcretset)
580  return clamp_row_est(get_function_rows(root, expr->funcid, clause));
581  }
582  if (IsA(clause, OpExpr))
583  {
584  OpExpr *expr = (OpExpr *) clause;
585 
586  if (expr->opretset)
587  {
588  set_opfuncid(expr);
589  return clamp_row_est(get_function_rows(root, expr->opfuncid, clause));
590  }
591  }
592  return 1.0;
593 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
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:190
bool opretset
Definition: primnodes.h:519
double get_function_rows(PlannerInfo *root, Oid funcid, Node *node)
Definition: plancat.c:1969

◆ fetch_function_defaults()

static List * fetch_function_defaults ( HeapTuple  func_tuple)
static

Definition at line 4170 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().

4171 {
4172  List *defaults;
4173  Datum proargdefaults;
4174  bool isnull;
4175  char *str;
4176 
4177  /* The error cases here shouldn't happen, but check anyway */
4178  proargdefaults = SysCacheGetAttr(PROCOID, func_tuple,
4179  Anum_pg_proc_proargdefaults,
4180  &isnull);
4181  if (isnull)
4182  elog(ERROR, "not enough default arguments");
4183  str = TextDatumGetCString(proargdefaults);
4184  defaults = castNode(List, stringToNode(str));
4185  pfree(str);
4186  return defaults;
4187 }
#define castNode(_type_, nodeptr)
Definition: nodes.h:598
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:88
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:214
Definition: pg_list.h:50

◆ find_forced_null_var()

Var* find_forced_null_var ( Node node)

Definition at line 1980 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().

1981 {
1982  if (node == NULL)
1983  return NULL;
1984  if (IsA(node, NullTest))
1985  {
1986  /* check for var IS NULL */
1987  NullTest *expr = (NullTest *) node;
1988 
1989  if (expr->nulltesttype == IS_NULL && !expr->argisrow)
1990  {
1991  Var *var = (Var *) expr->arg;
1992 
1993  if (var && IsA(var, Var) &&
1994  var->varlevelsup == 0)
1995  return var;
1996  }
1997  }
1998  else if (IsA(node, BooleanTest))
1999  {
2000  /* var IS UNKNOWN is equivalent to var IS NULL */
2001  BooleanTest *expr = (BooleanTest *) node;
2002 
2003  if (expr->booltesttype == IS_UNKNOWN)
2004  {
2005  Var *var = (Var *) expr->arg;
2006 
2007  if (var && IsA(var, Var) &&
2008  var->varlevelsup == 0)
2009  return var;
2010  }
2011  }
2012  return NULL;
2013 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
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 1921 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().

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

◆ find_nonnullable_rels()

Relids find_nonnullable_rels ( Node clause)

Definition at line 1503 of file clauses.c.

References find_nonnullable_rels_walker().

Referenced by make_outerjoininfo(), and reduce_outer_joins_pass2().

1504 {
1505  return find_nonnullable_rels_walker(clause, true);
1506 }
static Relids find_nonnullable_rels_walker(Node *node, bool top_level)
Definition: clauses.c:1509

◆ find_nonnullable_rels_walker()

static Relids find_nonnullable_rels_walker ( Node node,
bool  top_level 
)
static

Definition at line 1509 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().

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

References find_nonnullable_vars_walker().

Referenced by reduce_outer_joins_pass2().

1729 {
1730  return find_nonnullable_vars_walker(clause, true);
1731 }
static List * find_nonnullable_vars_walker(Node *node, bool top_level)
Definition: clauses.c:1734

◆ find_nonnullable_vars_walker()

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

Definition at line 1734 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().

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

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

Referenced by grouping_planner().

510 {
511  WindowFuncLists *lists = palloc(sizeof(WindowFuncLists));
512 
513  lists->numWindowFuncs = 0;
514  lists->maxWinRef = maxWinRef;
515  lists->windowFuncs = (List **) palloc0((maxWinRef + 1) * sizeof(List *));
516  (void) find_window_functions_walker(clause, lists);
517  return lists;
518 }
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:521
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 521 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().

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

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

◆ get_agg_clause_costs_walker()

static bool get_agg_clause_costs_walker ( Node node,
get_agg_clause_costs_context context 
)
static

Definition at line 243 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().

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

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