PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
clauses.c File Reference
#include "postgres.h"
#include "access/htup_details.h"
#include "catalog/pg_aggregate.h"
#include "catalog/pg_class.h"
#include "catalog/pg_language.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "executor/executor.h"
#include "executor/functions.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
#include "optimizer/planmain.h"
#include "optimizer/prep.h"
#include "optimizer/var.h"
#include "parser/analyze.h"
#include "parser/parse_agg.h"
#include "parser/parse_coerce.h"
#include "parser/parse_func.h"
#include "rewrite/rewriteManip.h"
#include "tcop/tcopprot.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/datum.h"
#include "utils/fmgroids.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
Include dependency graph for clauses.c:

Go to the source code of this file.

Data Structures

struct  get_agg_clause_costs_context
 
struct  eval_const_expressions_context
 
struct  substitute_actual_parameters_context
 
struct  substitute_actual_srf_parameters_context
 
struct  inline_error_callback_arg
 
struct  max_parallel_hazard_context
 

Macros

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

Functions

static bool contain_agg_clause_walker (Node *node, void *context)
 
static bool get_agg_clause_costs_walker (Node *node, get_agg_clause_costs_context *context)
 
static bool find_window_functions_walker (Node *node, WindowFuncLists *lists)
 
static bool contain_subplans_walker (Node *node, void *context)
 
static bool contain_mutable_functions_walker (Node *node, void *context)
 
static bool contain_volatile_functions_walker (Node *node, void *context)
 
static bool contain_volatile_functions_not_nextval_walker (Node *node, void *context)
 
static bool max_parallel_hazard_walker (Node *node, max_parallel_hazard_context *context)
 
static bool contain_nonstrict_functions_walker (Node *node, void *context)
 
static bool contain_context_dependent_node (Node *clause)
 
static bool contain_context_dependent_node_walker (Node *node, int *flags)
 
static bool contain_leaked_vars_walker (Node *node, void *context)
 
static Relids find_nonnullable_rels_walker (Node *node, bool top_level)
 
static Listfind_nonnullable_vars_walker (Node *node, bool top_level)
 
static bool is_strict_saop (ScalarArrayOpExpr *expr, bool falseOK)
 
static Nodeeval_const_expressions_mutator (Node *node, eval_const_expressions_context *context)
 
static Listsimplify_or_arguments (List *args, eval_const_expressions_context *context, bool *haveNull, bool *forceTrue)
 
static Listsimplify_and_arguments (List *args, eval_const_expressions_context *context, bool *haveNull, bool *forceFalse)
 
static Nodesimplify_boolean_equality (Oid opno, List *args)
 
static Exprsimplify_function (Oid funcid, Oid result_type, int32 result_typmod, Oid result_collid, Oid input_collid, List **args_p, bool funcvariadic, bool process_args, bool allow_non_const, eval_const_expressions_context *context)
 
static Listexpand_function_arguments (List *args, Oid result_type, HeapTuple func_tuple)
 
static Listreorder_function_arguments (List *args, HeapTuple func_tuple)
 
static Listadd_function_defaults (List *args, HeapTuple func_tuple)
 
static Listfetch_function_defaults (HeapTuple func_tuple)
 
static void recheck_cast_function_args (List *args, Oid result_type, HeapTuple func_tuple)
 
static Exprevaluate_function (Oid funcid, Oid result_type, int32 result_typmod, Oid result_collid, Oid input_collid, List *args, bool funcvariadic, HeapTuple func_tuple, eval_const_expressions_context *context)
 
static Exprinline_function (Oid funcid, Oid result_type, Oid result_collid, Oid input_collid, List *args, bool funcvariadic, HeapTuple func_tuple, eval_const_expressions_context *context)
 
static Nodesubstitute_actual_parameters (Node *expr, int nargs, List *args, int *usecounts)
 
static Nodesubstitute_actual_parameters_mutator (Node *node, substitute_actual_parameters_context *context)
 
static void sql_inline_error_callback (void *arg)
 
static Exprevaluate_expr (Expr *expr, Oid result_type, int32 result_typmod, Oid result_collation)
 
static Querysubstitute_actual_srf_parameters (Query *expr, int nargs, List *args)
 
static Nodesubstitute_actual_srf_parameters_mutator (Node *node, substitute_actual_srf_parameters_context *context)
 
static bool tlist_matches_coltypelist (List *tlist, List *coltypelist)
 
Exprmake_opclause (Oid opno, Oid opresulttype, bool opretset, Expr *leftop, Expr *rightop, Oid opcollid, Oid inputcollid)
 
Nodeget_leftop (const Expr *clause)
 
Nodeget_rightop (const Expr *clause)
 
bool not_clause (Node *clause)
 
Exprmake_notclause (Expr *notclause)
 
Exprget_notclausearg (Expr *notclause)
 
bool or_clause (Node *clause)
 
Exprmake_orclause (List *orclauses)
 
bool and_clause (Node *clause)
 
Exprmake_andclause (List *andclauses)
 
Nodemake_and_qual (Node *qual1, Node *qual2)
 
Exprmake_ands_explicit (List *andclauses)
 
Listmake_ands_implicit (Expr *clause)
 
bool contain_agg_clause (Node *clause)
 
void get_agg_clause_costs (PlannerInfo *root, Node *clause, AggSplit aggsplit, AggClauseCosts *costs)
 
bool contain_window_function (Node *clause)
 
WindowFuncListsfind_window_functions (Node *clause, Index maxWinRef)
 
double expression_returns_set_rows (Node *clause)
 
bool contain_subplans (Node *clause)
 
bool contain_mutable_functions (Node *clause)
 
static bool contain_mutable_functions_checker (Oid func_id, void *context)
 
bool contain_volatile_functions (Node *clause)
 
static bool contain_volatile_functions_checker (Oid func_id, void *context)
 
bool contain_volatile_functions_not_nextval (Node *clause)
 
static bool contain_volatile_functions_not_nextval_checker (Oid func_id, void *context)
 
char max_parallel_hazard (Query *parse)
 
bool is_parallel_safe (PlannerInfo *root, Node *node)
 
static bool max_parallel_hazard_test (char proparallel, max_parallel_hazard_context *context)
 
static bool max_parallel_hazard_checker (Oid func_id, void *context)
 
bool contain_nonstrict_functions (Node *clause)
 
static bool contain_nonstrict_functions_checker (Oid func_id, void *context)
 
bool contain_leaked_vars (Node *clause)
 
static bool contain_leaked_vars_checker (Oid func_id, void *context)
 
Relids find_nonnullable_rels (Node *clause)
 
Listfind_nonnullable_vars (Node *clause)
 
Listfind_forced_null_vars (Node *node)
 
Varfind_forced_null_var (Node *node)
 
bool is_pseudo_constant_clause (Node *clause)
 
bool is_pseudo_constant_clause_relids (Node *clause, Relids relids)
 
int NumRelids (Node *clause)
 
void CommuteOpExpr (OpExpr *clause)
 
void CommuteRowCompareExpr (RowCompareExpr *clause)
 
static bool rowtype_field_matches (Oid rowtypeid, int fieldnum, Oid expectedtype, int32 expectedtypmod, Oid expectedcollation)
 
Nodeeval_const_expressions (PlannerInfo *root, Node *node)
 
Nodeestimate_expression_value (PlannerInfo *root, Node *node)
 
Queryinline_set_returning_function (PlannerInfo *root, RangeTblEntry *rte)
 

Macro Definition Documentation

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

Definition at line 1368 of file clauses.c.

Referenced by contain_context_dependent_node_walker().

Function Documentation

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

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

4043 {
4044  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4045  int nargsprovided = list_length(args);
4046  List *defaults;
4047  int ndelete;
4048 
4049  /* Get all the default expressions from the pg_proc tuple */
4050  defaults = fetch_function_defaults(func_tuple);
4051 
4052  /* Delete any unused defaults from the list */
4053  ndelete = nargsprovided + list_length(defaults) - funcform->pronargs;
4054  if (ndelete < 0)
4055  elog(ERROR, "not enough default arguments");
4056  while (ndelete-- > 0)
4057  defaults = list_delete_first(defaults);
4058 
4059  /* And form the combined argument list, not modifying the input list */
4060  return list_concat(list_copy(args), defaults);
4061 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
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:4067
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
bool and_clause ( Node clause)
void CommuteOpExpr ( OpExpr clause)

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

2199 {
2200  Oid opoid;
2201  Node *temp;
2202 
2203  /* Sanity checks: caller is at fault if these fail */
2204  if (!is_opclause(clause) ||
2205  list_length(clause->args) != 2)
2206  elog(ERROR, "cannot commute non-binary-operator clause");
2207 
2208  opoid = get_commutator(clause->opno);
2209 
2210  if (!OidIsValid(opoid))
2211  elog(ERROR, "could not find commutator for operator %u",
2212  clause->opno);
2213 
2214  /*
2215  * modify the clause in-place!
2216  */
2217  clause->opno = opoid;
2218  clause->opfuncid = InvalidOid;
2219  /* opresulttype, opretset, opcollid, inputcollid need not change */
2220 
2221  temp = linitial(clause->args);
2222  linitial(clause->args) = lsecond(clause->args);
2223  lsecond(clause->args) = temp;
2224 }
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1281
Definition: nodes.h:506
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:538
#define lsecond(l)
Definition: pg_list.h:114
#define linitial(l)
Definition: pg_list.h:110
#define ERROR
Definition: elog.h:43
#define is_opclause(clause)
Definition: clauses.h:20
Oid opfuncid
Definition: primnodes.h:496
#define InvalidOid
Definition: postgres_ext.h:36
static int list_length(const List *l)
Definition: pg_list.h:89
Oid opno
Definition: primnodes.h:495
#define elog
Definition: elog.h:219
List * args
Definition: primnodes.h:501
void CommuteRowCompareExpr ( RowCompareExpr clause)

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

2233 {
2234  List *newops;
2235  List *temp;
2236  ListCell *l;
2237 
2238  /* Sanity checks: caller is at fault if these fail */
2239  if (!IsA(clause, RowCompareExpr))
2240  elog(ERROR, "expected a RowCompareExpr");
2241 
2242  /* Build list of commuted operators */
2243  newops = NIL;
2244  foreach(l, clause->opnos)
2245  {
2246  Oid opoid = lfirst_oid(l);
2247 
2248  opoid = get_commutator(opoid);
2249  if (!OidIsValid(opoid))
2250  elog(ERROR, "could not find commutator for operator %u",
2251  lfirst_oid(l));
2252  newops = lappend_oid(newops, opoid);
2253  }
2254 
2255  /*
2256  * modify the clause in-place!
2257  */
2258  switch (clause->rctype)
2259  {
2260  case ROWCOMPARE_LT:
2261  clause->rctype = ROWCOMPARE_GT;
2262  break;
2263  case ROWCOMPARE_LE:
2264  clause->rctype = ROWCOMPARE_GE;
2265  break;
2266  case ROWCOMPARE_GE:
2267  clause->rctype = ROWCOMPARE_LE;
2268  break;
2269  case ROWCOMPARE_GT:
2270  clause->rctype = ROWCOMPARE_LT;
2271  break;
2272  default:
2273  elog(ERROR, "unexpected RowCompare type: %d",
2274  (int) clause->rctype);
2275  break;
2276  }
2277 
2278  clause->opnos = newops;
2279 
2280  /*
2281  * Note: we need not change the opfamilies list; we assume any btree
2282  * opfamily containing an operator will also contain its commutator.
2283  * Collations don't change either.
2284  */
2285 
2286  temp = clause->largs;
2287  clause->largs = clause->rargs;
2288  clause->rargs = temp;
2289 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:557
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1281
RowCompareType rctype
Definition: primnodes.h:1029
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:538
#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
bool contain_agg_clause ( Node clause)

Definition at line 416 of file clauses.c.

References contain_agg_clause_walker(), and NULL.

Referenced by get_eclass_for_sort_expr(), and subquery_planner().

417 {
418  return contain_agg_clause_walker(clause, NULL);
419 }
static bool contain_agg_clause_walker(Node *node, void *context)
Definition: clauses.c:422
#define NULL
Definition: c.h:229
static bool contain_agg_clause_walker ( Node node,
void *  context 
)
static

Definition at line 422 of file clauses.c.

References Assert, expression_tree_walker(), IsA, and NULL.

Referenced by contain_agg_clause().

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

Definition at line 1361 of file clauses.c.

References contain_context_dependent_node_walker().

Referenced by inline_function().

1362 {
1363  int flags = 0;
1364 
1365  return contain_context_dependent_node_walker(clause, &flags);
1366 }
static bool contain_context_dependent_node_walker(Node *node, int *flags)
Definition: clauses.c:1371
static bool contain_context_dependent_node_walker ( Node node,
int *  flags 
)
static

Definition at line 1371 of file clauses.c.

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

Referenced by contain_context_dependent_node().

1372 {
1373  if (node == NULL)
1374  return false;
1375  if (IsA(node, CaseTestExpr))
1376  return !(*flags & CCDN_IN_CASEEXPR);
1377  if (IsA(node, CaseExpr))
1378  {
1379  CaseExpr *caseexpr = (CaseExpr *) node;
1380 
1381  /*
1382  * If this CASE doesn't have a test expression, then it doesn't create
1383  * a context in which CaseTestExprs should appear, so just fall
1384  * through and treat it as a generic expression node.
1385  */
1386  if (caseexpr->arg)
1387  {
1388  int save_flags = *flags;
1389  bool res;
1390 
1391  /*
1392  * Note: in principle, we could distinguish the various sub-parts
1393  * of a CASE construct and set the flag bit only for some of them,
1394  * since we are only expecting CaseTestExprs to appear in the
1395  * "expr" subtree of the CaseWhen nodes. But it doesn't really
1396  * seem worth any extra code. If there are any bare CaseTestExprs
1397  * elsewhere in the CASE, something's wrong already.
1398  */
1399  *flags |= CCDN_IN_CASEEXPR;
1400  res = expression_tree_walker(node,
1402  (void *) flags);
1403  *flags = save_flags;
1404  return res;
1405  }
1406  }
1408  (void *) flags);
1409 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:557
#define CCDN_IN_CASEEXPR
Definition: clauses.c:1368
#define NULL
Definition: c.h:229
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1855
Expr * arg
Definition: primnodes.h:906
static bool contain_context_dependent_node_walker(Node *node, int *flags)
Definition: clauses.c:1371
bool contain_leaked_vars ( Node clause)

Definition at line 1427 of file clauses.c.

References contain_leaked_vars_walker(), and NULL.

Referenced by make_restrictinfo_internal(), and qual_is_pushdown_safe().

1428 {
1429  return contain_leaked_vars_walker(clause, NULL);
1430 }
#define NULL
Definition: c.h:229
static bool contain_leaked_vars_walker(Node *node, void *context)
Definition: clauses.c:1439
static bool contain_leaked_vars_checker ( Oid  func_id,
void *  context 
)
static

Definition at line 1433 of file clauses.c.

References get_func_leakproof().

Referenced by contain_leaked_vars_walker().

1434 {
1435  return !get_func_leakproof(func_id);
1436 }
bool get_func_leakproof(Oid funcid)
Definition: lsyscache.c:1590
static bool contain_leaked_vars_walker ( Node node,
void *  context 
)
static

Definition at line 1439 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, NULL, 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_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().

1440 {
1441  if (node == NULL)
1442  return false;
1443 
1444  switch (nodeTag(node))
1445  {
1446  case T_Var:
1447  case T_Const:
1448  case T_Param:
1449  case T_ArrayRef:
1450  case T_ArrayExpr:
1451  case T_FieldSelect:
1452  case T_FieldStore:
1453  case T_NamedArgExpr:
1454  case T_BoolExpr:
1455  case T_RelabelType:
1456  case T_CollateExpr:
1457  case T_CaseExpr:
1458  case T_CaseTestExpr:
1459  case T_RowExpr:
1460  case T_MinMaxExpr:
1461  case T_SQLValueFunction:
1462  case T_NullTest:
1463  case T_BooleanTest:
1464  case T_List:
1465 
1466  /*
1467  * We know these node types don't contain function calls; but
1468  * something further down in the node tree might.
1469  */
1470  break;
1471 
1472  case T_FuncExpr:
1473  case T_OpExpr:
1474  case T_DistinctExpr:
1475  case T_NullIfExpr:
1476  case T_ScalarArrayOpExpr:
1477  case T_CoerceViaIO:
1478  case T_ArrayCoerceExpr:
1479 
1480  /*
1481  * If node contains a leaky function call, and there's any Var
1482  * underneath it, reject.
1483  */
1485  context) &&
1486  contain_var_clause(node))
1487  return true;
1488  break;
1489 
1490  case T_RowCompareExpr:
1491  {
1492  /*
1493  * It's worth special-casing this because a leaky comparison
1494  * function only compromises one pair of row elements, which
1495  * might not contain Vars while others do.
1496  */
1497  RowCompareExpr *rcexpr = (RowCompareExpr *) node;
1498  ListCell *opid;
1499  ListCell *larg;
1500  ListCell *rarg;
1501 
1502  forthree(opid, rcexpr->opnos,
1503  larg, rcexpr->largs,
1504  rarg, rcexpr->rargs)
1505  {
1506  Oid funcid = get_opcode(lfirst_oid(opid));
1507 
1508  if (!get_func_leakproof(funcid) &&
1509  (contain_var_clause((Node *) lfirst(larg)) ||
1510  contain_var_clause((Node *) lfirst(rarg))))
1511  return true;
1512  }
1513  }
1514  break;
1515 
1516  case T_CurrentOfExpr:
1517 
1518  /*
1519  * WHERE CURRENT OF doesn't contain leaky function calls.
1520  * Moreover, it is essential that this is considered non-leaky,
1521  * since the planner must always generate a TID scan when CURRENT
1522  * OF is present -- c.f. cost_tidscan.
1523  */
1524  return false;
1525 
1526  default:
1527 
1528  /*
1529  * If we don't recognize the node tag, assume it might be leaky.
1530  * This prevents an unexpected security hole if someone adds a new
1531  * node type that can call a function.
1532  */
1533  return true;
1534  }
1536  context);
1537 }
bool get_func_leakproof(Oid funcid)
Definition: lsyscache.c:1590
#define forthree(cell1, list1, cell2, list2, cell3, list3)
Definition: pg_list.h:183
Definition: nodes.h:506
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:1663
Definition: nodes.h:288
Definition: nodes.h:145
Definition: nodes.h:144
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1062
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1855
#define nodeTag(nodeptr)
Definition: nodes.h:511
static bool contain_leaked_vars_checker(Oid func_id, void *context)
Definition: clauses.c:1433
static bool contain_leaked_vars_walker(Node *node, void *context)
Definition: clauses.c:1439
#define lfirst_oid(lc)
Definition: pg_list.h:108
Definition: nodes.h:146
bool contain_mutable_functions ( Node clause)

Definition at line 877 of file clauses.c.

References contain_mutable_functions_walker(), and NULL.

Referenced by check_index_predicates(), CheckMutability(), ComputePartitionAttrs(), create_bitmap_scan_plan(), create_indexscan_plan(), find_minmax_aggs_walker(), inline_function(), is_foreign_expr(), and relation_excluded_by_constraints().

878 {
879  return contain_mutable_functions_walker(clause, NULL);
880 }
static bool contain_mutable_functions_walker(Node *node, void *context)
Definition: clauses.c:889
#define NULL
Definition: c.h:229
static bool contain_mutable_functions_checker ( Oid  func_id,
void *  context 
)
static

Definition at line 883 of file clauses.c.

References func_volatile(), and PROVOLATILE_IMMUTABLE.

Referenced by contain_mutable_functions_walker().

884 {
885  return (func_volatile(func_id) != PROVOLATILE_IMMUTABLE);
886 }
#define PROVOLATILE_IMMUTABLE
Definition: pg_proc.h:5436
char func_volatile(Oid funcid)
Definition: lsyscache.c:1552
static bool contain_mutable_functions_walker ( Node node,
void *  context 
)
static

Definition at line 889 of file clauses.c.

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

Referenced by contain_mutable_functions().

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

Definition at line 1234 of file clauses.c.

References contain_nonstrict_functions_walker(), and NULL.

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

1235 {
1236  return contain_nonstrict_functions_walker(clause, NULL);
1237 }
static bool contain_nonstrict_functions_walker(Node *node, void *context)
Definition: clauses.c:1246
#define NULL
Definition: c.h:229
static bool contain_nonstrict_functions_checker ( Oid  func_id,
void *  context 
)
static

Definition at line 1240 of file clauses.c.

References func_strict().

Referenced by contain_nonstrict_functions_walker().

1241 {
1242  return !func_strict(func_id);
1243 }
bool func_strict(Oid funcid)
Definition: lsyscache.c:1533
static bool contain_nonstrict_functions_walker ( Node node,
void *  context 
)
static

Definition at line 1246 of file clauses.c.

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

Referenced by contain_nonstrict_functions().

1247 {
1248  if (node == NULL)
1249  return false;
1250  if (IsA(node, Aggref))
1251  {
1252  /* an aggregate could return non-null with null input */
1253  return true;
1254  }
1255  if (IsA(node, GroupingFunc))
1256  {
1257  /*
1258  * A GroupingFunc doesn't evaluate its arguments, and therefore must
1259  * be treated as nonstrict.
1260  */
1261  return true;
1262  }
1263  if (IsA(node, WindowFunc))
1264  {
1265  /* a window function could return non-null with null input */
1266  return true;
1267  }
1268  if (IsA(node, ArrayRef))
1269  {
1270  /* array assignment is nonstrict, but subscripting is strict */
1271  if (((ArrayRef *) node)->refassgnexpr != NULL)
1272  return true;
1273  /* else fall through to check args */
1274  }
1275  if (IsA(node, DistinctExpr))
1276  {
1277  /* IS DISTINCT FROM is inherently non-strict */
1278  return true;
1279  }
1280  if (IsA(node, NullIfExpr))
1281  {
1282  /* NULLIF is inherently non-strict */
1283  return true;
1284  }
1285  if (IsA(node, BoolExpr))
1286  {
1287  BoolExpr *expr = (BoolExpr *) node;
1288 
1289  switch (expr->boolop)
1290  {
1291  case AND_EXPR:
1292  case OR_EXPR:
1293  /* AND, OR are inherently non-strict */
1294  return true;
1295  default:
1296  break;
1297  }
1298  }
1299  if (IsA(node, SubLink))
1300  {
1301  /* In some cases a sublink might be strict, but in general not */
1302  return true;
1303  }
1304  if (IsA(node, SubPlan))
1305  return true;
1306  if (IsA(node, AlternativeSubPlan))
1307  return true;
1308  if (IsA(node, FieldStore))
1309  return true;
1310  if (IsA(node, CaseExpr))
1311  return true;
1312  if (IsA(node, ArrayExpr))
1313  return true;
1314  if (IsA(node, RowExpr))
1315  return true;
1316  if (IsA(node, RowCompareExpr))
1317  return true;
1318  if (IsA(node, CoalesceExpr))
1319  return true;
1320  if (IsA(node, MinMaxExpr))
1321  return true;
1322  if (IsA(node, XmlExpr))
1323  return true;
1324  if (IsA(node, NullTest))
1325  return true;
1326  if (IsA(node, BooleanTest))
1327  return true;
1328 
1329  /*
1330  * Check other function-containing nodes; but ArrayCoerceExpr is strict at
1331  * the array level, regardless of elemfunc.
1332  */
1333  if (!IsA(node, ArrayCoerceExpr) &&
1335  context))
1336  return true;
1338  context);
1339 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:557
static bool contain_nonstrict_functions_walker(Node *node, void *context)
Definition: clauses.c:1246
bool check_functions_in_node(Node *node, check_function_callback checker, void *context)
Definition: nodeFuncs.c:1663
BoolExprType boolop
Definition: primnodes.h:561
#define NULL
Definition: c.h:229
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1855
static bool contain_nonstrict_functions_checker(Oid func_id, void *context)
Definition: clauses.c:1240
bool contain_subplans ( Node clause)

Definition at line 842 of file clauses.c.

References contain_subplans_walker(), and NULL.

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

843 {
844  return contain_subplans_walker(clause, NULL);
845 }
#define NULL
Definition: c.h:229
static bool contain_subplans_walker(Node *node, void *context)
Definition: clauses.c:848
static bool contain_subplans_walker ( Node node,
void *  context 
)
static

Definition at line 848 of file clauses.c.

References expression_tree_walker(), IsA, and NULL.

Referenced by contain_subplans().

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

Definition at line 956 of file clauses.c.

References func_volatile(), and PROVOLATILE_VOLATILE.

Referenced by contain_volatile_functions_walker().

957 {
958  return (func_volatile(func_id) == PROVOLATILE_VOLATILE);
959 }
#define PROVOLATILE_VOLATILE
Definition: pg_proc.h:5438
char func_volatile(Oid funcid)
Definition: lsyscache.c:1552
bool contain_volatile_functions_not_nextval ( Node clause)

Definition at line 994 of file clauses.c.

References contain_volatile_functions_not_nextval_walker(), and NULL.

Referenced by BeginCopyFrom().

995 {
997 }
static bool contain_volatile_functions_not_nextval_walker(Node *node, void *context)
Definition: clauses.c:1007
#define NULL
Definition: c.h:229
static bool contain_volatile_functions_not_nextval_checker ( Oid  func_id,
void *  context 
)
static

Definition at line 1000 of file clauses.c.

References func_volatile(), and PROVOLATILE_VOLATILE.

Referenced by contain_volatile_functions_not_nextval_walker().

1001 {
1002  return (func_id != F_NEXTVAL_OID &&
1003  func_volatile(func_id) == PROVOLATILE_VOLATILE);
1004 }
#define PROVOLATILE_VOLATILE
Definition: pg_proc.h:5438
char func_volatile(Oid funcid)
Definition: lsyscache.c:1552
static bool contain_volatile_functions_not_nextval_walker ( Node node,
void *  context 
)
static

Definition at line 1007 of file clauses.c.

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

Referenced by contain_volatile_functions_not_nextval().

1008 {
1009  if (node == NULL)
1010  return false;
1011  /* Check for volatile functions in node itself */
1012  if (check_functions_in_node(node,
1014  context))
1015  return true;
1016 
1017  /*
1018  * See notes in contain_mutable_functions_walker about why we treat
1019  * MinMaxExpr, XmlExpr, and CoerceToDomain as immutable, while
1020  * SQLValueFunction is stable. Hence, none of them are of interest here.
1021  */
1022 
1023  /* Recurse to check arguments */
1024  if (IsA(node, Query))
1025  {
1026  /* Recurse into subselects */
1027  return query_tree_walker((Query *) node,
1029  context, 0);
1030  }
1031  return expression_tree_walker(node,
1033  context);
1034 }
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2257
#define IsA(nodeptr, _type_)
Definition: nodes.h:557
static bool contain_volatile_functions_not_nextval_walker(Node *node, void *context)
Definition: clauses.c:1007
bool check_functions_in_node(Node *node, check_function_callback checker, void *context)
Definition: nodeFuncs.c:1663
#define NULL
Definition: c.h:229
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1855
static bool contain_volatile_functions_not_nextval_checker(Oid func_id, void *context)
Definition: clauses.c:1000
static bool contain_volatile_functions_walker ( Node node,
void *  context 
)
static

Definition at line 962 of file clauses.c.

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

Referenced by contain_volatile_functions().

963 {
964  if (node == NULL)
965  return false;
966  /* Check for volatile functions in node itself */
968  context))
969  return true;
970 
971  /*
972  * See notes in contain_mutable_functions_walker about why we treat
973  * MinMaxExpr, XmlExpr, and CoerceToDomain as immutable, while
974  * SQLValueFunction is stable. Hence, none of them are of interest here.
975  */
976 
977  /* Recurse to check arguments */
978  if (IsA(node, Query))
979  {
980  /* Recurse into subselects */
981  return query_tree_walker((Query *) node,
983  context, 0);
984  }
986  context);
987 }
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2257
#define IsA(nodeptr, _type_)
Definition: nodes.h:557
bool check_functions_in_node(Node *node, check_function_callback checker, void *context)
Definition: nodeFuncs.c:1663
static bool contain_volatile_functions_walker(Node *node, void *context)
Definition: clauses.c:962
#define NULL
Definition: c.h:229
static bool contain_volatile_functions_checker(Oid func_id, void *context)
Definition: clauses.c:956
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1855
bool contain_window_function ( Node clause)

Definition at line 726 of file clauses.c.

References contain_windowfuncs().

Referenced by get_eclass_for_sort_expr(), and qual_is_pushdown_safe().

727 {
728  return contain_windowfuncs(clause);
729 }
bool contain_windowfuncs(Node *node)
Definition: rewriteManip.c:197
Node* estimate_expression_value ( PlannerInfo root,
Node node 
)

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

2400 {
2402 
2403  context.boundParams = root->glob->boundParams; /* bound Params */
2404  /* we do not need to mark the plan as depending on inlined functions */
2405  context.root = NULL;
2406  context.active_fns = NIL; /* nothing being recursively simplified */
2407  context.case_val = NULL; /* no CASE being examined */
2408  context.estimate = true; /* unsafe transformations OK */
2409  return eval_const_expressions_mutator(node, &context);
2410 }
#define NIL
Definition: pg_list.h:69
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2413
ParamListInfo boundParams
Definition: clauses.c:65
PlannerGlobal * glob
Definition: relation.h:156
#define NULL
Definition: c.h:229
ParamListInfo boundParams
Definition: relation.h:96
Node* eval_const_expressions ( PlannerInfo root,
Node node 
)

Definition at line 2366 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, NULL, and eval_const_expressions_context::root.

Referenced by ATExecAttachPartition(), convert_EXISTS_to_ANY(), expression_planner(), get_relation_constraints(), inline_set_returning_function(), preprocess_expression(), process_implied_equality(), RelationBuildPartitionKey(), RelationGetIndexExpressions(), RelationGetIndexPredicate(), set_append_rel_size(), and simplify_EXISTS_query().

2367 {
2369 
2370  if (root)
2371  context.boundParams = root->glob->boundParams; /* bound Params */
2372  else
2373  context.boundParams = NULL;
2374  context.root = root; /* for inlined-function dependencies */
2375  context.active_fns = NIL; /* nothing being recursively simplified */
2376  context.case_val = NULL; /* no CASE being examined */
2377  context.estimate = false; /* safe transformations only */
2378  return eval_const_expressions_mutator(node, &context);
2379 }
#define NIL
Definition: pg_list.h:69
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2413
ParamListInfo boundParams
Definition: clauses.c:65
PlannerGlobal * glob
Definition: relation.h:156
#define NULL
Definition: c.h:229
ParamListInfo boundParams
Definition: relation.h:96
static Node * eval_const_expressions_mutator ( Node node,
eval_const_expressions_context context 
)
static

Definition at line 2413 of file clauses.c.

References WindowFunc::aggfilter, AND_EXPR, arg, FieldSelect::arg, RelabelType::arg, CoerceViaIO::arg, ArrayCoerceExpr::arg, CollateExpr::arg, CaseExpr::arg, NullTest::arg, BooleanTest::arg, NullTest::argisrow, generate_unaccent_rules::args, WindowFunc::args, FuncExpr::args, OpExpr::args, BoolExpr::args, CaseExpr::args, RowExpr::args, CoalesceExpr::args, ArrayExpr::array_collid, ArrayExpr::array_typeid, Assert, BooleanEqualOperator, BooleanNotEqualOperator, BoolGetDatum, BoolExpr::boolop, BooleanTest::booltesttype, eval_const_expressions_context::boundParams, eval_const_expressions_context::case_val, CaseExpr::casecollid, CaseExpr::casetype, castNode, CoalesceExpr::coalescecollid, CoalesceExpr::coalescetype, COERCE_IMPLICIT_CAST, CoerceViaIO::coerceformat, ArrayCoerceExpr::coerceformat, CollateExpr::collOid, Const::constcollid, Const::constisnull, Const::consttype, Const::consttypmod, Const::constvalue, copyObject, CSTRINGOID, datumCopy(), DatumGetBool, CaseExpr::defresult, element(), ArrayExpr::element_typeid, ArrayExpr::elements, ArrayCoerceExpr::elemfuncid, elog, ERROR, eval_const_expressions_context::estimate, evaluate_expr(), expand_function_arguments(), CaseWhen::expr, exprCollation(), expression_tree_mutator(), exprType(), exprTypmod(), FieldSelect::fieldnum, func_volatile(), 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, ArrayCoerceExpr::isExplicit, ParamExternData::isnull, lappend(), lfirst, linitial, list_length(), list_make1, list_make3, list_nth(), WindowFunc::location, FuncExpr::location, OpExpr::location, RelabelType::location, CoerceViaIO::location, ArrayCoerceExpr::location, CollateExpr::location, CaseExpr::location, CaseWhen::location, ArrayExpr::location, CoalesceExpr::location, NullTest::location, BooleanTest::location, make_andclause(), make_orclause(), makeBoolConst(), makeConst(), makeNode, makeNullConst(), makeVar(), ArrayExpr::multidims, negate_clause(), NIL, nodeTag, NOT_EXPR, NULL, NullTest::nulltesttype, ParamListInfoData::numParams, ObjectIdGetDatum, OidIsValid, OIDOID, OpExpr::opcollid, OpExpr::opfuncid, OpExpr::opno, OpExpr::opresulttype, OpExpr::opretset, OR_EXPR, PARAM_EXTERN, PARAM_FLAG_CONST, Param::paramcollid, Param::paramid, Param::paramkind, ParamListInfoData::params, Param::paramtype, Param::paramtypmod, ParamExternData::pflags, PlaceHolderVar::phexpr, PROCOID, PROVOLATILE_IMMUTABLE, ParamExternData::ptype, RelabelType::relabelformat, ReleaseSysCache(), CaseWhen::result, result, FieldSelect::resultcollid, RelabelType::resultcollid, CoerceViaIO::resultcollid, ArrayCoerceExpr::resultcollid, FieldSelect::resulttype, RelabelType::resulttype, CoerceViaIO::resulttype, ArrayCoerceExpr::resulttype, FieldSelect::resulttypmod, RelabelType::resulttypmod, ArrayCoerceExpr::resulttypmod, RowExpr::row_typeid, rowtype_field_matches(), SearchSysCache1, set_opfuncid(), simplify_and_arguments(), simplify_boolean_equality(), simplify_function(), simplify_or_arguments(), T_AlternativeSubPlan, T_ArrayCoerceExpr, T_ArrayExpr, T_BooleanTest, T_BoolExpr, T_CaseExpr, T_CaseTestExpr, T_CoalesceExpr, T_CoerceViaIO, T_CollateExpr, T_DistinctExpr, T_FieldSelect, T_FuncExpr, T_NullTest, T_OpExpr, T_Param, T_PlaceHolderVar, T_RelabelType, T_SQLValueFunction, T_SubPlan, T_WindowFunc, SQLValueFunction::type, SQLValueFunction::typmod, 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().

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

Definition at line 4644 of file clauses.c.

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

Referenced by eval_const_expressions_mutator(), and evaluate_function().

4646 {
4647  EState *estate;
4648  ExprState *exprstate;
4649  MemoryContext oldcontext;
4650  Datum const_val;
4651  bool const_is_null;
4652  int16 resultTypLen;
4653  bool resultTypByVal;
4654 
4655  /*
4656  * To use the executor, we need an EState.
4657  */
4658  estate = CreateExecutorState();
4659 
4660  /* We can use the estate's working context to avoid memory leaks. */
4661  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
4662 
4663  /* Make sure any opfuncids are filled in. */
4664  fix_opfuncids((Node *) expr);
4665 
4666  /*
4667  * Prepare expr for execution. (Note: we can't use ExecPrepareExpr
4668  * because it'd result in recursively invoking eval_const_expressions.)
4669  */
4670  exprstate = ExecInitExpr(expr, NULL);
4671 
4672  /*
4673  * And evaluate it.
4674  *
4675  * It is OK to use a default econtext because none of the ExecEvalExpr()
4676  * code used in this situation will use econtext. That might seem
4677  * fortuitous, but it's not so unreasonable --- a constant expression does
4678  * not depend on context, by definition, n'est ce pas?
4679  */
4680  const_val = ExecEvalExprSwitchContext(exprstate,
4681  GetPerTupleExprContext(estate),
4682  &const_is_null);
4683 
4684  /* Get info needed about result datatype */
4685  get_typlenbyval(result_type, &resultTypLen, &resultTypByVal);
4686 
4687  /* Get back to outer memory context */
4688  MemoryContextSwitchTo(oldcontext);
4689 
4690  /*
4691  * Must copy result out of sub-context used by expression eval.
4692  *
4693  * Also, if it's varlena, forcibly detoast it. This protects us against
4694  * storing TOAST pointers into plans that might outlive the referenced
4695  * data. (makeConst would handle detoasting anyway, but it's worth a few
4696  * extra lines here so that we can do the copy and detoast in one step.)
4697  */
4698  if (!const_is_null)
4699  {
4700  if (resultTypLen == -1)
4701  const_val = PointerGetDatum(PG_DETOAST_DATUM_COPY(const_val));
4702  else
4703  const_val = datumCopy(const_val, resultTypByVal, resultTypLen);
4704  }
4705 
4706  /* Release all the junk we just created */
4707  FreeExecutorState(estate);
4708 
4709  /*
4710  * Make the constant result node.
4711  */
4712  return (Expr *) makeConst(result_type, result_typmod, result_collation,
4713  resultTypLen,
4714  const_val, const_is_null,
4715  resultTypByVal);
4716 }
signed short int16
Definition: c.h:255
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:281
#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:1594
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Definition: nodes.h:506
Const * makeConst(Oid consttype, int32 consttypmod, Oid constcollid, int constlen, Datum constvalue, bool constisnull, bool constbyval)
Definition: makefuncs.c:296
void FreeExecutorState(EState *estate)
Definition: execUtils.c:173
#define GetPerTupleExprContext(estate)
Definition: executor.h:456
MemoryContext es_query_cxt
Definition: execnodes.h:435
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:128
EState * CreateExecutorState(void)
Definition: execUtils.c:77
uintptr_t Datum
Definition: postgres.h:372
#define NULL
Definition: c.h:229
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:1969
ExprState * ExecInitExpr(Expr *node, PlanState *parent)
Definition: execExpr.c:113
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 4146 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(), NULL, PROVOLATILE_IMMUTABLE, PROVOLATILE_STABLE, and RECORDOID.

Referenced by simplify_function().

4151 {
4152  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4153  bool has_nonconst_input = false;
4154  bool has_null_input = false;
4155  ListCell *arg;
4156  FuncExpr *newexpr;
4157 
4158  /*
4159  * Can't simplify if it returns a set.
4160  */
4161  if (funcform->proretset)
4162  return NULL;
4163 
4164  /*
4165  * Can't simplify if it returns RECORD. The immediate problem is that it
4166  * will be needing an expected tupdesc which we can't supply here.
4167  *
4168  * In the case where it has OUT parameters, it could get by without an
4169  * expected tupdesc, but we still have issues: get_expr_result_type()
4170  * doesn't know how to extract type info from a RECORD constant, and in
4171  * the case of a NULL function result there doesn't seem to be any clean
4172  * way to fix that. In view of the likelihood of there being still other
4173  * gotchas, seems best to leave the function call unreduced.
4174  */
4175  if (funcform->prorettype == RECORDOID)
4176  return NULL;
4177 
4178  /*
4179  * Check for constant inputs and especially constant-NULL inputs.
4180  */
4181  foreach(arg, args)
4182  {
4183  if (IsA(lfirst(arg), Const))
4184  has_null_input |= ((Const *) lfirst(arg))->constisnull;
4185  else
4186  has_nonconst_input = true;
4187  }
4188 
4189  /*
4190  * If the function is strict and has a constant-NULL input, it will never
4191  * be called at all, so we can replace the call by a NULL constant, even
4192  * if there are other inputs that aren't constant, and even if the
4193  * function is not otherwise immutable.
4194  */
4195  if (funcform->proisstrict && has_null_input)
4196  return (Expr *) makeNullConst(result_type, result_typmod,
4197  result_collid);
4198 
4199  /*
4200  * Otherwise, can simplify only if all inputs are constants. (For a
4201  * non-strict function, constant NULL inputs are treated the same as
4202  * constant non-NULL inputs.)
4203  */
4204  if (has_nonconst_input)
4205  return NULL;
4206 
4207  /*
4208  * Ordinarily we are only allowed to simplify immutable functions. But for
4209  * purposes of estimation, we consider it okay to simplify functions that
4210  * are merely stable; the risk that the result might change from planning
4211  * time to execution time is worth taking in preference to not being able
4212  * to estimate the value at all.
4213  */
4214  if (funcform->provolatile == PROVOLATILE_IMMUTABLE)
4215  /* okay */ ;
4216  else if (context->estimate && funcform->provolatile == PROVOLATILE_STABLE)
4217  /* okay */ ;
4218  else
4219  return NULL;
4220 
4221  /*
4222  * OK, looks like we can simplify this operator/function.
4223  *
4224  * Build a new FuncExpr node containing the already-simplified arguments.
4225  */
4226  newexpr = makeNode(FuncExpr);
4227  newexpr->funcid = funcid;
4228  newexpr->funcresulttype = result_type;
4229  newexpr->funcretset = false;
4230  newexpr->funcvariadic = funcvariadic;
4231  newexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
4232  newexpr->funccollid = result_collid; /* doesn't matter */
4233  newexpr->inputcollid = input_collid;
4234  newexpr->args = args;
4235  newexpr->location = -1;
4236 
4237  return evaluate_expr((Expr *) newexpr, result_type, result_typmod,
4238  result_collid);
4239 }
Oid funcresulttype
Definition: primnodes.h:449
#define IsA(nodeptr, _type_)
Definition: nodes.h:557
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
static Expr * evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod, Oid result_collation)
Definition: clauses.c:4644
#define PROVOLATILE_IMMUTABLE
Definition: pg_proc.h:5436
List * args
Definition: primnodes.h:456
Oid funccollid
Definition: primnodes.h:454
bool funcretset
Definition: primnodes.h:450
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:334
CoercionForm funcformat
Definition: primnodes.h:453
Oid funcid
Definition: primnodes.h:448
#define PROVOLATILE_STABLE
Definition: pg_proc.h:5437
#define RECORDOID
Definition: pg_type.h:676
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:83
#define makeNode(_type_)
Definition: nodes.h:554
Oid inputcollid
Definition: primnodes.h:455
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
void * arg
int location
Definition: primnodes.h:457
bool funcvariadic
Definition: primnodes.h:451
static List * expand_function_arguments ( List args,
Oid  result_type,
HeapTuple  func_tuple 
)
static

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

3930 {
3931  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
3932  bool has_named_args = false;
3933  ListCell *lc;
3934 
3935  /* Do we have any named arguments? */
3936  foreach(lc, args)
3937  {
3938  Node *arg = (Node *) lfirst(lc);
3939 
3940  if (IsA(arg, NamedArgExpr))
3941  {
3942  has_named_args = true;
3943  break;
3944  }
3945  }
3946 
3947  /* If so, we must apply reorder_function_arguments */
3948  if (has_named_args)
3949  {
3950  args = reorder_function_arguments(args, func_tuple);
3951  /* Recheck argument types and add casts if needed */
3952  recheck_cast_function_args(args, result_type, func_tuple);
3953  }
3954  else if (list_length(args) < funcform->pronargs)
3955  {
3956  /* No named args, but we seem to be short some defaults */
3957  args = add_function_defaults(args, func_tuple);
3958  /* Recheck argument types and add casts if needed */
3959  recheck_cast_function_args(args, result_type, func_tuple);
3960  }
3961 
3962  return args;
3963 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:557
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
Definition: nodes.h:506
static void recheck_cast_function_args(List *args, Oid result_type, HeapTuple func_tuple)
Definition: clauses.c:4102
static List * add_function_defaults(List *args, HeapTuple func_tuple)
Definition: clauses.c:4042
static List * reorder_function_arguments(List *args, HeapTuple func_tuple)
Definition: clauses.c:3972
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
double expression_returns_set_rows ( Node clause)

Definition at line 801 of file clauses.c.

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

Referenced by create_set_projection_path(), and set_function_size_estimates().

802 {
803  if (clause == NULL)
804  return 1.0;
805  if (IsA(clause, FuncExpr))
806  {
807  FuncExpr *expr = (FuncExpr *) clause;
808 
809  if (expr->funcretset)
810  return clamp_row_est(get_func_rows(expr->funcid));
811  }
812  if (IsA(clause, OpExpr))
813  {
814  OpExpr *expr = (OpExpr *) clause;
815 
816  if (expr->opretset)
817  {
818  set_opfuncid(expr);
819  return clamp_row_est(get_func_rows(expr->opfuncid));
820  }
821  }
822  return 1.0;
823 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:557
float4 get_func_rows(Oid funcid)
Definition: lsyscache.c:1628
bool funcretset
Definition: primnodes.h:450
Oid funcid
Definition: primnodes.h:448
Oid opfuncid
Definition: primnodes.h:496
#define NULL
Definition: c.h:229
void set_opfuncid(OpExpr *opexpr)
Definition: nodeFuncs.c:1625
double clamp_row_est(double nrows)
Definition: costsize.c:173
bool opretset
Definition: primnodes.h:498
static List * fetch_function_defaults ( HeapTuple  func_tuple)
static

Definition at line 4067 of file clauses.c.

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

Referenced by add_function_defaults(), and reorder_function_arguments().

4068 {
4069  List *defaults;
4070  Datum proargdefaults;
4071  bool isnull;
4072  char *str;
4073 
4074  /* The error cases here shouldn't happen, but check anyway */
4075  proargdefaults = SysCacheGetAttr(PROCOID, func_tuple,
4077  &isnull);
4078  if (isnull)
4079  elog(ERROR, "not enough default arguments");
4080  str = TextDatumGetCString(proargdefaults);
4081  defaults = castNode(List, stringToNode(str));
4082  pfree(str);
4083  return defaults;
4084 }
void * stringToNode(char *str)
Definition: read.c:38
#define castNode(_type_, nodeptr)
Definition: nodes.h:575
void pfree(void *pointer)
Definition: mcxt.c:950
#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:1278
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
Var* find_forced_null_var ( Node node)

Definition at line 2031 of file clauses.c.

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

Referenced by check_redundant_nullability_qual(), and find_forced_null_vars().

2032 {
2033  if (node == NULL)
2034  return NULL;
2035  if (IsA(node, NullTest))
2036  {
2037  /* check for var IS NULL */
2038  NullTest *expr = (NullTest *) node;
2039 
2040  if (expr->nulltesttype == IS_NULL && !expr->argisrow)
2041  {
2042  Var *var = (Var *) expr->arg;
2043 
2044  if (var && IsA(var, Var) &&
2045  var->varlevelsup == 0)
2046  return var;
2047  }
2048  }
2049  else if (IsA(node, BooleanTest))
2050  {
2051  /* var IS UNKNOWN is equivalent to var IS NULL */
2052  BooleanTest *expr = (BooleanTest *) node;
2053 
2054  if (expr->booltesttype == IS_UNKNOWN)
2055  {
2056  Var *var = (Var *) expr->arg;
2057 
2058  if (var && IsA(var, Var) &&
2059  var->varlevelsup == 0)
2060  return var;
2061  }
2062  }
2063  return NULL;
2064 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:557
Index varlevelsup
Definition: primnodes.h:173
Definition: primnodes.h:163
Expr * arg
Definition: primnodes.h:1178
Expr * arg
Definition: primnodes.h:1201
BoolTestType booltesttype
Definition: primnodes.h:1202
NullTestType nulltesttype
Definition: primnodes.h:1179
#define NULL
Definition: c.h:229
bool argisrow
Definition: primnodes.h:1180
List* find_forced_null_vars ( Node node)

Definition at line 1972 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, NIL, NULL, and result.

Referenced by find_forced_null_vars(), and reduce_outer_joins_pass2().

1973 {
1974  List *result = NIL;
1975  Var *var;
1976  ListCell *l;
1977 
1978  if (node == NULL)
1979  return NIL;
1980  /* Check single-clause cases using subroutine */
1981  var = find_forced_null_var(node);
1982  if (var)
1983  {
1984  result = list_make1(var);
1985  }
1986  /* Otherwise, handle AND-conditions */
1987  else if (IsA(node, List))
1988  {
1989  /*
1990  * At top level, we are examining an implicit-AND list: if any of the
1991  * arms produces FALSE-or-NULL then the result is FALSE-or-NULL.
1992  */
1993  foreach(l, (List *) node)
1994  {
1995  result = list_concat(result,
1997  }
1998  }
1999  else if (IsA(node, BoolExpr))
2000  {
2001  BoolExpr *expr = (BoolExpr *) node;
2002 
2003  /*
2004  * We don't bother considering the OR case, because it's fairly
2005  * unlikely anyone would write "v1 IS NULL OR v1 IS NULL". Likewise,
2006  * the NOT case isn't worth expending code on.
2007  */
2008  if (expr->boolop == AND_EXPR)
2009  {
2010  /* At top level we can just recurse (to the List case) */
2011  result = find_forced_null_vars((Node *) expr->args);
2012  }
2013  }
2014  return result;
2015 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:557
Definition: nodes.h:506
List * list_concat(List *list1, List *list2)
Definition: list.c:321
return result
Definition: formatting.c:1618
Definition: primnodes.h:163
List * find_forced_null_vars(Node *node)
Definition: clauses.c:1972
#define list_make1(x1)
Definition: pg_list.h:133
BoolExprType boolop
Definition: primnodes.h:561
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
List * args
Definition: primnodes.h:562
Definition: pg_list.h:45
Var * find_forced_null_var(Node *node)
Definition: clauses.c:2031
Relids find_nonnullable_rels ( Node clause)

Definition at line 1571 of file clauses.c.

References find_nonnullable_rels_walker().

Referenced by make_outerjoininfo(), and reduce_outer_joins_pass2().

1572 {
1573  return find_nonnullable_rels_walker(clause, true);
1574 }
static Relids find_nonnullable_rels_walker(Node *node, bool top_level)
Definition: clauses.c:1577
static Relids find_nonnullable_rels_walker ( Node node,
bool  top_level 
)
static

Definition at line 1577 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, NULL, NullTest::nulltesttype, OpExpr::opfuncid, OR_EXPR, PlaceHolderVar::phexpr, result, set_opfuncid(), Var::varlevelsup, and Var::varno.

Referenced by find_nonnullable_rels().

1578 {
1579  Relids result = NULL;
1580  ListCell *l;
1581 
1582  if (node == NULL)
1583  return NULL;
1584  if (IsA(node, Var))
1585  {
1586  Var *var = (Var *) node;
1587 
1588  if (var->varlevelsup == 0)
1589  result = bms_make_singleton(var->varno);
1590  }
1591  else if (IsA(node, List))
1592  {
1593  /*
1594  * At top level, we are examining an implicit-AND list: if any of the
1595  * arms produces FALSE-or-NULL then the result is FALSE-or-NULL. If
1596  * not at top level, we are examining the arguments of a strict
1597  * function: if any of them produce NULL then the result of the
1598  * function must be NULL. So in both cases, the set of nonnullable
1599  * rels is the union of those found in the arms, and we pass down the
1600  * top_level flag unmodified.
1601  */
1602  foreach(l, (List *) node)
1603  {
1604  result = bms_join(result,
1606  top_level));
1607  }
1608  }
1609  else if (IsA(node, FuncExpr))
1610  {
1611  FuncExpr *expr = (FuncExpr *) node;
1612 
1613  if (func_strict(expr->funcid))
1614  result = find_nonnullable_rels_walker((Node *) expr->args, false);
1615  }
1616  else if (IsA(node, OpExpr))
1617  {
1618  OpExpr *expr = (OpExpr *) node;
1619 
1620  set_opfuncid(expr);
1621  if (func_strict(expr->opfuncid))
1622  result = find_nonnullable_rels_walker((Node *) expr->args, false);
1623  }
1624  else if (IsA(node, ScalarArrayOpExpr))
1625  {
1626  ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1627 
1628  if (is_strict_saop(expr, true))
1629  result = find_nonnullable_rels_walker((Node *) expr->args, false);
1630  }
1631  else if (IsA(node, BoolExpr))
1632  {
1633  BoolExpr *expr = (BoolExpr *) node;
1634 
1635  switch (expr->boolop)
1636  {
1637  case AND_EXPR:
1638  /* At top level we can just recurse (to the List case) */
1639  if (top_level)
1640  {
1641  result = find_nonnullable_rels_walker((Node *) expr->args,
1642  top_level);
1643  break;
1644  }
1645 
1646  /*
1647  * Below top level, even if one arm produces NULL, the result
1648  * could be FALSE (hence not NULL). However, if *all* the
1649  * arms produce NULL then the result is NULL, so we can take
1650  * the intersection of the sets of nonnullable rels, just as
1651  * for OR. Fall through to share code.
1652  */
1653  /* FALL THRU */
1654  case OR_EXPR:
1655 
1656  /*
1657  * OR is strict if all of its arms are, so we can take the
1658  * intersection of the sets of nonnullable rels for each arm.
1659  * This works for both values of top_level.
1660  */
1661  foreach(l, expr->args)
1662  {
1663  Relids subresult;
1664 
1665  subresult = find_nonnullable_rels_walker(lfirst(l),
1666  top_level);
1667  if (result == NULL) /* first subresult? */
1668  result = subresult;
1669  else
1670  result = bms_int_members(result, subresult);
1671 
1672  /*
1673  * If the intersection is empty, we can stop looking. This
1674  * also justifies the test for first-subresult above.
1675  */
1676  if (bms_is_empty(result))
1677  break;
1678  }
1679  break;
1680  case NOT_EXPR:
1681  /* NOT will return null if its arg is null */
1682  result = find_nonnullable_rels_walker((Node *) expr->args,
1683  false);
1684  break;
1685  default:
1686  elog(ERROR, "unrecognized boolop: %d", (int) expr->boolop);
1687  break;
1688  }
1689  }
1690  else if (IsA(node, RelabelType))
1691  {
1692  RelabelType *expr = (RelabelType *) node;
1693 
1694  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1695  }
1696  else if (IsA(node, CoerceViaIO))
1697  {
1698  /* not clear this is useful, but it can't hurt */
1699  CoerceViaIO *expr = (CoerceViaIO *) node;
1700 
1701  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1702  }
1703  else if (IsA(node, ArrayCoerceExpr))
1704  {
1705  /* ArrayCoerceExpr is strict at the array level */
1706  ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
1707 
1708  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1709  }
1710  else if (IsA(node, ConvertRowtypeExpr))
1711  {
1712  /* not clear this is useful, but it can't hurt */
1713  ConvertRowtypeExpr *expr = (ConvertRowtypeExpr *) node;
1714 
1715  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1716  }
1717  else if (IsA(node, CollateExpr))
1718  {
1719  CollateExpr *expr = (CollateExpr *) node;
1720 
1721  result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1722  }
1723  else if (IsA(node, NullTest))
1724  {
1725  /* IS NOT NULL can be considered strict, but only at top level */
1726  NullTest *expr = (NullTest *) node;
1727 
1728  if (top_level && expr->nulltesttype == IS_NOT_NULL && !expr->argisrow)
1729  result = find_nonnullable_rels_walker((Node *) expr->arg, false);
1730  }
1731  else if (IsA(node, BooleanTest))
1732  {
1733  /* Boolean tests that reject NULL are strict at top level */
1734  BooleanTest *expr = (BooleanTest *) node;
1735 
1736  if (top_level &&
1737  (expr->booltesttype == IS_TRUE ||
1738  expr->booltesttype == IS_FALSE ||
1739  expr->booltesttype == IS_NOT_UNKNOWN))
1740  result = find_nonnullable_rels_walker((Node *) expr->arg, false);
1741  }
1742  else if (IsA(node, PlaceHolderVar))
1743  {
1744  PlaceHolderVar *phv = (PlaceHolderVar *) node;
1745 
1746  result = find_nonnullable_rels_walker((Node *) phv->phexpr, top_level);
1747  }
1748  return result;
1749 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:557
Index varlevelsup
Definition: primnodes.h:173
List * args
Definition: primnodes.h:456
Expr * arg
Definition: primnodes.h:789
Definition: nodes.h:506
return result
Definition: formatting.c:1618
Definition: primnodes.h:163
Oid funcid
Definition: primnodes.h:448
#define ERROR
Definition: elog.h:43
Expr * phexpr
Definition: relation.h:1802
Bitmapset * bms_join(Bitmapset *a, Bitmapset *b)
Definition: bitmapset.c:838
BoolExprType boolop
Definition: primnodes.h:561
Expr * arg
Definition: primnodes.h:1178
Bitmapset * bms_make_singleton(int x)
Definition: bitmapset.c:179
Expr * arg
Definition: primnodes.h:1201
Expr * arg
Definition: primnodes.h:809
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:663
Index varno
Definition: primnodes.h:166
BoolTestType booltesttype
Definition: primnodes.h:1202
Oid opfuncid
Definition: primnodes.h:496
static Relids find_nonnullable_rels_walker(Node *node, bool top_level)
Definition: clauses.c:1577
NullTestType nulltesttype
Definition: primnodes.h:1179
static bool is_strict_saop(ScalarArrayOpExpr *expr, bool falseOK)
Definition: clauses.c:2080
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
Expr * arg
Definition: primnodes.h:874
List * args
Definition: primnodes.h:562
bool func_strict(Oid funcid)
Definition: lsyscache.c:1533
void set_opfuncid(OpExpr *opexpr)
Definition: nodeFuncs.c:1625
bool argisrow
Definition: primnodes.h:1180
#define elog
Definition: elog.h:219
List * args
Definition: primnodes.h:501
Bitmapset * bms_int_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:791
Definition: pg_list.h:45
List* find_nonnullable_vars ( Node clause)

Definition at line 1779 of file clauses.c.

References find_nonnullable_vars_walker().

Referenced by reduce_outer_joins_pass2().

1780 {
1781  return find_nonnullable_vars_walker(clause, true);
1782 }
static List * find_nonnullable_vars_walker(Node *node, bool top_level)
Definition: clauses.c:1785
static List * find_nonnullable_vars_walker ( Node node,
bool  top_level 
)
static

Definition at line 1785 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, NULL, NullTest::nulltesttype, OpExpr::opfuncid, OR_EXPR, PlaceHolderVar::phexpr, result, set_opfuncid(), and Var::varlevelsup.

Referenced by find_nonnullable_vars().

1786 {
1787  List *result = NIL;
1788  ListCell *l;
1789 
1790  if (node == NULL)
1791  return NIL;
1792  if (IsA(node, Var))
1793  {
1794  Var *var = (Var *) node;
1795 
1796  if (var->varlevelsup == 0)
1797  result = list_make1(var);
1798  }
1799  else if (IsA(node, List))
1800  {
1801  /*
1802  * At top level, we are examining an implicit-AND list: if any of the
1803  * arms produces FALSE-or-NULL then the result is FALSE-or-NULL. If
1804  * not at top level, we are examining the arguments of a strict
1805  * function: if any of them produce NULL then the result of the
1806  * function must be NULL. So in both cases, the set of nonnullable
1807  * vars is the union of those found in the arms, and we pass down the
1808  * top_level flag unmodified.
1809  */
1810  foreach(l, (List *) node)
1811  {
1812  result = list_concat(result,
1814  top_level));
1815  }
1816  }
1817  else if (IsA(node, FuncExpr))
1818  {
1819  FuncExpr *expr = (FuncExpr *) node;
1820 
1821  if (func_strict(expr->funcid))
1822  result = find_nonnullable_vars_walker((Node *) expr->args, false);
1823  }
1824  else if (IsA(node, OpExpr))
1825  {
1826  OpExpr *expr = (OpExpr *) node;
1827 
1828  set_opfuncid(expr);
1829  if (func_strict(expr->opfuncid))
1830  result = find_nonnullable_vars_walker((Node *) expr->args, false);
1831  }
1832  else if (IsA(node, ScalarArrayOpExpr))
1833  {
1834  ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1835 
1836  if (is_strict_saop(expr, true))
1837  result = find_nonnullable_vars_walker((Node *) expr->args, false);
1838  }
1839  else if (IsA(node, BoolExpr))
1840  {
1841  BoolExpr *expr = (BoolExpr *) node;
1842 
1843  switch (expr->boolop)
1844  {
1845  case AND_EXPR:
1846  /* At top level we can just recurse (to the List case) */
1847  if (top_level)
1848  {
1849  result = find_nonnullable_vars_walker((Node *) expr->args,
1850  top_level);
1851  break;
1852  }
1853 
1854  /*
1855  * Below top level, even if one arm produces NULL, the result
1856  * could be FALSE (hence not NULL). However, if *all* the
1857  * arms produce NULL then the result is NULL, so we can take
1858  * the intersection of the sets of nonnullable vars, just as
1859  * for OR. Fall through to share code.
1860  */
1861  /* FALL THRU */
1862  case OR_EXPR:
1863 
1864  /*
1865  * OR is strict if all of its arms are, so we can take the
1866  * intersection of the sets of nonnullable vars for each arm.
1867  * This works for both values of top_level.
1868  */
1869  foreach(l, expr->args)
1870  {
1871  List *subresult;
1872 
1873  subresult = find_nonnullable_vars_walker(lfirst(l),
1874  top_level);
1875  if (result == NIL) /* first subresult? */
1876  result = subresult;
1877  else
1878  result = list_intersection(result, subresult);
1879 
1880  /*
1881  * If the intersection is empty, we can stop looking. This
1882  * also justifies the test for first-subresult above.
1883  */
1884  if (result == NIL)
1885  break;
1886  }
1887  break;
1888  case NOT_EXPR:
1889  /* NOT will return null if its arg is null */
1890  result = find_nonnullable_vars_walker((Node *) expr->args,
1891  false);
1892  break;
1893  default:
1894  elog(ERROR, "unrecognized boolop: %d", (int) expr->boolop);
1895  break;
1896  }
1897  }
1898  else if (IsA(node, RelabelType))
1899  {
1900  RelabelType *expr = (RelabelType *) node;
1901 
1902  result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1903  }
1904  else if (IsA(node, CoerceViaIO))
1905  {
1906  /* not clear this is useful, but it can't hurt */
1907  CoerceViaIO *expr = (CoerceViaIO *) node;
1908 
1909  result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1910  }
1911  else if (IsA(node, ArrayCoerceExpr))
1912  {
1913  /* ArrayCoerceExpr is strict at the array level */
1914  ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
1915 
1916  result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1917  }
1918  else if (IsA(node, ConvertRowtypeExpr))
1919  {
1920  /* not clear this is useful, but it can't hurt */
1921  ConvertRowtypeExpr *expr = (ConvertRowtypeExpr *) node;
1922 
1923  result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1924  }
1925  else if (IsA(node, CollateExpr))
1926  {
1927  CollateExpr *expr = (CollateExpr *) node;
1928 
1929  result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1930  }
1931  else if (IsA(node, NullTest))
1932  {
1933  /* IS NOT NULL can be considered strict, but only at top level */
1934  NullTest *expr = (NullTest *) node;
1935 
1936  if (top_level && expr->nulltesttype == IS_NOT_NULL && !expr->argisrow)
1937  result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1938  }
1939  else if (IsA(node, BooleanTest))
1940  {
1941  /* Boolean tests that reject NULL are strict at top level */
1942  BooleanTest *expr = (BooleanTest *) node;
1943 
1944  if (top_level &&
1945  (expr->booltesttype == IS_TRUE ||
1946  expr->booltesttype == IS_FALSE ||
1947  expr->booltesttype == IS_NOT_UNKNOWN))
1948  result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1949  }
1950  else if (IsA(node, PlaceHolderVar))
1951  {
1952  PlaceHolderVar *phv = (PlaceHolderVar *) node;
1953 
1954  result = find_nonnullable_vars_walker((Node *) phv->phexpr, top_level);
1955  }
1956  return result;
1957 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:557
Index varlevelsup
Definition: primnodes.h:173
List * args
Definition: primnodes.h:456
Expr * arg
Definition: primnodes.h:789
Definition: nodes.h:506
List * list_concat(List *list1, List *list2)
Definition: list.c:321
return result
Definition: formatting.c:1618
Definition: primnodes.h:163
#define list_make1(x1)
Definition: pg_list.h:133
Oid funcid
Definition: primnodes.h:448
#define ERROR
Definition: elog.h:43
Expr * phexpr
Definition: relation.h:1802
BoolExprType boolop
Definition: primnodes.h:561
Expr * arg
Definition: primnodes.h:1178
Expr * arg
Definition: primnodes.h:1201
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:1785
Expr * arg
Definition: primnodes.h:809
BoolTestType booltesttype
Definition: primnodes.h:1202
Oid opfuncid
Definition: primnodes.h:496
NullTestType nulltesttype
Definition: primnodes.h:1179
static bool is_strict_saop(ScalarArrayOpExpr *expr, bool falseOK)
Definition: clauses.c:2080
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
Expr * arg
Definition: primnodes.h:874
List * args
Definition: primnodes.h:562
bool func_strict(Oid funcid)
Definition: lsyscache.c:1533
void set_opfuncid(OpExpr *opexpr)
Definition: nodeFuncs.c:1625
bool argisrow
Definition: primnodes.h:1180
#define elog
Definition: elog.h:219
List * args
Definition: primnodes.h:501
Definition: pg_list.h:45
WindowFuncLists* find_window_functions ( Node clause,
Index  maxWinRef 
)

Definition at line 739 of file clauses.c.

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

Referenced by grouping_planner().

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

Definition at line 751 of file clauses.c.

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

Referenced by find_window_functions().

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

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

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

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

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

Definition at line 264 of file clauses.c.

References generate_unaccent_rules::args, and linitial.

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

265 {
266  return linitial(((BoolExpr *) notclause)->args);
267 }
#define linitial(l)
Definition: pg_list.h:110
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 4273 of file clauses.c.

References ACL_EXECUTE, ACLCHECK_OK, eval_const_expressions_context::active_fns, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate(), Anum_pg_proc_proconfig, Anum_pg_proc_prosrc, arg, ErrorContextCallback::arg, CollateExpr::arg, generate_unaccent_rules::args, FuncExpr::args, Assert, ErrorContextCallback::callback, check_sql_fn_retval(), CMD_SELECT, COERCE_EXPLICIT_CALL, CollateExpr::collOid, Query::commandType, contain_context_dependent_node(), contain_mutable_functions(), contain_nonstrict_functions(), contain_subplans(), contain_volatile_functions(), copyObject, cost_qual_eval(), cpu_operator_cost, Query::cteList, CurrentMemoryContext, Query::distinctClause, elog, ERROR, error_context_stack, eval_const_expressions_mutator(), exprCollation(), exprType(), FmgrHookIsNeeded, free_parsestate(), FromExpr::fromlist, FuncExpr::funccollid, FuncExpr::funcformat, FuncExpr::funcid, FuncExpr::funcresulttype, FuncExpr::funcretset, FuncExpr::funcvariadic, GETSTRUCT, GetUserId(), Query::groupClause, Query::groupingSets, Query::hasAggs, Query::hasSubLinks, Query::hasTargetSRFs, Query::hasWindowFuncs, Query::havingQual, heap_attisnull(), i, FuncExpr::inputcollid, IsA, Query::jointree, lcons_oid(), lfirst, Query::limitCount, Query::limitOffset, linitial, list_delete_first(), list_length(), list_make1, list_member_oid(), FuncExpr::location, CollateExpr::location, make_parsestate(), makeNode, MemoryContextDelete(), MemoryContextSwitchTo(), NameStr, NULL, 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().

4278 {
4279  Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4280  char *src;
4281  Datum tmp;
4282  bool isNull;
4283  bool modifyTargetList;
4284  MemoryContext oldcxt;
4285  MemoryContext mycxt;
4286  inline_error_callback_arg callback_arg;
4287  ErrorContextCallback sqlerrcontext;
4288  FuncExpr *fexpr;
4290  ParseState *pstate;
4291  List *raw_parsetree_list;
4292  Query *querytree;
4293  Node *newexpr;
4294  int *usecounts;
4295  ListCell *arg;
4296  int i;
4297 
4298  /*
4299  * Forget it if the function is not SQL-language or has other showstopper
4300  * properties. (The nargs check is just paranoia.)
4301  */
4302  if (funcform->prolang != SQLlanguageId ||
4303  funcform->prosecdef ||
4304  funcform->proretset ||
4305  funcform->prorettype == RECORDOID ||
4306  !heap_attisnull(func_tuple, Anum_pg_proc_proconfig) ||
4307  funcform->pronargs != list_length(args))
4308  return NULL;
4309 
4310  /* Check for recursive function, and give up trying to expand if so */
4311  if (list_member_oid(context->active_fns, funcid))
4312  return NULL;
4313 
4314  /* Check permission to call function (fail later, if not) */
4316  return NULL;
4317 
4318  /* Check whether a plugin wants to hook function entry/exit */
4319  if (FmgrHookIsNeeded(funcid))
4320  return NULL;
4321 
4322  /*
4323  * Make a temporary memory context, so that we don't leak all the stuff
4324  * that parsing might create.
4325  */
4327  "inline_function",
4329  oldcxt = MemoryContextSwitchTo(mycxt);
4330 
4331  /* Fetch the function body */
4332  tmp = SysCacheGetAttr(PROCOID,
4333  func_tuple,
4335  &isNull);
4336  if (isNull)
4337  elog(ERROR, "null prosrc for function %u", funcid);
4338  src = TextDatumGetCString(tmp);
4339 
4340  /*
4341  * Setup error traceback support for ereport(). This is so that we can
4342  * finger the function that bad information came from.
4343  */
4344  callback_arg.proname = NameStr(funcform->proname);
4345  callback_arg.prosrc = src;
4346 
4347  sqlerrcontext.callback = sql_inline_error_callback;
4348  sqlerrcontext.arg = (void *) &callback_arg;
4349  sqlerrcontext.previous = error_context_stack;
4350  error_context_stack = &sqlerrcontext;
4351 
4352  /*
4353  * Set up to handle parameters while parsing the function body. We need a
4354  * dummy FuncExpr node containing the already-simplified arguments to pass
4355  * to prepare_sql_fn_parse_info. (It is really only needed if there are
4356  * some polymorphic arguments, but for simplicity we always build it.)
4357  */
4358  fexpr = makeNode(FuncExpr);
4359  fexpr->funcid = funcid;
4360  fexpr->funcresulttype = result_type;
4361  fexpr->funcretset = false;
4362  fexpr->funcvariadic = funcvariadic;
4363  fexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
4364  fexpr->funccollid = result_collid; /* doesn't matter */
4365  fexpr->inputcollid = input_collid;
4366  fexpr->args = args;
4367  fexpr->location = -1;
4368 
4369  pinfo = prepare_sql_fn_parse_info(func_tuple,
4370  (Node *) fexpr,
4371  input_collid);
4372 
4373  /*
4374  * We just do parsing and parse analysis, not rewriting, because rewriting
4375  * will not affect table-free-SELECT-only queries, which is all that we
4376  * care about. Also, we can punt as soon as we detect more than one
4377  * command in the function body.
4378  */
4379  raw_parsetree_list = pg_parse_query(src);
4380  if (list_length(raw_parsetree_list) != 1)
4381  goto fail;
4382 
4383  pstate = make_parsestate(NULL);
4384  pstate->p_sourcetext = src;
4385  sql_fn_parser_setup(pstate, pinfo);
4386 
4387  querytree = transformTopLevelStmt(pstate, linitial(raw_parsetree_list));
4388 
4389  free_parsestate(pstate);
4390 
4391  /*
4392  * The single command must be a simple "SELECT expression".
4393  */
4394  if (!IsA(querytree, Query) ||
4395  querytree->commandType != CMD_SELECT ||
4396  querytree->hasAggs ||
4397  querytree->hasWindowFuncs ||
4398  querytree->hasTargetSRFs ||
4399  querytree->hasSubLinks ||
4400  querytree->cteList ||
4401  querytree->rtable ||
4402  querytree->jointree->fromlist ||
4403  querytree->jointree->quals ||
4404  querytree->groupClause ||
4405  querytree->groupingSets ||
4406  querytree->havingQual ||
4407  querytree->windowClause ||
4408  querytree->distinctClause ||
4409  querytree->sortClause ||
4410  querytree->limitOffset ||
4411  querytree->limitCount ||
4412  querytree->setOperations ||
4413  list_length(querytree->targetList) != 1)
4414  goto fail;
4415 
4416  /*
4417  * Make sure the function (still) returns what it's declared to. This
4418  * will raise an error if wrong, but that's okay since the function would
4419  * fail at runtime anyway. Note that check_sql_fn_retval will also insert
4420  * a RelabelType if needed to make the tlist expression match the declared
4421  * type of the function.
4422  *
4423  * Note: we do not try this until we have verified that no rewriting was
4424  * needed; that's probably not important, but let's be careful.
4425  */
4426  if (check_sql_fn_retval(funcid, result_type, list_make1(querytree),
4427  &modifyTargetList, NULL))
4428  goto fail; /* reject whole-tuple-result cases */
4429 
4430  /* Now we can grab the tlist expression */
4431  newexpr = (Node *) ((TargetEntry *) linitial(querytree->targetList))->expr;
4432 
4433  /* Assert that check_sql_fn_retval did the right thing */
4434  Assert(exprType(newexpr) == result_type);
4435  /* It couldn't have made any dangerous tlist changes, either */
4436  Assert(!modifyTargetList);
4437 
4438  /*
4439  * Additional validity checks on the expression. It mustn't be more
4440  * volatile than the surrounding function (this is to avoid breaking hacks
4441  * that involve pretending a function is immutable when it really ain't).
4442  * If the surrounding function is declared strict, then the expression
4443  * must contain only strict constructs and must use all of the function
4444  * parameters (this is overkill, but an exact analysis is hard).
4445  */
4446  if (funcform->provolatile == PROVOLATILE_IMMUTABLE &&
4447  contain_mutable_functions(newexpr))
4448  goto fail;
4449  else if (funcform->provolatile == PROVOLATILE_STABLE &&
4450  contain_volatile_functions(newexpr))
4451  goto fail;
4452 
4453  if (funcform->proisstrict &&
4454  contain_nonstrict_functions(newexpr))
4455  goto fail;
4456 
4457  /*
4458  * If any parameter expression contains a context-dependent node, we can't
4459  * inline, for fear of putting such a node into the wrong context.
4460  */
4461  if (contain_context_dependent_node((Node *) args))
4462  goto fail;
4463 
4464  /*
4465  * We may be able to do it; there are still checks on parameter usage to
4466  * make, but those are most easily done in combination with the actual
4467  * substitution of the inputs. So start building expression with inputs
4468  * substituted.
4469  */
4470  usecounts = (int *) palloc0(funcform->pronargs * sizeof(int));
4471  newexpr = substitute_actual_parameters(newexpr, funcform->pronargs,
4472  args, usecounts);
4473 
4474  /* Now check for parameter usage */
4475  i = 0;
4476  foreach(arg, args)
4477  {
4478  Node *param = lfirst(arg);
4479 
4480  if (usecounts[i] == 0)
4481  {
4482  /* Param not used at all: uncool if func is strict */
4483  if (funcform->proisstrict)
4484  goto fail;
4485  }
4486  else if (usecounts[i] != 1)
4487  {
4488  /* Param used multiple times: uncool if expensive or volatile */
4489  QualCost eval_cost;
4490 
4491  /*
4492  * We define "expensive" as "contains any subplan or more than 10
4493  * operators". Note that the subplan search has to be done
4494  * explicitly, since cost_qual_eval() will barf on unplanned
4495  * subselects.
4496  */
4497  if (contain_subplans(param))
4498  goto fail;
4499  cost_qual_eval(&eval_cost, list_make1(param), NULL);
4500  if (eval_cost.startup + eval_cost.per_tuple >
4501  10 * cpu_operator_cost)
4502  goto fail;
4503 
4504  /*
4505  * Check volatility last since this is more expensive than the
4506  * above tests
4507  */
4508  if (contain_volatile_functions(param))
4509  goto fail;
4510  }
4511  i++;
4512  }
4513 
4514  /*
4515  * Whew --- we can make the substitution. Copy the modified expression
4516  * out of the temporary memory context, and clean up.
4517  */
4518  MemoryContextSwitchTo(oldcxt);
4519 
4520  newexpr = copyObject(newexpr);
4521 
4522  MemoryContextDelete(mycxt);
4523 
4524  /*
4525  * If the result is of a collatable type, force the result to expose the
4526  * correct collation. In most cases this does not matter, but it's
4527  * possible that the function result is used directly as a sort key or in
4528  * other places where we expect exprCollation() to tell the truth.
4529  */
4530  if (OidIsValid(result_collid))
4531  {
4532  Oid exprcoll = exprCollation(newexpr);
4533 
4534  if (OidIsValid(exprcoll) && exprcoll != result_collid)
4535  {
4536  CollateExpr *newnode = makeNode(CollateExpr);
4537 
4538  newnode->arg = (Expr *) newexpr;
4539  newnode->collOid = result_collid;
4540  newnode->location = -1;
4541 
4542  newexpr = (Node *) newnode;
4543  }
4544  }
4545 
4546  /*
4547  * Since there is now no trace of the function in the plan tree, we must
4548  * explicitly record the plan's dependency on the function.
4549  */
4550  if (context->root)
4551  record_plan_function_dependency(context->root, funcid);
4552 
4553  /*
4554  * Recursively try to simplify the modified expression. Here we must add
4555  * the current function to the context list of active functions.
4556  */
4557  context->active_fns = lcons_oid(funcid, context->active_fns);
4558  newexpr = eval_const_expressions_mutator(newexpr, context);
4559  context->active_fns = list_delete_first(context->active_fns);
4560 
4561  error_context_stack = sqlerrcontext.previous;
4562 
4563  return (Expr *) newexpr;
4564 
4565  /* Here if func is not inlinable: release temp memory and return NULL */
4566 fail:
4567  MemoryContextSwitchTo(oldcxt);
4568  MemoryContextDelete(mycxt);
4569  error_context_stack = sqlerrcontext.previous;
4570 
4571  return NULL;
4572 }
Node * limitOffset
Definition: parsenodes.h:149
Oid funcresulttype
Definition: primnodes.h:449
#define IsA(nodeptr, _type_)
Definition: nodes.h:557
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define PROVOLATILE_IMMUTABLE
Definition: pg_proc.h:5436
List * sortClause
Definition: parsenodes.h:147
List * args
Definition: primnodes.h:456
FromExpr * jointree
Definition: parsenodes.h:129
Oid GetUserId(void)
Definition: miscinit.c:283
Oid funccollid
Definition: primnodes.h:454
void sql_fn_parser_setup(struct ParseState *pstate, SQLFunctionParseInfoPtr pinfo)
Definition: functions.c:273
bool hasAggs
Definition: parsenodes.h:116
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define Anum_pg_proc_prosrc
Definition: pg_proc.h:115
List * groupingSets
Definition: parsenodes.h:139
Definition: nodes.h:506
bool check_sql_fn_retval(Oid func_id, Oid rettype, List *queryTreeList, bool *modifyTargetList, JunkFilter **junkFilter)
Definition: functions.c:1527
bool funcretset
Definition: primnodes.h:450
List * lcons_oid(Oid datum, List *list)
Definition: list.c:295
List * fromlist
Definition: primnodes.h:1455
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:950
unsigned int Oid
Definition: postgres_ext.h:31
struct ErrorContextCallback * previous
Definition: elog.h:238
#define OidIsValid(objectId)
Definition: c.h:538
#define FmgrHookIsNeeded(fn_oid)
Definition: fmgr.h:728
Node * quals
Definition: primnodes.h:1456
Cost startup
Definition: relation.h:45
#define Anum_pg_proc_proconfig
Definition: pg_proc.h:117
List * windowClause
Definition: parsenodes.h:143
List * targetList
Definition: parsenodes.h:131
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:133
bool contain_subplans(Node *clause)
Definition: clauses.c:842
CoercionForm funcformat
Definition: primnodes.h:453
Cost per_tuple
Definition: relation.h:46
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2413
#define linitial(l)
Definition: pg_list.h:110
List * rtable
Definition: parsenodes.h:128
List * distinctClause
Definition: parsenodes.h:145
Oid funcid
Definition: primnodes.h:448
#define ERROR
Definition: elog.h:43
#define SQLlanguageId
Definition: pg_language.h:80
#define PROVOLATILE_STABLE
Definition: pg_proc.h:5437
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3364
List * pg_parse_query(const char *query_string)
Definition: postgres.c:602
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:165
Node * limitCount
Definition: parsenodes.h:150
bool heap_attisnull(HeapTuple tup, int attnum)
Definition: heaptuple.c:297
double cpu_operator_cost
Definition: costsize.c:108
#define RECORDOID
Definition: pg_type.h:676
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
const char * p_sourcetext
Definition: parse_node.h:167
static Node * substitute_actual_parameters(Node *expr, int nargs, List *args, int *usecounts)
Definition: clauses.c:4578
static void sql_inline_error_callback(void *arg)
Definition: clauses.c:4620
#define TextDatumGetCString(d)
Definition: builtins.h:92
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:322
void * palloc0(Size size)
Definition: mcxt.c:878
uintptr_t Datum
Definition: postgres.h:372
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1278
void record_plan_function_dependency(PlannerInfo *root, Oid funcid)
Definition: setrefs.c:2473
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:83
CmdType commandType
Definition: parsenodes.h:103
bool hasTargetSRFs
Definition: parsenodes.h:118
#define makeNode(_type_)
Definition: nodes.h:554
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:505
Oid inputcollid
Definition: primnodes.h:455
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
bool hasWindowFuncs
Definition: parsenodes.h:117
Query * transformTopLevelStmt(ParseState *pstate, RawStmt *parseTree)
Definition: analyze.c:184
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:745
Expr * arg
Definition: primnodes.h:874
Datum querytree(PG_FUNCTION_ARGS)
Definition: _int_bool.c:665
static bool contain_context_dependent_node(Node *clause)
Definition: clauses.c:1361
List * cteList
Definition: parsenodes.h:126
Node * setOperations
Definition: parsenodes.h:154
List * groupClause
Definition: parsenodes.h:137
void(* callback)(void *arg)
Definition: elog.h:239
bool hasSubLinks
Definition: parsenodes.h:119
#define ACL_EXECUTE
Definition: parsenodes.h:72
AclResult pg_proc_aclcheck(Oid proc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4446
int i
#define NameStr(name)
Definition: c.h:499
void * arg
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:877
int location
Definition: primnodes.h:457
#define elog
Definition: elog.h:219
bool contain_nonstrict_functions(Node *clause)
Definition: clauses.c:1234
SQLFunctionParseInfoPtr prepare_sql_fn_parse_info(HeapTuple procedureTuple, Node *call_expr, Oid inputCollation)
Definition: functions.c:184
#define copyObject(obj)
Definition: nodes.h:618
Node * havingQual
Definition: parsenodes.h:141
int location
Definition: primnodes.h:876
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:75
Definition: pg_list.h:45
bool funcvariadic
Definition: primnodes.h:451
List * list_delete_first(List *list)
Definition: list.c:666
Query* inline_set_returning_function ( PlannerInfo root,
RangeTblEntry rte 
)

Definition at line 4732 of file clauses.c.

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

Referenced by inline_set_returning_functions().

4733 {
4734  RangeTblFunction *rtfunc;
4735  FuncExpr *fexpr;
4736  Oid func_oid;
4737  HeapTuple func_tuple;
4738  Form_pg_proc funcform;
4739  char *src;
4740  Datum tmp;
4741  bool isNull;
4742  bool modifyTargetList;
4743  MemoryContext oldcxt;
4744  MemoryContext mycxt;
4745  List *saveInvalItems;
4746  inline_error_callback_arg callback_arg;
4747  ErrorContextCallback sqlerrcontext;
4749  List *raw_parsetree_list;
4750  List *querytree_list;
4751  Query *querytree;
4752 
4753  Assert(rte->rtekind == RTE_FUNCTION);
4754 
4755  /*
4756  * It doesn't make a lot of sense for a SQL SRF to refer to itself in its
4757  * own FROM clause, since that must cause infinite recursion at runtime.
4758  * It will cause this code to recurse too, so check for stack overflow.
4759  * (There's no need to do more.)
4760  */
4762 
4763  /* Fail if the RTE has ORDINALITY - we don't implement that here. */
4764  if (rte->funcordinality)
4765  return NULL;
4766