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 Listexpand_function_arguments (List *args, Oid result_type, HeapTuple func_tuple)
 
static Listreorder_function_arguments (List *args, HeapTuple func_tuple)
 
static Listadd_function_defaults (List *args, HeapTuple func_tuple)
 
static Listfetch_function_defaults (HeapTuple func_tuple)
 
static void recheck_cast_function_args (List *args, Oid result_type, HeapTuple func_tuple)
 
static Exprevaluate_function (Oid funcid, Oid result_type, int32 result_typmod, Oid result_collid, Oid input_collid, List *args, bool funcvariadic, HeapTuple func_tuple, eval_const_expressions_context *context)
 
static Exprinline_function (Oid funcid, Oid result_type, Oid result_collid, Oid input_collid, List *args, bool funcvariadic, HeapTuple func_tuple, eval_const_expressions_context *context)
 
static Nodesubstitute_actual_parameters (Node *expr, int nargs, List *args, int *usecounts)
 
static Nodesubstitute_actual_parameters_mutator (Node *node, substitute_actual_parameters_context *context)
 
static void sql_inline_error_callback (void *arg)
 
static Exprevaluate_expr (Expr *expr, Oid result_type, int32 result_typmod, Oid result_collation)
 
static Querysubstitute_actual_srf_parameters (Query *expr, int nargs, List *args)
 
static Nodesubstitute_actual_srf_parameters_mutator (Node *node, substitute_actual_srf_parameters_context *context)
 
static bool tlist_matches_coltypelist (List *tlist, List *coltypelist)
 
Exprmake_opclause (Oid opno, Oid opresulttype, bool opretset, Expr *leftop, Expr *rightop, Oid opcollid, Oid inputcollid)
 
Nodeget_leftop (const Expr *clause)
 
Nodeget_rightop (const Expr *clause)
 
bool not_clause (Node *clause)
 
Exprmake_notclause (Expr *notclause)
 
Exprget_notclausearg (Expr *notclause)
 
bool or_clause (Node *clause)
 
Exprmake_orclause (List *orclauses)
 
bool and_clause (Node *clause)
 
Exprmake_andclause (List *andclauses)
 
Nodemake_and_qual (Node *qual1, Node *qual2)
 
Exprmake_ands_explicit (List *andclauses)
 
Listmake_ands_implicit (Expr *clause)
 
bool contain_agg_clause (Node *clause)
 
void get_agg_clause_costs (PlannerInfo *root, Node *clause, AggSplit aggsplit, AggClauseCosts *costs)
 
bool contain_window_function (Node *clause)
 
WindowFuncListsfind_window_functions (Node *clause, Index maxWinRef)
 
double expression_returns_set_rows (Node *clause)
 
bool contain_subplans (Node *clause)
 
bool contain_mutable_functions (Node *clause)
 
static bool contain_mutable_functions_checker (Oid func_id, void *context)
 
bool contain_volatile_functions (Node *clause)
 
static bool contain_volatile_functions_checker (Oid func_id, void *context)
 
bool contain_volatile_functions_not_nextval (Node *clause)
 
static bool contain_volatile_functions_not_nextval_checker (Oid func_id, void *context)
 
char max_parallel_hazard (Query *parse)
 
bool is_parallel_safe (PlannerInfo *root, Node *node)
 
static bool max_parallel_hazard_test (char proparallel, max_parallel_hazard_context *context)
 
static bool max_parallel_hazard_checker (Oid func_id, void *context)
 
bool contain_nonstrict_functions (Node *clause)
 
static bool contain_nonstrict_functions_checker (Oid func_id, void *context)
 
bool contain_leaked_vars (Node *clause)
 
static bool contain_leaked_vars_checker (Oid func_id, void *context)
 
Relids find_nonnullable_rels (Node *clause)
 
Listfind_nonnullable_vars (Node *clause)
 
Listfind_forced_null_vars (Node *node)
 
Varfind_forced_null_var (Node *node)
 
bool is_pseudo_constant_clause (Node *clause)
 
bool is_pseudo_constant_clause_relids (Node *clause, Relids relids)
 
int NumRelids (Node *clause)
 
void CommuteOpExpr (OpExpr *clause)
 
void CommuteRowCompareExpr (RowCompareExpr *clause)
 
static bool rowtype_field_matches (Oid rowtypeid, int fieldnum, Oid expectedtype, int32 expectedtypmod, Oid expectedcollation)
 
Nodeeval_const_expressions (PlannerInfo *root, Node *node)
 
Nodeestimate_expression_value (PlannerInfo *root, Node *node)
 
Queryinline_set_returning_function (PlannerInfo *root, RangeTblEntry *rte)
 

Macro Definition Documentation

◆ CCDN_IN_CASEEXPR

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

Definition at line 1459 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 2526 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:4837
Definition: nodes.h:512
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42

Definition at line 2530 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:2409
Definition: nodes.h:512
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2540

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

4230 {
4231  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4232  int nargsprovided = list_length(args);
4233  List *defaults;
4234  int ndelete;
4235 
4236  /* Get all the default expressions from the pg_proc tuple */
4237  defaults = fetch_function_defaults(func_tuple);
4238 
4239  /* Delete any unused defaults from the list */
4240  ndelete = nargsprovided + list_length(defaults) - funcform->pronargs;
4241  if (ndelete < 0)
4242  elog(ERROR, "not enough default arguments");
4243  while (ndelete-- > 0)
4244  defaults = list_delete_first(defaults);
4245 
4246  /* And form the combined argument list, not modifying the input list */
4247  return list_concat(list_copy(args), defaults);
4248 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
List * list_copy(const List *oldlist)
Definition: list.c:1160
List * list_concat(List *list1, List *list2)
Definition: list.c:321
#define ERROR
Definition: elog.h:43
static List * fetch_function_defaults(HeapTuple func_tuple)
Definition: clauses.c:4254
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:83
static int list_length(const List *l)
Definition: pg_list.h:89
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
List * list_delete_first(List *list)
Definition: list.c:666

◆ and_clause()

bool and_clause ( Node clause)

◆ CommuteOpExpr()

void CommuteOpExpr ( OpExpr clause)

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

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

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

References contain_agg_clause_walker().

Referenced by get_eclass_for_sort_expr(), and subquery_planner().

421 {
422  return contain_agg_clause_walker(clause, NULL);
423 }
static bool contain_agg_clause_walker(Node *node, void *context)
Definition: clauses.c:426

◆ contain_agg_clause_walker()

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

Definition at line 426 of file clauses.c.

References Assert, expression_tree_walker(), and IsA.

Referenced by contain_agg_clause().

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

References contain_context_dependent_node_walker().

Referenced by inline_function().

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

◆ contain_context_dependent_node_walker()

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

Definition at line 1462 of file clauses.c.

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

Referenced by contain_context_dependent_node().

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

◆ contain_leaked_vars()

bool contain_leaked_vars ( Node clause)

Definition at line 1518 of file clauses.c.

References contain_leaked_vars_walker().

Referenced by make_restrictinfo_internal(), and qual_is_pushdown_safe().

1519 {
1520  return contain_leaked_vars_walker(clause, NULL);
1521 }
static bool contain_leaked_vars_walker(Node *node, void *context)
Definition: clauses.c:1530

◆ contain_leaked_vars_checker()

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

Definition at line 1524 of file clauses.c.

References get_func_leakproof().

Referenced by contain_leaked_vars_walker().

1525 {
1526  return !get_func_leakproof(func_id);
1527 }
bool get_func_leakproof(Oid funcid)
Definition: lsyscache.c:1641

◆ contain_leaked_vars_walker()

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

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

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

◆ contain_mutable_functions()

bool contain_mutable_functions ( Node clause)

◆ contain_mutable_functions_checker()

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

Definition at line 887 of file clauses.c.

References func_volatile(), and PROVOLATILE_IMMUTABLE.

Referenced by contain_mutable_functions_walker().

888 {
889  return (func_volatile(func_id) != PROVOLATILE_IMMUTABLE);
890 }
#define PROVOLATILE_IMMUTABLE
Definition: pg_proc.h:5544
char func_volatile(Oid funcid)
Definition: lsyscache.c:1584

◆ contain_mutable_functions_walker()

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

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

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

References expression_tree_walker(), and IsA.

3685 {
3686  if (node == NULL)
3687  return false;
3688  if (IsA(node, Const))
3689  return false;
3690  if (IsA(node, List))
3691  return expression_tree_walker(node, contain_non_const_walker, context);
3692  /* Otherwise, abort the tree traversal and return true */
3693  return true;
3694 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:563
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:3684

◆ contain_nonstrict_functions()

bool contain_nonstrict_functions ( Node clause)

Definition at line 1317 of file clauses.c.

References contain_nonstrict_functions_walker().

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

1318 {
1319  return contain_nonstrict_functions_walker(clause, NULL);
1320 }
static bool contain_nonstrict_functions_walker(Node *node, void *context)
Definition: clauses.c:1329

◆ contain_nonstrict_functions_checker()

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

Definition at line 1323 of file clauses.c.

References func_strict().

Referenced by contain_nonstrict_functions_walker().

1324 {
1325  return !func_strict(func_id);
1326 }
bool func_strict(Oid funcid)
Definition: lsyscache.c:1565

◆ contain_nonstrict_functions_walker()

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

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

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

◆ contain_subplans()

bool contain_subplans ( Node clause)

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

847 {
848  return contain_subplans_walker(clause, NULL);
849 }
static bool contain_subplans_walker(Node *node, void *context)
Definition: clauses.c:852

◆ contain_subplans_walker()

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

Definition at line 852 of file clauses.c.

References expression_tree_walker(), and IsA.

Referenced by contain_subplans().

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

◆ contain_volatile_functions()

◆ contain_volatile_functions_checker()

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

Definition at line 966 of file clauses.c.

References func_volatile(), and PROVOLATILE_VOLATILE.

Referenced by contain_volatile_functions_walker().

967 {
968  return (func_volatile(func_id) == PROVOLATILE_VOLATILE);
969 }
#define PROVOLATILE_VOLATILE
Definition: pg_proc.h:5546
char func_volatile(Oid funcid)
Definition: lsyscache.c:1584

◆ contain_volatile_functions_not_nextval()

bool contain_volatile_functions_not_nextval ( Node clause)

Definition at line 1010 of file clauses.c.

References contain_volatile_functions_not_nextval_walker().

Referenced by BeginCopyFrom().

1011 {
1012  return contain_volatile_functions_not_nextval_walker(clause, NULL);
1013 }
static bool contain_volatile_functions_not_nextval_walker(Node *node, void *context)
Definition: clauses.c:1023

◆ contain_volatile_functions_not_nextval_checker()

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

Definition at line 1016 of file clauses.c.

References func_volatile(), and PROVOLATILE_VOLATILE.

Referenced by contain_volatile_functions_not_nextval_walker().

1017 {
1018  return (func_id != F_NEXTVAL_OID &&
1019  func_volatile(func_id) == PROVOLATILE_VOLATILE);
1020 }
#define PROVOLATILE_VOLATILE
Definition: pg_proc.h:5546
char func_volatile(Oid funcid)
Definition: lsyscache.c:1584

◆ contain_volatile_functions_not_nextval_walker()

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

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

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

◆ contain_volatile_functions_walker()

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

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

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

References contain_windowfuncs().

Referenced by get_eclass_for_sort_expr(), and qual_is_pushdown_safe().

731 {
732  return contain_windowfuncs(clause);
733 }
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 3700 of file clauses.c.

References eval_const_expressions_context::estimate, func_volatile(), PROVOLATILE_IMMUTABLE, and PROVOLATILE_STABLE.

Referenced by eval_const_expressions_mutator().

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

◆ estimate_expression_value()

Node* estimate_expression_value ( PlannerInfo root,
Node node 
)

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

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

◆ eval_const_expressions()

Node* eval_const_expressions ( PlannerInfo root,
Node node 
)

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

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

◆ eval_const_expressions_mutator()

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

Definition at line 2540 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, BooleanEqualOperator, BooleanNotEqualOperator, BoolGetDatum, BoolExpr::boolop, BooleanTest::booltesttype, eval_const_expressions_context::boundParams, eval_const_expressions_context::case_val, CaseExpr::casecollid, CaseExpr::casetype, castNode, CoalesceExpr::coalescecollid, CoalesceExpr::coalescetype, COERCE_IMPLICIT_CAST, CoerceViaIO::coerceformat, CollateExpr::collOid, Const::constcollid, Const::constisnull, Const::consttype, Const::consttypmod, Const::constvalue, contain_mutable_functions(), copyObject, CSTRINGOID, 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, INT4OID, InvalidAttrNumber, InvalidOid, IS_FALSE, IS_NOT_FALSE, IS_NOT_NULL, IS_NOT_TRUE, IS_NOT_UNKNOWN, IS_NULL, IS_TRUE, IS_UNKNOWN, IsA, ParamExternData::isnull, lappend(), lfirst, lfirst_node, linitial, list_length(), list_make1, list_make3, list_nth(), WindowFunc::location, FuncExpr::location, OpExpr::location, RelabelType::location, CoerceViaIO::location, 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, OIDOID, 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().

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

◆ evaluate_expr()

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

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

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

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

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

Referenced by simplify_function().

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

◆ expand_function_arguments()

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

Definition at line 4116 of file clauses.c.

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

Referenced by eval_const_expressions_mutator(), and simplify_function().

4117 {
4118  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4119  bool has_named_args = false;
4120  ListCell *lc;
4121 
4122  /* Do we have any named arguments? */
4123  foreach(lc, args)
4124  {
4125  Node *arg = (Node *) lfirst(lc);
4126 
4127  if (IsA(arg, NamedArgExpr))
4128  {
4129  has_named_args = true;
4130  break;
4131  }
4132  }
4133 
4134  /* If so, we must apply reorder_function_arguments */
4135  if (has_named_args)
4136  {
4137  args = reorder_function_arguments(args, func_tuple);
4138  /* Recheck argument types and add casts if needed */
4139  recheck_cast_function_args(args, result_type, func_tuple);
4140  }
4141  else if (list_length(args) < funcform->pronargs)
4142  {
4143  /* No named args, but we seem to be short some defaults */
4144  args = add_function_defaults(args, func_tuple);
4145  /* Recheck argument types and add casts if needed */
4146  recheck_cast_function_args(args, result_type, func_tuple);
4147  }
4148 
4149  return args;
4150 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:563
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
Definition: nodes.h:512
static void recheck_cast_function_args(List *args, Oid result_type, HeapTuple func_tuple)
Definition: clauses.c:4289
static List * add_function_defaults(List *args, HeapTuple func_tuple)
Definition: clauses.c:4229
static List * reorder_function_arguments(List *args, HeapTuple func_tuple)
Definition: clauses.c:4159
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:83
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
void * arg

◆ expression_returns_set_rows()

double expression_returns_set_rows ( Node clause)

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

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

◆ fetch_function_defaults()

static List * fetch_function_defaults ( HeapTuple  func_tuple)
static

Definition at line 4254 of file clauses.c.

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

Referenced by add_function_defaults(), and reorder_function_arguments().

4255 {
4256  List *defaults;
4257  Datum proargdefaults;
4258  bool isnull;
4259  char *str;
4260 
4261  /* The error cases here shouldn't happen, but check anyway */
4262  proargdefaults = SysCacheGetAttr(PROCOID, func_tuple,
4264  &isnull);
4265  if (isnull)
4266  elog(ERROR, "not enough default arguments");
4267  str = TextDatumGetCString(proargdefaults);
4268  defaults = castNode(List, stringToNode(str));
4269  pfree(str);
4270  return defaults;
4271 }
void * stringToNode(char *str)
Definition: read.c:38
#define castNode(_type_, nodeptr)
Definition: nodes.h:581
void pfree(void *pointer)
Definition: mcxt.c:936
#define ERROR
Definition: elog.h:43
#define Anum_pg_proc_proargdefaults
Definition: pg_proc.h:113
#define TextDatumGetCString(d)
Definition: builtins.h:92
uintptr_t Datum
Definition: postgres.h:372
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1368
#define elog
Definition: elog.h:219
Definition: pg_list.h:45

◆ find_forced_null_var()

Var* find_forced_null_var ( Node node)

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

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

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

◆ find_nonnullable_rels()

Relids find_nonnullable_rels ( Node clause)

Definition at line 1663 of file clauses.c.

References find_nonnullable_rels_walker().

Referenced by make_outerjoininfo(), and reduce_outer_joins_pass2().

1664 {
1665  return find_nonnullable_rels_walker(clause, true);
1666 }
static Relids find_nonnullable_rels_walker(Node *node, bool top_level)
Definition: clauses.c:1669

◆ find_nonnullable_rels_walker()

static Relids find_nonnullable_rels_walker ( Node node,
bool  top_level 
)
static

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

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

◆ find_nonnullable_vars()

List* find_nonnullable_vars ( Node clause)

Definition at line 1871 of file clauses.c.

References find_nonnullable_vars_walker().

Referenced by reduce_outer_joins_pass2().

1872 {
1873  return find_nonnullable_vars_walker(clause, true);
1874 }
static List * find_nonnullable_vars_walker(Node *node, bool top_level)
Definition: clauses.c:1877

◆ find_nonnullable_vars_walker()

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

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

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

◆ find_window_functions()

WindowFuncLists* find_window_functions ( Node clause,
Index  maxWinRef 
)

Definition at line 743 of file clauses.c.

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

Referenced by grouping_planner().

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

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

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

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

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

◆ get_agg_clause_costs_walker()

static bool get_agg_clause_costs_walker ( Node node,
get_agg_clause_costs_context context 
)
static

Definition at line 482 of file clauses.c.

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

Referenced by get_agg_clause_costs().

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

◆ get_leftop()

◆ get_notclausearg()

Expr* get_notclausearg ( Expr notclause)

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

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

Referenced by simplify_function().

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