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 "optimizer/clauses.h"
#include "optimizer/cost.h"
#include "optimizer/planmain.h"
#include "optimizer/prep.h"
#include "optimizer/var.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_IN_CASEEXPR   0x0001 /* CaseTestExpr okay here? */
 

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 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 Listexpand_function_arguments (List *args, Oid result_type, HeapTuple func_tuple)
 
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 Exprevaluate_expr (Expr *expr, Oid result_type, int32 result_typmod, Oid result_collation)
 
static Querysubstitute_actual_srf_parameters (Query *expr, int nargs, List *args)
 
static Nodesubstitute_actual_srf_parameters_mutator (Node *node, substitute_actual_srf_parameters_context *context)
 
static bool tlist_matches_coltypelist (List *tlist, List *coltypelist)
 
Exprmake_opclause (Oid opno, Oid opresulttype, bool opretset, Expr *leftop, Expr *rightop, Oid opcollid, Oid inputcollid)
 
Nodeget_leftop (const Expr *clause)
 
Nodeget_rightop (const Expr *clause)
 
bool not_clause (Node *clause)
 
Exprmake_notclause (Expr *notclause)
 
Exprget_notclausearg (Expr *notclause)
 
bool or_clause (Node *clause)
 
Exprmake_orclause (List *orclauses)
 
bool and_clause (Node *clause)
 
Exprmake_andclause (List *andclauses)
 
Nodemake_and_qual (Node *qual1, Node *qual2)
 
Exprmake_ands_explicit (List *andclauses)
 
Listmake_ands_implicit (Expr *clause)
 
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 (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)
 
void CommuteRowCompareExpr (RowCompareExpr *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)
 
Queryinline_set_returning_function (PlannerInfo *root, RangeTblEntry *rte)
 

Macro Definition Documentation

◆ CCDN_IN_CASEEXPR

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

Definition at line 1456 of file clauses.c.

Referenced by contain_context_dependent_node_walker().

Function Documentation

◆ add_function_defaults()

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

Definition at line 4141 of file clauses.c.

References elog, ERROR, fetch_function_defaults(), GETSTRUCT, list_concat(), list_copy(), list_delete_first(), and list_length().

Referenced by expand_function_arguments().

4142 {
4143  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4144  int nargsprovided = list_length(args);
4145  List *defaults;
4146  int ndelete;
4147 
4148  /* Get all the default expressions from the pg_proc tuple */
4149  defaults = fetch_function_defaults(func_tuple);
4150 
4151  /* Delete any unused defaults from the list */
4152  ndelete = nargsprovided + list_length(defaults) - funcform->pronargs;
4153  if (ndelete < 0)
4154  elog(ERROR, "not enough default arguments");
4155  while (ndelete-- > 0)
4156  defaults = list_delete_first(defaults);
4157 
4158  /* And form the combined argument list, not modifying the input list */
4159  return list_concat(list_copy(args), defaults);
4160 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
List * list_copy(const List *oldlist)
Definition: list.c:1160
List * list_concat(List *list1, List *list2)
Definition: list.c:321
#define ERROR
Definition: elog.h:43
static List * fetch_function_defaults(HeapTuple func_tuple)
Definition: clauses.c:4166
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:83
static int list_length(const List *l)
Definition: pg_list.h:89
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
List * list_delete_first(List *list)
Definition: list.c:666

◆ and_clause()

bool and_clause ( Node clause)

◆ CommuteOpExpr()

void CommuteOpExpr ( OpExpr clause)

Definition at line 2287 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 fix_indexqual_references(), and get_switched_clauses().

2288 {
2289  Oid opoid;
2290  Node *temp;
2291 
2292  /* Sanity checks: caller is at fault if these fail */
2293  if (!is_opclause(clause) ||
2294  list_length(clause->args) != 2)
2295  elog(ERROR, "cannot commute non-binary-operator clause");
2296 
2297  opoid = get_commutator(clause->opno);
2298 
2299  if (!OidIsValid(opoid))
2300  elog(ERROR, "could not find commutator for operator %u",
2301  clause->opno);
2302 
2303  /*
2304  * modify the clause in-place!
2305  */
2306  clause->opno = opoid;
2307  clause->opfuncid = InvalidOid;
2308  /* opresulttype, opretset, opcollid, inputcollid need not change */
2309 
2310  temp = linitial(clause->args);
2311  linitial(clause->args) = lsecond(clause->args);
2312  lsecond(clause->args) = temp;
2313 }
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1313
Definition: nodes.h:510
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:576
#define lsecond(l)
Definition: pg_list.h:116
#define linitial(l)
Definition: pg_list.h:111
#define ERROR
Definition: elog.h:43
#define is_opclause(clause)
Definition: clauses.h:20
Oid opfuncid
Definition: primnodes.h:497
#define InvalidOid
Definition: postgres_ext.h:36
static int list_length(const List *l)
Definition: pg_list.h:89
Oid opno
Definition: primnodes.h:496
#define elog
Definition: elog.h:219
List * args
Definition: primnodes.h:502

◆ CommuteRowCompareExpr()

void CommuteRowCompareExpr ( RowCompareExpr clause)

Definition at line 2321 of file clauses.c.

References elog, ERROR, get_commutator(), IsA, lappend_oid(), RowCompareExpr::largs, lfirst_oid, NIL, OidIsValid, RowCompareExpr::opnos, RowCompareExpr::rargs, RowCompareExpr::rctype, ROWCOMPARE_GE, ROWCOMPARE_GT, ROWCOMPARE_LE, and ROWCOMPARE_LT.

Referenced by fix_indexqual_references().

2322 {
2323  List *newops;
2324  List *temp;
2325  ListCell *l;
2326 
2327  /* Sanity checks: caller is at fault if these fail */
2328  if (!IsA(clause, RowCompareExpr))
2329  elog(ERROR, "expected a RowCompareExpr");
2330 
2331  /* Build list of commuted operators */
2332  newops = NIL;
2333  foreach(l, clause->opnos)
2334  {
2335  Oid opoid = lfirst_oid(l);
2336 
2337  opoid = get_commutator(opoid);
2338  if (!OidIsValid(opoid))
2339  elog(ERROR, "could not find commutator for operator %u",
2340  lfirst_oid(l));
2341  newops = lappend_oid(newops, opoid);
2342  }
2343 
2344  /*
2345  * modify the clause in-place!
2346  */
2347  switch (clause->rctype)
2348  {
2349  case ROWCOMPARE_LT:
2350  clause->rctype = ROWCOMPARE_GT;
2351  break;
2352  case ROWCOMPARE_LE:
2353  clause->rctype = ROWCOMPARE_GE;
2354  break;
2355  case ROWCOMPARE_GE:
2356  clause->rctype = ROWCOMPARE_LE;
2357  break;
2358  case ROWCOMPARE_GT:
2359  clause->rctype = ROWCOMPARE_LT;
2360  break;
2361  default:
2362  elog(ERROR, "unexpected RowCompare type: %d",
2363  (int) clause->rctype);
2364  break;
2365  }
2366 
2367  clause->opnos = newops;
2368 
2369  /*
2370  * Note: we need not change the opfamilies list; we assume any btree
2371  * opfamily containing an operator will also contain its commutator.
2372  * Collations don't change either.
2373  */
2374 
2375  temp = clause->largs;
2376  clause->largs = clause->rargs;
2377  clause->rargs = temp;
2378 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1313
RowCompareType rctype
Definition: primnodes.h:1038
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:164
#define OidIsValid(objectId)
Definition: c.h:576
#define ERROR
Definition: elog.h:43
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
#define lfirst_oid(lc)
Definition: pg_list.h:108

◆ contain_agg_clause()

bool contain_agg_clause ( Node clause)

Definition at line 417 of file clauses.c.

References contain_agg_clause_walker().

Referenced by get_eclass_for_sort_expr(), and subquery_planner().

418 {
419  return contain_agg_clause_walker(clause, NULL);
420 }
static bool contain_agg_clause_walker(Node *node, void *context)
Definition: clauses.c:423

◆ contain_agg_clause_walker()

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

Definition at line 423 of file clauses.c.

References Assert, expression_tree_walker(), and IsA.

Referenced by contain_agg_clause().

424 {
425  if (node == NULL)
426  return false;
427  if (IsA(node, Aggref))
428  {
429  Assert(((Aggref *) node)->agglevelsup == 0);
430  return true; /* abort the tree traversal and return true */
431  }
432  if (IsA(node, GroupingFunc))
433  {
434  Assert(((GroupingFunc *) node)->agglevelsup == 0);
435  return true; /* abort the tree traversal and return true */
436  }
437  Assert(!IsA(node, SubLink));
438  return expression_tree_walker(node, contain_agg_clause_walker, context);
439 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
static bool contain_agg_clause_walker(Node *node, void *context)
Definition: clauses.c:423
#define Assert(condition)
Definition: c.h:670
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1834

◆ contain_context_dependent_node()

static bool contain_context_dependent_node ( Node clause)
static

Definition at line 1449 of file clauses.c.

References contain_context_dependent_node_walker().

Referenced by inline_function().

1450 {
1451  int flags = 0;
1452 
1453  return contain_context_dependent_node_walker(clause, &flags);
1454 }
static bool contain_context_dependent_node_walker(Node *node, int *flags)
Definition: clauses.c:1459

◆ contain_context_dependent_node_walker()

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

Definition at line 1459 of file clauses.c.

References CaseExpr::arg, CCDN_IN_CASEEXPR, expression_tree_walker(), and IsA.

Referenced by contain_context_dependent_node().

1460 {
1461  if (node == NULL)
1462  return false;
1463  if (IsA(node, CaseTestExpr))
1464  return !(*flags & CCDN_IN_CASEEXPR);
1465  if (IsA(node, CaseExpr))
1466  {
1467  CaseExpr *caseexpr = (CaseExpr *) node;
1468 
1469  /*
1470  * If this CASE doesn't have a test expression, then it doesn't create
1471  * a context in which CaseTestExprs should appear, so just fall
1472  * through and treat it as a generic expression node.
1473  */
1474  if (caseexpr->arg)
1475  {
1476  int save_flags = *flags;
1477  bool res;
1478 
1479  /*
1480  * Note: in principle, we could distinguish the various sub-parts
1481  * of a CASE construct and set the flag bit only for some of them,
1482  * since we are only expecting CaseTestExprs to appear in the
1483  * "expr" subtree of the CaseWhen nodes. But it doesn't really
1484  * seem worth any extra code. If there are any bare CaseTestExprs
1485  * elsewhere in the CASE, something's wrong already.
1486  */
1487  *flags |= CCDN_IN_CASEEXPR;
1488  res = expression_tree_walker(node,
1490  (void *) flags);
1491  *flags = save_flags;
1492  return res;
1493  }
1494  }
1496  (void *) flags);
1497 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
#define CCDN_IN_CASEEXPR
Definition: clauses.c:1456
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1834
Expr * arg
Definition: primnodes.h:912
static bool contain_context_dependent_node_walker(Node *node, int *flags)
Definition: clauses.c:1459

◆ contain_leaked_vars()

bool contain_leaked_vars ( Node clause)

Definition at line 1515 of file clauses.c.

References contain_leaked_vars_walker().

Referenced by make_restrictinfo_internal(), and qual_is_pushdown_safe().

1516 {
1517  return contain_leaked_vars_walker(clause, NULL);
1518 }
static bool contain_leaked_vars_walker(Node *node, void *context)
Definition: clauses.c:1527

◆ contain_leaked_vars_checker()

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

Definition at line 1521 of file clauses.c.

References get_func_leakproof().

Referenced by contain_leaked_vars_walker().

1522 {
1523  return !get_func_leakproof(func_id);
1524 }
bool get_func_leakproof(Oid funcid)
Definition: lsyscache.c:1622

◆ contain_leaked_vars_walker()

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

Definition at line 1527 of file clauses.c.

References check_functions_in_node(), contain_leaked_vars_checker(), contain_var_clause(), expression_tree_walker(), forthree, get_func_leakproof(), get_opcode(), RowCompareExpr::largs, lfirst, lfirst_oid, nodeTag, RowCompareExpr::opnos, RowCompareExpr::rargs, T_ArrayCoerceExpr, T_ArrayExpr, T_ArrayRef, 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, and T_Var.

Referenced by contain_leaked_vars().

1528 {
1529  if (node == NULL)
1530  return false;
1531 
1532  switch (nodeTag(node))
1533  {
1534  case T_Var:
1535  case T_Const:
1536  case T_Param:
1537  case T_ArrayRef:
1538  case T_ArrayExpr:
1539  case T_FieldSelect:
1540  case T_FieldStore:
1541  case T_NamedArgExpr:
1542  case T_BoolExpr:
1543  case T_RelabelType:
1544  case T_CollateExpr:
1545  case T_CaseExpr:
1546  case T_CaseTestExpr:
1547  case T_RowExpr:
1548  case T_MinMaxExpr:
1549  case T_SQLValueFunction:
1550  case T_NullTest:
1551  case T_BooleanTest:
1552  case T_NextValueExpr:
1553  case T_List:
1554 
1555  /*
1556  * We know these node types don't contain function calls; but
1557  * something further down in the node tree might.
1558  */
1559  break;
1560 
1561  case T_FuncExpr:
1562  case T_OpExpr:
1563  case T_DistinctExpr:
1564  case T_NullIfExpr:
1565  case T_ScalarArrayOpExpr:
1566  case T_CoerceViaIO:
1567  case T_ArrayCoerceExpr:
1568 
1569  /*
1570  * If node contains a leaky function call, and there's any Var
1571  * underneath it, reject.
1572  */
1574  context) &&
1575  contain_var_clause(node))
1576  return true;
1577  break;
1578 
1579  case T_RowCompareExpr:
1580  {
1581  /*
1582  * It's worth special-casing this because a leaky comparison
1583  * function only compromises one pair of row elements, which
1584  * might not contain Vars while others do.
1585  */
1586  RowCompareExpr *rcexpr = (RowCompareExpr *) node;
1587  ListCell *opid;
1588  ListCell *larg;
1589  ListCell *rarg;
1590 
1591  forthree(opid, rcexpr->opnos,
1592  larg, rcexpr->largs,
1593  rarg, rcexpr->rargs)
1594  {
1595  Oid funcid = get_opcode(lfirst_oid(opid));
1596 
1597  if (!get_func_leakproof(funcid) &&
1598  (contain_var_clause((Node *) lfirst(larg)) ||
1599  contain_var_clause((Node *) lfirst(rarg))))
1600  return true;
1601  }
1602  }
1603  break;
1604 
1605  case T_CurrentOfExpr:
1606 
1607  /*
1608  * WHERE CURRENT OF doesn't contain leaky function calls.
1609  * Moreover, it is essential that this is considered non-leaky,
1610  * since the planner must always generate a TID scan when CURRENT
1611  * OF is present -- c.f. cost_tidscan.
1612  */
1613  return false;
1614 
1615  default:
1616 
1617  /*
1618  * If we don't recognize the node tag, assume it might be leaky.
1619  * This prevents an unexpected security hole if someone adds a new
1620  * node type that can call a function.
1621  */
1622  return true;
1623  }
1625  context);
1626 }
bool get_func_leakproof(Oid funcid)
Definition: lsyscache.c:1622
#define forthree(cell1, list1, cell2, list2, cell3, list3)
Definition: pg_list.h:203
Definition: nodes.h:510
bool contain_var_clause(Node *node)
Definition: var.c:331
unsigned int Oid
Definition: postgres_ext.h:31
bool check_functions_in_node(Node *node, check_function_callback checker, void *context)
Definition: nodeFuncs.c:1651
Definition: nodes.h:291
Definition: nodes.h:147
Definition: nodes.h:146
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1094
#define lfirst(lc)
Definition: pg_list.h:106
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1834
#define nodeTag(nodeptr)
Definition: nodes.h:515
static bool contain_leaked_vars_checker(Oid func_id, void *context)
Definition: clauses.c:1521
static bool contain_leaked_vars_walker(Node *node, void *context)
Definition: clauses.c:1527
#define lfirst_oid(lc)
Definition: pg_list.h:108
Definition: nodes.h:148

◆ contain_mutable_functions()

bool contain_mutable_functions ( Node clause)

◆ contain_mutable_functions_checker()

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

Definition at line 884 of file clauses.c.

References func_volatile(), and PROVOLATILE_IMMUTABLE.

Referenced by contain_mutable_functions_walker().

885 {
886  return (func_volatile(func_id) != PROVOLATILE_IMMUTABLE);
887 }
#define PROVOLATILE_IMMUTABLE
Definition: pg_proc.h:5537
char func_volatile(Oid funcid)
Definition: lsyscache.c:1584

◆ contain_mutable_functions_walker()

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

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

891 {
892  if (node == NULL)
893  return false;
894  /* Check for mutable functions in node itself */
896  context))
897  return true;
898 
899  if (IsA(node, SQLValueFunction))
900  {
901  /* all variants of SQLValueFunction are stable */
902  return true;
903  }
904 
905  if (IsA(node, NextValueExpr))
906  {
907  /* NextValueExpr is volatile */
908  return true;
909  }
910 
911  /*
912  * It should be safe to treat MinMaxExpr as immutable, because it will
913  * depend on a non-cross-type btree comparison function, and those should
914  * always be immutable. Treating XmlExpr as immutable is more dubious,
915  * and treating CoerceToDomain as immutable is outright dangerous. But we
916  * have done so historically, and changing this would probably cause more
917  * problems than it would fix. In practice, if you have a non-immutable
918  * domain constraint you are in for pain anyhow.
919  */
920 
921  /* Recurse to check arguments */
922  if (IsA(node, Query))
923  {
924  /* Recurse into subselects */
925  return query_tree_walker((Query *) node,
927  context, 0);
928  }
930  context);
931 }
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2245
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
static bool contain_mutable_functions_walker(Node *node, void *context)
Definition: clauses.c:890
static bool contain_mutable_functions_checker(Oid func_id, void *context)
Definition: clauses.c:884
bool check_functions_in_node(Node *node, check_function_callback checker, void *context)
Definition: nodeFuncs.c:1651
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1834

◆ contain_nonstrict_functions()

bool contain_nonstrict_functions ( Node clause)

Definition at line 1314 of file clauses.c.

References contain_nonstrict_functions_walker().

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

1315 {
1316  return contain_nonstrict_functions_walker(clause, NULL);
1317 }
static bool contain_nonstrict_functions_walker(Node *node, void *context)
Definition: clauses.c:1326

◆ contain_nonstrict_functions_checker()

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

Definition at line 1320 of file clauses.c.

References func_strict().

Referenced by contain_nonstrict_functions_walker().

1321 {
1322  return !func_strict(func_id);
1323 }
bool func_strict(Oid funcid)
Definition: lsyscache.c:1565

◆ contain_nonstrict_functions_walker()

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

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

1327 {
1328  if (node == NULL)
1329  return false;
1330  if (IsA(node, Aggref))
1331  {
1332  /* an aggregate could return non-null with null input */
1333  return true;
1334  }
1335  if (IsA(node, GroupingFunc))
1336  {
1337  /*
1338  * A GroupingFunc doesn't evaluate its arguments, and therefore must
1339  * be treated as nonstrict.
1340  */
1341  return true;
1342  }
1343  if (IsA(node, WindowFunc))
1344  {
1345  /* a window function could return non-null with null input */
1346  return true;
1347  }
1348  if (IsA(node, ArrayRef))
1349  {
1350  /* array assignment is nonstrict, but subscripting is strict */
1351  if (((ArrayRef *) node)->refassgnexpr != NULL)
1352  return true;
1353  /* else fall through to check args */
1354  }
1355  if (IsA(node, DistinctExpr))
1356  {
1357  /* IS DISTINCT FROM is inherently non-strict */
1358  return true;
1359  }
1360  if (IsA(node, NullIfExpr))
1361  {
1362  /* NULLIF is inherently non-strict */
1363  return true;
1364  }
1365  if (IsA(node, BoolExpr))
1366  {
1367  BoolExpr *expr = (BoolExpr *) node;
1368 
1369  switch (expr->boolop)
1370  {
1371  case AND_EXPR:
1372  case OR_EXPR:
1373  /* AND, OR are inherently non-strict */
1374  return true;
1375  default:
1376  break;
1377  }
1378  }
1379  if (IsA(node, SubLink))
1380  {
1381  /* In some cases a sublink might be strict, but in general not */
1382  return true;
1383  }
1384  if (IsA(node, SubPlan))
1385  return true;
1386  if (IsA(node, AlternativeSubPlan))
1387  return true;
1388  if (IsA(node, FieldStore))
1389  return true;
1390  if (IsA(node, ArrayCoerceExpr))
1391  {
1392  /*
1393  * ArrayCoerceExpr is strict at the array level, regardless of what
1394  * the per-element expression is; so we should ignore elemexpr and
1395  * recurse only into the arg.
1396  */
1397  return expression_tree_walker((Node *) ((ArrayCoerceExpr *) node)->arg,
1399  context);
1400  }
1401  if (IsA(node, CaseExpr))
1402  return true;
1403  if (IsA(node, ArrayExpr))
1404  return true;
1405  if (IsA(node, RowExpr))
1406  return true;
1407  if (IsA(node, RowCompareExpr))
1408  return true;
1409  if (IsA(node, CoalesceExpr))
1410  return true;
1411  if (IsA(node, MinMaxExpr))
1412  return true;
1413  if (IsA(node, XmlExpr))
1414  return true;
1415  if (IsA(node, NullTest))
1416  return true;
1417  if (IsA(node, BooleanTest))
1418  return true;
1419 
1420  /* Check other function-containing nodes */
1422  context))
1423  return true;
1424 
1426  context);
1427 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
Definition: nodes.h:510
static bool contain_nonstrict_functions_walker(Node *node, void *context)
Definition: clauses.c:1326
bool check_functions_in_node(Node *node, check_function_callback checker, void *context)
Definition: nodeFuncs.c:1651
BoolExprType boolop
Definition: primnodes.h:562
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1834
void * arg
static bool contain_nonstrict_functions_checker(Oid func_id, void *context)
Definition: clauses.c:1320

◆ contain_subplans()

bool contain_subplans ( Node clause)

Definition at line 843 of file clauses.c.

References contain_subplans_walker().

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

844 {
845  return contain_subplans_walker(clause, NULL);
846 }
static bool contain_subplans_walker(Node *node, void *context)
Definition: clauses.c:849

◆ contain_subplans_walker()

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

Definition at line 849 of file clauses.c.

References expression_tree_walker(), and IsA.

Referenced by contain_subplans().

850 {
851  if (node == NULL)
852  return false;
853  if (IsA(node, SubPlan) ||
854  IsA(node, AlternativeSubPlan) ||
855  IsA(node, SubLink))
856  return true; /* abort the tree traversal and return true */
857  return expression_tree_walker(node, contain_subplans_walker, context);
858 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1834
static bool contain_subplans_walker(Node *node, void *context)
Definition: clauses.c:849

◆ contain_volatile_functions()

◆ contain_volatile_functions_checker()

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

Definition at line 963 of file clauses.c.

References func_volatile(), and PROVOLATILE_VOLATILE.

Referenced by contain_volatile_functions_walker().

964 {
965  return (func_volatile(func_id) == PROVOLATILE_VOLATILE);
966 }
#define PROVOLATILE_VOLATILE
Definition: pg_proc.h:5539
char func_volatile(Oid funcid)
Definition: lsyscache.c:1584

◆ contain_volatile_functions_not_nextval()

bool contain_volatile_functions_not_nextval ( Node clause)

Definition at line 1007 of file clauses.c.

References contain_volatile_functions_not_nextval_walker().

Referenced by BeginCopyFrom().

1008 {
1009  return contain_volatile_functions_not_nextval_walker(clause, NULL);
1010 }
static bool contain_volatile_functions_not_nextval_walker(Node *node, void *context)
Definition: clauses.c:1020

◆ contain_volatile_functions_not_nextval_checker()

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

Definition at line 1013 of file clauses.c.

References func_volatile(), and PROVOLATILE_VOLATILE.

Referenced by contain_volatile_functions_not_nextval_walker().

1014 {
1015  return (func_id != F_NEXTVAL_OID &&
1016  func_volatile(func_id) == PROVOLATILE_VOLATILE);
1017 }
#define PROVOLATILE_VOLATILE
Definition: pg_proc.h:5539
char func_volatile(Oid funcid)
Definition: lsyscache.c:1584

◆ contain_volatile_functions_not_nextval_walker()

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

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

1021 {
1022  if (node == NULL)
1023  return false;
1024  /* Check for volatile functions in node itself */
1025  if (check_functions_in_node(node,
1027  context))
1028  return true;
1029 
1030  /*
1031  * See notes in contain_mutable_functions_walker about why we treat
1032  * MinMaxExpr, XmlExpr, and CoerceToDomain as immutable, while
1033  * SQLValueFunction is stable. Hence, none of them are of interest here.
1034  * Also, since we're intentionally ignoring nextval(), presumably we
1035  * should ignore NextValueExpr.
1036  */
1037 
1038  /* Recurse to check arguments */
1039  if (IsA(node, Query))
1040  {
1041  /* Recurse into subselects */
1042  return query_tree_walker((Query *) node,
1044  context, 0);
1045  }
1046  return expression_tree_walker(node,
1048  context);
1049 }
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2245
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
static bool contain_volatile_functions_not_nextval_walker(Node *node, void *context)
Definition: clauses.c:1020
bool check_functions_in_node(Node *node, check_function_callback checker, void *context)
Definition: nodeFuncs.c:1651
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1834
static bool contain_volatile_functions_not_nextval_checker(Oid func_id, void *context)
Definition: clauses.c:1013

◆ contain_volatile_functions_walker()

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

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

970 {
971  if (node == NULL)
972  return false;
973  /* Check for volatile functions in node itself */
975  context))
976  return true;
977 
978  if (IsA(node, NextValueExpr))
979  {
980  /* NextValueExpr is volatile */
981  return true;
982  }
983 
984  /*
985  * See notes in contain_mutable_functions_walker about why we treat
986  * MinMaxExpr, XmlExpr, and CoerceToDomain as immutable, while
987  * SQLValueFunction is stable. Hence, none of them are of interest here.
988  */
989 
990  /* Recurse to check arguments */
991  if (IsA(node, Query))
992  {
993  /* Recurse into subselects */
994  return query_tree_walker((Query *) node,
996  context, 0);
997  }
999  context);
1000 }
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2245
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
bool check_functions_in_node(Node *node, check_function_callback checker, void *context)
Definition: nodeFuncs.c:1651
static bool contain_volatile_functions_walker(Node *node, void *context)
Definition: clauses.c:969
static bool contain_volatile_functions_checker(Oid func_id, void *context)
Definition: clauses.c:963
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1834

◆ contain_window_function()

bool contain_window_function ( Node clause)

Definition at line 727 of file clauses.c.

References contain_windowfuncs().

Referenced by get_eclass_for_sort_expr(), and qual_is_pushdown_safe().

728 {
729  return contain_windowfuncs(clause);
730 }
bool contain_windowfuncs(Node *node)
Definition: rewriteManip.c:197

◆ estimate_expression_value()

Node* estimate_expression_value ( PlannerInfo root,
Node node 
)

Definition at line 2492 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 bernoulli_samplescangetsamplesize(), clause_selectivity(), get_restriction_variable(), gincost_opexpr(), gincost_scalararrayopexpr(), preprocess_limit(), scalararraysel(), system_rows_samplescangetsamplesize(), system_samplescangetsamplesize(), and system_time_samplescangetsamplesize().

2493 {
2495 
2496  context.boundParams = root->glob->boundParams; /* bound Params */
2497  /* we do not need to mark the plan as depending on inlined functions */
2498  context.root = NULL;
2499  context.active_fns = NIL; /* nothing being recursively simplified */
2500  context.case_val = NULL; /* no CASE being examined */
2501  context.estimate = true; /* unsafe transformations OK */
2502  return eval_const_expressions_mutator(node, &context);
2503 }
#define NIL
Definition: pg_list.h:69
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2506
ParamListInfo boundParams
Definition: clauses.c:65
PlannerGlobal * glob
Definition: relation.h:157
ParamListInfo boundParams
Definition: relation.h:96

◆ eval_const_expressions()

Node* eval_const_expressions ( PlannerInfo root,
Node node 
)

Definition at line 2459 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 ATExecAttachPartition(), convert_EXISTS_to_ANY(), expression_planner(), get_proposed_default_constraint(), get_relation_constraints(), inline_set_returning_function(), PartConstraintImpliedByRelConstraint(), preprocess_expression(), process_implied_equality(), RelationBuildPartitionKey(), RelationGetIndexExpressions(), RelationGetIndexPredicate(), set_append_rel_size(), and simplify_EXISTS_query().

2460 {
2462 
2463  if (root)
2464  context.boundParams = root->glob->boundParams; /* bound Params */
2465  else
2466  context.boundParams = NULL;
2467  context.root = root; /* for inlined-function dependencies */
2468  context.active_fns = NIL; /* nothing being recursively simplified */
2469  context.case_val = NULL; /* no CASE being examined */
2470  context.estimate = false; /* safe transformations only */
2471  return eval_const_expressions_mutator(node, &context);
2472 }
#define NIL
Definition: pg_list.h:69
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2506
ParamListInfo boundParams
Definition: clauses.c:65
PlannerGlobal * glob
Definition: relation.h:157
ParamListInfo boundParams
Definition: relation.h:96

◆ eval_const_expressions_mutator()

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

Definition at line 2506 of file clauses.c.

References WindowFunc::aggfilter, AND_EXPR, arg, FieldSelect::arg, RelabelType::arg, CoerceViaIO::arg, ArrayCoerceExpr::arg, CollateExpr::arg, CaseExpr::arg, NullTest::arg, BooleanTest::arg, NullTest::argisrow, generate_unaccent_rules::args, WindowFunc::args, FuncExpr::args, OpExpr::args, BoolExpr::args, CaseExpr::args, RowExpr::args, CoalesceExpr::args, ArrayExpr::array_collid, ArrayExpr::array_typeid, Assert, BooleanEqualOperator, BooleanNotEqualOperator, 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, ArrayCoerceExpr::coerceformat, CollateExpr::collOid, Const::constcollid, Const::constisnull, Const::consttype, Const::consttypmod, Const::constvalue, contain_mutable_functions(), copyObject, CSTRINGOID, datumCopy(), DatumGetBool, CaseExpr::defresult, element(), ArrayExpr::element_typeid, ArrayExpr::elements, 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, INT4OID, 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, ArrayCoerceExpr::location, CollateExpr::location, CaseExpr::location, CaseWhen::location, ArrayExpr::location, CoalesceExpr::location, NullTest::location, BooleanTest::location, make_andclause(), make_orclause(), makeBoolConst(), makeConst(), makeNode, makeNullConst(), makeVar(), ArrayExpr::multidims, negate_clause(), NIL, nodeTag, NOT_EXPR, NullTest::nulltesttype, ParamListInfoData::numParams, ObjectIdGetDatum, OidIsValid, OIDOID, OpExpr::opcollid, OpExpr::opfuncid, OpExpr::opno, OpExpr::opresulttype, OpExpr::opretset, OR_EXPR, PARAM_EXTERN, PARAM_FLAG_CONST, Param::paramcollid, Param::paramid, Param::paramkind, ParamListInfoData::params, Param::paramtype, Param::paramtypmod, ParamExternData::pflags, PlaceHolderVar::phexpr, PROCOID, ParamExternData::ptype, RelabelType::relabelformat, ReleaseSysCache(), CaseWhen::result, FieldSelect::resultcollid, RelabelType::resultcollid, CoerceViaIO::resultcollid, ArrayCoerceExpr::resultcollid, FieldSelect::resulttype, RelabelType::resulttype, CoerceViaIO::resulttype, ArrayCoerceExpr::resulttype, FieldSelect::resulttypmod, RelabelType::resulttypmod, ArrayCoerceExpr::resulttypmod, RowExpr::row_typeid, rowtype_field_matches(), SearchSysCache1(), set_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_CoerceViaIO, T_CollateExpr, T_DistinctExpr, T_FieldSelect, T_FuncExpr, T_NullTest, T_OpExpr, T_Param, T_PlaceHolderVar, T_RelabelType, T_SQLValueFunction, T_SubPlan, 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().

2508 {
2509  if (node == NULL)
2510  return NULL;
2511  switch (nodeTag(node))
2512  {
2513  case T_Param:
2514  {
2515  Param *param = (Param *) node;
2516 
2517  /* Look to see if we've been given a value for this Param */
2518  if (param->paramkind == PARAM_EXTERN &&
2519  context->boundParams != NULL &&
2520  param->paramid > 0 &&
2521  param->paramid <= context->boundParams->numParams)
2522  {
2523  ParamExternData *prm = &context->boundParams->params[param->paramid - 1];
2524 
2525  if (OidIsValid(prm->ptype))
2526  {
2527  /* OK to substitute parameter value? */
2528  if (context->estimate ||
2529  (prm->pflags & PARAM_FLAG_CONST))
2530  {
2531  /*
2532  * Return a Const representing the param value.
2533  * Must copy pass-by-ref datatypes, since the
2534  * Param might be in a memory context
2535  * shorter-lived than our output plan should be.
2536  */
2537  int16 typLen;
2538  bool typByVal;
2539  Datum pval;
2540 
2541  Assert(prm->ptype == param->paramtype);
2542  get_typlenbyval(param->paramtype,
2543  &typLen, &typByVal);
2544  if (prm->isnull || typByVal)
2545  pval = prm->value;
2546  else
2547  pval = datumCopy(prm->value, typByVal, typLen);
2548  return (Node *) makeConst(param->paramtype,
2549  param->paramtypmod,
2550  param->paramcollid,
2551  (int) typLen,
2552  pval,
2553  prm->isnull,
2554  typByVal);
2555  }
2556  }
2557  }
2558 
2559  /*
2560  * Not replaceable, so just copy the Param (no need to
2561  * recurse)
2562  */
2563  return (Node *) copyObject(param);
2564  }
2565  case T_WindowFunc:
2566  {
2567  WindowFunc *expr = (WindowFunc *) node;
2568  Oid funcid = expr->winfnoid;
2569  List *args;
2570  Expr *aggfilter;
2571  HeapTuple func_tuple;
2572  WindowFunc *newexpr;
2573 
2574  /*
2575  * We can't really simplify a WindowFunc node, but we mustn't
2576  * just fall through to the default processing, because we
2577  * have to apply expand_function_arguments to its argument
2578  * list. That takes care of inserting default arguments and
2579  * expanding named-argument notation.
2580  */
2581  func_tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
2582  if (!HeapTupleIsValid(func_tuple))
2583  elog(ERROR, "cache lookup failed for function %u", funcid);
2584 
2585  args = expand_function_arguments(expr->args, expr->wintype,
2586  func_tuple);
2587 
2588  ReleaseSysCache(func_tuple);
2589 
2590  /* Now, recursively simplify the args (which are a List) */
2591  args = (List *)
2594  (void *) context);
2595  /* ... and the filter expression, which isn't */
2596  aggfilter = (Expr *)
2598  context);
2599 
2600  /* And build the replacement WindowFunc node */
2601  newexpr = makeNode(WindowFunc);
2602  newexpr->winfnoid = expr->winfnoid;
2603  newexpr->wintype = expr->wintype;
2604  newexpr->wincollid = expr->wincollid;
2605  newexpr->inputcollid = expr->inputcollid;
2606  newexpr->args = args;
2607  newexpr->aggfilter = aggfilter;
2608  newexpr->winref = expr->winref;
2609  newexpr->winstar = expr->winstar;
2610  newexpr->winagg = expr->winagg;
2611  newexpr->location = expr->location;
2612 
2613  return (Node *) newexpr;
2614  }
2615  case T_FuncExpr:
2616  {
2617  FuncExpr *expr = (FuncExpr *) node;
2618  List *args = expr->args;
2619  Expr *simple;
2620  FuncExpr *newexpr;
2621 
2622  /*
2623  * Code for op/func reduction is pretty bulky, so split it out
2624  * as a separate function. Note: exprTypmod normally returns
2625  * -1 for a FuncExpr, but not when the node is recognizably a
2626  * length coercion; we want to preserve the typmod in the
2627  * eventual Const if so.
2628  */
2629  simple = simplify_function(expr->funcid,
2630  expr->funcresulttype,
2631  exprTypmod(node),
2632  expr->funccollid,
2633  expr->inputcollid,
2634  &args,
2635  expr->funcvariadic,
2636  true,
2637  true,
2638  context);
2639  if (simple) /* successfully simplified it */
2640  return (Node *) simple;
2641 
2642  /*
2643  * The expression cannot be simplified any further, so build
2644  * and return a replacement FuncExpr node using the
2645  * possibly-simplified arguments. Note that we have also
2646  * converted the argument list to positional notation.
2647  */
2648  newexpr = makeNode(FuncExpr);
2649  newexpr->funcid = expr->funcid;
2650  newexpr->funcresulttype = expr->funcresulttype;
2651  newexpr->funcretset = expr->funcretset;
2652  newexpr->funcvariadic = expr->funcvariadic;
2653  newexpr->funcformat = expr->funcformat;
2654  newexpr->funccollid = expr->funccollid;
2655  newexpr->inputcollid = expr->inputcollid;
2656  newexpr->args = args;
2657  newexpr->location = expr->location;
2658  return (Node *) newexpr;
2659  }
2660  case T_OpExpr:
2661  {
2662  OpExpr *expr = (OpExpr *) node;
2663  List *args = expr->args;
2664  Expr *simple;
2665  OpExpr *newexpr;
2666 
2667  /*
2668  * Need to get OID of underlying function. Okay to scribble
2669  * on input to this extent.
2670  */
2671  set_opfuncid(expr);
2672 
2673  /*
2674  * Code for op/func reduction is pretty bulky, so split it out
2675  * as a separate function.
2676  */
2677  simple = simplify_function(expr->opfuncid,
2678  expr->opresulttype, -1,
2679  expr->opcollid,
2680  expr->inputcollid,
2681  &args,
2682  false,
2683  true,
2684  true,
2685  context);
2686  if (simple) /* successfully simplified it */
2687  return (Node *) simple;
2688 
2689  /*
2690  * If the operator is boolean equality or inequality, we know
2691  * how to simplify cases involving one constant and one
2692  * non-constant argument.
2693  */
2694  if (expr->opno == BooleanEqualOperator ||
2695  expr->opno == BooleanNotEqualOperator)
2696  {
2697  simple = (Expr *) simplify_boolean_equality(expr->opno,
2698  args);
2699  if (simple) /* successfully simplified it */
2700  return (Node *) simple;
2701  }
2702 
2703  /*
2704  * The expression cannot be simplified any further, so build
2705  * and return a replacement OpExpr node using the
2706  * possibly-simplified arguments.
2707  */
2708  newexpr = makeNode(OpExpr);
2709  newexpr->opno = expr->opno;
2710  newexpr->opfuncid = expr->opfuncid;
2711  newexpr->opresulttype = expr->opresulttype;
2712  newexpr->opretset = expr->opretset;
2713  newexpr->opcollid = expr->opcollid;
2714  newexpr->inputcollid = expr->inputcollid;
2715  newexpr->args = args;
2716  newexpr->location = expr->location;
2717  return (Node *) newexpr;
2718  }
2719  case T_DistinctExpr:
2720  {
2721  DistinctExpr *expr = (DistinctExpr *) node;
2722  List *args;
2723  ListCell *arg;
2724  bool has_null_input = false;
2725  bool all_null_input = true;
2726  bool has_nonconst_input = false;
2727  Expr *simple;
2728  DistinctExpr *newexpr;
2729 
2730  /*
2731  * Reduce constants in the DistinctExpr's arguments. We know
2732  * args is either NIL or a List node, so we can call
2733  * expression_tree_mutator directly rather than recursing to
2734  * self.
2735  */
2736  args = (List *) expression_tree_mutator((Node *) expr->args,
2738  (void *) context);
2739 
2740  /*
2741  * We must do our own check for NULLs because DistinctExpr has
2742  * different results for NULL input than the underlying
2743  * operator does.
2744  */
2745  foreach(arg, args)
2746  {
2747  if (IsA(lfirst(arg), Const))
2748  {
2749  has_null_input |= ((Const *) lfirst(arg))->constisnull;
2750  all_null_input &= ((Const *) lfirst(arg))->constisnull;
2751  }
2752  else
2753  has_nonconst_input = true;
2754  }
2755 
2756  /* all constants? then can optimize this out */
2757  if (!has_nonconst_input)
2758  {
2759  /* all nulls? then not distinct */
2760  if (all_null_input)
2761  return makeBoolConst(false, false);
2762 
2763  /* one null? then distinct */
2764  if (has_null_input)
2765  return makeBoolConst(true, false);
2766 
2767  /* otherwise try to evaluate the '=' operator */
2768  /* (NOT okay to try to inline it, though!) */
2769 
2770  /*
2771  * Need to get OID of underlying function. Okay to
2772  * scribble on input to this extent.
2773  */
2774  set_opfuncid((OpExpr *) expr); /* rely on struct
2775  * equivalence */
2776 
2777  /*
2778  * Code for op/func reduction is pretty bulky, so split it
2779  * out as a separate function.
2780  */
2781  simple = simplify_function(expr->opfuncid,
2782  expr->opresulttype, -1,
2783  expr->opcollid,
2784  expr->inputcollid,
2785  &args,
2786  false,
2787  false,
2788  false,
2789  context);
2790  if (simple) /* successfully simplified it */
2791  {
2792  /*
2793  * Since the underlying operator is "=", must negate
2794  * its result
2795  */
2796  Const *csimple = castNode(Const, simple);
2797 
2798  csimple->constvalue =
2799  BoolGetDatum(!DatumGetBool(csimple->constvalue));
2800  return (Node *) csimple;
2801  }
2802  }
2803 
2804  /*
2805  * The expression cannot be simplified any further, so build
2806  * and return a replacement DistinctExpr node using the
2807  * possibly-simplified arguments.
2808  */
2809  newexpr = makeNode(DistinctExpr);
2810  newexpr->opno = expr->opno;
2811  newexpr->opfuncid = expr->opfuncid;
2812  newexpr->opresulttype = expr->opresulttype;
2813  newexpr->opretset = expr->opretset;
2814  newexpr->opcollid = expr->opcollid;
2815  newexpr->inputcollid = expr->inputcollid;
2816  newexpr->args = args;
2817  newexpr->location = expr->location;
2818  return (Node *) newexpr;
2819  }
2820  case T_BoolExpr:
2821  {
2822  BoolExpr *expr = (BoolExpr *) node;
2823 
2824  switch (expr->boolop)
2825  {
2826  case OR_EXPR:
2827  {
2828  List *newargs;
2829  bool haveNull = false;
2830  bool forceTrue = false;
2831 
2832  newargs = simplify_or_arguments(expr->args,
2833  context,
2834  &haveNull,
2835  &forceTrue);
2836  if (forceTrue)
2837  return makeBoolConst(true, false);
2838  if (haveNull)
2839  newargs = lappend(newargs,
2840  makeBoolConst(false, true));
2841  /* If all the inputs are FALSE, result is FALSE */
2842  if (newargs == NIL)
2843  return makeBoolConst(false, false);
2844 
2845  /*
2846  * If only one nonconst-or-NULL input, it's the
2847  * result
2848  */
2849  if (list_length(newargs) == 1)
2850  return (Node *) linitial(newargs);
2851  /* Else we still need an OR node */
2852  return (Node *) make_orclause(newargs);
2853  }
2854  case AND_EXPR:
2855  {
2856  List *newargs;
2857  bool haveNull = false;
2858  bool forceFalse = false;
2859 
2860  newargs = simplify_and_arguments(expr->args,
2861  context,
2862  &haveNull,
2863  &forceFalse);
2864  if (forceFalse)
2865  return makeBoolConst(false, false);
2866  if (haveNull)
2867  newargs = lappend(newargs,
2868  makeBoolConst(false, true));
2869  /* If all the inputs are TRUE, result is TRUE */
2870  if (newargs == NIL)
2871  return makeBoolConst(true, false);
2872 
2873  /*
2874  * If only one nonconst-or-NULL input, it's the
2875  * result
2876  */
2877  if (list_length(newargs) == 1)
2878  return (Node *) linitial(newargs);
2879  /* Else we still need an AND node */
2880  return (Node *) make_andclause(newargs);
2881  }
2882  case NOT_EXPR:
2883  {
2884  Node *arg;
2885 
2886  Assert(list_length(expr->args) == 1);
2888  context);
2889 
2890  /*
2891  * Use negate_clause() to see if we can simplify
2892  * away the NOT.
2893  */
2894  return negate_clause(arg);
2895  }
2896  default:
2897  elog(ERROR, "unrecognized boolop: %d",
2898  (int) expr->boolop);
2899  break;
2900  }
2901  break;
2902  }
2903  case T_SubPlan:
2904  case T_AlternativeSubPlan:
2905 
2906  /*
2907  * Return a SubPlan unchanged --- too late to do anything with it.
2908  *
2909  * XXX should we ereport() here instead? Probably this routine
2910  * should never be invoked after SubPlan creation.
2911  */
2912  return node;
2913  case T_RelabelType:
2914  {
2915  /*
2916  * If we can simplify the input to a constant, then we don't
2917  * need the RelabelType node anymore: just change the type
2918  * field of the Const node. Otherwise, must copy the
2919  * RelabelType node.
2920  */
2921  RelabelType *relabel = (RelabelType *) node;
2922  Node *arg;
2923 
2924  arg = eval_const_expressions_mutator((Node *) relabel->arg,
2925  context);
2926 
2927  /*
2928  * If we find stacked RelabelTypes (eg, from foo :: int ::
2929  * oid) we can discard all but the top one.
2930  */
2931  while (arg && IsA(arg, RelabelType))
2932  arg = (Node *) ((RelabelType *) arg)->arg;
2933 
2934  if (arg && IsA(arg, Const))
2935  {
2936  Const *con = (Const *) arg;
2937 
2938  con->consttype = relabel->resulttype;
2939  con->consttypmod = relabel->resulttypmod;
2940  con->constcollid = relabel->resultcollid;
2941  return (Node *) con;
2942  }
2943  else
2944  {
2945  RelabelType *newrelabel = makeNode(RelabelType);
2946 
2947  newrelabel->arg = (Expr *) arg;
2948  newrelabel->resulttype = relabel->resulttype;
2949  newrelabel->resulttypmod = relabel->resulttypmod;
2950  newrelabel->resultcollid = relabel->resultcollid;
2951  newrelabel->relabelformat = relabel->relabelformat;
2952  newrelabel->location = relabel->location;
2953  return (Node *) newrelabel;
2954  }
2955  }
2956  case T_CoerceViaIO:
2957  {
2958  CoerceViaIO *expr = (CoerceViaIO *) node;
2959  List *args;
2960  Oid outfunc;
2961  bool outtypisvarlena;
2962  Oid infunc;
2963  Oid intypioparam;
2964  Expr *simple;
2965  CoerceViaIO *newexpr;
2966 
2967  /* Make a List so we can use simplify_function */
2968  args = list_make1(expr->arg);
2969 
2970  /*
2971  * CoerceViaIO represents calling the source type's output
2972  * function then the result type's input function. So, try to
2973  * simplify it as though it were a stack of two such function
2974  * calls. First we need to know what the functions are.
2975  *
2976  * Note that the coercion functions are assumed not to care
2977  * about input collation, so we just pass InvalidOid for that.
2978  */
2979  getTypeOutputInfo(exprType((Node *) expr->arg),
2980  &outfunc, &outtypisvarlena);
2982  &infunc, &intypioparam);
2983 
2984  simple = simplify_function(outfunc,
2985  CSTRINGOID, -1,
2986  InvalidOid,
2987  InvalidOid,
2988  &args,
2989  false,
2990  true,
2991  true,
2992  context);
2993  if (simple) /* successfully simplified output fn */
2994  {
2995  /*
2996  * Input functions may want 1 to 3 arguments. We always
2997  * supply all three, trusting that nothing downstream will
2998  * complain.
2999  */
3000  args = list_make3(simple,
3001  makeConst(OIDOID,
3002  -1,
3003  InvalidOid,
3004  sizeof(Oid),
3005  ObjectIdGetDatum(intypioparam),
3006  false,
3007  true),
3009  -1,
3010  InvalidOid,
3011  sizeof(int32),
3012  Int32GetDatum(-1),
3013  false,
3014  true));
3015 
3016  simple = simplify_function(infunc,
3017  expr->resulttype, -1,
3018  expr->resultcollid,
3019  InvalidOid,
3020  &args,
3021  false,
3022  false,
3023  true,
3024  context);
3025  if (simple) /* successfully simplified input fn */
3026  return (Node *) simple;
3027  }
3028 
3029  /*
3030  * The expression cannot be simplified any further, so build
3031  * and return a replacement CoerceViaIO node using the
3032  * possibly-simplified argument.
3033  */
3034  newexpr = makeNode(CoerceViaIO);
3035  newexpr->arg = (Expr *) linitial(args);
3036  newexpr->resulttype = expr->resulttype;
3037  newexpr->resultcollid = expr->resultcollid;
3038  newexpr->coerceformat = expr->coerceformat;
3039  newexpr->location = expr->location;
3040  return (Node *) newexpr;
3041  }
3042  case T_ArrayCoerceExpr:
3043  {
3044  ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
3045  Expr *arg;
3046  Expr *elemexpr;
3047  ArrayCoerceExpr *newexpr;
3048 
3049  /*
3050  * Reduce constants in the ArrayCoerceExpr's argument and
3051  * per-element expressions, then build a new ArrayCoerceExpr.
3052  */
3053  arg = (Expr *) eval_const_expressions_mutator((Node *) expr->arg,
3054  context);
3055  elemexpr = (Expr *) eval_const_expressions_mutator((Node *) expr->elemexpr,
3056  context);
3057 
3058  newexpr = makeNode(ArrayCoerceExpr);
3059  newexpr->arg = arg;
3060  newexpr->elemexpr = elemexpr;
3061  newexpr->resulttype = expr->resulttype;
3062  newexpr->resulttypmod = expr->resulttypmod;
3063  newexpr->resultcollid = expr->resultcollid;
3064  newexpr->coerceformat = expr->coerceformat;
3065  newexpr->location = expr->location;
3066 
3067  /*
3068  * If constant argument and per-element expression is
3069  * immutable, we can simplify the whole thing to a constant.
3070  * Exception: although contain_mutable_functions considers
3071  * CoerceToDomain immutable for historical reasons, let's not
3072  * do so here; this ensures coercion to an array-over-domain
3073  * does not apply the domain's constraints until runtime.
3074  */
3075  if (arg && IsA(arg, Const) &&
3076  elemexpr && !IsA(elemexpr, CoerceToDomain) &&
3077  !contain_mutable_functions((Node *) elemexpr))
3078  return (Node *) evaluate_expr((Expr *) newexpr,
3079  newexpr->resulttype,
3080  newexpr->resulttypmod,
3081  newexpr->resultcollid);
3082 
3083  /* Else we must return the partially-simplified node */
3084  return (Node *) newexpr;
3085  }
3086  case T_CollateExpr:
3087  {
3088  /*
3089  * If we can simplify the input to a constant, then we don't
3090  * need the CollateExpr node at all: just change the
3091  * constcollid field of the Const node. Otherwise, replace
3092  * the CollateExpr with a RelabelType. (We do that so as to
3093  * improve uniformity of expression representation and thus
3094  * simplify comparison of expressions.)
3095  */
3096  CollateExpr *collate = (CollateExpr *) node;
3097  Node *arg;
3098 
3099  arg = eval_const_expressions_mutator((Node *) collate->arg,
3100  context);
3101 
3102  if (arg && IsA(arg, Const))
3103  {
3104  Const *con = (Const *) arg;
3105 
3106  con->constcollid = collate->collOid;
3107  return (Node *) con;
3108  }
3109  else if (collate->collOid == exprCollation(arg))
3110  {
3111  /* Don't need a RelabelType either... */
3112  return arg;
3113  }
3114  else
3115  {
3116  RelabelType *relabel = makeNode(RelabelType);
3117 
3118  relabel->resulttype = exprType(arg);
3119  relabel->resulttypmod = exprTypmod(arg);
3120  relabel->resultcollid = collate->collOid;
3122  relabel->location = collate->location;
3123 
3124  /* Don't create stacked RelabelTypes */
3125  while (arg && IsA(arg, RelabelType))
3126  arg = (Node *) ((RelabelType *) arg)->arg;
3127  relabel->arg = (Expr *) arg;
3128 
3129  return (Node *) relabel;
3130  }
3131  }
3132  case T_CaseExpr:
3133  {
3134  /*----------
3135  * CASE expressions can be simplified if there are constant
3136  * condition clauses:
3137  * FALSE (or NULL): drop the alternative
3138  * TRUE: drop all remaining alternatives
3139  * If the first non-FALSE alternative is a constant TRUE,
3140  * we can simplify the entire CASE to that alternative's
3141  * expression. If there are no non-FALSE alternatives,
3142  * we simplify the entire CASE to the default result (ELSE).
3143  *
3144  * If we have a simple-form CASE with constant test
3145  * expression, we substitute the constant value for contained
3146  * CaseTestExpr placeholder nodes, so that we have the
3147  * opportunity to reduce constant test conditions. For
3148  * example this allows
3149  * CASE 0 WHEN 0 THEN 1 ELSE 1/0 END
3150  * to reduce to 1 rather than drawing a divide-by-0 error.
3151  * Note that when the test expression is constant, we don't
3152  * have to include it in the resulting CASE; for example
3153  * CASE 0 WHEN x THEN y ELSE z END
3154  * is transformed by the parser to
3155  * CASE 0 WHEN CaseTestExpr = x THEN y ELSE z END
3156  * which we can simplify to
3157  * CASE WHEN 0 = x THEN y ELSE z END
3158  * It is not necessary for the executor to evaluate the "arg"
3159  * expression when executing the CASE, since any contained
3160  * CaseTestExprs that might have referred to it will have been
3161  * replaced by the constant.
3162  *----------
3163  */
3164  CaseExpr *caseexpr = (CaseExpr *) node;
3165  CaseExpr *newcase;
3166  Node *save_case_val;
3167  Node *newarg;
3168  List *newargs;
3169  bool const_true_cond;
3170  Node *defresult = NULL;
3171  ListCell *arg;
3172 
3173  /* Simplify the test expression, if any */
3174  newarg = eval_const_expressions_mutator((Node *) caseexpr->arg,
3175  context);
3176 
3177  /* Set up for contained CaseTestExpr nodes */
3178  save_case_val = context->case_val;
3179  if (newarg && IsA(newarg, Const))
3180  {
3181  context->case_val = newarg;
3182  newarg = NULL; /* not needed anymore, see above */
3183  }
3184  else
3185  context->case_val = NULL;
3186 
3187  /* Simplify the WHEN clauses */
3188  newargs = NIL;
3189  const_true_cond = false;
3190  foreach(arg, caseexpr->args)
3191  {
3192  CaseWhen *oldcasewhen = lfirst_node(CaseWhen, arg);
3193  Node *casecond;
3194  Node *caseresult;
3195 
3196  /* Simplify this alternative's test condition */
3197  casecond = eval_const_expressions_mutator((Node *) oldcasewhen->expr,
3198  context);
3199 
3200  /*
3201  * If the test condition is constant FALSE (or NULL), then
3202  * drop this WHEN clause completely, without processing
3203  * the result.
3204  */
3205  if (casecond && IsA(casecond, Const))
3206  {
3207  Const *const_input = (Const *) casecond;
3208 
3209  if (const_input->constisnull ||
3210  !DatumGetBool(const_input->constvalue))
3211  continue; /* drop alternative with FALSE cond */
3212  /* Else it's constant TRUE */
3213  const_true_cond = true;
3214  }
3215 
3216  /* Simplify this alternative's result value */
3217  caseresult = eval_const_expressions_mutator((Node *) oldcasewhen->result,
3218  context);
3219 
3220  /* If non-constant test condition, emit a new WHEN node */
3221  if (!const_true_cond)
3222  {
3223  CaseWhen *newcasewhen = makeNode(CaseWhen);
3224 
3225  newcasewhen->expr = (Expr *) casecond;
3226  newcasewhen->result = (Expr *) caseresult;
3227  newcasewhen->location = oldcasewhen->location;
3228  newargs = lappend(newargs, newcasewhen);
3229  continue;
3230  }
3231 
3232  /*
3233  * Found a TRUE condition, so none of the remaining
3234  * alternatives can be reached. We treat the result as
3235  * the default result.
3236  */
3237  defresult = caseresult;
3238  break;
3239  }
3240 
3241  /* Simplify the default result, unless we replaced it above */
3242  if (!const_true_cond)
3243  defresult = eval_const_expressions_mutator((Node *) caseexpr->defresult,
3244  context);
3245 
3246  context->case_val = save_case_val;
3247 
3248  /*
3249  * If no non-FALSE alternatives, CASE reduces to the default
3250  * result
3251  */
3252  if (newargs == NIL)
3253  return defresult;
3254  /* Otherwise we need a new CASE node */
3255  newcase = makeNode(CaseExpr);
3256  newcase->casetype = caseexpr->casetype;
3257  newcase->casecollid = caseexpr->casecollid;
3258  newcase->arg = (Expr *) newarg;
3259  newcase->args = newargs;
3260  newcase->defresult = (Expr *) defresult;
3261  newcase->location = caseexpr->location;
3262  return (Node *) newcase;
3263  }
3264  case T_CaseTestExpr:
3265  {
3266  /*
3267  * If we know a constant test value for the current CASE
3268  * construct, substitute it for the placeholder. Else just
3269  * return the placeholder as-is.
3270  */
3271  if (context->case_val)
3272  return copyObject(context->case_val);
3273  else
3274  return copyObject(node);
3275  }
3276  case T_ArrayExpr:
3277  {
3278  ArrayExpr *arrayexpr = (ArrayExpr *) node;
3279  ArrayExpr *newarray;
3280  bool all_const = true;
3281  List *newelems;
3282  ListCell *element;
3283 
3284  newelems = NIL;
3285  foreach(element, arrayexpr->elements)
3286  {
3287  Node *e;
3288 
3289  e = eval_const_expressions_mutator((Node *) lfirst(element),
3290  context);
3291  if (!IsA(e, Const))
3292  all_const = false;
3293  newelems = lappend(newelems, e);
3294  }
3295 
3296  newarray = makeNode(ArrayExpr);
3297  newarray->array_typeid = arrayexpr->array_typeid;
3298  newarray->array_collid = arrayexpr->array_collid;
3299  newarray->element_typeid = arrayexpr->element_typeid;
3300  newarray->elements = newelems;
3301  newarray->multidims = arrayexpr->multidims;
3302  newarray->location = arrayexpr->location;
3303 
3304  if (all_const)
3305  return (Node *) evaluate_expr((Expr *) newarray,
3306  newarray->array_typeid,
3307  exprTypmod(node),
3308  newarray->array_collid);
3309 
3310  return (Node *) newarray;
3311  }
3312  case T_CoalesceExpr:
3313  {
3314  CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
3315  CoalesceExpr *newcoalesce;
3316  List *newargs;
3317  ListCell *arg;
3318 
3319  newargs = NIL;
3320  foreach(arg, coalesceexpr->args)
3321  {
3322  Node *e;
3323 
3325  context);
3326 
3327  /*
3328  * We can remove null constants from the list. For a
3329  * non-null constant, if it has not been preceded by any
3330  * other non-null-constant expressions then it is the
3331  * result. Otherwise, it's the next argument, but we can
3332  * drop following arguments since they will never be
3333  * reached.
3334  */
3335  if (IsA(e, Const))
3336  {
3337  if (((Const *) e)->constisnull)
3338  continue; /* drop null constant */
3339  if (newargs == NIL)
3340  return e; /* first expr */
3341  newargs = lappend(newargs, e);
3342  break;
3343  }
3344  newargs = lappend(newargs, e);
3345  }
3346 
3347  /*
3348  * If all the arguments were constant null, the result is just
3349  * null
3350  */
3351  if (newargs == NIL)
3352  return (Node *) makeNullConst(coalesceexpr->coalescetype,
3353  -1,
3354  coalesceexpr->coalescecollid);
3355 
3356  newcoalesce = makeNode(CoalesceExpr);
3357  newcoalesce->coalescetype = coalesceexpr->coalescetype;
3358  newcoalesce->coalescecollid = coalesceexpr->coalescecollid;
3359  newcoalesce->args = newargs;
3360  newcoalesce->location = coalesceexpr->location;
3361  return (Node *) newcoalesce;
3362  }
3363  case T_SQLValueFunction:
3364  {
3365  /*
3366  * All variants of SQLValueFunction are stable, so if we are
3367  * estimating the expression's value, we should evaluate the
3368  * current function value. Otherwise just copy.
3369  */
3370  SQLValueFunction *svf = (SQLValueFunction *) node;
3371 
3372  if (context->estimate)
3373  return (Node *) evaluate_expr((Expr *) svf,
3374  svf->type,
3375  svf->typmod,
3376  InvalidOid);
3377  else
3378  return copyObject((Node *) svf);
3379  }
3380  case T_FieldSelect:
3381  {
3382  /*
3383  * We can optimize field selection from a whole-row Var into a
3384  * simple Var. (This case won't be generated directly by the
3385  * parser, because ParseComplexProjection short-circuits it.
3386  * But it can arise while simplifying functions.) Also, we
3387  * can optimize field selection from a RowExpr construct.
3388  *
3389  * However, replacing a whole-row Var in this way has a
3390  * pitfall: if we've already built the rel targetlist for the
3391  * source relation, then the whole-row Var is scheduled to be
3392  * produced by the relation scan, but the simple Var probably
3393  * isn't, which will lead to a failure in setrefs.c. This is
3394  * not a problem when handling simple single-level queries, in
3395  * which expression simplification always happens first. It
3396  * is a risk for lateral references from subqueries, though.
3397  * To avoid such failures, don't optimize uplevel references.
3398  *
3399  * We must also check that the declared type of the field is
3400  * still the same as when the FieldSelect was created --- this
3401  * can change if someone did ALTER COLUMN TYPE on the rowtype.
3402  */
3403  FieldSelect *fselect = (FieldSelect *) node;
3404  FieldSelect *newfselect;
3405  Node *arg;
3406 
3407  arg = eval_const_expressions_mutator((Node *) fselect->arg,
3408  context);
3409  if (arg && IsA(arg, Var) &&
3410  ((Var *) arg)->varattno == InvalidAttrNumber &&
3411  ((Var *) arg)->varlevelsup == 0)
3412  {
3413  if (rowtype_field_matches(((Var *) arg)->vartype,
3414  fselect->fieldnum,
3415  fselect->resulttype,
3416  fselect->resulttypmod,
3417  fselect->resultcollid))
3418  return (Node *) makeVar(((Var *) arg)->varno,
3419  fselect->fieldnum,
3420  fselect->resulttype,
3421  fselect->resulttypmod,
3422  fselect->resultcollid,
3423  ((Var *) arg)->varlevelsup);
3424  }
3425  if (arg && IsA(arg, RowExpr))
3426  {
3427  RowExpr *rowexpr = (RowExpr *) arg;
3428 
3429  if (fselect->fieldnum > 0 &&
3430  fselect->fieldnum <= list_length(rowexpr->args))
3431  {
3432  Node *fld = (Node *) list_nth(rowexpr->args,
3433  fselect->fieldnum - 1);
3434 
3435  if (rowtype_field_matches(rowexpr->row_typeid,
3436  fselect->fieldnum,
3437  fselect->resulttype,
3438  fselect->resulttypmod,
3439  fselect->resultcollid) &&
3440  fselect->resulttype == exprType(fld) &&
3441  fselect->resulttypmod == exprTypmod(fld) &&
3442  fselect->resultcollid == exprCollation(fld))
3443  return fld;
3444  }
3445  }
3446  newfselect = makeNode(FieldSelect);
3447  newfselect->arg = (Expr *) arg;
3448  newfselect->fieldnum = fselect->fieldnum;
3449  newfselect->resulttype = fselect->resulttype;
3450  newfselect->resulttypmod = fselect->resulttypmod;
3451  newfselect->resultcollid = fselect->resultcollid;
3452  return (Node *) newfselect;
3453  }
3454  case T_NullTest:
3455  {
3456  NullTest *ntest = (NullTest *) node;
3457  NullTest *newntest;
3458  Node *arg;
3459 
3460  arg = eval_const_expressions_mutator((Node *) ntest->arg,
3461  context);
3462  if (ntest->argisrow && arg && IsA(arg, RowExpr))
3463  {
3464  /*
3465  * We break ROW(...) IS [NOT] NULL into separate tests on
3466  * its component fields. This form is usually more
3467  * efficient to evaluate, as well as being more amenable
3468  * to optimization.
3469  */
3470  RowExpr *rarg = (RowExpr *) arg;
3471  List *newargs = NIL;
3472  ListCell *l;
3473 
3474  foreach(l, rarg->args)
3475  {
3476  Node *relem = (Node *) lfirst(l);
3477 
3478  /*
3479  * A constant field refutes the whole NullTest if it's
3480  * of the wrong nullness; else we can discard it.
3481  */
3482  if (relem && IsA(relem, Const))
3483  {
3484  Const *carg = (Const *) relem;
3485 
3486  if (carg->constisnull ?
3487  (ntest->nulltesttype == IS_NOT_NULL) :
3488  (ntest->nulltesttype == IS_NULL))
3489  return makeBoolConst(false, false);
3490  continue;
3491  }
3492 
3493  /*
3494  * Else, make a scalar (argisrow == false) NullTest
3495  * for this field. Scalar semantics are required
3496  * because IS [NOT] NULL doesn't recurse; see comments
3497  * in ExecEvalRowNullInt().
3498  */
3499  newntest = makeNode(NullTest);
3500  newntest->arg = (Expr *) relem;
3501  newntest->nulltesttype = ntest->nulltesttype;
3502  newntest->argisrow = false;
3503  newntest->location = ntest->location;
3504  newargs = lappend(newargs, newntest);
3505  }
3506  /* If all the inputs were constants, result is TRUE */
3507  if (newargs == NIL)
3508  return makeBoolConst(true, false);
3509  /* If only one nonconst input, it's the result */
3510  if (list_length(newargs) == 1)
3511  return (Node *) linitial(newargs);
3512  /* Else we need an AND node */
3513  return (Node *) make_andclause(newargs);
3514  }
3515  if (!ntest->argisrow && arg && IsA(arg, Const))
3516  {
3517  Const *carg = (Const *) arg;
3518  bool result;
3519 
3520  switch (ntest->nulltesttype)
3521  {
3522  case IS_NULL:
3523  result = carg->constisnull;
3524  break;
3525  case IS_NOT_NULL:
3526  result = !carg->constisnull;
3527  break;
3528  default:
3529  elog(ERROR, "unrecognized nulltesttype: %d",
3530  (int) ntest->nulltesttype);
3531  result = false; /* keep compiler quiet */
3532  break;
3533  }
3534 
3535  return makeBoolConst(result, false);
3536  }
3537 
3538  newntest = makeNode(NullTest);
3539  newntest->arg = (Expr *) arg;
3540  newntest->nulltesttype = ntest->nulltesttype;
3541  newntest->argisrow = ntest->argisrow;
3542  newntest->location = ntest->location;
3543  return (Node *) newntest;
3544  }
3545  case T_BooleanTest:
3546  {
3547  BooleanTest *btest = (BooleanTest *) node;
3548  BooleanTest *newbtest;
3549  Node *arg;
3550 
3551  arg = eval_const_expressions_mutator((Node *) btest->arg,
3552  context);
3553  if (arg && IsA(arg, Const))
3554  {
3555  Const *carg = (Const *) arg;
3556  bool result;
3557 
3558  switch (btest->booltesttype)
3559  {
3560  case IS_TRUE:
3561  result = (!carg->constisnull &&
3562  DatumGetBool(carg->constvalue));
3563  break;
3564  case IS_NOT_TRUE:
3565  result = (carg->constisnull ||
3566  !DatumGetBool(carg->constvalue));
3567  break;
3568  case IS_FALSE:
3569  result = (!carg->constisnull &&
3570  !DatumGetBool(carg->constvalue));
3571  break;
3572  case IS_NOT_FALSE:
3573  result = (carg->constisnull ||
3574  DatumGetBool(carg->constvalue));
3575  break;
3576  case IS_UNKNOWN:
3577  result = carg->constisnull;
3578  break;
3579  case IS_NOT_UNKNOWN:
3580  result = !carg->constisnull;
3581  break;
3582  default:
3583  elog(ERROR, "unrecognized booltesttype: %d",
3584  (int) btest->booltesttype);
3585  result = false; /* keep compiler quiet */
3586  break;
3587  }
3588 
3589  return makeBoolConst(result, false);
3590  }
3591 
3592  newbtest = makeNode(BooleanTest);
3593  newbtest->arg = (Expr *) arg;
3594  newbtest->booltesttype = btest->booltesttype;
3595  newbtest->location = btest->location;
3596  return (Node *) newbtest;
3597  }
3598  case T_PlaceHolderVar:
3599 
3600  /*
3601  * In estimation mode, just strip the PlaceHolderVar node
3602  * altogether; this amounts to estimating that the contained value
3603  * won't be forced to null by an outer join. In regular mode we
3604  * just use the default behavior (ie, simplify the expression but
3605  * leave the PlaceHolderVar node intact).
3606  */
3607  if (context->estimate)
3608  {
3609  PlaceHolderVar *phv = (PlaceHolderVar *) node;
3610 
3611  return eval_const_expressions_mutator((Node *) phv->phexpr,
3612  context);
3613  }
3614  break;
3615  default:
3616  break;
3617  }
3618 
3619  /*
3620  * For any node type not handled above, we recurse using
3621  * expression_tree_mutator, which will copy the node unchanged but try to
3622  * simplify its arguments (if any) using this routine. For example: we
3623  * cannot eliminate an ArrayRef node, but we might be able to simplify
3624  * constant expressions in its subscripts.
3625  */
3626  return expression_tree_mutator(node, eval_const_expressions_mutator,
3627  (void *) context);
3628 }
Datum constvalue
Definition: primnodes.h:196
#define list_make3(x1, x2, x3)
Definition: pg_list.h:141
signed short int16
Definition: c.h:283
Oid funcresulttype
Definition: primnodes.h:450
bool multidims
Definition: primnodes.h:960
ParamExternData params[FLEXIBLE_ARRAY_MEMBER]
Definition: params.h:76
#define NIL
Definition: pg_list.h:69
Datum value
Definition: params.h:56
List * args
Definition: primnodes.h:990
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
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:3931
Node * negate_clause(Node *node)
Definition: prepqual.c:73
Node * expression_tree_mutator(Node *node, Node *(*mutator)(), void *context)
Definition: nodeFuncs.c:2409
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2646
static Expr * evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod, Oid result_collation)
Definition: clauses.c:4748
List * args
Definition: primnodes.h:359
List * args
Definition: primnodes.h:457
Oid wincollid
Definition: primnodes.h:357
Oid resulttype
Definition: primnodes.h:744
#define castNode(_type_, nodeptr)
Definition: nodes.h:579
#define OIDOID
Definition: pg_type.h:328
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:276
Oid funccollid
Definition: primnodes.h:455
Oid resulttype
Definition: primnodes.h:815
Oid casecollid
Definition: primnodes.h:911
Expr * arg
Definition: primnodes.h:794
#define INT4OID
Definition: pg_type.h:316
ParamKind paramkind
Definition: primnodes.h:244
Definition: nodes.h:510
Oid array_typeid
Definition: primnodes.h:956
Expr * arg
Definition: primnodes.h:742
bool funcretset
Definition: primnodes.h:451
Oid casetype
Definition: primnodes.h:910
unsigned int Oid
Definition: postgres_ext.h:31
Index winref
Definition: primnodes.h:361
Definition: primnodes.h:163
Const * makeConst(Oid consttype, int32 consttypmod, Oid constcollid, int constlen, Datum constvalue, bool constisnull, bool constbyval)
Definition: makefuncs.c:298
#define OidIsValid(objectId)
Definition: c.h:576
#define BooleanEqualOperator
Definition: pg_operator.h:114
int location
Definition: primnodes.h:926
signed int int32
Definition: c.h:284
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:336
#define list_make1(x1)
Definition: pg_list.h:139
Oid consttype
Definition: primnodes.h:192
CoercionForm funcformat
Definition: primnodes.h:454
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2506
Oid opresulttype
Definition: primnodes.h:498
ParamListInfo boundParams
Definition: clauses.c:65
#define linitial(l)
Definition: pg_list.h:111
Oid funcid
Definition: primnodes.h:449
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
Expr * phexpr
Definition: relation.h:1940
static bool rowtype_field_matches(Oid rowtypeid, int fieldnum, Oid expectedtype, int32 expectedtypmod, Oid expectedcollation)
Definition: clauses.c:2391
Oid paramcollid
Definition: primnodes.h:248
List * args
Definition: primnodes.h:1054
BoolExprType boolop
Definition: primnodes.h:562
Node * makeBoolConst(bool value, bool isnull)
Definition: makefuncs.c:356
Expr * arg
Definition: primnodes.h:1187
Oid constcollid
Definition: primnodes.h:194
Oid resultcollid
Definition: primnodes.h:747
#define lfirst_node(type, lc)
Definition: pg_list.h:109
struct Const Const
void * list_nth(const List *list, int n)
Definition: list.c:410
int location
Definition: primnodes.h:503
Expr * arg
Definition: primnodes.h:1210
#define DatumGetBool(X)
Definition: postgres.h:399
Oid winfnoid
Definition: primnodes.h:355
Expr * arg
Definition: primnodes.h:814
List * elements
Definition: primnodes.h:959
Expr * elemexpr
Definition: primnodes.h:839
static List * expand_function_arguments(List *args, Oid result_type, HeapTuple func_tuple)
Definition: clauses.c:4028
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2613
Oid opcollid
Definition: primnodes.h:500
Var * makeVar(Index varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:67
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:128
List * lappend(List *list, void *datum)
Definition: list.c:128
#define BooleanNotEqualOperator
Definition: pg_operator.h:111
static chr element(struct vars *v, const chr *startp, const chr *endp)
Definition: regc_locale.c:380
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
List * args
Definition: primnodes.h:913
CoercionForm coerceformat
Definition: primnodes.h:843
int location
Definition: primnodes.h:961
BoolTestType booltesttype
Definition: primnodes.h:1211
uintptr_t Datum
Definition: postgres.h:372
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
Oid resultcollid
Definition: primnodes.h:817
Oid opfuncid
Definition: primnodes.h:497
Oid resulttype
Definition: primnodes.h:795
NullTestType nulltesttype
Definition: primnodes.h:1188
#define BoolGetDatum(X)
Definition: postgres.h:408
Oid resultcollid
Definition: primnodes.h:797
#define InvalidOid
Definition: postgres_ext.h:36
int32 paramtypmod
Definition: primnodes.h:247
#define makeNode(_type_)
Definition: nodes.h:558
static Node * simplify_boolean_equality(Oid opno, List *args)
Definition: clauses.c:3862
int location
Definition: primnodes.h:819
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
int location
Definition: primnodes.h:364
Oid inputcollid
Definition: primnodes.h:456
#define CSTRINGOID
Definition: pg_type.h:684
#define Assert(condition)
Definition: c.h:670
#define lfirst(lc)
Definition: pg_list.h:106
Expr * aggfilter
Definition: primnodes.h:360
int paramid
Definition: primnodes.h:245
Oid array_collid
Definition: primnodes.h:957
uint16 pflags
Definition: params.h:58
int location
Definition: primnodes.h:1190
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
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:991
static int list_length(const List *l)
Definition: pg_list.h:89
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:720
Expr * arg
Definition: primnodes.h:880
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2001
int location
Definition: primnodes.h:915
Oid inputcollid
Definition: primnodes.h:501
Oid inputcollid
Definition: primnodes.h:358
List * args
Definition: primnodes.h:563
#define InvalidAttrNumber
Definition: attnum.h:23
#define nodeTag(nodeptr)
Definition: nodes.h:515
int32 consttypmod
Definition: primnodes.h:193
Oid element_typeid
Definition: primnodes.h:958
Oid wintype
Definition: primnodes.h:356
CoercionForm coerceformat
Definition: primnodes.h:818
static List * simplify_or_arguments(List *args, eval_const_expressions_context *context, bool *haveNull, bool *forceTrue)
Definition: clauses.c:3650
#define Int32GetDatum(X)
Definition: postgres.h:485
e
Definition: preproc-init.c:82
void set_opfuncid(OpExpr *opexpr)
Definition: nodeFuncs.c:1613
bool winagg
Definition: primnodes.h:363
Oid coalescetype
Definition: primnodes.h:1052
void * arg
NodeTag type
Definition: primnodes.h:134
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:878
bool argisrow
Definition: primnodes.h:1189
Expr * make_andclause(List *andclauses)
Definition: clauses.c:327
int32 resulttypmod
Definition: primnodes.h:796
Expr * arg
Definition: primnodes.h:912
int location
Definition: primnodes.h:458
Oid opno
Definition: primnodes.h:496
int32 resulttypmod
Definition: primnodes.h:841
#define elog
Definition: elog.h:219
Expr * result
Definition: primnodes.h:925
#define copyObject(obj)
Definition: nodes.h:623
List * args
Definition: primnodes.h:502
CoercionForm relabelformat
Definition: primnodes.h:798
Expr * defresult
Definition: primnodes.h:914
Expr * expr
Definition: primnodes.h:924
int location
Definition: primnodes.h:882
Definition: pg_list.h:45
bool isnull
Definition: params.h:57
Expr * make_orclause(List *orclauses)
Definition: clauses.c:293
Oid paramtype
Definition: primnodes.h:246
int location
Definition: primnodes.h:799
bool constisnull
Definition: primnodes.h:197
Oid coalescecollid
Definition: primnodes.h:1053
bool funcvariadic
Definition: primnodes.h:452
#define PARAM_FLAG_CONST
Definition: params.h:52
bool opretset
Definition: primnodes.h:499
int32 resulttypmod
Definition: primnodes.h:746
bool winstar
Definition: primnodes.h:362
Definition: nodes.h:148
AttrNumber fieldnum
Definition: primnodes.h:743

◆ evaluate_expr()

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

Definition at line 4748 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(), and evaluate_function().

4750 {
4751  EState *estate;
4752  ExprState *exprstate;
4753  MemoryContext oldcontext;
4754  Datum const_val;
4755  bool const_is_null;
4756  int16 resultTypLen;
4757  bool resultTypByVal;
4758 
4759  /*
4760  * To use the executor, we need an EState.
4761  */
4762  estate = CreateExecutorState();
4763 
4764  /* We can use the estate's working context to avoid memory leaks. */
4765  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
4766 
4767  /* Make sure any opfuncids are filled in. */
4768  fix_opfuncids((Node *) expr);
4769 
4770  /*
4771  * Prepare expr for execution. (Note: we can't use ExecPrepareExpr
4772  * because it'd result in recursively invoking eval_const_expressions.)
4773  */
4774  exprstate = ExecInitExpr(expr, NULL);
4775 
4776  /*
4777  * And evaluate it.
4778  *
4779  * It is OK to use a default econtext because none of the ExecEvalExpr()
4780  * code used in this situation will use econtext. That might seem
4781  * fortuitous, but it's not so unreasonable --- a constant expression does
4782  * not depend on context, by definition, n'est ce pas?
4783  */
4784  const_val = ExecEvalExprSwitchContext(exprstate,
4785  GetPerTupleExprContext(estate),
4786  &const_is_null);
4787 
4788  /* Get info needed about result datatype */
4789  get_typlenbyval(result_type, &resultTypLen, &resultTypByVal);
4790 
4791  /* Get back to outer memory context */
4792  MemoryContextSwitchTo(oldcontext);
4793 
4794  /*
4795  * Must copy result out of sub-context used by expression eval.
4796  *
4797  * Also, if it's varlena, forcibly detoast it. This protects us against
4798  * storing TOAST pointers into plans that might outlive the referenced
4799  * data. (makeConst would handle detoasting anyway, but it's worth a few
4800  * extra lines here so that we can do the copy and detoast in one step.)
4801  */
4802  if (!const_is_null)
4803  {
4804  if (resultTypLen == -1)
4805  const_val = PointerGetDatum(PG_DETOAST_DATUM_COPY(const_val));
4806  else
4807  const_val = datumCopy(const_val, resultTypByVal, resultTypLen);
4808  }
4809 
4810  /* Release all the junk we just created */
4811  FreeExecutorState(estate);
4812 
4813  /*
4814  * Make the constant result node.
4815  */
4816  return (Expr *) makeConst(result_type, result_typmod, result_collation,
4817  resultTypLen,
4818  const_val, const_is_null,
4819  resultTypByVal);
4820 }
signed short int16
Definition: c.h:283
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:291
#define PG_DETOAST_DATUM_COPY(datum)
Definition: fmgr.h:207
#define PointerGetDatum(X)
Definition: postgres.h:562
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1582
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Definition: nodes.h:510
Const * makeConst(Oid consttype, int32 consttypmod, Oid constcollid, int constlen, Datum constvalue, bool constisnull, bool constbyval)
Definition: makefuncs.c:298
void FreeExecutorState(EState *estate)
Definition: execUtils.c:185
#define GetPerTupleExprContext(estate)
Definition: executor.h:467
MemoryContext es_query_cxt
Definition: execnodes.h:471
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:128
EState * CreateExecutorState(void)
Definition: execUtils.c:80
uintptr_t Datum
Definition: postgres.h:372
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2001
ExprState * ExecInitExpr(Expr *node, PlanState *parent)
Definition: execExpr.c:113

◆ 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 4245 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, makeNullConst(), PROVOLATILE_IMMUTABLE, PROVOLATILE_STABLE, and RECORDOID.

Referenced by simplify_function().

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

◆ expand_function_arguments()

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

Definition at line 4028 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(), and simplify_function().

4029 {
4030  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4031  bool has_named_args = false;
4032  ListCell *lc;
4033 
4034  /* Do we have any named arguments? */
4035  foreach(lc, args)
4036  {
4037  Node *arg = (Node *) lfirst(lc);
4038 
4039  if (IsA(arg, NamedArgExpr))
4040  {
4041  has_named_args = true;
4042  break;
4043  }
4044  }
4045 
4046  /* If so, we must apply reorder_function_arguments */
4047  if (has_named_args)
4048  {
4049  args = reorder_function_arguments(args, func_tuple);
4050  /* Recheck argument types and add casts if needed */
4051  recheck_cast_function_args(args, result_type, func_tuple);
4052  }
4053  else if (list_length(args) < funcform->pronargs)
4054  {
4055  /* No named args, but we seem to be short some defaults */
4056  args = add_function_defaults(args, func_tuple);
4057  /* Recheck argument types and add casts if needed */
4058  recheck_cast_function_args(args, result_type, func_tuple);
4059  }
4060 
4061  return args;
4062 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
Definition: nodes.h:510
static void recheck_cast_function_args(List *args, Oid result_type, HeapTuple func_tuple)
Definition: clauses.c:4201
static List * add_function_defaults(List *args, HeapTuple func_tuple)
Definition: clauses.c:4141
static List * reorder_function_arguments(List *args, HeapTuple func_tuple)
Definition: clauses.c:4071
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:83
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
void * arg

◆ expression_returns_set_rows()

double expression_returns_set_rows ( Node clause)

Definition at line 802 of file clauses.c.

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

Referenced by create_set_projection_path(), and set_function_size_estimates().

803 {
804  if (clause == NULL)
805  return 1.0;
806  if (IsA(clause, FuncExpr))
807  {
808  FuncExpr *expr = (FuncExpr *) clause;
809 
810  if (expr->funcretset)
811  return clamp_row_est(get_func_rows(expr->funcid));
812  }
813  if (IsA(clause, OpExpr))
814  {
815  OpExpr *expr = (OpExpr *) clause;
816 
817  if (expr->opretset)
818  {
819  set_opfuncid(expr);
820  return clamp_row_est(get_func_rows(expr->opfuncid));
821  }
822  }
823  return 1.0;
824 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
float4 get_func_rows(Oid funcid)
Definition: lsyscache.c:1660
bool funcretset
Definition: primnodes.h:451
Oid funcid
Definition: primnodes.h:449
Oid opfuncid
Definition: primnodes.h:497
void set_opfuncid(OpExpr *opexpr)
Definition: nodeFuncs.c:1613
double clamp_row_est(double nrows)
Definition: costsize.c:174
bool opretset
Definition: primnodes.h:499

◆ fetch_function_defaults()

static List * fetch_function_defaults ( HeapTuple  func_tuple)
static

Definition at line 4166 of file clauses.c.

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

Referenced by add_function_defaults(), and reorder_function_arguments().

4167 {
4168  List *defaults;
4169  Datum proargdefaults;
4170  bool isnull;
4171  char *str;
4172 
4173  /* The error cases here shouldn't happen, but check anyway */
4174  proargdefaults = SysCacheGetAttr(PROCOID, func_tuple,
4176  &isnull);
4177  if (isnull)
4178  elog(ERROR, "not enough default arguments");
4179  str = TextDatumGetCString(proargdefaults);
4180  defaults = castNode(List, stringToNode(str));
4181  pfree(str);
4182  return defaults;
4183 }
void * stringToNode(char *str)
Definition: read.c:38
#define castNode(_type_, nodeptr)
Definition: nodes.h:579
void pfree(void *pointer)
Definition: mcxt.c:949
#define ERROR
Definition: elog.h:43
#define Anum_pg_proc_proargdefaults
Definition: pg_proc.h:113
#define TextDatumGetCString(d)
Definition: builtins.h:92
uintptr_t Datum
Definition: postgres.h:372
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1368
#define elog
Definition: elog.h:219
Definition: pg_list.h:45

◆ find_forced_null_var()

Var* find_forced_null_var ( Node node)

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

2121 {
2122  if (node == NULL)
2123  return NULL;
2124  if (IsA(node, NullTest))
2125  {
2126  /* check for var IS NULL */
2127  NullTest *expr = (NullTest *) node;
2128 
2129  if (expr->nulltesttype == IS_NULL && !expr->argisrow)
2130  {
2131  Var *var = (Var *) expr->arg;
2132 
2133  if (var && IsA(var, Var) &&
2134  var->varlevelsup == 0)
2135  return var;
2136  }
2137  }
2138  else if (IsA(node, BooleanTest))
2139  {
2140  /* var IS UNKNOWN is equivalent to var IS NULL */
2141  BooleanTest *expr = (BooleanTest *) node;
2142 
2143  if (expr->booltesttype == IS_UNKNOWN)
2144  {
2145  Var *var = (Var *) expr->arg;
2146 
2147  if (var && IsA(var, Var) &&
2148  var->varlevelsup == 0)
2149  return var;
2150  }
2151  }
2152  return NULL;
2153 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
Index varlevelsup
Definition: primnodes.h:173
Definition: primnodes.h:163
Expr * arg
Definition: primnodes.h:1187
Expr * arg
Definition: primnodes.h:1210
BoolTestType booltesttype
Definition: primnodes.h:1211
NullTestType nulltesttype
Definition: primnodes.h:1188
bool argisrow
Definition: primnodes.h:1189

◆ find_forced_null_vars()

List* find_forced_null_vars ( Node node)

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

2062 {
2063  List *result = NIL;
2064  Var *var;
2065  ListCell *l;
2066 
2067  if (node == NULL)
2068  return NIL;
2069  /* Check single-clause cases using subroutine */
2070  var = find_forced_null_var(node);
2071  if (var)
2072  {
2073  result = list_make1(var);
2074  }
2075  /* Otherwise, handle AND-conditions */
2076  else if (IsA(node, List))
2077  {
2078  /*
2079  * At top level, we are examining an implicit-AND list: if any of the
2080  * arms produces FALSE-or-NULL then the result is FALSE-or-NULL.
2081  */
2082  foreach(l, (List *) node)
2083  {
2084  result = list_concat(result,
2086  }
2087  }
2088  else if (IsA(node, BoolExpr))
2089  {
2090  BoolExpr *expr = (BoolExpr *) node;
2091 
2092  /*
2093  * We don't bother considering the OR case, because it's fairly
2094  * unlikely anyone would write "v1 IS NULL OR v1 IS NULL". Likewise,
2095  * the NOT case isn't worth expending code on.
2096  */
2097  if (expr->boolop == AND_EXPR)
2098  {
2099  /* At top level we can just recurse (to the List case) */
2100  result = find_forced_null_vars((Node *) expr->args);
2101  }
2102  }
2103  return result;
2104 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
Definition: nodes.h:510
List * list_concat(List *list1, List *list2)
Definition: list.c:321
Definition: primnodes.h:163
List * find_forced_null_vars(Node *node)
Definition: clauses.c:2061
#define list_make1(x1)
Definition: pg_list.h:139
BoolExprType boolop
Definition: primnodes.h:562
#define lfirst(lc)
Definition: pg_list.h:106
List * args
Definition: primnodes.h:563
Definition: pg_list.h:45
Var * find_forced_null_var(Node *node)
Definition: clauses.c:2120

◆ find_nonnullable_rels()

Relids find_nonnullable_rels ( Node clause)

Definition at line 1660 of file clauses.c.

References find_nonnullable_rels_walker().

Referenced by make_outerjoininfo(), and reduce_outer_joins_pass2().

1661 {
1662  return find_nonnullable_rels_walker(clause, true);
1663 }
static Relids find_nonnullable_rels_walker(Node *node, bool top_level)
Definition: clauses.c:1666

◆ find_nonnullable_rels_walker()

static Relids find_nonnullable_rels_walker ( Node node,
bool  top_level 
)
static

Definition at line 1666 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_int_members(), bms_is_empty(), bms_join(), bms_make_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, set_opfuncid(), Var::varlevelsup, and Var::varno.

Referenced by find_nonnullable_rels().

1667 {
1668  Relids result = NULL;
1669  ListCell *l;
1670 
1671  if (node == NULL)
1672  return NULL;
1673  if (IsA(node, Var))
1674  {
1675  Var *var = (Var *) node;
1676 
1677  if (var->varlevelsup == 0)
1678  result = bms_make_singleton(var->varno);
1679  }
1680  else if (IsA(node, List))
1681  {
1682  /*
1683  * At top level, we are examining an implicit-AND list: if any of the
1684  * arms produces FALSE-or-NULL then the result is FALSE-or-NULL. If
1685  * not at top level, we are examining the arguments of a strict
1686  * function: if any of them produce NULL then the result of the
1687  * function must be NULL. So in both cases, the set of nonnullable
1688  * rels is the union of those found in the arms, and we pass down the
1689  * top_level flag unmodified.
1690  */
1691  foreach(l, (List *) node)
1692  {
1693  result = bms_join(result,
1695  top_level));
1696  }
1697  }
1698  else if (IsA(node, FuncExpr))
1699  {
1700  FuncExpr *expr = (FuncExpr *) node;
1701 
1702  if (func_strict(expr->funcid))
1703  result = find_nonnullable_rels_walker((Node *) expr->args, false);
1704  }
1705  else if (IsA(node, OpExpr))
1706  {
1707  OpExpr *expr = (OpExpr *) node;
1708 
1709  set_opfuncid(expr);
1710  if (func_strict(expr->opfuncid))
1711  result = find_nonnullable_rels_walker((Node *) expr->args, false);
1712  }
1713  else if (IsA(node, ScalarArrayOpExpr))
1714  {
1715  ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1716 
1717  if (is_strict_saop(expr, true))
1718  result = find_nonnullable_rels_walker((Node *) expr->args, false);
1719  }
1720  else if (IsA(node, BoolExpr))
1721  {
1722  BoolExpr *expr = (BoolExpr *) node;
1723 
1724  switch (expr->boolop)
1725  {
1726  case AND_EXPR:
1727  /* At top level we can just recurse (to the List case) */
1728  if (top_level)
1729  {
1730  result = find_nonnullable_rels_walker((Node *) expr->args,
1731  top_level);
1732  break;
1733  }
1734 
1735  /*
1736  * Below top level, even if one arm produces NULL, the result
1737  * could be FALSE (hence not NULL). However, if *all* the
1738  * arms produce NULL then the result is NULL, so we can take
1739  * the intersection of the sets of nonnullable rels, just as
1740  * for OR. Fall through to share code.
1741  */
1742  /* FALL THRU */
1743  case OR_EXPR:
1744 
1745  /*
1746  * OR is strict if all of its arms are, so we can take the
1747  * intersection of the sets of nonnullable rels for each arm.
1748  * This works for both values of top_level.
1749  */
1750  foreach(l, expr->args)
1751  {
1752  Relids subresult;
1753 
1754  subresult = find_nonnullable_rels_walker(lfirst(l),
1755  top_level);
1756  if (result == NULL) /* first subresult? */
1757  result = subresult;
1758  else
1759  result = bms_int_members(result, subresult);
1760 
1761  /*
1762  * If the intersection is empty, we can stop looking. This
1763  * also justifies the test for first-subresult above.
1764  */
1765  if (bms_is_empty(result))
1766  break;
1767  }
1768  break;
1769  case NOT_EXPR:
1770  /* NOT will return null if its arg is null */
1771  result = find_nonnullable_rels_walker((Node *) expr->args,
1772  false);
1773  break;
1774  default:
1775  elog(ERROR, "unrecognized boolop: %d", (int) expr->boolop);
1776  break;
1777  }
1778  }
1779  else if (IsA(node, RelabelType))
1780  {
1781  RelabelType *expr = (RelabelType *) node;
1782 
1783  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1784  }
1785  else if (IsA(node, CoerceViaIO))
1786  {
1787  /* not clear this is useful, but it can't hurt */
1788  CoerceViaIO *expr = (CoerceViaIO *) node;
1789 
1790  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1791  }
1792  else if (IsA(node, ArrayCoerceExpr))
1793  {
1794  /* ArrayCoerceExpr is strict at the array level; ignore elemexpr */
1795  ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
1796 
1797  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1798  }
1799  else if (IsA(node, ConvertRowtypeExpr))
1800  {
1801  /* not clear this is useful, but it can't hurt */
1802  ConvertRowtypeExpr *expr = (ConvertRowtypeExpr *) node;
1803 
1804  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1805  }
1806  else if (IsA(node, CollateExpr))
1807  {
1808  CollateExpr *expr = (CollateExpr *) node;
1809 
1810  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1811  }
1812  else if (IsA(node, NullTest))
1813  {
1814  /* IS NOT NULL can be considered strict, but only at top level */
1815  NullTest *expr = (NullTest *) node;
1816 
1817  if (top_level && expr->nulltesttype == IS_NOT_NULL && !expr->argisrow)
1818  result = find_nonnullable_rels_walker((Node *) expr->arg, false);
1819  }
1820  else if (IsA(node, BooleanTest))
1821  {
1822  /* Boolean tests that reject NULL are strict at top level */
1823  BooleanTest *expr = (BooleanTest *) node;
1824 
1825  if (top_level &&
1826  (expr->booltesttype == IS_TRUE ||
1827  expr->booltesttype == IS_FALSE ||
1828  expr->booltesttype == IS_NOT_UNKNOWN))
1829  result = find_nonnullable_rels_walker((Node *) expr->arg, false);
1830  }
1831  else if (IsA(node, PlaceHolderVar))
1832  {
1833  PlaceHolderVar *phv = (PlaceHolderVar *) node;
1834 
1835  result = find_nonnullable_rels_walker((Node *) phv->phexpr, top_level);
1836  }
1837  return result;
1838 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
Index varlevelsup
Definition: primnodes.h:173
List * args
Definition: primnodes.h:457
Expr * arg
Definition: primnodes.h:794
Definition: nodes.h:510
Definition: primnodes.h:163
Oid funcid
Definition: primnodes.h:449
#define ERROR
Definition: elog.h:43
Expr * phexpr
Definition: relation.h:1940
Bitmapset * bms_join(Bitmapset *a, Bitmapset *b)
Definition: bitmapset.c:838
BoolExprType boolop
Definition: primnodes.h:562
Expr * arg
Definition: primnodes.h:1187
Bitmapset * bms_make_singleton(int x)
Definition: bitmapset.c:179
Expr * arg
Definition: primnodes.h:1210
Expr * arg
Definition: primnodes.h:814
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:663
Index varno
Definition: primnodes.h:166
BoolTestType booltesttype
Definition: primnodes.h:1211
Oid opfuncid
Definition: primnodes.h:497
static Relids find_nonnullable_rels_walker(Node *node, bool top_level)
Definition: clauses.c:1666
NullTestType nulltesttype
Definition: primnodes.h:1188
static bool is_strict_saop(ScalarArrayOpExpr *expr, bool falseOK)
Definition: clauses.c:2169
#define lfirst(lc)
Definition: pg_list.h:106
Expr * arg
Definition: primnodes.h:880
List * args
Definition: primnodes.h:563
bool func_strict(Oid funcid)
Definition: lsyscache.c:1565
void set_opfuncid(OpExpr *opexpr)
Definition: nodeFuncs.c:1613
bool argisrow
Definition: primnodes.h:1189
#define elog
Definition: elog.h:219
List * args
Definition: primnodes.h:502
Bitmapset * bms_int_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:791
Definition: pg_list.h:45

◆ find_nonnullable_vars()

List* find_nonnullable_vars ( Node clause)

Definition at line 1868 of file clauses.c.

References find_nonnullable_vars_walker().

Referenced by reduce_outer_joins_pass2().

1869 {
1870  return find_nonnullable_vars_walker(clause, true);
1871 }
static List * find_nonnullable_vars_walker(Node *node, bool top_level)
Definition: clauses.c:1874

◆ find_nonnullable_vars_walker()

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

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

1875 {
1876  List *result = NIL;
1877  ListCell *l;
1878 
1879  if (node == NULL)
1880  return NIL;
1881  if (IsA(node, Var))
1882  {
1883  Var *var = (Var *) node;
1884 
1885  if (var->varlevelsup == 0)
1886  result = list_make1(var);
1887  }
1888  else if (IsA(node, List))
1889  {
1890  /*
1891  * At top level, we are examining an implicit-AND list: if any of the
1892  * arms produces FALSE-or-NULL then the result is FALSE-or-NULL. If
1893  * not at top level, we are examining the arguments of a strict
1894  * function: if any of them produce NULL then the result of the
1895  * function must be NULL. So in both cases, the set of nonnullable
1896  * vars is the union of those found in the arms, and we pass down the
1897  * top_level flag unmodified.
1898  */
1899  foreach(l, (List *) node)
1900  {
1901  result = list_concat(result,
1903  top_level));
1904  }
1905  }
1906  else if (IsA(node, FuncExpr))
1907  {
1908  FuncExpr *expr = (FuncExpr *) node;
1909 
1910  if (func_strict(expr->funcid))
1911  result = find_nonnullable_vars_walker((Node *) expr->args, false);
1912  }
1913  else if (IsA(node, OpExpr))
1914  {
1915  OpExpr *expr = (OpExpr *) node;
1916 
1917  set_opfuncid(expr);
1918  if (func_strict(expr->opfuncid))
1919  result = find_nonnullable_vars_walker((Node *) expr->args, false);
1920  }
1921  else if (IsA(node, ScalarArrayOpExpr))
1922  {
1923  ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1924 
1925  if (is_strict_saop(expr, true))
1926  result = find_nonnullable_vars_walker((Node *) expr->args, false);
1927  }
1928  else if (IsA(node, BoolExpr))
1929  {
1930  BoolExpr *expr = (BoolExpr *) node;
1931 
1932  switch (expr->boolop)
1933  {
1934  case AND_EXPR:
1935  /* At top level we can just recurse (to the List case) */
1936  if (top_level)
1937  {
1938  result = find_nonnullable_vars_walker((Node *) expr->args,
1939  top_level);
1940  break;
1941  }
1942 
1943  /*
1944  * Below top level, even if one arm produces NULL, the result
1945  * could be FALSE (hence not NULL). However, if *all* the
1946  * arms produce NULL then the result is NULL, so we can take
1947  * the intersection of the sets of nonnullable vars, just as
1948  * for OR. Fall through to share code.
1949  */
1950  /* FALL THRU */
1951  case OR_EXPR:
1952 
1953  /*
1954  * OR is strict if all of its arms are, so we can take the
1955  * intersection of the sets of nonnullable vars for each arm.
1956  * This works for both values of top_level.
1957  */
1958  foreach(l, expr->args)
1959  {
1960  List *subresult;
1961 
1962  subresult = find_nonnullable_vars_walker(lfirst(l),
1963  top_level);
1964  if (result == NIL) /* first subresult? */
1965  result = subresult;
1966  else
1967  result = list_intersection(result, subresult);
1968 
1969  /*
1970  * If the intersection is empty, we can stop looking. This
1971  * also justifies the test for first-subresult above.
1972  */
1973  if (result == NIL)
1974  break;
1975  }
1976  break;
1977  case NOT_EXPR:
1978  /* NOT will return null if its arg is null */
1979  result = find_nonnullable_vars_walker((Node *) expr->args,
1980  false);
1981  break;
1982  default:
1983  elog(ERROR, "unrecognized boolop: %d", (int) expr->boolop);
1984  break;
1985  }
1986  }
1987  else if (IsA(node, RelabelType))
1988  {
1989  RelabelType *expr = (RelabelType *) node;
1990 
1991  result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1992  }
1993  else if (IsA(node, CoerceViaIO))
1994  {
1995  /* not clear this is useful, but it can't hurt */
1996  CoerceViaIO *expr = (CoerceViaIO *) node;
1997 
1998  result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1999  }
2000  else if (IsA(node, ArrayCoerceExpr))
2001  {
2002  /* ArrayCoerceExpr is strict at the array level; ignore elemexpr */
2003  ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
2004 
2005  result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
2006  }
2007  else if (IsA(node, ConvertRowtypeExpr))
2008  {
2009  /* not clear this is useful, but it can't hurt */
2010  ConvertRowtypeExpr *expr = (ConvertRowtypeExpr *) node;
2011 
2012  result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
2013  }
2014  else if (IsA(node, CollateExpr))
2015  {
2016  CollateExpr *expr = (CollateExpr *) node;
2017 
2018  result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
2019  }
2020  else if (IsA(node, NullTest))
2021  {
2022  /* IS NOT NULL can be considered strict, but only at top level */
2023  NullTest *expr = (NullTest *) node;
2024 
2025  if (top_level && expr->nulltesttype == IS_NOT_NULL && !expr->argisrow)
2026  result = find_nonnullable_vars_walker((Node *) expr->arg, false);
2027  }
2028  else if (IsA(node, BooleanTest))
2029  {
2030  /* Boolean tests that reject NULL are strict at top level */
2031  BooleanTest *expr = (BooleanTest *) node;
2032 
2033  if (top_level &&
2034  (expr->booltesttype == IS_TRUE ||
2035  expr->booltesttype == IS_FALSE ||
2036  expr->booltesttype == IS_NOT_UNKNOWN))
2037  result = find_nonnullable_vars_walker((Node *) expr->arg, false);
2038  }
2039  else if (IsA(node, PlaceHolderVar))
2040  {
2041  PlaceHolderVar *phv = (PlaceHolderVar *) node;
2042 
2043  result = find_nonnullable_vars_walker((Node *) phv->phexpr, top_level);
2044  }
2045  return result;
2046 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
Index varlevelsup
Definition: primnodes.h:173
List * args
Definition: primnodes.h:457
Expr * arg
Definition: primnodes.h:794
Definition: nodes.h:510
List * list_concat(List *list1, List *list2)
Definition: list.c:321
Definition: primnodes.h:163
#define list_make1(x1)
Definition: pg_list.h:139
Oid funcid
Definition: primnodes.h:449
#define ERROR
Definition: elog.h:43
Expr * phexpr
Definition: relation.h:1940
BoolExprType boolop
Definition: primnodes.h:562
Expr * arg
Definition: primnodes.h:1187
Expr * arg
Definition: primnodes.h:1210
List * list_intersection(const List *list1, const List *list2)
Definition: list.c:800
static List * find_nonnullable_vars_walker(Node *node, bool top_level)
Definition: clauses.c:1874
Expr * arg
Definition: primnodes.h:814
BoolTestType booltesttype
Definition: primnodes.h:1211
Oid opfuncid
Definition: primnodes.h:497
NullTestType nulltesttype
Definition: primnodes.h:1188
static bool is_strict_saop(ScalarArrayOpExpr *expr, bool falseOK)
Definition: clauses.c:2169
#define lfirst(lc)
Definition: pg_list.h:106
Expr * arg
Definition: primnodes.h:880
List * args
Definition: primnodes.h:563
bool func_strict(Oid funcid)
Definition: lsyscache.c:1565
void set_opfuncid(OpExpr *opexpr)
Definition: nodeFuncs.c:1613
bool argisrow
Definition: primnodes.h:1189
#define elog
Definition: elog.h:219
List * args
Definition: primnodes.h:502
Definition: pg_list.h:45

◆ find_window_functions()

WindowFuncLists* find_window_functions ( Node clause,
Index  maxWinRef 
)

Definition at line 740 of file clauses.c.

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

Referenced by grouping_planner().

741 {
742  WindowFuncLists *lists = palloc(sizeof(WindowFuncLists));
743 
744  lists->numWindowFuncs = 0;
745  lists->maxWinRef = maxWinRef;
746  lists->windowFuncs = (List **) palloc0((maxWinRef + 1) * sizeof(List *));
747  (void) find_window_functions_walker(clause, lists);
748  return lists;
749 }
Index maxWinRef
Definition: clauses.h:26
int numWindowFuncs
Definition: clauses.h:25
void * palloc0(Size size)
Definition: mcxt.c:877
void * palloc(Size size)
Definition: mcxt.c:848
static bool find_window_functions_walker(Node *node, WindowFuncLists *lists)
Definition: clauses.c:752
Definition: pg_list.h:45
List ** windowFuncs
Definition: clauses.h:27

◆ find_window_functions_walker()

static bool find_window_functions_walker ( Node node,
WindowFuncLists lists 
)
static

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

753 {
754  if (node == NULL)
755  return false;
756  if (IsA(node, WindowFunc))
757  {
758  WindowFunc *wfunc = (WindowFunc *) node;
759 
760  /* winref is unsigned, so one-sided test is OK */
761  if (wfunc->winref > lists->maxWinRef)
762  elog(ERROR, "WindowFunc contains out-of-range winref %u",
763  wfunc->winref);
764  /* eliminate duplicates, so that we avoid repeated computation */
765  if (!list_member(lists->windowFuncs[wfunc->winref], wfunc))
766  {
767  lists->windowFuncs[wfunc->winref] =
768  lappend(lists->windowFuncs[wfunc->winref], wfunc);
769  lists->numWindowFuncs++;
770  }
771 
772  /*
773  * We assume that the parser checked that there are no window
774  * functions in the arguments or filter clause. Hence, we need not
775  * recurse into them. (If either the parser or the planner screws up
776  * on this point, the executor will still catch it; see ExecInitExpr.)
777  */
778  return false;
779  }
780  Assert(!IsA(node, SubLink));
782  (void *) lists);
783 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
Index maxWinRef
Definition: clauses.h:26
int numWindowFuncs
Definition: clauses.h:25
Index winref
Definition: primnodes.h:361
#define ERROR
Definition: elog.h:43
bool list_member(const List *list, const void *datum)
Definition: list.c:444
List * lappend(List *list, void *datum)
Definition: list.c:128
#define Assert(condition)
Definition: c.h:670
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1834
static bool find_window_functions_walker(Node *node, WindowFuncLists *lists)
Definition: clauses.c:752
#define elog
Definition: elog.h:219
List ** windowFuncs
Definition: clauses.h:27

◆ get_agg_clause_costs()

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

Definition at line 467 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_grouping_paths(), estimate_path_cost_size(), and grouping_planner().

469 {
471 
472  context.root = root;
473  context.aggsplit = aggsplit;
474  context.costs = costs;
475  (void) get_agg_clause_costs_walker(clause, &context);
476 }
AggClauseCosts * costs
Definition: clauses.c:60
static bool get_agg_clause_costs_walker(Node *node, get_agg_clause_costs_context *context)
Definition: clauses.c:479

◆ get_agg_clause_costs_walker()

static bool get_agg_clause_costs_walker ( Node node,
get_agg_clause_costs_context context 
)
static

Definition at line 479 of file clauses.c.

References 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, cpu_operator_cost, 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_func_cost(), get_typavgwidth(), get_typbyval(), GETSTRUCT, AggClauseCosts::hasNonPartial, AggClauseCosts::hasNonSerial, HeapTupleIsValid, INTERNALOID, 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().

480 {
481  if (node == NULL)
482  return false;
483  if (IsA(node, Aggref))
484  {
485  Aggref *aggref = (Aggref *) node;
486  AggClauseCosts *costs = context->costs;
487  HeapTuple aggTuple;
488  Form_pg_aggregate aggform;
489  Oid aggtransfn;
490  Oid aggfinalfn;
491  Oid aggcombinefn;
492  Oid aggserialfn;
493  Oid aggdeserialfn;
494  Oid aggtranstype;
495  int32 aggtransspace;
496  QualCost argcosts;
497 
498  Assert(aggref->agglevelsup == 0);
499 
500  /*
501  * Fetch info about aggregate from pg_aggregate. Note it's correct to
502  * ignore the moving-aggregate variant, since what we're concerned
503  * with here is aggregates not window functions.
504  */
505  aggTuple = SearchSysCache1(AGGFNOID,
506  ObjectIdGetDatum(aggref->aggfnoid));
507  if (!HeapTupleIsValid(aggTuple))
508  elog(ERROR, "cache lookup failed for aggregate %u",
509  aggref->aggfnoid);
510  aggform = (Form_pg_aggregate) GETSTRUCT(aggTuple);
511  aggtransfn = aggform->aggtransfn;
512  aggfinalfn = aggform->aggfinalfn;
513  aggcombinefn = aggform->aggcombinefn;
514  aggserialfn = aggform->aggserialfn;
515  aggdeserialfn = aggform->aggdeserialfn;
516  aggtranstype = aggform->aggtranstype;
517  aggtransspace = aggform->aggtransspace;
518  ReleaseSysCache(aggTuple);
519 
520  /*
521  * Resolve the possibly-polymorphic aggregate transition type, unless
522  * already done in a previous pass over the expression.
523  */
524  if (OidIsValid(aggref->aggtranstype))
525  aggtranstype = aggref->aggtranstype;
526  else
527  {
528  Oid inputTypes[FUNC_MAX_ARGS];
529  int numArguments;
530 
531  /* extract argument types (ignoring any ORDER BY expressions) */
532  numArguments = get_aggregate_argtypes(aggref, inputTypes);
533 
534  /* resolve actual type of transition state, if polymorphic */
535  aggtranstype = resolve_aggregate_transtype(aggref->aggfnoid,
536  aggtranstype,
537  inputTypes,
538  numArguments);
539  aggref->aggtranstype = aggtranstype;
540  }
541 
542  /*
543  * Count it, and check for cases requiring ordered input. Note that
544  * ordered-set aggs always have nonempty aggorder. Any ordered-input
545  * case also defeats partial aggregation.
546  */
547  costs->numAggs++;
548  if (aggref->aggorder != NIL || aggref->aggdistinct != NIL)
549  {
550  costs->numOrderedAggs++;
551  costs->hasNonPartial = true;
552  }
553 
554  /*
555  * Check whether partial aggregation is feasible, unless we already
556  * found out that we can't do it.
557  */
558  if (!costs->hasNonPartial)
559  {
560  /*
561  * If there is no combine function, then partial aggregation is
562  * not possible.
563  */
564  if (!OidIsValid(aggcombinefn))
565  costs->hasNonPartial = true;
566 
567  /*
568  * If we have any aggs with transtype INTERNAL then we must check
569  * whether they have serialization/deserialization functions; if
570  * not, we can't serialize partial-aggregation results.
571  */
572  else if (aggtranstype == INTERNALOID &&
573  (!OidIsValid(aggserialfn) || !OidIsValid(aggdeserialfn)))
574  costs->hasNonSerial = true;
575  }
576 
577  /*
578  * Add the appropriate component function execution costs to
579  * appropriate totals.
580  */
581  if (DO_AGGSPLIT_COMBINE(context->aggsplit))
582  {
583  /* charge for combining previously aggregated states */
584  costs->transCost.per_tuple += get_func_cost(aggcombinefn) * cpu_operator_cost;
585  }
586  else
587  costs->transCost.per_tuple += get_func_cost(aggtransfn) * cpu_operator_cost;
588  if (DO_AGGSPLIT_DESERIALIZE(context->aggsplit) &&
589  OidIsValid(aggdeserialfn))
590  costs->transCost.per_tuple += get_func_cost(aggdeserialfn) * cpu_operator_cost;
591  if (DO_AGGSPLIT_SERIALIZE(context->aggsplit) &&
592  OidIsValid(aggserialfn))
593  costs->finalCost += get_func_cost(aggserialfn) * cpu_operator_cost;
594  if (!DO_AGGSPLIT_SKIPFINAL(context->aggsplit) &&
595  OidIsValid(aggfinalfn))
596  costs->finalCost += get_func_cost(aggfinalfn) * cpu_operator_cost;
597 
598  /*
599  * These costs are incurred only by the initial aggregate node, so we
600  * mustn't include them again at upper levels.
601  */
602  if (!DO_AGGSPLIT_COMBINE(context->aggsplit))
603  {
604  /* add the input expressions' cost to per-input-row costs */
605  cost_qual_eval_node(&argcosts, (Node *) aggref->args, context->root);
606  costs->transCost.startup += argcosts.startup;
607  costs->transCost.per_tuple += argcosts.per_tuple;
608 
609  /*
610  * Add any filter's cost to per-input-row costs.
611  *
612  * XXX Ideally we should reduce input expression costs according
613  * to filter selectivity, but it's not clear it's worth the
614  * trouble.
615  */
616  if (aggref->aggfilter)
617  {
618  cost_qual_eval_node(&argcosts, (Node *) aggref->aggfilter,
619  context->root);
620  costs->transCost.startup += argcosts.startup;
621  costs->transCost.per_tuple += argcosts.per_tuple;
622  }
623  }
624 
625  /*
626  * If there are direct arguments, treat their evaluation cost like the
627  * cost of the finalfn.
628  */
629  if (aggref->aggdirectargs)
630  {
631  cost_qual_eval_node(&argcosts, (Node *) aggref->aggdirectargs,
632  context->root);
633  costs->transCost.startup += argcosts.startup;
634  costs->finalCost += argcosts.per_tuple;
635  }
636 
637  /*
638  * If the transition type is pass-by-value then it doesn't add
639  * anything to the required size of the hashtable. If it is
640  * pass-by-reference then we have to add the estimated size of the
641  * value itself, plus palloc overhead.
642  */
643  if (!get_typbyval(aggtranstype))
644  {
645  int32 avgwidth;
646 
647  /* Use average width if aggregate definition gave one */
648  if (aggtransspace > 0)
649  avgwidth = aggtransspace;
650  else if (aggtransfn == F_ARRAY_APPEND)
651  {
652  /*
653  * If the transition function is array_append(), it'll use an
654  * expanded array as transvalue, which will occupy at least
655  * ALLOCSET_SMALL_INITSIZE and possibly more. Use that as the
656  * estimate for lack of a better idea.
657  */
658  avgwidth = ALLOCSET_SMALL_INITSIZE;
659  }
660  else
661  {
662  /*
663  * If transition state is of same type as first aggregated
664  * input, assume it's the same typmod (same width) as well.
665  * This works for cases like MAX/MIN and is probably somewhat
666  * reasonable otherwise.
667  */
668  int32 aggtranstypmod = -1;
669 
670  if (aggref->args)
671  {
672  TargetEntry *tle = (TargetEntry *) linitial(aggref->args);
673 
674  if (aggtranstype == exprType((Node *) tle->expr))
675  aggtranstypmod = exprTypmod((Node *) tle->expr);
676  }
677 
678  avgwidth = get_typavgwidth(aggtranstype, aggtranstypmod);
679  }
680 
681  avgwidth = MAXALIGN(avgwidth);
682  costs->transitionSpace += avgwidth + 2 * sizeof(void *);
683  }
684  else if (aggtranstype == INTERNALOID)
685  {
686  /*
687  * INTERNAL transition type is a special case: although INTERNAL
688  * is pass-by-value, it's almost certainly being used as a pointer
689  * to some large data structure. The aggregate definition can
690  * provide an estimate of the size. If it doesn't, then we assume
691  * ALLOCSET_DEFAULT_INITSIZE, which is a good guess if the data is
692  * being kept in a private memory context, as is done by
693  * array_agg() for instance.
694  */
695  if (aggtransspace > 0)
696  costs->transitionSpace += aggtransspace;
697  else
699  }
700 
701  /*
702  * We assume that the parser checked that there are no aggregates (of
703  * this level anyway) in the aggregated arguments, direct arguments,
704  * or filter clause. Hence, we need not recurse into any of them.
705  */
706  return false;
707  }
708  Assert(!IsA(node, SubLink));
710  (void *) context);
711 }
List * aggdistinct
Definition: primnodes.h:303
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:3534
#define NIL
Definition: pg_list.h:69
AggClauseCosts * costs
Definition: clauses.c:60
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:276
Definition: nodes.h:510
List * args
Definition: primnodes.h:301
bool hasNonSerial
Definition: relation.h:61
bool hasNonPartial
Definition: relation.h:60
QualCost transCost
Definition: relation.h:62
float4 get_func_cost(Oid funcid)
Definition: lsyscache.c:1641
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:576
#define DO_AGGSPLIT_COMBINE(as)
Definition: nodes.h:769
Cost startup
Definition: relation.h:45
static bool get_agg_clause_costs_walker(Node *node, get_agg_clause_costs_context *context)
Definition: clauses.c:479
signed int int32
Definition: c.h:284
#define FUNC_MAX_ARGS
bool get_typbyval(Oid typid)
Definition: lsyscache.c:1972
Cost per_tuple
Definition: relation.h:46
#define DO_AGGSPLIT_SERIALIZE(as)
Definition: nodes.h:771
#define linitial(l)
Definition: pg_list.h:111
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
List * aggorder
Definition: primnodes.h:302
Index agglevelsup
Definition: primnodes.h:309
List * aggdirectargs
Definition: primnodes.h:300
double cpu_operator_cost
Definition: costsize.c:108
int numOrderedAggs
Definition: relation.h:59
#define ALLOCSET_SMALL_INITSIZE
Definition: memutils.h:173
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition: lsyscache.c:2328
Cost finalCost
Definition: relation.h:63
Oid aggfnoid
Definition: primnodes.h:294
#define INTERNALOID
Definition: pg_type.h:698
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define Assert(condition)
Definition: c.h:670
FormData_pg_aggregate * Form_pg_aggregate
Definition: pg_aggregate.h:89
Expr * expr
Definition: primnodes.h:1375
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1834
#define DO_AGGSPLIT_SKIPFINAL(as)
Definition: nodes.h:770
Expr * aggfilter
Definition: primnodes.h:304
#define MAXALIGN(LEN)
Definition: c.h:623
#define DO_AGGSPLIT_DESERIALIZE(as)
Definition: nodes.h:772
#define ALLOCSET_DEFAULT_INITSIZE
Definition: memutils.h:163
Oid aggtranstype
Definition: primnodes.h:298
Size transitionSpace
Definition: relation.h:64
#define elog
Definition: elog.h:219
int get_aggregate_argtypes(Aggref *aggref, Oid *inputTypes)
Definition: parse_agg.c:1801
Oid resolve_aggregate_transtype(Oid aggfuncid, Oid aggtranstype, Oid *inputTypes, int numArguments)
Definition: parse_agg.c:1827

◆ get_leftop()

◆ get_notclausearg()

Expr* get_notclausearg ( Expr notclause)

Definition at line 265 of file clauses.c.

References generate_unaccent_rules::args, and linitial.

Referenced by clause_selectivity(), expand_boolean_index_clause(), match_boolean_index_clause(), and pull_up_sublinks_qual_recurse().

266 {
267  return linitial(((BoolExpr *) notclause)->args);
268 }
#define linitial(l)
Definition: pg_list.h:111

◆ get_rightop()

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

References ACL_EXECUTE, ACLCHECK_OK, eval_const_expressions_context::active_fns, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate(), Anum_pg_proc_proconfig, Anum_pg_proc_prosrc, arg, ErrorContextCallback::arg, CollateExpr::arg, generate_unaccent_rules::args, FuncExpr::args, Assert, 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, GETSTRUCT, GetUserId(), Query::groupClause, Query::groupingSets, Query::hasAggs, Query::hasSubLinks, Query::hasTargetSRFs, Query::hasWindowFuncs, Query::havingQual, heap_attisnull(), i, FuncExpr::inputcollid, IsA, Query::jointree, lcons_oid(), lfirst, Query::limitCount, Query::limitOffset, linitial, list_delete_first(), 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, PROVOLATILE_IMMUTABLE, PROVOLATILE_STABLE, FromExpr::quals, querytree(), record_plan_function_dependency(), RECORDOID, eval_const_expressions_context::root, Query::rtable, Query::setOperations, Query::sortClause, sql_fn_parser_setup(), sql_inline_error_callback(), SQLlanguageId, QualCost::startup, substitute_actual_parameters(), SysCacheGetAttr(), Query::targetList, TextDatumGetCString, transformTopLevelStmt(), and Query::windowClause.

Referenced by simplify_function().

4377 {
4378  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4379  char *src;
4380  Datum tmp;
4381  bool isNull;
4382  bool modifyTargetList;
4383  MemoryContext oldcxt;
4384  MemoryContext mycxt;
4385  inline_error_callback_arg callback_arg;
4386  ErrorContextCallback sqlerrcontext;
4387  FuncExpr *fexpr;
4389  ParseState *pstate;
4390  List *raw_parsetree_list;
4391  Query *querytree;
4392  Node *newexpr;
4393  int *usecounts;
4394  ListCell *arg;
4395  int i;
4396 
4397  /*
4398  * Forget it if the function is not SQL-language or has other showstopper
4399  * properties. (The nargs check is just paranoia.)
4400  */
4401  if (funcform->prolang != SQLlanguageId ||
4402  funcform->prosecdef ||
4403  funcform->proretset ||
4404  funcform->prorettype == RECORDOID ||
4405  !heap_attisnull(func_tuple, Anum_pg_proc_proconfig) ||
4406  funcform->pronargs != list_length(args))
4407  return NULL;
4408 
4409  /* Check for recursive function, and give up trying to expand if so */
4410  if (list_member_oid(context->active_fns, funcid))
4411  return NULL;
4412 
4413  /* Check permission to call function (fail later, if not) */
4415  return NULL;
4416 
4417  /* Check whether a plugin wants to hook function entry/exit */
4418  if (FmgrHookIsNeeded(funcid))
4419  return NULL;
4420 
4421  /*
4422  * Make a temporary memory context, so that we don't leak all the stuff
4423  * that parsing might create.
4424  */
4426  "inline_function",
4428  oldcxt = MemoryContextSwitchTo(mycxt);
4429 
4430  /* Fetch the function body */
4431  tmp = SysCacheGetAttr(PROCOID,
4432  func_tuple,
4434  &isNull);
4435  if (isNull)
4436  elog(ERROR, "null prosrc for function %u", funcid);
4437  src = TextDatumGetCString(tmp);
4438 
4439  /*
4440  * Setup error traceback support for ereport(). This is so that we can
4441  * finger the function that bad information came from.
4442  */
4443  callback_arg.proname = NameStr(funcform->proname);
4444  callback_arg.prosrc = src;
4445 
4446  sqlerrcontext.callback = sql_inline_error_callback;
4447  sqlerrcontext.arg = (void *) &callback_arg;
4448  sqlerrcontext.previous = error_context_stack;
4449  error_context_stack = &sqlerrcontext;
4450 
4451  /*
4452  * Set up to handle parameters while parsing the function body. We need a
4453  * dummy FuncExpr node containing the already-simplified arguments to pass
4454  * to prepare_sql_fn_parse_info. (It is really only needed if there are
4455  * some polymorphic arguments, but for simplicity we always build it.)
4456  */
4457  fexpr = makeNode(FuncExpr);
4458  fexpr->funcid = funcid;
4459  fexpr->funcresulttype = result_type;
4460  fexpr->funcretset = false;
4461  fexpr->funcvariadic = funcvariadic;
4462  fexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
4463  fexpr->funccollid = result_collid; /* doesn't matter */
4464  fexpr->inputcollid = input_collid;
4465  fexpr->args = args;
4466  fexpr->location = -1;
4467 
4468  pinfo = prepare_sql_fn_parse_info(func_tuple,
4469  (Node *) fexpr,
4470  input_collid);
4471 
4472  /*
4473  * We just do parsing and parse analysis, not rewriting, because rewriting
4474  * will not affect table-free-SELECT-only queries, which is all that we
4475  * care about. Also, we can punt as soon as we detect more than one
4476  * command in the function body.
4477  */
4478  raw_parsetree_list = pg_parse_query(src);
4479  if (list_length(raw_parsetree_list) != 1)
4480  goto fail;
4481 
4482  pstate = make_parsestate(NULL);
4483  pstate->p_sourcetext = src;
4484  sql_fn_parser_setup(pstate, pinfo);
4485 
4486  querytree = transformTopLevelStmt(pstate, linitial(raw_parsetree_list));
4487 
4488  free_parsestate(pstate);
4489 
4490  /*
4491  * The single command must be a simple "SELECT expression".
4492  *
4493  * Note: if you change the tests involved in this, see also plpgsql's
4494  * exec_simple_check_plan(). That generally needs to have the same idea
4495  * of what's a "simple expression", so that inlining a function that
4496  * previously wasn't inlined won't change plpgsql's conclusion.
4497  */
4498  if (!IsA(querytree, Query) ||
4499  querytree->commandType != CMD_SELECT ||
4500  querytree->hasAggs ||
4501  querytree->hasWindowFuncs ||
4502  querytree->hasTargetSRFs ||
4503  querytree->hasSubLinks ||
4504  querytree->cteList ||
4505  querytree->rtable ||
4506  querytree->jointree->fromlist ||
4507  querytree->jointree->quals ||
4508  querytree->groupClause ||
4509  querytree->groupingSets ||
4510  querytree->havingQual ||
4511  querytree->windowClause ||
4512  querytree->distinctClause ||
4513  querytree->sortClause ||
4514  querytree->limitOffset ||
4515  querytree->limitCount ||
4516  querytree->setOperations ||
4517  list_length(querytree->targetList) != 1)
4518  goto fail;
4519 
4520  /*
4521  * Make sure the function (still) returns what it's declared to. This
4522  * will raise an error if wrong, but that's okay since the function would
4523  * fail at runtime anyway. Note that check_sql_fn_retval will also insert
4524  * a RelabelType if needed to make the tlist expression match the declared
4525  * type of the function.
4526  *
4527  * Note: we do not try this until we have verified that no rewriting was
4528  * needed; that's probably not important, but let's be careful.
4529  */
4530  if (check_sql_fn_retval(funcid, result_type, list_make1(querytree),
4531  &modifyTargetList, NULL))
4532  goto fail; /* reject whole-tuple-result cases */
4533 
4534  /* Now we can grab the tlist expression */
4535  newexpr = (Node *) ((TargetEntry *) linitial(querytree->targetList))->expr;
4536 
4537  /* Assert that check_sql_fn_retval did the right thing */
4538  Assert(exprType(newexpr) == result_type);
4539  /* It couldn't have made any dangerous tlist changes, either */
4540  Assert(!modifyTargetList);
4541 
4542  /*
4543  * Additional validity checks on the expression. It mustn't be more
4544  * volatile than the surrounding function (this is to avoid breaking hacks
4545  * that involve pretending a function is immutable when it really ain't).
4546  * If the surrounding function is declared strict, then the expression
4547  * must contain only strict constructs and must use all of the function
4548  * parameters (this is overkill, but an exact analysis is hard).
4549  */
4550  if (funcform->provolatile == PROVOLATILE_IMMUTABLE &&
4551  contain_mutable_functions(newexpr))
4552  goto fail;
4553  else if (funcform->provolatile == PROVOLATILE_STABLE &&
4554  contain_volatile_functions(newexpr))
4555  goto fail;
4556 
4557  if (funcform->proisstrict &&
4558  contain_nonstrict_functions(newexpr))
4559  goto fail;
4560 
4561  /*
4562  * If any parameter expression contains a context-dependent node, we can't
4563  * inline, for fear of putting such a node into the wrong context.
4564  */
4565  if (contain_context_dependent_node((Node *) args))
4566  goto fail;
4567 
4568  /*
4569  * We may be able to do it; there are still checks on parameter usage to
4570  * make, but those are most easily done in combination with the actual
4571  * substitution of the inputs. So start building expression with inputs
4572  * substituted.
4573  */
4574  usecounts = (int *) palloc0(funcform->pronargs * sizeof(int));
4575  newexpr = substitute_actual_parameters(newexpr, funcform->pronargs,
4576  args, usecounts);
4577 
4578  /* Now check for parameter usage */
4579  i = 0;
4580  foreach(arg, args)
4581  {
4582  Node *param = lfirst(arg);
4583 
4584  if (usecounts[i] == 0)
4585  {
4586  /* Param not used at all: uncool if func is strict */
4587  if (funcform->proisstrict)
4588  goto fail;
4589  }
4590  else if (usecounts[i] != 1)
4591  {
4592  /* Param used multiple times: uncool if expensive or volatile */
4593  QualCost eval_cost;
4594 
4595  /*
4596  * We define "expensive" as "contains any subplan or more than 10
4597  * operators". Note that the subplan search has to be done
4598  * explicitly, since cost_qual_eval() will barf on unplanned
4599  * subselects.
4600  */
4601  if (contain_subplans(param))
4602  goto fail;
4603  cost_qual_eval(&eval_cost, list_make1(param), NULL);
4604  if (eval_cost.startup + eval_cost.per_tuple >
4605  10 * cpu_operator_cost)
4606  goto fail;
4607 
4608  /*
4609  * Check volatility last since this is more expensive than the
4610  * above tests
4611  */
4612  if (contain_volatile_functions(param))
4613  goto fail;
4614  }
4615  i++;
4616  }
4617 
4618  /*
4619  * Whew --- we can make the substitution. Copy the modified expression
4620  * out of the temporary memory context, and clean up.
4621  */
4622  MemoryContextSwitchTo(oldcxt);
4623 
4624  newexpr = copyObject(newexpr);
4625 
4626  MemoryContextDelete(mycxt);
4627 
4628  /*
4629  * If the result is of a collatable type, force the result to expose the
4630  * correct collation. In most cases this does not matter, but it's
4631  * possible that the function result is used directly as a sort key or in
4632  * other places where we expect exprCollation() to tell the truth.
4633  */
4634  if (OidIsValid(result_collid))
4635  {
4636  Oid exprcoll = exprCollation(newexpr);
4637 
4638  if (OidIsValid(exprcoll) && exprcoll != result_collid)
4639  {
4640  CollateExpr *newnode = makeNode(CollateExpr);
4641 
4642  newnode->arg = (Expr *) newexpr;
4643  newnode->collOid = result_collid;
4644  newnode->location = -1;
4645 
4646  newexpr = (Node *) newnode;
4647  }
4648  }
4649 
4650  /*
4651  * Since there is now no trace of the function in the plan tree, we must
4652  * explicitly record the plan's dependency on the function.
4653  */
4654  if (context->root)
4655  record_plan_function_dependency(context->root, funcid);
4656 
4657  /*
4658  * Recursively try to simplify the modified expression. Here we must add
4659  * the current function to the context list of active functions.
4660  */
4661  context->active_fns = lcons_oid(funcid, context->active_fns);
4662  newexpr = eval_const_expressions_mutator(newexpr, context);
4663  context->active_fns = list_delete_first(context->active_fns);
4664 
4665  error_context_stack = sqlerrcontext.previous;
4666 
4667  return (Expr *) newexpr;
4668 
4669  /* Here if func is not inlinable: release temp memory and return NULL */
4670 fail:
4671  MemoryContextSwitchTo(oldcxt);
4672  MemoryContextDelete(mycxt);
4673  error_context_stack = sqlerrcontext.previous;
4674 
4675  return NULL;
4676 }
Node * limitOffset
Definition: parsenodes.h:158
Oid funcresulttype
Definition: primnodes.h:450
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
#define PROVOLATILE_IMMUTABLE
Definition: pg_proc.h:5537
List * sortClause
Definition: parsenodes.h:156
List * args
Definition: primnodes.h:457
FromExpr * jointree
Definition: parsenodes.h:136
Oid GetUserId(void)
Definition: miscinit.c:284
Oid funccollid
Definition: primnodes.h:455
void sql_fn_parser_setup(struct ParseState *pstate, SQLFunctionParseInfoPtr pinfo)
Definition: functions.c:273
bool hasAggs
Definition: parsenodes.h:123
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define Anum_pg_proc_prosrc
Definition: pg_proc.h:115
List * groupingSets
Definition: parsenodes.h:148
Definition: nodes.h:510
bool check_sql_fn_retval(Oid func_id, Oid rettype, List *queryTreeList, bool *modifyTargetList, JunkFilter **junkFilter)
Definition: functions.c:1532
bool funcretset
Definition: primnodes.h:451
List * lcons_oid(Oid datum, List *list)
Definition: list.c:295
List * fromlist
Definition: primnodes.h:1478
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:957
unsigned int Oid
Definition: postgres_ext.h:31
void(* callback)(void *arg)
Definition: elog.h:239
struct ErrorContextCallback * previous
Definition: elog.h:238
#define OidIsValid(objectId)
Definition: c.h:576
#define FmgrHookIsNeeded(fn_oid)
Definition: fmgr.h:730
Node * quals
Definition: primnodes.h:1479
Cost startup
Definition: relation.h:45
#define Anum_pg_proc_proconfig
Definition: pg_proc.h:117
List * windowClause
Definition: parsenodes.h:152
List * targetList
Definition: parsenodes.h:138
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
ErrorContextCallback * error_context_stack
Definition: elog.c:88
#define list_make1(x1)
Definition: pg_list.h:139
bool contain_subplans(Node *clause)
Definition: clauses.c:843
CoercionForm funcformat
Definition: primnodes.h:454
Cost per_tuple
Definition: relation.h:46
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2506
#define linitial(l)
Definition: pg_list.h:111
List * rtable
Definition: parsenodes.h:135
List * distinctClause
Definition: parsenodes.h:154
Oid funcid
Definition: primnodes.h:449
#define ERROR
Definition: elog.h:43
#define SQLlanguageId
Definition: pg_language.h:80
#define PROVOLATILE_STABLE
Definition: pg_proc.h:5538
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3508
List * pg_parse_query(const char *query_string)
Definition: postgres.c:607
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:165
Node * limitCount
Definition: parsenodes.h:159
bool heap_attisnull(HeapTuple tup, int attnum)
Definition: heaptuple.c:296
double cpu_operator_cost
Definition: costsize.c:108
#define RECORDOID
Definition: pg_type.h:680
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
const char * p_sourcetext
Definition: parse_node.h:171
static Node * substitute_actual_parameters(Node *expr, int nargs, List *args, int *usecounts)
Definition: clauses.c:4682
static void sql_inline_error_callback(void *arg)
Definition: clauses.c:4724
#define TextDatumGetCString(d)
Definition: builtins.h:92
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:322
void * palloc0(Size size)
Definition: mcxt.c:877
uintptr_t Datum
Definition: postgres.h:372
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1368
void record_plan_function_dependency(PlannerInfo *root, Oid funcid)
Definition: setrefs.c:2558
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:83
CmdType commandType
Definition: parsenodes.h:110
bool hasTargetSRFs
Definition: parsenodes.h:125
#define makeNode(_type_)
Definition: nodes.h:558
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:505
Oid inputcollid
Definition: primnodes.h:456
#define Assert(condition)
Definition: c.h:670
#define lfirst(lc)
Definition: pg_list.h:106
bool hasWindowFuncs
Definition: parsenodes.h:124
Query * transformTopLevelStmt(ParseState *pstate, RawStmt *parseTree)
Definition: analyze.c:187
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
static int list_length(const List *l)
Definition: pg_list.h:89
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:720
Expr * arg
Definition: primnodes.h:880
Datum querytree(PG_FUNCTION_ARGS)
Definition: _int_bool.c:665
static bool contain_context_dependent_node(Node *clause)
Definition: clauses.c:1449
List * cteList
Definition: parsenodes.h:133
Node * setOperations
Definition: parsenodes.h:163
List * groupClause
Definition: parsenodes.h:146
bool hasSubLinks
Definition: parsenodes.h:126
#define ACL_EXECUTE
Definition: parsenodes.h:79
AclResult pg_proc_aclcheck(Oid proc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4446
int i
#define NameStr(name)
Definition: c.h:547
void * arg
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:878
int location
Definition: primnodes.h:458
#define elog
Definition: elog.h:219
bool contain_nonstrict_functions(Node *clause)
Definition: clauses.c:1314
SQLFunctionParseInfoPtr prepare_sql_fn_parse_info(HeapTuple procedureTuple, Node *call_expr, Oid inputCollation)
Definition: functions.c:184
#define copyObject(obj)
Definition: nodes.h:623
Node * havingQual
Definition: parsenodes.h:150
int location
Definition: primnodes.h:882
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:77
Definition: pg_list.h:45
bool funcvariadic
Definition: primnodes.h:452
List * list_delete_first(List *list)
Definition: list.c:666

◆ inline_set_returning_function()

Query* inline_set_returning_function ( PlannerInfo root,
RangeTblEntry rte 
)

Definition at line 4836 of file clauses.c.

References ACL_EXECUTE, ACLCHECK_OK, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate(), Anum_pg_proc_proconfig, Anum_pg_proc_prosrc, ErrorContextCallback::arg, FuncExpr::args, Assert, ErrorContextCallback::callback, check_sql_fn_retval(), check_stack_depth(), CMD_SELECT, Query::commandType, contain_subplans(), contain_volatile_functions(), copyObject, CurrentMemoryContext, elog, ERROR, error_context_stack, eval_const_expressions(), FmgrHookIsNeeded, RangeTblFunction::funccoltypes, RangeTblFunction::funcexpr, FuncExpr::funcid, RangeTblEntry::funcordinality, FuncExpr::funcretset, RangeTblEntry::functions, get_func_result_type(), get_typtype(), GETSTRUCT, GetUserId(), PlannerInfo::glob, heap_attisnull(), HeapTupleIsValid, PlannerGlobal::invalItems, IsA, linitial, list_concat(), list_length(), MemoryContextDelete(), MemoryContextSwitchTo(), NameStr, NIL, ObjectIdGetDatum, pg_analyze_and_rewrite_params(), pg_parse_query(), pg_proc_aclcheck(), prepare_sql_fn_parse_info(), ErrorContextCallback::previous, PROCOID, inline_error_callback_arg::proname, inline_error_callback_arg::prosrc, PROVOLATILE_VOLATILE, querytree(), record_plan_function_dependency(), RECORDOID, ReleaseSysCache(), RTE_FUNCTION, RangeTblEntry::rtekind, SearchSysCache1(), sql_fn_parser_setup(), sql_inline_error_callback(), SQLlanguageId, substitute_actual_srf_parameters(), SysCacheGetAttr(), Query::targetList, TextDatumGetCString, tlist_matches_coltypelist(), TYPEFUNC_RECORD, and TYPTYPE_COMPOSITE.

Referenced by inline_set_returning_functions().

4837 {
4838  RangeTblFunction *rtfunc;
4839  FuncExpr *fexpr;
4840  Oid func_oid;
4841  HeapTuple func_tuple;
4842  Form_pg_proc funcform;
4843  char *src;
4844  Datum tmp;
4845  bool isNull;
4846  bool modifyTargetList;
4847  MemoryContext oldcxt;
4848  MemoryContext mycxt;
4849  List *saveInvalItems;
4850  inline_error_callback_arg callback_arg;
4851  ErrorContextCallback sqlerrcontext;
4853  List *raw_parsetree_list;
4854  List *querytree_list;
4855  Query *querytree;
4856 
4857  Assert(rte->rtekind == RTE_FUNCTION);
4858 
4859  /*
4860  * It doesn't make a lot of sense for a SQL SRF to refer to itself in its
4861  * own FROM clause, since that must cause infinite recursion at runtime.
4862  * It will cause this code to recurse too, so check for stack overflow.
4863  * (There's no need to do more.)
4864  */
4866 
4867  /* Fail if the RTE has ORDINALITY - we don't implement that here. */
4868  if (rte->funcordinality)
4869  return NULL;
4870 
4871  /* Fail if RTE isn't a single, simple FuncExpr */
4872  if (list_length(rte->functions) != 1)
4873  return NULL;
4874  rtfunc = (RangeTblFunction *) linitial(rte->functions);
4875 
4876  if (!IsA(rtfunc->funcexpr, FuncExpr))
4877  return NULL;
4878  fexpr = (FuncExpr *) rtfunc->funcexpr;
4879 
4880  func_oid = fexpr->funcid;
4881 
4882  /*
4883  * The function must be declared to return a set, else inlining would
4884  * change the results if the contained SELECT didn't return exactly one
4885  * row.
4886  */
4887  if (!fexpr->funcretset)
4888  return NULL;
4889 
4890  /*
4891  * Refuse to inline if the arguments contain any volatile functions or
4892  * sub-selects. Volatile functions are rejected because inlining may
4893  * result in the arguments being evaluated multiple times, risking a
4894  * change in behavior. Sub-selects are rejected partly for implementation
4895  * reasons (pushing them down another level might change their behavior)
4896  * and partly because they're likely to be expensive and so multiple
4897  * evaluation would be bad.
4898  */
4899  if (contain_volatile_functions((Node *) fexpr->args) ||
4900  contain_subplans((Node *) fexpr->args))
4901  return NULL;
4902 
4903  /* Check permission to call function (fail later, if not) */
4904  if (