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? */
 
#define ece_generic_processing(node)
 
#define ece_all_arguments_const(node)   (!expression_tree_walker((Node *) (node), contain_non_const_walker, NULL))
 
#define ece_evaluate_expr(node)
 

Functions

static bool contain_agg_clause_walker (Node *node, void *context)
 
static bool get_agg_clause_costs_walker (Node *node, get_agg_clause_costs_context *context)
 
static bool find_window_functions_walker (Node *node, WindowFuncLists *lists)
 
static bool contain_subplans_walker (Node *node, void *context)
 
static bool contain_mutable_functions_walker (Node *node, void *context)
 
static bool contain_volatile_functions_walker (Node *node, void *context)
 
static bool contain_volatile_functions_not_nextval_walker (Node *node, void *context)
 
static bool max_parallel_hazard_walker (Node *node, max_parallel_hazard_context *context)
 
static bool contain_nonstrict_functions_walker (Node *node, void *context)
 
static bool contain_context_dependent_node (Node *clause)
 
static bool contain_context_dependent_node_walker (Node *node, int *flags)
 
static bool contain_leaked_vars_walker (Node *node, void *context)
 
static Relids find_nonnullable_rels_walker (Node *node, bool top_level)
 
static Listfind_nonnullable_vars_walker (Node *node, bool top_level)
 
static bool is_strict_saop (ScalarArrayOpExpr *expr, bool falseOK)
 
static Nodeeval_const_expressions_mutator (Node *node, eval_const_expressions_context *context)
 
static bool contain_non_const_walker (Node *node, void *context)
 
static bool ece_function_is_safe (Oid funcid, eval_const_expressions_context *context)
 
static Listsimplify_or_arguments (List *args, eval_const_expressions_context *context, bool *haveNull, bool *forceTrue)
 
static Listsimplify_and_arguments (List *args, eval_const_expressions_context *context, bool *haveNull, bool *forceFalse)
 
static Nodesimplify_boolean_equality (Oid opno, List *args)
 
static Exprsimplify_function (Oid funcid, Oid result_type, int32 result_typmod, Oid result_collid, Oid input_collid, List **args_p, bool funcvariadic, bool process_args, bool allow_non_const, eval_const_expressions_context *context)
 
static Listreorder_function_arguments (List *args, HeapTuple func_tuple)
 
static Listadd_function_defaults (List *args, HeapTuple func_tuple)
 
static Listfetch_function_defaults (HeapTuple func_tuple)
 
static void recheck_cast_function_args (List *args, Oid result_type, HeapTuple func_tuple)
 
static Exprevaluate_function (Oid funcid, Oid result_type, int32 result_typmod, Oid result_collid, Oid input_collid, List *args, bool funcvariadic, HeapTuple func_tuple, eval_const_expressions_context *context)
 
static Exprinline_function (Oid funcid, Oid result_type, Oid result_collid, Oid input_collid, List *args, bool funcvariadic, HeapTuple func_tuple, eval_const_expressions_context *context)
 
static Nodesubstitute_actual_parameters (Node *expr, int nargs, List *args, int *usecounts)
 
static Nodesubstitute_actual_parameters_mutator (Node *node, substitute_actual_parameters_context *context)
 
static void sql_inline_error_callback (void *arg)
 
static 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)
 
Listexpand_function_arguments (List *args, Oid result_type, HeapTuple func_tuple)
 
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 1457 of file clauses.c.

Referenced by contain_context_dependent_node_walker().

◆ ece_all_arguments_const

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

Definition at line 2524 of file clauses.c.

Referenced by eval_const_expressions_mutator().

◆ ece_evaluate_expr

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

Definition at line 2528 of file clauses.c.

Referenced by eval_const_expressions_mutator().

◆ ece_generic_processing

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

Definition at line 2515 of file clauses.c.

Referenced by eval_const_expressions_mutator().

Function Documentation

◆ add_function_defaults()

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

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

4228 {
4229  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4230  int nargsprovided = list_length(args);
4231  List *defaults;
4232  int ndelete;
4233 
4234  /* Get all the default expressions from the pg_proc tuple */
4235  defaults = fetch_function_defaults(func_tuple);
4236 
4237  /* Delete any unused defaults from the list */
4238  ndelete = nargsprovided + list_length(defaults) - funcform->pronargs;
4239  if (ndelete < 0)
4240  elog(ERROR, "not enough default arguments");
4241  while (ndelete-- > 0)
4242  defaults = list_delete_first(defaults);
4243 
4244  /* And form the combined argument list, not modifying the input list */
4245  return list_concat(list_copy(args), defaults);
4246 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:668
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:4252
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:132
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()

◆ CommuteOpExpr()

void CommuteOpExpr ( OpExpr clause)

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

2289 {
2290  Oid opoid;
2291  Node *temp;
2292 
2293  /* Sanity checks: caller is at fault if these fail */
2294  if (!is_opclause(clause) ||
2295  list_length(clause->args) != 2)
2296  elog(ERROR, "cannot commute non-binary-operator clause");
2297 
2298  opoid = get_commutator(clause->opno);
2299 
2300  if (!OidIsValid(opoid))
2301  elog(ERROR, "could not find commutator for operator %u",
2302  clause->opno);
2303 
2304  /*
2305  * modify the clause in-place!
2306  */
2307  clause->opno = opoid;
2308  clause->opfuncid = InvalidOid;
2309  /* opresulttype, opretset, opcollid, inputcollid need not change */
2310 
2311  temp = linitial(clause->args);
2312  linitial(clause->args) = lsecond(clause->args);
2313  lsecond(clause->args) = temp;
2314 }
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1298
Definition: nodes.h:516
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:605
#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 2322 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().

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

References contain_agg_clause_walker().

Referenced by get_eclass_for_sort_expr(), and subquery_planner().

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

◆ contain_agg_clause_walker()

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

Definition at line 424 of file clauses.c.

References Assert, expression_tree_walker(), and IsA.

Referenced by contain_agg_clause().

425 {
426  if (node == NULL)
427  return false;
428  if (IsA(node, Aggref))
429  {
430  Assert(((Aggref *) node)->agglevelsup == 0);
431  return true; /* abort the tree traversal and return true */
432  }
433  if (IsA(node, GroupingFunc))
434  {
435  Assert(((GroupingFunc *) node)->agglevelsup == 0);
436  return true; /* abort the tree traversal and return true */
437  }
438  Assert(!IsA(node, SubLink));
439  return expression_tree_walker(node, contain_agg_clause_walker, context);
440 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:567
static bool contain_agg_clause_walker(Node *node, void *context)
Definition: clauses.c:424
#define Assert(condition)
Definition: c.h:699
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 1450 of file clauses.c.

References contain_context_dependent_node_walker().

Referenced by inline_function().

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

◆ contain_context_dependent_node_walker()

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

Definition at line 1460 of file clauses.c.

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

Referenced by contain_context_dependent_node().

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

◆ contain_leaked_vars()

bool contain_leaked_vars ( Node clause)

Definition at line 1516 of file clauses.c.

References contain_leaked_vars_walker().

Referenced by make_restrictinfo_internal(), and qual_is_pushdown_safe().

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

◆ contain_leaked_vars_checker()

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

Definition at line 1522 of file clauses.c.

References get_func_leakproof().

Referenced by contain_leaked_vars_walker().

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

◆ contain_leaked_vars_walker()

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

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

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

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

References func_volatile().

Referenced by contain_mutable_functions_walker().

886 {
887  return (func_volatile(func_id) != PROVOLATILE_IMMUTABLE);
888 }
char func_volatile(Oid funcid)
Definition: lsyscache.c:1569

◆ contain_mutable_functions_walker()

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

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

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

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

Definition at line 3682 of file clauses.c.

References expression_tree_walker(), and IsA.

3683 {
3684  if (node == NULL)
3685  return false;
3686  if (IsA(node, Const))
3687  return false;
3688  if (IsA(node, List))
3689  return expression_tree_walker(node, contain_non_const_walker, context);
3690  /* Otherwise, abort the tree traversal and return true */
3691  return true;
3692 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:567
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1834
Definition: pg_list.h:45
static bool contain_non_const_walker(Node *node, void *context)
Definition: clauses.c:3682

◆ contain_nonstrict_functions()

bool contain_nonstrict_functions ( Node clause)

Definition at line 1315 of file clauses.c.

References contain_nonstrict_functions_walker().

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

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

◆ contain_nonstrict_functions_checker()

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

Definition at line 1321 of file clauses.c.

References func_strict().

Referenced by contain_nonstrict_functions_walker().

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

◆ contain_nonstrict_functions_walker()

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

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

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

◆ contain_subplans()

bool contain_subplans ( Node clause)

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

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

◆ contain_subplans_walker()

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

Definition at line 850 of file clauses.c.

References expression_tree_walker(), and IsA.

Referenced by contain_subplans().

851 {
852  if (node == NULL)
853  return false;
854  if (IsA(node, SubPlan) ||
855  IsA(node, AlternativeSubPlan) ||
856  IsA(node, SubLink))
857  return true; /* abort the tree traversal and return true */
858  return expression_tree_walker(node, contain_subplans_walker, context);
859 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:567
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:850

◆ contain_volatile_functions()

◆ contain_volatile_functions_checker()

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

Definition at line 964 of file clauses.c.

References func_volatile().

Referenced by contain_volatile_functions_walker().

965 {
966  return (func_volatile(func_id) == PROVOLATILE_VOLATILE);
967 }
char func_volatile(Oid funcid)
Definition: lsyscache.c:1569

◆ contain_volatile_functions_not_nextval()

bool contain_volatile_functions_not_nextval ( Node clause)

Definition at line 1008 of file clauses.c.

References contain_volatile_functions_not_nextval_walker().

Referenced by BeginCopyFrom().

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

◆ contain_volatile_functions_not_nextval_checker()

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

Definition at line 1014 of file clauses.c.

References func_volatile().

Referenced by contain_volatile_functions_not_nextval_walker().

1015 {
1016  return (func_id != F_NEXTVAL_OID &&
1017  func_volatile(func_id) == PROVOLATILE_VOLATILE);
1018 }
char func_volatile(Oid funcid)
Definition: lsyscache.c:1569

◆ contain_volatile_functions_not_nextval_walker()

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

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

1022 {
1023  if (node == NULL)
1024  return false;
1025  /* Check for volatile functions in node itself */
1026  if (check_functions_in_node(node,
1028  context))
1029  return true;
1030 
1031  /*
1032  * See notes in contain_mutable_functions_walker about why we treat
1033  * MinMaxExpr, XmlExpr, and CoerceToDomain as immutable, while
1034  * SQLValueFunction is stable. Hence, none of them are of interest here.
1035  * Also, since we're intentionally ignoring nextval(), presumably we
1036  * should ignore NextValueExpr.
1037  */
1038 
1039  /* Recurse to check arguments */
1040  if (IsA(node, Query))
1041  {
1042  /* Recurse into subselects */
1043  return query_tree_walker((Query *) node,
1045  context, 0);
1046  }
1047  return expression_tree_walker(node,
1049  context);
1050 }
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2256
#define IsA(nodeptr, _type_)
Definition: nodes.h:567
static bool contain_volatile_functions_not_nextval_walker(Node *node, void *context)
Definition: clauses.c:1021
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:1014

◆ contain_volatile_functions_walker()

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

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

971 {
972  if (node == NULL)
973  return false;
974  /* Check for volatile functions in node itself */
976  context))
977  return true;
978 
979  if (IsA(node, NextValueExpr))
980  {
981  /* NextValueExpr is volatile */
982  return true;
983  }
984 
985  /*
986  * See notes in contain_mutable_functions_walker about why we treat
987  * MinMaxExpr, XmlExpr, and CoerceToDomain as immutable, while
988  * SQLValueFunction is stable. Hence, none of them are of interest here.
989  */
990 
991  /* Recurse to check arguments */
992  if (IsA(node, Query))
993  {
994  /* Recurse into subselects */
995  return query_tree_walker((Query *) node,
997  context, 0);
998  }
1000  context);
1001 }
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2256
#define IsA(nodeptr, _type_)
Definition: nodes.h:567
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:970
static bool contain_volatile_functions_checker(Oid func_id, void *context)
Definition: clauses.c:964
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 728 of file clauses.c.

References contain_windowfuncs().

Referenced by get_eclass_for_sort_expr(), and qual_is_pushdown_safe().

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

◆ ece_function_is_safe()

static bool ece_function_is_safe ( Oid  funcid,
eval_const_expressions_context context 
)
static

Definition at line 3698 of file clauses.c.

References eval_const_expressions_context::estimate, and func_volatile().

Referenced by eval_const_expressions_mutator().

3699 {
3700  char provolatile = func_volatile(funcid);
3701 
3702  /*
3703  * Ordinarily we are only allowed to simplify immutable functions. But for
3704  * purposes of estimation, we consider it okay to simplify functions that
3705  * are merely stable; the risk that the result might change from planning
3706  * time to execution time is worth taking in preference to not being able
3707  * to estimate the value at all.
3708  */
3709  if (provolatile == PROVOLATILE_IMMUTABLE)
3710  return true;
3711  if (context->estimate && provolatile == PROVOLATILE_STABLE)
3712  return true;
3713  return false;
3714 }
char func_volatile(Oid funcid)
Definition: lsyscache.c:1569

◆ estimate_expression_value()

Node* estimate_expression_value ( PlannerInfo root,
Node node 
)

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

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

◆ eval_const_expressions()

Node* eval_const_expressions ( PlannerInfo root,
Node node 
)

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

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

◆ eval_const_expressions_mutator()

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

Definition at line 2538 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, Assert, BoolGetDatum, BoolExpr::boolop, BooleanTest::booltesttype, eval_const_expressions_context::boundParams, eval_const_expressions_context::case_val, CaseExpr::casecollid, CaseExpr::casetype, castNode, CoalesceExpr::coalescecollid, CoalesceExpr::coalescetype, COERCE_IMPLICIT_CAST, CoerceViaIO::coerceformat, CollateExpr::collOid, Const::constcollid, Const::constisnull, Const::consttype, Const::consttypmod, Const::constvalue, contain_mutable_functions(), copyObject, datumCopy(), DatumGetBool, CaseExpr::defresult, ece_all_arguments_const, ece_evaluate_expr, ece_function_is_safe(), ece_generic_processing, ArrayCoerceExpr::elemexpr, elog, ERROR, eval_const_expressions_context::estimate, evaluate_expr(), expand_function_arguments(), CaseWhen::expr, exprCollation(), expression_tree_mutator(), exprType(), exprTypmod(), FieldSelect::fieldnum, FuncExpr::funccollid, FuncExpr::funcformat, FuncExpr::funcid, FuncExpr::funcresulttype, FuncExpr::funcretset, FuncExpr::funcvariadic, get_typlenbyval(), getTypeInputInfo(), getTypeOutputInfo(), HeapTupleIsValid, WindowFunc::inputcollid, FuncExpr::inputcollid, OpExpr::inputcollid, Int32GetDatum, InvalidAttrNumber, InvalidOid, IS_FALSE, IS_NOT_FALSE, IS_NOT_NULL, IS_NOT_TRUE, IS_NOT_UNKNOWN, IS_NULL, IS_TRUE, IS_UNKNOWN, IsA, ParamExternData::isnull, lappend(), lfirst, lfirst_node, linitial, list_length(), list_make1, list_make3, list_nth(), WindowFunc::location, FuncExpr::location, OpExpr::location, RelabelType::location, CoerceViaIO::location, CollateExpr::location, CaseExpr::location, CaseWhen::location, CoalesceExpr::location, NullTest::location, BooleanTest::location, make_andclause(), make_orclause(), makeBoolConst(), makeConst(), makeNode, makeNullConst(), makeVar(), negate_clause(), NIL, nodeTag, NOT_EXPR, NullTest::nulltesttype, ParamListInfoData::numParams, ObjectIdGetDatum, OidIsValid, OpExpr::opcollid, OpExpr::opfuncid, ScalarArrayOpExpr::opfuncid, OpExpr::opno, OpExpr::opresulttype, OpExpr::opretset, OR_EXPR, PARAM_EXTERN, PARAM_FLAG_CONST, Param::paramcollid, ParamListInfoData::paramFetch, Param::paramid, Param::paramkind, ParamListInfoData::params, Param::paramtype, Param::paramtypmod, ParamExternData::pflags, PlaceHolderVar::phexpr, PROCOID, ParamExternData::ptype, RelabelType::relabelformat, ReleaseSysCache(), CaseWhen::result, FieldSelect::resultcollid, RelabelType::resultcollid, CoerceViaIO::resultcollid, FieldSelect::resulttype, RelabelType::resulttype, CoerceViaIO::resulttype, FieldSelect::resulttypmod, RelabelType::resulttypmod, RowExpr::row_typeid, rowtype_field_matches(), SearchSysCache1(), set_opfuncid(), set_sa_opfuncid(), simplify_and_arguments(), simplify_boolean_equality(), simplify_function(), simplify_or_arguments(), T_AlternativeSubPlan, T_ArrayCoerceExpr, T_ArrayExpr, T_ArrayRef, 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_RowExpr, T_ScalarArrayOpExpr, 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().

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

◆ evaluate_expr()

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

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

4846 {
4847  EState *estate;
4848  ExprState *exprstate;
4849  MemoryContext oldcontext;
4850  Datum const_val;
4851  bool const_is_null;
4852  int16 resultTypLen;
4853  bool resultTypByVal;
4854 
4855  /*
4856  * To use the executor, we need an EState.
4857  */
4858  estate = CreateExecutorState();
4859 
4860  /* We can use the estate's working context to avoid memory leaks. */
4861  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
4862 
4863  /* Make sure any opfuncids are filled in. */
4864  fix_opfuncids((Node *) expr);
4865 
4866  /*
4867  * Prepare expr for execution. (Note: we can't use ExecPrepareExpr
4868  * because it'd result in recursively invoking eval_const_expressions.)
4869  */
4870  exprstate = ExecInitExpr(expr, NULL);
4871 
4872  /*
4873  * And evaluate it.
4874  *
4875  * It is OK to use a default econtext because none of the ExecEvalExpr()
4876  * code used in this situation will use econtext. That might seem
4877  * fortuitous, but it's not so unreasonable --- a constant expression does
4878  * not depend on context, by definition, n'est ce pas?
4879  */
4880  const_val = ExecEvalExprSwitchContext(exprstate,
4881  GetPerTupleExprContext(estate),
4882  &const_is_null);
4883 
4884  /* Get info needed about result datatype */
4885  get_typlenbyval(result_type, &resultTypLen, &resultTypByVal);
4886 
4887  /* Get back to outer memory context */
4888  MemoryContextSwitchTo(oldcontext);
4889 
4890  /*
4891  * Must copy result out of sub-context used by expression eval.
4892  *
4893  * Also, if it's varlena, forcibly detoast it. This protects us against
4894  * storing TOAST pointers into plans that might outlive the referenced
4895  * data. (makeConst would handle detoasting anyway, but it's worth a few
4896  * extra lines here so that we can do the copy and detoast in one step.)
4897  */
4898  if (!const_is_null)
4899  {
4900  if (resultTypLen == -1)
4901  const_val = PointerGetDatum(PG_DETOAST_DATUM_COPY(const_val));
4902  else
4903  const_val = datumCopy(const_val, resultTypByVal, resultTypLen);
4904  }
4905 
4906  /* Release all the junk we just created */
4907  FreeExecutorState(estate);
4908 
4909  /*
4910  * Make the constant result node.
4911  */
4912  return (Expr *) makeConst(result_type, result_typmod, result_collation,
4913  resultTypLen,
4914  const_val, const_is_null,
4915  resultTypByVal);
4916 }
signed short int16
Definition: c.h:312
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:295
#define PG_DETOAST_DATUM_COPY(datum)
Definition: fmgr.h:212
#define PointerGetDatum(X)
Definition: postgres.h:541
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1582
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Definition: nodes.h:516
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:188
#define GetPerTupleExprContext(estate)
Definition: executor.h:488
MemoryContext es_query_cxt
Definition: execnodes.h:523
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:367
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2005
ExprState * ExecInitExpr(Expr *node, PlanState *parent)
Definition: execExpr.c:119

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

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

Referenced by simplify_function().

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

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

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

4115 {
4116  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4117  bool has_named_args = false;
4118  ListCell *lc;
4119 
4120  /* Do we have any named arguments? */
4121  foreach(lc, args)
4122  {
4123  Node *arg = (Node *) lfirst(lc);
4124 
4125  if (IsA(arg, NamedArgExpr))
4126  {
4127  has_named_args = true;
4128  break;
4129  }
4130  }
4131 
4132  /* If so, we must apply reorder_function_arguments */
4133  if (has_named_args)
4134  {
4135  args = reorder_function_arguments(args, func_tuple);
4136  /* Recheck argument types and add casts if needed */
4137  recheck_cast_function_args(args, result_type, func_tuple);
4138  }
4139  else if (list_length(args) < funcform->pronargs)
4140  {
4141  /* No named args, but we seem to be short some defaults */
4142  args = add_function_defaults(args, func_tuple);
4143  /* Recheck argument types and add casts if needed */
4144  recheck_cast_function_args(args, result_type, func_tuple);
4145  }
4146 
4147  return args;
4148 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:567
#define GETSTRUCT(TUP)
Definition: htup_details.h:668
Definition: nodes.h:516
static void recheck_cast_function_args(List *args, Oid result_type, HeapTuple func_tuple)
Definition: clauses.c:4287
static List * add_function_defaults(List *args, HeapTuple func_tuple)
Definition: clauses.c:4227
static List * reorder_function_arguments(List *args, HeapTuple func_tuple)
Definition: clauses.c:4157
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:132
#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 803 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(), estimate_num_groups(), and set_function_size_estimates().

804 {
805  if (clause == NULL)
806  return 1.0;
807  if (IsA(clause, FuncExpr))
808  {
809  FuncExpr *expr = (FuncExpr *) clause;
810 
811  if (expr->funcretset)
812  return clamp_row_est(get_func_rows(expr->funcid));
813  }
814  if (IsA(clause, OpExpr))
815  {
816  OpExpr *expr = (OpExpr *) clause;
817 
818  if (expr->opretset)
819  {
820  set_opfuncid(expr);
821  return clamp_row_est(get_func_rows(expr->opfuncid));
822  }
823  }
824  return 1.0;
825 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:567
float4 get_func_rows(Oid funcid)
Definition: lsyscache.c:1664
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:188
bool opretset
Definition: primnodes.h:499

◆ fetch_function_defaults()

static List * fetch_function_defaults ( HeapTuple  func_tuple)
static

Definition at line 4252 of file clauses.c.

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

Referenced by add_function_defaults(), and reorder_function_arguments().

4253 {
4254  List *defaults;
4255  Datum proargdefaults;
4256  bool isnull;
4257  char *str;
4258 
4259  /* The error cases here shouldn't happen, but check anyway */
4260  proargdefaults = SysCacheGetAttr(PROCOID, func_tuple,
4261  Anum_pg_proc_proargdefaults,
4262  &isnull);
4263  if (isnull)
4264  elog(ERROR, "not enough default arguments");
4265  str = TextDatumGetCString(proargdefaults);
4266  defaults = castNode(List, stringToNode(str));
4267  pfree(str);
4268  return defaults;
4269 }
void * stringToNode(char *str)
Definition: read.c:39
#define castNode(_type_, nodeptr)
Definition: nodes.h:585
void pfree(void *pointer)
Definition: mcxt.c:1031
#define ERROR
Definition: elog.h:43
#define TextDatumGetCString(d)
Definition: builtins.h:96
uintptr_t Datum
Definition: postgres.h:367
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 2121 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().

2122 {
2123  if (node == NULL)
2124  return NULL;
2125  if (IsA(node, NullTest))
2126  {
2127  /* check for var IS NULL */
2128  NullTest *expr = (NullTest *) node;
2129 
2130  if (expr->nulltesttype == IS_NULL && !expr->argisrow)
2131  {
2132  Var *var = (Var *) expr->arg;
2133 
2134  if (var && IsA(var, Var) &&
2135  var->varlevelsup == 0)
2136  return var;
2137  }
2138  }
2139  else if (IsA(node, BooleanTest))
2140  {
2141  /* var IS UNKNOWN is equivalent to var IS NULL */
2142  BooleanTest *expr = (BooleanTest *) node;
2143 
2144  if (expr->booltesttype == IS_UNKNOWN)
2145  {
2146  Var *var = (Var *) expr->arg;
2147 
2148  if (var && IsA(var, Var) &&
2149  var->varlevelsup == 0)
2150  return var;
2151  }
2152  }
2153  return NULL;
2154 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:567
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 2062 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().

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

◆ find_nonnullable_rels()

Relids find_nonnullable_rels ( Node clause)

Definition at line 1661 of file clauses.c.

References find_nonnullable_rels_walker().

Referenced by make_outerjoininfo(), and reduce_outer_joins_pass2().

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

◆ find_nonnullable_rels_walker()

static Relids find_nonnullable_rels_walker ( Node node,
bool  top_level 
)
static

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

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

◆ find_nonnullable_vars()

List* find_nonnullable_vars ( Node clause)

Definition at line 1869 of file clauses.c.

References find_nonnullable_vars_walker().

Referenced by reduce_outer_joins_pass2().

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

◆ find_nonnullable_vars_walker()

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

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

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

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

Referenced by grouping_planner().

742 {
743  WindowFuncLists *lists = palloc(sizeof(WindowFuncLists));
744 
745  lists->numWindowFuncs = 0;
746  lists->maxWinRef = maxWinRef;
747  lists->windowFuncs = (List **) palloc0((maxWinRef + 1) * sizeof(List *));
748  (void) find_window_functions_walker(clause, lists);
749  return lists;
750 }
Index maxWinRef
Definition: clauses.h:26
int numWindowFuncs
Definition: clauses.h:25
void * palloc0(Size size)
Definition: mcxt.c:955
void * palloc(Size size)
Definition: mcxt.c:924
static bool find_window_functions_walker(Node *node, WindowFuncLists *lists)
Definition: clauses.c:753
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 753 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().

754 {
755  if (node == NULL)
756  return false;
757  if (IsA(node, WindowFunc))
758  {
759  WindowFunc *wfunc = (WindowFunc *) node;
760 
761  /* winref is unsigned, so one-sided test is OK */
762  if (wfunc->winref > lists->maxWinRef)
763  elog(ERROR, "WindowFunc contains out-of-range winref %u",
764  wfunc->winref);
765  /* eliminate duplicates, so that we avoid repeated computation */
766  if (!list_member(lists->windowFuncs[wfunc->winref], wfunc))
767  {
768  lists->windowFuncs[wfunc->winref] =
769  lappend(lists->windowFuncs[wfunc->winref], wfunc);
770  lists->numWindowFuncs++;
771  }
772 
773  /*
774  * We assume that the parser checked that there are no window
775  * functions in the arguments or filter clause. Hence, we need not
776  * recurse into them. (If either the parser or the planner screws up
777  * on this point, the executor will still catch it; see ExecInitExpr.)
778  */
779  return false;
780  }
781  Assert(!IsA(node, SubLink));
783  (void *) lists);
784 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:567
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:699
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:753
#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 468 of file clauses.c.

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

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

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

◆ get_agg_clause_costs_walker()

static bool get_agg_clause_costs_walker ( Node node,
get_agg_clause_costs_context context 
)
static

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

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

◆ get_leftop()

◆ get_notclausearg()

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

References ACL_EXECUTE, ACLCHECK_OK, eval_const_expressions_context::active_fns, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, arg, ErrorContextCallback::arg, CollateExpr::arg, generate_unaccent_rules::args, FuncExpr::args, 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, FromExpr::quals, querytree(), record_plan_function_dependency(), eval_const_expressions_context::root, Query::rtable, Query::setOperations, Query::sortClause, sql_fn_parser_setup(), sql_inline_error_callback(), QualCost::startup, substitute_actual_parameters(), SysCacheGetAttr(), Query::targetList, TextDatumGetCString, transformTopLevelStmt(), and Query::windowClause.

Referenced by simplify_function().

4463 {
4464  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4465  char *src;
4466  Datum tmp;
4467  bool isNull;
4468  bool modifyTargetList;
4469  MemoryContext oldcxt;
4470  MemoryContext mycxt;
4471  inline_error_callback_arg callback_arg;
4472  ErrorContextCallback sqlerrcontext;
4473  FuncExpr *fexpr;
4475  ParseState *pstate;
4476  List *raw_parsetree_list;
4477  Query *querytree;
4478  Node *newexpr;
4479  int *usecounts;
4480  ListCell *arg;
4481  int i;
4482 
4483  /*
4484  * Forget it if the function is not SQL-language or has other showstopper
4485  * properties. (The prokind and nargs checks are just paranoia.)
4486  */
4487  if (funcform->prolang != SQLlanguageId ||
4488  funcform->prokind != PROKIND_FUNCTION ||
4489  funcform->prosecdef ||
4490  funcform->proretset ||
4491  funcform->prorettype == RECORDOID ||
4492  !heap_attisnull(func_tuple, Anum_pg_proc_proconfig, NULL) ||
4493  funcform->pronargs != list_length(args))
4494  return NULL;
4495 
4496  /* Check for recursive function, and give up trying to expand if so */
4497  if (list_member_oid(context->active_fns, funcid))
4498  return NULL;
4499 
4500  /* Check permission to call function (fail later, if not) */
4502  return NULL;
4503 
4504  /* Check whether a plugin wants to hook function entry/exit */
4505  if (FmgrHookIsNeeded(funcid))
4506  return NULL;
4507 
4508  /*
4509  * Make a temporary memory context, so that we don't leak all the stuff
4510  * that parsing might create.
4511  */
4513  "inline_function",
4515  oldcxt = MemoryContextSwitchTo(mycxt);
4516 
4517  /* Fetch the function body */
4518  tmp = SysCacheGetAttr(PROCOID,
4519  func_tuple,
4520  Anum_pg_proc_prosrc,
4521  &isNull);
4522  if (isNull)
4523  elog(ERROR, "null prosrc for function %u", funcid);
4524  src = TextDatumGetCString(tmp);
4525 
4526  /*
4527  * Setup error traceback support for ereport(). This is so that we can
4528  * finger the function that bad information came from.
4529  */
4530  callback_arg.proname = NameStr(funcform->proname);
4531  callback_arg.prosrc = src;
4532 
4533  sqlerrcontext.callback = sql_inline_error_callback;
4534  sqlerrcontext.arg = (void *) &callback_arg;
4535  sqlerrcontext.previous = error_context_stack;
4536  error_context_stack = &sqlerrcontext;
4537 
4538  /*
4539  * Set up to handle parameters while parsing the function body. We need a
4540  * dummy FuncExpr node containing the already-simplified arguments to pass
4541  * to prepare_sql_fn_parse_info. (It is really only needed if there are
4542  * some polymorphic arguments, but for simplicity we always build it.)
4543  */
4544  fexpr = makeNode(FuncExpr);
4545  fexpr->funcid = funcid;
4546  fexpr->funcresulttype = result_type;
4547  fexpr->funcretset = false;
4548  fexpr->funcvariadic = funcvariadic;
4549  fexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
4550  fexpr->funccollid = result_collid; /* doesn't matter */
4551  fexpr->inputcollid = input_collid;
4552  fexpr->args = args;
4553  fexpr->location = -1;
4554 
4555  pinfo = prepare_sql_fn_parse_info(func_tuple,
4556  (Node *) fexpr,
4557  input_collid);
4558 
4559  /*
4560  * We just do parsing and parse analysis, not rewriting, because rewriting
4561  * will not affect table-free-SELECT-only queries, which is all that we
4562  * care about. Also, we can punt as soon as we detect more than one
4563  * command in the function body.
4564  */
4565  raw_parsetree_list = pg_parse_query(src);
4566  if (list_length(raw_parsetree_list) != 1)
4567  goto fail;
4568 
4569  pstate = make_parsestate(NULL);
4570  pstate->p_sourcetext = src;
4571  sql_fn_parser_setup(pstate, pinfo);
4572 
4573  querytree = transformTopLevelStmt(pstate, linitial(raw_parsetree_list));
4574 
4575  free_parsestate(pstate);
4576 
4577  /*
4578  * The single command must be a simple "SELECT expression".
4579  *
4580  * Note: if you change the tests involved in this, see also plpgsql's
4581  * exec_simple_check_plan(). That generally needs to have the same idea
4582  * of what's a "simple expression", so that inlining a function that
4583  * previously wasn't inlined won't change plpgsql's conclusion.
4584  */
4585  if (!IsA(querytree, Query) ||
4586  querytree->commandType != CMD_SELECT ||
4587  querytree->hasAggs ||
4588  querytree->hasWindowFuncs ||
4589  querytree->hasTargetSRFs ||
4590  querytree->hasSubLinks ||
4591  querytree->cteList ||
4592  querytree->rtable ||
4593  querytree->jointree->fromlist ||
4594  querytree->jointree->quals ||
4595  querytree->groupClause ||
4596  querytree->groupingSets ||
4597  querytree->havingQual ||
4598  querytree->windowClause ||
4599  querytree->distinctClause ||
4600  querytree->sortClause ||
4601  querytree->limitOffset ||
4602  querytree->limitCount ||
4603  querytree->setOperations ||
4604  list_length(querytree->targetList) != 1)
4605  goto fail;
4606 
4607  /*
4608  * Make sure the function (still) returns what it's declared to. This
4609  * will raise an error if wrong, but that's okay since the function would
4610  * fail at runtime anyway. Note that check_sql_fn_retval will also insert
4611  * a RelabelType if needed to make the tlist expression match the declared
4612  * type of the function.
4613  *
4614  * Note: we do not try this until we have verified that no rewriting was
4615  * needed; that's probably not important, but let's be careful.
4616  */
4617  if (check_sql_fn_retval(funcid, result_type, list_make1(querytree),
4618  &modifyTargetList, NULL))
4619  goto fail; /* reject whole-tuple-result cases */
4620 
4621  /* Now we can grab the tlist expression */
4622  newexpr = (Node *) ((TargetEntry *) linitial(querytree->targetList))->expr;
4623 
4624  /*
4625  * If the SQL function returns VOID, we can only inline it if it is a
4626  * SELECT of an expression returning VOID (ie, it's just a redirection to
4627  * another VOID-returning function). In all non-VOID-returning cases,
4628  * check_sql_fn_retval should ensure that newexpr returns the function's
4629  * declared result type, so this test shouldn't fail otherwise; but we may
4630  * as well cope gracefully if it does.
4631  */
4632  if (exprType(newexpr) != result_type)
4633  goto fail;
4634 
4635  /* check_sql_fn_retval couldn't have made any dangerous tlist changes */
4636  Assert(!modifyTargetList);
4637 
4638  /*
4639  * Additional validity checks on the expression. It mustn't be more
4640  * volatile than the surrounding function (this is to avoid breaking hacks
4641  * that involve pretending a function is immutable when it really ain't).
4642  * If the surrounding function is declared strict, then the expression
4643  * must contain only strict constructs and must use all of the function
4644  * parameters (this is overkill, but an exact analysis is hard).
4645  */
4646  if (funcform->provolatile == PROVOLATILE_IMMUTABLE &&
4647  contain_mutable_functions(newexpr))
4648  goto fail;
4649  else if (funcform->provolatile == PROVOLATILE_STABLE &&
4650  contain_volatile_functions(newexpr))
4651  goto fail;
4652 
4653  if (funcform->proisstrict &&
4654  contain_nonstrict_functions(newexpr))
4655  goto fail;
4656 
4657  /*
4658  * If any parameter expression contains a context-dependent node, we can't
4659  * inline, for fear of putting such a node into the wrong context.
4660  */
4661  if (contain_context_dependent_node((Node *) args))
4662  goto fail;
4663 
4664  /*
4665  * We may be able to do it; there are still checks on parameter usage to
4666  * make, but those are most easily done in combination with the actual
4667  * substitution of the inputs. So start building expression with inputs
4668  * substituted.
4669  */
4670  usecounts = (int *) palloc0(funcform->pronargs * sizeof(int));
4671  newexpr = substitute_actual_parameters(newexpr, funcform->pronargs,
4672  args, usecounts);
4673 
4674  /* Now check for parameter usage */
4675  i = 0;
4676  foreach(arg, args)
4677  {
4678  Node *param = lfirst(arg);
4679 
4680  if (usecounts[i] == 0)
4681  {
4682  /* Param not used at all: uncool if func is strict */
4683  if (funcform->proisstrict)
4684  goto fail;
4685  }
4686  else if (usecounts[i] != 1)
4687  {
4688  /* Param used multiple times: uncool if expensive or volatile */
4689  QualCost eval_cost;
4690 
4691  /*
4692  * We define "expensive" as "contains any subplan or more than 10
4693  * operators". Note that the subplan search has to be done
4694  * explicitly, since cost_qual_eval() will barf on unplanned
4695  * subselects.
4696  */
4697  if (contain_subplans(param))
4698  goto fail;
4699  cost_qual_eval(&eval_cost, list_make1(param), NULL);
4700  if (eval_cost.startup + eval_cost.per_tuple >
4701  10 * cpu_operator_cost)
4702  goto fail;
4703 
4704  /*
4705  * Check volatility last since this is more expensive than the
4706  * above tests
4707  */
4708  if (contain_volatile_functions(param))
4709  goto fail;
4710  }
4711  i++;
4712  }
4713 
4714  /*
4715  * Whew --- we can make the substitution. Copy the modified expression
4716  * out of the temporary memory context, and clean up.
4717  */
4718  MemoryContextSwitchTo(oldcxt);
4719 
4720  newexpr = copyObject(newexpr);
4721 
4722  MemoryContextDelete(mycxt);
4723 
4724  /*
4725  * If the result is of a collatable type, force the result to expose the
4726  * correct collation. In most cases this does not matter, but it's
4727  * possible that the function result is used directly as a sort key or in
4728  * other places where we expect exprCollation() to tell the truth.
4729  */
4730  if (OidIsValid(result_collid))
4731  {
4732  Oid exprcoll = exprCollation(newexpr);
4733 
4734  if (OidIsValid(exprcoll) && exprcoll != result_collid)
4735  {
4736  CollateExpr *newnode = makeNode(CollateExpr);
4737 
4738  newnode->arg = (Expr *) newexpr;
4739  newnode->collOid = result_collid;
4740  newnode->location = -1;
4741 
4742  newexpr = (Node *) newnode;
4743  }
4744  }
4745 
4746  /*
4747  * Since there is now no trace of the function in the plan tree, we must
4748  * explicitly record the plan's dependency on the function.
4749  */
4750  if (context->root)
4751  record_plan_function_dependency(context->root, funcid);
4752 
4753  /*
4754  * Recursively try to simplify the modified expression. Here we must add
4755  * the current function to the context list of active functions.
4756  */
4757  context->active_fns = lcons_oid(funcid, context->active_fns);
4758  newexpr = eval_const_expressions_mutator(newexpr, context);
4759  context->active_fns = list_delete_first(context->active_fns);
4760 
4761  error_context_stack = sqlerrcontext.previous;
4762 
4763  return (Expr *) newexpr;
4764 
4765  /* Here if func is not inlinable: release temp memory and return NULL */
4766 fail:
4767  MemoryContextSwitchTo(oldcxt);
4768  MemoryContextDelete(mycxt);
4769  error_context_stack = sqlerrcontext.previous;
4770 
4771  return NULL;
4772 }
Node * limitOffset
Definition: parsenodes.h:160
Oid funcresulttype
Definition: primnodes.h:450
#define IsA(nodeptr, _type_)
Definition: nodes.h:567
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
#define GETSTRUCT(TUP)
Definition: htup_details.h:668
List * sortClause
Definition: parsenodes.h:158
List * args
Definition: primnodes.h:457
FromExpr * jointree
Definition: parsenodes.h:138
Oid GetUserId(void)
Definition: miscinit.c:379
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:125
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
List * groupingSets
Definition: parsenodes.h:150
Definition: nodes.h:516
bool check_sql_fn_retval(Oid func_id, Oid rettype, List *queryTreeList, bool *modifyTargetList, JunkFilter **junkFilter)
Definition: functions.c:1586
bool heap_attisnull(HeapTuple tup, int attnum, TupleDesc tupleDesc)
Definition: heaptuple.c:397
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:958
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:605
#define FmgrHookIsNeeded(fn_oid)
Definition: fmgr.h:735
Node * quals
Definition: primnodes.h:1479
Cost startup
Definition: relation.h:46
List * windowClause
Definition: parsenodes.h:154
List * targetList
Definition: parsenodes.h:140
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:844
CoercionForm funcformat
Definition: primnodes.h:454
Cost per_tuple
Definition: relation.h:47
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2538
#define linitial(l)
Definition: pg_list.h:111
List * rtable
Definition: parsenodes.h:137
List * distinctClause
Definition: parsenodes.h:156
Oid funcid
Definition: primnodes.h:449
#define ERROR
Definition: elog.h:43
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3716
List * pg_parse_query(const char *query_string)
Definition: postgres.c:609
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
Node * limitCount
Definition: parsenodes.h:161
double cpu_operator_cost
Definition: costsize.c:115
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
const char * p_sourcetext
Definition: parse_node.h:173
static Node * substitute_actual_parameters(Node *expr, int nargs, List *args, int *usecounts)
Definition: clauses.c:4778
#define AllocSetContextCreate(parent, name, allocparams)
Definition: memutils.h:170
static void sql_inline_error_callback(void *arg)
Definition: clauses.c:4820
#define TextDatumGetCString(d)
Definition: builtins.h:96
void * palloc0(Size size)
Definition: mcxt.c:955
uintptr_t Datum
Definition: postgres.h:367
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:132
CmdType commandType
Definition: parsenodes.h:112
bool hasTargetSRFs
Definition: parsenodes.h:127
#define makeNode(_type_)
Definition: nodes.h:564
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:699
#define lfirst(lc)
Definition: pg_list.h:106
bool hasWindowFuncs
Definition: parsenodes.h:126
Query * transformTopLevelStmt(ParseState *pstate, RawStmt *parseTree)
Definition: analyze.c:191
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:1450
List * cteList
Definition: parsenodes.h:135
Node * setOperations
Definition: parsenodes.h:165
List * groupClause
Definition: parsenodes.h:148
bool hasSubLinks
Definition: parsenodes.h:128
#define ACL_EXECUTE
Definition: parsenodes.h:81
AclResult pg_proc_aclcheck(Oid proc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4651
int i
#define NameStr(name)
Definition: c.h:576
void * arg
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:879
int location
Definition: primnodes.h:458
#define elog
Definition: elog.h:219
bool contain_nonstrict_functions(Node *clause)
Definition: clauses.c:1315
SQLFunctionParseInfoPtr prepare_sql_fn_parse_info(HeapTuple procedureTuple, Node *call_expr, Oid inputCollation)
Definition: functions.c:184
#define copyObject(obj)
Definition: nodes.h:629
Node * havingQual
Definition: parsenodes.h:152
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 4932 of file clauses.c.

References ACL_EXECUTE, ACLCHECK_OK, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, 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, querytree(), record_plan_function_dependency(), ReleaseSysCache(), RTE_FUNCTION, RangeTblEntry::rtekind, SearchSysCache1(), sql_fn_parser_setup(), sql_inline_error_callback(), substitute_actual_srf_parameters(), SysCacheGetAttr(), Query::targetList, TextDatumGetCString, tlist_matches_coltypelist(), and TYPEFUNC_RECORD.

Referenced by inline_set_returning_functions().

4933 {
4934  RangeTblFunction *rtfunc;
4935  FuncExpr *fexpr;
4936  Oid func_oid;
4937  HeapTuple func_tuple;
4938  Form_pg_proc funcform;
4939  char *src;
4940  Datum tmp;
4941  bool isNull;
4942  bool modifyTargetList;