PostgreSQL Source Code  git master
functions.h File Reference
#include "nodes/execnodes.h"
#include "tcop/dest.h"
Include dependency graph for functions.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Typedefs

typedef struct SQLFunctionParseInfoSQLFunctionParseInfoPtr
 

Functions

Datum fmgr_sql (PG_FUNCTION_ARGS)
 
SQLFunctionParseInfoPtr prepare_sql_fn_parse_info (HeapTuple procedureTuple, Node *call_expr, Oid inputCollation)
 
void sql_fn_parser_setup (struct ParseState *pstate, SQLFunctionParseInfoPtr pinfo)
 
void check_sql_fn_statements (List *queryTreeLists)
 
bool check_sql_fn_retval (List *queryTreeLists, Oid rettype, TupleDesc rettupdesc, bool insertDroppedCols, List **resultTargetList)
 
DestReceiverCreateSQLFunctionDestReceiver (void)
 

Typedef Documentation

◆ SQLFunctionParseInfoPtr

Definition at line 21 of file functions.h.

Function Documentation

◆ check_sql_fn_retval()

bool check_sql_fn_retval ( List queryTreeLists,
Oid  rettype,
TupleDesc  rettupdesc,
bool  insertDroppedCols,
List **  resultTargetList 
)

Definition at line 1601 of file functions.c.

References RangeTblEntry::alias, Assert, Query::canSetTag, CMD_DELETE, CMD_INSERT, CMD_SELECT, CMD_UPDATE, coerce_fn_result_column(), Query::commandType, RangeTblEntry::eref, ereport, errcode(), errdetail(), errmsg(), ERROR, ExecCleanTargetListLength(), TargetEntry::expr, exprType(), format_type_be(), get_typtype(), RangeTblEntry::inFromCl, RangeTblEntry::inh, InvalidOid, Query::jointree, lappend(), RangeTblEntry::lateral, lfirst, lfirst_node, linitial, list_length(), list_make1, makeAlias(), makeConst(), makeFromExpr(), makeNode, makeString(), makeTargetEntry(), TupleDescData::natts, NIL, parse(), Query::querySource, TargetEntry::resjunk, TargetEntry::resname, Query::returningList, Query::rtable, RTE_SUBQUERY, RangeTblEntry::rtekind, RangeTblRef::rtindex, Query::setOperations, RangeTblEntry::subquery, Query::targetList, and TupleDescAttr.

Referenced by fmgr_sql_validator(), init_sql_fcache(), inline_function(), and inline_set_returning_function().

1605 {
1606  bool is_tuple_result = false;
1607  Query *parse;
1608  ListCell *parse_cell;
1609  List *tlist;
1610  int tlistlen;
1611  bool tlist_is_modifiable;
1612  char fn_typtype;
1613  List *upper_tlist = NIL;
1614  bool upper_tlist_nontrivial = false;
1615  ListCell *lc;
1616 
1617  if (resultTargetList)
1618  *resultTargetList = NIL; /* initialize in case of VOID result */
1619 
1620  /*
1621  * If it's declared to return VOID, we don't care what's in the function.
1622  * (This takes care of the procedure case, as well.)
1623  */
1624  if (rettype == VOIDOID)
1625  return false;
1626 
1627  /*
1628  * Find the last canSetTag query in the function body (which is presented
1629  * to us as a list of sublists of Query nodes). This isn't necessarily
1630  * the last parsetree, because rule rewriting can insert queries after
1631  * what the user wrote. Note that it might not even be in the last
1632  * sublist, for example if the last query rewrites to DO INSTEAD NOTHING.
1633  * (It might not be unreasonable to throw an error in such a case, but
1634  * this is the historical behavior and it doesn't seem worth changing.)
1635  */
1636  parse = NULL;
1637  parse_cell = NULL;
1638  foreach(lc, queryTreeLists)
1639  {
1640  List *sublist = lfirst_node(List, lc);
1641  ListCell *lc2;
1642 
1643  foreach(lc2, sublist)
1644  {
1645  Query *q = lfirst_node(Query, lc2);
1646 
1647  if (q->canSetTag)
1648  {
1649  parse = q;
1650  parse_cell = lc2;
1651  }
1652  }
1653  }
1654 
1655  /*
1656  * If it's a plain SELECT, it returns whatever the targetlist says.
1657  * Otherwise, if it's INSERT/UPDATE/DELETE with RETURNING, it returns
1658  * that. Otherwise, the function return type must be VOID.
1659  *
1660  * Note: eventually replace this test with QueryReturnsTuples? We'd need
1661  * a more general method of determining the output type, though. Also, it
1662  * seems too dangerous to consider FETCH or EXECUTE as returning a
1663  * determinable rowtype, since they depend on relatively short-lived
1664  * entities.
1665  */
1666  if (parse &&
1667  parse->commandType == CMD_SELECT)
1668  {
1669  tlist = parse->targetList;
1670  /* tlist is modifiable unless it's a dummy in a setop query */
1671  tlist_is_modifiable = (parse->setOperations == NULL);
1672  }
1673  else if (parse &&
1674  (parse->commandType == CMD_INSERT ||
1675  parse->commandType == CMD_UPDATE ||
1676  parse->commandType == CMD_DELETE) &&
1677  parse->returningList)
1678  {
1679  tlist = parse->returningList;
1680  /* returningList can always be modified */
1681  tlist_is_modifiable = true;
1682  }
1683  else
1684  {
1685  /* Empty function body, or last statement is a utility command */
1686  ereport(ERROR,
1687  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1688  errmsg("return type mismatch in function declared to return %s",
1689  format_type_be(rettype)),
1690  errdetail("Function's final statement must be SELECT or INSERT/UPDATE/DELETE RETURNING.")));
1691  return false; /* keep compiler quiet */
1692  }
1693 
1694  /*
1695  * OK, check that the targetlist returns something matching the declared
1696  * type, and modify it if necessary. If possible, we insert any coercion
1697  * steps right into the final statement's targetlist. However, that might
1698  * risk changes in the statement's semantics --- we can't safely change
1699  * the output type of a grouping column, for instance. In such cases we
1700  * handle coercions by inserting an extra level of Query that effectively
1701  * just does a projection.
1702  */
1703 
1704  /*
1705  * Count the non-junk entries in the result targetlist.
1706  */
1707  tlistlen = ExecCleanTargetListLength(tlist);
1708 
1709  fn_typtype = get_typtype(rettype);
1710 
1711  if (fn_typtype == TYPTYPE_BASE ||
1712  fn_typtype == TYPTYPE_DOMAIN ||
1713  fn_typtype == TYPTYPE_ENUM ||
1714  fn_typtype == TYPTYPE_RANGE)
1715  {
1716  /*
1717  * For scalar-type returns, the target list must have exactly one
1718  * non-junk entry, and its type must be coercible to rettype.
1719  */
1720  TargetEntry *tle;
1721 
1722  if (tlistlen != 1)
1723  ereport(ERROR,
1724  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1725  errmsg("return type mismatch in function declared to return %s",
1726  format_type_be(rettype)),
1727  errdetail("Final statement must return exactly one column.")));
1728 
1729  /* We assume here that non-junk TLEs must come first in tlists */
1730  tle = (TargetEntry *) linitial(tlist);
1731  Assert(!tle->resjunk);
1732 
1733  if (!coerce_fn_result_column(tle, rettype, -1,
1734  tlist_is_modifiable,
1735  &upper_tlist,
1736  &upper_tlist_nontrivial))
1737  ereport(ERROR,
1738  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1739  errmsg("return type mismatch in function declared to return %s",
1740  format_type_be(rettype)),
1741  errdetail("Actual return type is %s.",
1742  format_type_be(exprType((Node *) tle->expr)))));
1743  }
1744  else if (fn_typtype == TYPTYPE_COMPOSITE || rettype == RECORDOID)
1745  {
1746  /*
1747  * Returns a rowtype.
1748  *
1749  * Note that we will not consider a domain over composite to be a
1750  * "rowtype" return type; it goes through the scalar case above. This
1751  * is because we only provide column-by-column implicit casting, and
1752  * will not cast the complete record result. So the only way to
1753  * produce a domain-over-composite result is to compute it as an
1754  * explicit single-column result. The single-composite-column code
1755  * path just below could handle such cases, but it won't be reached.
1756  */
1757  int tupnatts; /* physical number of columns in tuple */
1758  int tuplogcols; /* # of nondeleted columns in tuple */
1759  int colindex; /* physical column index */
1760 
1761  /*
1762  * If the target list has one non-junk entry, and that expression has
1763  * or can be coerced to the declared return type, take it as the
1764  * result. This allows, for example, 'SELECT func2()', where func2
1765  * has the same composite return type as the function that's calling
1766  * it. This provision creates some ambiguity --- maybe the expression
1767  * was meant to be the lone field of the composite result --- but it
1768  * works well enough as long as we don't get too enthusiastic about
1769  * inventing coercions from scalar to composite types.
1770  *
1771  * XXX Note that if rettype is RECORD and the expression is of a named
1772  * composite type, or vice versa, this coercion will succeed, whether
1773  * or not the record type really matches. For the moment we rely on
1774  * runtime type checking to catch any discrepancy, but it'd be nice to
1775  * do better at parse time.
1776  */
1777  if (tlistlen == 1)
1778  {
1779  TargetEntry *tle = (TargetEntry *) linitial(tlist);
1780 
1781  Assert(!tle->resjunk);
1782  if (coerce_fn_result_column(tle, rettype, -1,
1783  tlist_is_modifiable,
1784  &upper_tlist,
1785  &upper_tlist_nontrivial))
1786  {
1787  /* Note that we're NOT setting is_tuple_result */
1788  goto tlist_coercion_finished;
1789  }
1790  }
1791 
1792  /*
1793  * If the caller didn't provide an expected tupdesc, we can't do any
1794  * further checking. Assume we're returning the whole tuple.
1795  */
1796  if (rettupdesc == NULL)
1797  {
1798  /* Return tlist if requested */
1799  if (resultTargetList)
1800  *resultTargetList = tlist;
1801  return true;
1802  }
1803 
1804  /*
1805  * Verify that the targetlist matches the return tuple type. We scan
1806  * the non-resjunk columns, and coerce them if necessary to match the
1807  * datatypes of the non-deleted attributes. For deleted attributes,
1808  * insert NULL result columns if the caller asked for that.
1809  */
1810  tupnatts = rettupdesc->natts;
1811  tuplogcols = 0; /* we'll count nondeleted cols as we go */
1812  colindex = 0;
1813 
1814  foreach(lc, tlist)
1815  {
1816  TargetEntry *tle = (TargetEntry *) lfirst(lc);
1817  Form_pg_attribute attr;
1818 
1819  /* resjunk columns can simply be ignored */
1820  if (tle->resjunk)
1821  continue;
1822 
1823  do
1824  {
1825  colindex++;
1826  if (colindex > tupnatts)
1827  ereport(ERROR,
1828  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1829  errmsg("return type mismatch in function declared to return %s",
1830  format_type_be(rettype)),
1831  errdetail("Final statement returns too many columns.")));
1832  attr = TupleDescAttr(rettupdesc, colindex - 1);
1833  if (attr->attisdropped && insertDroppedCols)
1834  {
1835  Expr *null_expr;
1836 
1837  /* The type of the null we insert isn't important */
1838  null_expr = (Expr *) makeConst(INT4OID,
1839  -1,
1840  InvalidOid,
1841  sizeof(int32),
1842  (Datum) 0,
1843  true, /* isnull */
1844  true /* byval */ );
1845  upper_tlist = lappend(upper_tlist,
1846  makeTargetEntry(null_expr,
1847  list_length(upper_tlist) + 1,
1848  NULL,
1849  false));
1850  upper_tlist_nontrivial = true;
1851  }
1852  } while (attr->attisdropped);
1853  tuplogcols++;
1854 
1855  if (!coerce_fn_result_column(tle,
1856  attr->atttypid, attr->atttypmod,
1857  tlist_is_modifiable,
1858  &upper_tlist,
1859  &upper_tlist_nontrivial))
1860  ereport(ERROR,
1861  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1862  errmsg("return type mismatch in function declared to return %s",
1863  format_type_be(rettype)),
1864  errdetail("Final statement returns %s instead of %s at column %d.",
1865  format_type_be(exprType((Node *) tle->expr)),
1866  format_type_be(attr->atttypid),
1867  tuplogcols)));
1868  }
1869 
1870  /* remaining columns in rettupdesc had better all be dropped */
1871  for (colindex++; colindex <= tupnatts; colindex++)
1872  {
1873  if (!TupleDescAttr(rettupdesc, colindex - 1)->attisdropped)
1874  ereport(ERROR,
1875  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1876  errmsg("return type mismatch in function declared to return %s",
1877  format_type_be(rettype)),
1878  errdetail("Final statement returns too few columns.")));
1879  if (insertDroppedCols)
1880  {
1881  Expr *null_expr;
1882 
1883  /* The type of the null we insert isn't important */
1884  null_expr = (Expr *) makeConst(INT4OID,
1885  -1,
1886  InvalidOid,
1887  sizeof(int32),
1888  (Datum) 0,
1889  true, /* isnull */
1890  true /* byval */ );
1891  upper_tlist = lappend(upper_tlist,
1892  makeTargetEntry(null_expr,
1893  list_length(upper_tlist) + 1,
1894  NULL,
1895  false));
1896  upper_tlist_nontrivial = true;
1897  }
1898  }
1899 
1900  /* Report that we are returning entire tuple result */
1901  is_tuple_result = true;
1902  }
1903  else
1904  ereport(ERROR,
1905  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1906  errmsg("return type %s is not supported for SQL functions",
1907  format_type_be(rettype))));
1908 
1909 tlist_coercion_finished:
1910 
1911  /*
1912  * If necessary, modify the final Query by injecting an extra Query level
1913  * that just performs a projection. (It'd be dubious to do this to a
1914  * non-SELECT query, but we never have to; RETURNING lists can always be
1915  * modified in-place.)
1916  */
1917  if (upper_tlist_nontrivial)
1918  {
1919  Query *newquery;
1920  List *colnames;
1921  RangeTblEntry *rte;
1922  RangeTblRef *rtr;
1923 
1924  Assert(parse->commandType == CMD_SELECT);
1925 
1926  /* Most of the upper Query struct can be left as zeroes/nulls */
1927  newquery = makeNode(Query);
1928  newquery->commandType = CMD_SELECT;
1929  newquery->querySource = parse->querySource;
1930  newquery->canSetTag = true;
1931  newquery->targetList = upper_tlist;
1932 
1933  /* We need a moderately realistic colnames list for the subquery RTE */
1934  colnames = NIL;
1935  foreach(lc, parse->targetList)
1936  {
1937  TargetEntry *tle = (TargetEntry *) lfirst(lc);
1938 
1939  if (tle->resjunk)
1940  continue;
1941  colnames = lappend(colnames,
1942  makeString(tle->resname ? tle->resname : ""));
1943  }
1944 
1945  /* Build a suitable RTE for the subquery */
1946  rte = makeNode(RangeTblEntry);
1947  rte->rtekind = RTE_SUBQUERY;
1948  rte->subquery = parse;
1949  rte->eref = rte->alias = makeAlias("*SELECT*", colnames);
1950  rte->lateral = false;
1951  rte->inh = false;
1952  rte->inFromCl = true;
1953  newquery->rtable = list_make1(rte);
1954 
1955  rtr = makeNode(RangeTblRef);
1956  rtr->rtindex = 1;
1957  newquery->jointree = makeFromExpr(list_make1(rtr), NULL);
1958 
1959  /* Replace original query in the correct element of the query list */
1960  lfirst(parse_cell) = newquery;
1961  }
1962 
1963  /* Return tlist (possibly modified) if requested */
1964  if (resultTargetList)
1965  *resultTargetList = upper_tlist;
1966 
1967  return is_tuple_result;
1968 }
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:65
FromExpr * makeFromExpr(List *fromlist, Node *quals)
Definition: makefuncs.c:285
Alias * alias
Definition: parsenodes.h:1119
FromExpr * jointree
Definition: parsenodes.h:138
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
Definition: nodes.h:527
int errcode(int sqlerrcode)
Definition: elog.c:691
char get_typtype(Oid typid)
Definition: lsyscache.c:2522
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
char * resname
Definition: primnodes.h:1424
Const * makeConst(Oid consttype, int32 consttypmod, Oid constcollid, int constlen, Datum constvalue, bool constisnull, bool constbyval)
Definition: makefuncs.c:299
signed int int32
Definition: c.h:417
List * targetList
Definition: parsenodes.h:140
#define list_make1(x1)
Definition: pg_list.h:206
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:387
bool resjunk
Definition: primnodes.h:1429
#define linitial(l)
Definition: pg_list.h:174
List * rtable
Definition: parsenodes.h:137
#define ERROR
Definition: elog.h:43
#define lfirst_node(type, lc)
Definition: pg_list.h:172
int errdetail(const char *fmt,...)
Definition: elog.c:1035
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
List * returningList
Definition: parsenodes.h:146
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:238
List * lappend(List *list, void *datum)
Definition: list.c:321
int ExecCleanTargetListLength(List *targetlist)
Definition: execUtils.c:1146
uintptr_t Datum
Definition: postgres.h:367
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:155
CmdType commandType
Definition: parsenodes.h:112
#define makeNode(_type_)
Definition: nodes.h:575
QuerySource querySource
Definition: parsenodes.h:114
#define Assert(condition)
Definition: c.h:800
#define lfirst(lc)
Definition: pg_list.h:169
Expr * expr
Definition: primnodes.h:1422
static bool coerce_fn_result_column(TargetEntry *src_tle, Oid res_type, int32 res_typmod, bool tlist_is_modifiable, List **upper_tlist, bool *upper_tlist_nontrivial)
Definition: functions.c:1981
bool canSetTag
Definition: parsenodes.h:118
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
static int list_length(const List *l)
Definition: pg_list.h:149
RTEKind rtekind
Definition: parsenodes.h:981
Node * setOperations
Definition: parsenodes.h:166
Query * subquery
Definition: parsenodes.h:1016
int errmsg(const char *fmt,...)
Definition: elog.c:902
Alias * eref
Definition: parsenodes.h:1120
Definition: pg_list.h:50
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:648

◆ check_sql_fn_statements()

void check_sql_fn_statements ( List queryTreeLists)

Definition at line 1507 of file functions.c.

References castNode, CMD_UTILITY, Query::commandType, elog, ereport, errcode(), errmsg(), ERROR, CallStmt::funcexpr, FuncExpr::funcid, get_func_arg_info(), HeapTupleIsValid, i, IsA, lfirst_node, ObjectIdGetDatum, PROCOID, ReleaseSysCache(), SearchSysCache1(), execution_state::stmt, and Query::utilityStmt.

Referenced by fmgr_sql_validator(), and init_sql_fcache().

1508 {
1509  ListCell *lc;
1510 
1511  /* We are given a list of sublists of Queries */
1512  foreach(lc, queryTreeLists)
1513  {
1514  List *sublist = lfirst_node(List, lc);
1515  ListCell *lc2;
1516 
1517  foreach(lc2, sublist)
1518  {
1519  Query *query = lfirst_node(Query, lc2);
1520 
1521  /*
1522  * Disallow procedures with output arguments. The current
1523  * implementation would just throw the output values away, unless
1524  * the statement is the last one. Per SQL standard, we should
1525  * assign the output values by name. By disallowing this here, we
1526  * preserve an opportunity for future improvement.
1527  */
1528  if (query->commandType == CMD_UTILITY &&
1529  IsA(query->utilityStmt, CallStmt))
1530  {
1531  CallStmt *stmt = castNode(CallStmt, query->utilityStmt);
1532  HeapTuple tuple;
1533  int numargs;
1534  Oid *argtypes;
1535  char **argnames;
1536  char *argmodes;
1537  int i;
1538 
1539  tuple = SearchSysCache1(PROCOID,
1540  ObjectIdGetDatum(stmt->funcexpr->funcid));
1541  if (!HeapTupleIsValid(tuple))
1542  elog(ERROR, "cache lookup failed for function %u",
1543  stmt->funcexpr->funcid);
1544  numargs = get_func_arg_info(tuple,
1545  &argtypes, &argnames, &argmodes);
1546  ReleaseSysCache(tuple);
1547 
1548  for (i = 0; i < numargs; i++)
1549  {
1550  if (argmodes && (argmodes[i] == PROARGMODE_INOUT ||
1551  argmodes[i] == PROARGMODE_OUT))
1552  ereport(ERROR,
1553  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1554  errmsg("calling procedures with output arguments is not supported in SQL functions")));
1555  }
1556  }
1557  }
1558  }
1559 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:578
FuncExpr * funcexpr
Definition: parsenodes.h:2899
#define castNode(_type_, nodeptr)
Definition: nodes.h:596
int get_func_arg_info(HeapTuple procTup, Oid **p_argtypes, char ***p_argnames, char **p_argmodes)
Definition: funcapi.c:1094
int errcode(int sqlerrcode)
Definition: elog.c:691
unsigned int Oid
Definition: postgres_ext.h:31
Node * utilityStmt
Definition: parsenodes.h:120
Oid funcid
Definition: primnodes.h:481
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
#define lfirst_node(type, lc)
Definition: pg_list.h:172
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1115
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1163
#define ereport(elevel,...)
Definition: elog.h:155
CmdType commandType
Definition: parsenodes.h:112
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
int errmsg(const char *fmt,...)
Definition: elog.c:902
#define elog(elevel,...)
Definition: elog.h:228
int i
Definition: pg_list.h:50

◆ CreateSQLFunctionDestReceiver()

DestReceiver* CreateSQLFunctionDestReceiver ( void  )

Definition at line 2047 of file functions.c.

References DestSQLFunction, palloc0(), sqlfunction_destroy(), sqlfunction_receive(), sqlfunction_shutdown(), and sqlfunction_startup().

Referenced by CreateDestReceiver().

2048 {
2049  DR_sqlfunction *self = (DR_sqlfunction *) palloc0(sizeof(DR_sqlfunction));
2050 
2051  self->pub.receiveSlot = sqlfunction_receive;
2052  self->pub.rStartup = sqlfunction_startup;
2053  self->pub.rShutdown = sqlfunction_shutdown;
2054  self->pub.rDestroy = sqlfunction_destroy;
2055  self->pub.mydest = DestSQLFunction;
2056 
2057  /* private fields will be set by postquel_start */
2058 
2059  return (DestReceiver *) self;
2060 }
static void sqlfunction_destroy(DestReceiver *self)
Definition: functions.c:2101
static void sqlfunction_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: functions.c:2066
static bool sqlfunction_receive(TupleTableSlot *slot, DestReceiver *self)
Definition: functions.c:2075
void * palloc0(Size size)
Definition: mcxt.c:981
static void sqlfunction_shutdown(DestReceiver *self)
Definition: functions.c:2092

◆ fmgr_sql()

Datum fmgr_sql ( PG_FUNCTION_ARGS  )

Definition at line 1002 of file functions.c.

References ReturnSetInfo::allowedModes, ErrorContextCallback::arg, Assert, ErrorContextCallback::callback, CommandCounterIncrement(), CreateTupleDescCopy(), ReturnSetInfo::econtext, elog, ereport, errcode(), errmsg(), ERROR, error_context_stack, ExprEndResult, ExprMultipleResult, F_EXEC_DONE, F_EXEC_START, SQLFunctionCache::fcontext, SQLFunctionCache::func_state, GetTransactionSnapshot(), init_sql_fcache(), IsA, ReturnSetInfo::isDone, JunkFilter::jf_cleanTupType, JunkFilter::jf_resultSlot, SQLFunctionCache::junkFilter, execution_state::lazyEval, SQLFunctionCache::lazyEval, lfirst, lnext(), SQLFunctionCache::lxid, PGPROC::lxid, MemoryContextDelete(), MemoryContextSwitchTo(), MyProc, execution_state::next, PG_GET_COLLATION, PointerGetDatum, PopActiveSnapshot(), postquel_end(), postquel_get_single_result(), postquel_getnext(), postquel_start(), postquel_sub_params(), ErrorContextCallback::previous, PushActiveSnapshot(), execution_state::qd, SQLFunctionCache::readonly_func, RegisterExprContextCallback(), SQLFunctionCache::rettype, ReturnSetInfo::returnMode, SQLFunctionCache::returnsSet, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, SFRM_Materialize, SFRM_Materialize_Preferred, SFRM_Materialize_Random, SFRM_ValuePerCall, SQLFunctionCache::shutdown_reg, ShutdownSQLFunction(), QueryDesc::snapshot, sql_exec_error_callback(), execution_state::status, SubTransactionIsActive(), SQLFunctionCache::subxid, SQLFunctionCache::tstore, tuplestore_begin_heap(), tuplestore_clear(), tuplestore_gettupleslot(), UnregisterExprContextCallback(), UpdateActiveSnapshotCommandId(), and work_mem.

Referenced by fmgr_info_cxt_security().

1003 {
1004  SQLFunctionCachePtr fcache;
1005  ErrorContextCallback sqlerrcontext;
1006  MemoryContext oldcontext;
1007  bool randomAccess;
1008  bool lazyEvalOK;
1009  bool is_first;
1010  bool pushed_snapshot;
1011  execution_state *es;
1012  TupleTableSlot *slot;
1013  Datum result;
1014  List *eslist;
1015  ListCell *eslc;
1016 
1017  /*
1018  * Setup error traceback support for ereport()
1019  */
1020  sqlerrcontext.callback = sql_exec_error_callback;
1021  sqlerrcontext.arg = fcinfo->flinfo;
1022  sqlerrcontext.previous = error_context_stack;
1023  error_context_stack = &sqlerrcontext;
1024 
1025  /* Check call context */
1026  if (fcinfo->flinfo->fn_retset)
1027  {
1028  ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
1029 
1030  /*
1031  * For simplicity, we require callers to support both set eval modes.
1032  * There are cases where we must use one or must use the other, and
1033  * it's not really worthwhile to postpone the check till we know. But
1034  * note we do not require caller to provide an expectedDesc.
1035  */
1036  if (!rsi || !IsA(rsi, ReturnSetInfo) ||
1037  (rsi->allowedModes & SFRM_ValuePerCall) == 0 ||
1038  (rsi->allowedModes & SFRM_Materialize) == 0)
1039  ereport(ERROR,
1040  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1041  errmsg("set-valued function called in context that cannot accept a set")));
1042  randomAccess = rsi->allowedModes & SFRM_Materialize_Random;
1043  lazyEvalOK = !(rsi->allowedModes & SFRM_Materialize_Preferred);
1044  }
1045  else
1046  {
1047  randomAccess = false;
1048  lazyEvalOK = true;
1049  }
1050 
1051  /*
1052  * Initialize fcache (build plans) if first time through; or re-initialize
1053  * if the cache is stale.
1054  */
1055  fcache = (SQLFunctionCachePtr) fcinfo->flinfo->fn_extra;
1056 
1057  if (fcache != NULL)
1058  {
1059  if (fcache->lxid != MyProc->lxid ||
1060  !SubTransactionIsActive(fcache->subxid))
1061  {
1062  /* It's stale; unlink and delete */
1063  fcinfo->flinfo->fn_extra = NULL;
1064  MemoryContextDelete(fcache->fcontext);
1065  fcache = NULL;
1066  }
1067  }
1068 
1069  if (fcache == NULL)
1070  {
1071  init_sql_fcache(fcinfo, PG_GET_COLLATION(), lazyEvalOK);
1072  fcache = (SQLFunctionCachePtr) fcinfo->flinfo->fn_extra;
1073  }
1074 
1075  /*
1076  * Switch to context in which the fcache lives. This ensures that our
1077  * tuplestore etc will have sufficient lifetime. The sub-executor is
1078  * responsible for deleting per-tuple information. (XXX in the case of a
1079  * long-lived FmgrInfo, this policy represents more memory leakage, but
1080  * it's not entirely clear where to keep stuff instead.)
1081  */
1082  oldcontext = MemoryContextSwitchTo(fcache->fcontext);
1083 
1084  /*
1085  * Find first unfinished query in function, and note whether it's the
1086  * first query.
1087  */
1088  eslist = fcache->func_state;
1089  es = NULL;
1090  is_first = true;
1091  foreach(eslc, eslist)
1092  {
1093  es = (execution_state *) lfirst(eslc);
1094 
1095  while (es && es->status == F_EXEC_DONE)
1096  {
1097  is_first = false;
1098  es = es->next;
1099  }
1100 
1101  if (es)
1102  break;
1103  }
1104 
1105  /*
1106  * Convert params to appropriate format if starting a fresh execution. (If
1107  * continuing execution, we can re-use prior params.)
1108  */
1109  if (is_first && es && es->status == F_EXEC_START)
1110  postquel_sub_params(fcache, fcinfo);
1111 
1112  /*
1113  * Build tuplestore to hold results, if we don't have one already. Note
1114  * it's in the query-lifespan context.
1115  */
1116  if (!fcache->tstore)
1117  fcache->tstore = tuplestore_begin_heap(randomAccess, false, work_mem);
1118 
1119  /*
1120  * Execute each command in the function one after another until we either
1121  * run out of commands or get a result row from a lazily-evaluated SELECT.
1122  *
1123  * Notes about snapshot management:
1124  *
1125  * In a read-only function, we just use the surrounding query's snapshot.
1126  *
1127  * In a non-read-only function, we rely on the fact that we'll never
1128  * suspend execution between queries of the function: the only reason to
1129  * suspend execution before completion is if we are returning a row from a
1130  * lazily-evaluated SELECT. So, when first entering this loop, we'll
1131  * either start a new query (and push a fresh snapshot) or re-establish
1132  * the active snapshot from the existing query descriptor. If we need to
1133  * start a new query in a subsequent execution of the loop, either we need
1134  * a fresh snapshot (and pushed_snapshot is false) or the existing
1135  * snapshot is on the active stack and we can just bump its command ID.
1136  */
1137  pushed_snapshot = false;
1138  while (es)
1139  {
1140  bool completed;
1141 
1142  if (es->status == F_EXEC_START)
1143  {
1144  /*
1145  * If not read-only, be sure to advance the command counter for
1146  * each command, so that all work to date in this transaction is
1147  * visible. Take a new snapshot if we don't have one yet,
1148  * otherwise just bump the command ID in the existing snapshot.
1149  */
1150  if (!fcache->readonly_func)
1151  {
1153  if (!pushed_snapshot)
1154  {
1156  pushed_snapshot = true;
1157  }
1158  else
1160  }
1161 
1162  postquel_start(es, fcache);
1163  }
1164  else if (!fcache->readonly_func && !pushed_snapshot)
1165  {
1166  /* Re-establish active snapshot when re-entering function */
1168  pushed_snapshot = true;
1169  }
1170 
1171  completed = postquel_getnext(es, fcache);
1172 
1173  /*
1174  * If we ran the command to completion, we can shut it down now. Any
1175  * row(s) we need to return are safely stashed in the tuplestore, and
1176  * we want to be sure that, for example, AFTER triggers get fired
1177  * before we return anything. Also, if the function doesn't return
1178  * set, we can shut it down anyway because it must be a SELECT and we
1179  * don't care about fetching any more result rows.
1180  */
1181  if (completed || !fcache->returnsSet)
1182  postquel_end(es);
1183 
1184  /*
1185  * Break from loop if we didn't shut down (implying we got a
1186  * lazily-evaluated row). Otherwise we'll press on till the whole
1187  * function is done, relying on the tuplestore to keep hold of the
1188  * data to eventually be returned. This is necessary since an
1189  * INSERT/UPDATE/DELETE RETURNING that sets the result might be
1190  * followed by additional rule-inserted commands, and we want to
1191  * finish doing all those commands before we return anything.
1192  */
1193  if (es->status != F_EXEC_DONE)
1194  break;
1195 
1196  /*
1197  * Advance to next execution_state, which might be in the next list.
1198  */
1199  es = es->next;
1200  while (!es)
1201  {
1202  eslc = lnext(eslist, eslc);
1203  if (!eslc)
1204  break; /* end of function */
1205 
1206  es = (execution_state *) lfirst(eslc);
1207 
1208  /*
1209  * Flush the current snapshot so that we will take a new one for
1210  * the new query list. This ensures that new snaps are taken at
1211  * original-query boundaries, matching the behavior of interactive
1212  * execution.
1213  */
1214  if (pushed_snapshot)
1215  {
1217  pushed_snapshot = false;
1218  }
1219  }
1220  }
1221 
1222  /*
1223  * The tuplestore now contains whatever row(s) we are supposed to return.
1224  */
1225  if (fcache->returnsSet)
1226  {
1227  ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
1228 
1229  if (es)
1230  {
1231  /*
1232  * If we stopped short of being done, we must have a lazy-eval
1233  * row.
1234  */
1235  Assert(es->lazyEval);
1236  /* Re-use the junkfilter's output slot to fetch back the tuple */
1237  Assert(fcache->junkFilter);
1238  slot = fcache->junkFilter->jf_resultSlot;
1239  if (!tuplestore_gettupleslot(fcache->tstore, true, false, slot))
1240  elog(ERROR, "failed to fetch lazy-eval tuple");
1241  /* Extract the result as a datum, and copy out from the slot */
1242  result = postquel_get_single_result(slot, fcinfo,
1243  fcache, oldcontext);
1244  /* Clear the tuplestore, but keep it for next time */
1245  /* NB: this might delete the slot's content, but we don't care */
1246  tuplestore_clear(fcache->tstore);
1247 
1248  /*
1249  * Let caller know we're not finished.
1250  */
1251  rsi->isDone = ExprMultipleResult;
1252 
1253  /*
1254  * Ensure we will get shut down cleanly if the exprcontext is not
1255  * run to completion.
1256  */
1257  if (!fcache->shutdown_reg)
1258  {
1261  PointerGetDatum(fcache));
1262  fcache->shutdown_reg = true;
1263  }
1264  }
1265  else if (fcache->lazyEval)
1266  {
1267  /*
1268  * We are done with a lazy evaluation. Clean up.
1269  */
1270  tuplestore_clear(fcache->tstore);
1271 
1272  /*
1273  * Let caller know we're finished.
1274  */
1275  rsi->isDone = ExprEndResult;
1276 
1277  fcinfo->isnull = true;
1278  result = (Datum) 0;
1279 
1280  /* Deregister shutdown callback, if we made one */
1281  if (fcache->shutdown_reg)
1282  {
1285  PointerGetDatum(fcache));
1286  fcache->shutdown_reg = false;
1287  }
1288  }
1289  else
1290  {
1291  /*
1292  * We are done with a non-lazy evaluation. Return whatever is in
1293  * the tuplestore. (It is now caller's responsibility to free the
1294  * tuplestore when done.)
1295  */
1297  rsi->setResult = fcache->tstore;
1298  fcache->tstore = NULL;
1299  /* must copy desc because execSRF.c will free it */
1300  if (fcache->junkFilter)
1302 
1303  fcinfo->isnull = true;
1304  result = (Datum) 0;
1305 
1306  /* Deregister shutdown callback, if we made one */
1307  if (fcache->shutdown_reg)
1308  {
1311  PointerGetDatum(fcache));
1312  fcache->shutdown_reg = false;
1313  }
1314  }
1315  }
1316  else
1317  {
1318  /*
1319  * Non-set function. If we got a row, return it; else return NULL.
1320  */
1321  if (fcache->junkFilter)
1322  {
1323  /* Re-use the junkfilter's output slot to fetch back the tuple */
1324  slot = fcache->junkFilter->jf_resultSlot;
1325  if (tuplestore_gettupleslot(fcache->tstore, true, false, slot))
1326  result = postquel_get_single_result(slot, fcinfo,
1327  fcache, oldcontext);
1328  else
1329  {
1330  fcinfo->isnull = true;
1331  result = (Datum) 0;
1332  }
1333  }
1334  else
1335  {
1336  /* Should only get here for VOID functions and procedures */
1337  Assert(fcache->rettype == VOIDOID);
1338  fcinfo->isnull = true;
1339  result = (Datum) 0;
1340  }
1341 
1342  /* Clear the tuplestore, but keep it for next time */
1343  tuplestore_clear(fcache->tstore);
1344  }
1345 
1346  /* Pop snapshot if we have pushed one */
1347  if (pushed_snapshot)
1349 
1350  /*
1351  * If we've gone through every command in the function, we are done. Reset
1352  * the execution states to start over again on next call.
1353  */
1354  if (es == NULL)
1355  {
1356  foreach(eslc, fcache->func_state)
1357  {
1358  es = (execution_state *) lfirst(eslc);
1359  while (es)
1360  {
1361  es->status = F_EXEC_START;
1362  es = es->next;
1363  }
1364  }
1365  }
1366 
1367  error_context_stack = sqlerrcontext.previous;
1368 
1369  MemoryContextSwitchTo(oldcontext);
1370 
1371  return result;
1372 }
bool SubTransactionIsActive(SubTransactionId subxid)
Definition: xact.c:737
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:110
void UpdateActiveSnapshotCommandId(void)
Definition: snapmgr.c:728
#define IsA(nodeptr, _type_)
Definition: nodes.h:578
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:212
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:310
MemoryContext fcontext
Definition: functions.c:122
PGPROC * MyProc
Definition: proc.c:67
void UnregisterExprContextCallback(ExprContext *econtext, ExprContextCallbackFunction function, Datum arg)
Definition: execUtils.c:950
#define PointerGetDatum(X)
Definition: postgres.h:556
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
ExecStatus status
Definition: functions.c:67
int errcode(int sqlerrcode)
Definition: elog.c:691
TupleTableSlot * jf_resultSlot
Definition: execnodes.h:371
JunkFilter * junkFilter
Definition: functions.c:112
static void postquel_start(execution_state *es, SQLFunctionCachePtr fcache)
Definition: functions.c:803
void PopActiveSnapshot(void)
Definition: snapmgr.c:759
Tuplestorestate * tstore
Definition: functions.c:110
void(* callback)(void *arg)
Definition: elog.h:243
struct ErrorContextCallback * previous
Definition: elog.h:242
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
#define PG_GET_COLLATION()
Definition: fmgr.h:198
Snapshot snapshot
Definition: execdesc.h:39
ErrorContextCallback * error_context_stack
Definition: elog.c:92
#define ERROR
Definition: elog.h:43
static void sql_exec_error_callback(void *arg)
Definition: functions.c:1379
void tuplestore_clear(Tuplestorestate *state)
Definition: tuplestore.c:418
static void postquel_end(execution_state *es)
Definition: functions.c:899
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:680
List * func_state
Definition: functions.c:120
LocalTransactionId lxid
Definition: functions.c:125
TupleDesc jf_cleanTupType
Definition: execnodes.h:369
static void ShutdownSQLFunction(Datum arg)
Definition: functions.c:1461
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318
uintptr_t Datum
Definition: postgres.h:367
void CommandCounterIncrement(void)
Definition: xact.c:1021
int work_mem
Definition: globals.c:121
QueryDesc * qd
Definition: functions.c:71
#define ereport(elevel,...)
Definition: elog.h:155
int allowedModes
Definition: execnodes.h:304
SetFunctionReturnMode returnMode
Definition: execnodes.h:306
static Datum postquel_get_single_result(TupleTableSlot *slot, FunctionCallInfo fcinfo, SQLFunctionCachePtr fcache, MemoryContext resultcontext)
Definition: functions.c:959
bool tuplestore_gettupleslot(Tuplestorestate *state, bool forward, bool copy, TupleTableSlot *slot)
Definition: tuplestore.c:1078
#define Assert(condition)
Definition: c.h:800
#define lfirst(lc)
Definition: pg_list.h:169
void RegisterExprContextCallback(ExprContext *econtext, ExprContextCallbackFunction function, Datum arg)
Definition: execUtils.c:924
static void init_sql_fcache(FunctionCallInfo fcinfo, Oid collation, bool lazyEvalOK)
Definition: functions.c:599
Tuplestorestate * setResult
Definition: execnodes.h:309
ExprContext * econtext
Definition: execnodes.h:302
SQLFunctionCache * SQLFunctionCachePtr
Definition: functions.c:129
TupleDesc setDesc
Definition: execnodes.h:310
int errmsg(const char *fmt,...)
Definition: elog.c:902
#define elog(elevel,...)
Definition: elog.h:228
ExprDoneCond isDone
Definition: execnodes.h:307
SubTransactionId subxid
Definition: functions.c:126
struct execution_state * next
Definition: functions.c:66
static bool postquel_getnext(execution_state *es, SQLFunctionCachePtr fcache)
Definition: functions.c:865
Definition: pg_list.h:50
static void postquel_sub_params(SQLFunctionCachePtr fcache, FunctionCallInfo fcinfo)
Definition: functions.c:919
LocalTransactionId lxid
Definition: proc.h:139

◆ prepare_sql_fn_parse_info()

SQLFunctionParseInfoPtr prepare_sql_fn_parse_info ( HeapTuple  procedureTuple,
Node call_expr,
Oid  inputCollation 
)

Definition at line 190 of file functions.c.

References SQLFunctionParseInfo::argnames, SQLFunctionParseInfo::argtypes, SQLFunctionParseInfo::collation, ereport, errcode(), errmsg(), ERROR, SQLFunctionParseInfo::fname, format_type_be(), get_call_expr_argtype(), get_func_input_arg_names(), GETSTRUCT, InvalidOid, NameStr, SQLFunctionParseInfo::nargs, palloc(), palloc0(), PointerGetDatum, PROCNAMEARGSNSP, pstrdup(), and SysCacheGetAttr().

Referenced by fmgr_sql_validator(), init_sql_fcache(), inline_function(), and inline_set_returning_function().

193 {
195  Form_pg_proc procedureStruct = (Form_pg_proc) GETSTRUCT(procedureTuple);
196  int nargs;
197 
199 
200  /* Function's name (only) can be used to qualify argument names */
201  pinfo->fname = pstrdup(NameStr(procedureStruct->proname));
202 
203  /* Save the function's input collation */
204  pinfo->collation = inputCollation;
205 
206  /*
207  * Copy input argument types from the pg_proc entry, then resolve any
208  * polymorphic types.
209  */
210  pinfo->nargs = nargs = procedureStruct->pronargs;
211  if (nargs > 0)
212  {
213  Oid *argOidVect;
214  int argnum;
215 
216  argOidVect = (Oid *) palloc(nargs * sizeof(Oid));
217  memcpy(argOidVect,
218  procedureStruct->proargtypes.values,
219  nargs * sizeof(Oid));
220 
221  for (argnum = 0; argnum < nargs; argnum++)
222  {
223  Oid argtype = argOidVect[argnum];
224 
225  if (IsPolymorphicType(argtype))
226  {
227  argtype = get_call_expr_argtype(call_expr, argnum);
228  if (argtype == InvalidOid)
229  ereport(ERROR,
230  (errcode(ERRCODE_DATATYPE_MISMATCH),
231  errmsg("could not determine actual type of argument declared %s",
232  format_type_be(argOidVect[argnum]))));
233  argOidVect[argnum] = argtype;
234  }
235  }
236 
237  pinfo->argtypes = argOidVect;
238  }
239 
240  /*
241  * Collect names of arguments, too, if any
242  */
243  if (nargs > 0)
244  {
245  Datum proargnames;
246  Datum proargmodes;
247  int n_arg_names;
248  bool isNull;
249 
250  proargnames = SysCacheGetAttr(PROCNAMEARGSNSP, procedureTuple,
251  Anum_pg_proc_proargnames,
252  &isNull);
253  if (isNull)
254  proargnames = PointerGetDatum(NULL); /* just to be sure */
255 
256  proargmodes = SysCacheGetAttr(PROCNAMEARGSNSP, procedureTuple,
257  Anum_pg_proc_proargmodes,
258  &isNull);
259  if (isNull)
260  proargmodes = PointerGetDatum(NULL); /* just to be sure */
261 
262  n_arg_names = get_func_input_arg_names(procedureStruct->prokind,
263  proargnames, proargmodes,
264  &pinfo->argnames);
265 
266  /* Paranoia: ignore the result if too few array entries */
267  if (n_arg_names < nargs)
268  pinfo->argnames = NULL;
269  }
270  else
271  pinfo->argnames = NULL;
272 
273  return pinfo;
274 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define PointerGetDatum(X)
Definition: postgres.h:556
char * pstrdup(const char *in)
Definition: mcxt.c:1187
struct SQLFunctionParseInfo * SQLFunctionParseInfoPtr
Definition: functions.h:21
int errcode(int sqlerrcode)
Definition: elog.c:691
Oid get_call_expr_argtype(Node *expr, int argnum)
Definition: fmgr.c:1823
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
unsigned int Oid
Definition: postgres_ext.h:31
#define ERROR
Definition: elog.h:43
void * palloc0(Size size)
Definition: mcxt.c:981
uintptr_t Datum
Definition: postgres.h:367
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1376
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:133
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:155
void * palloc(Size size)
Definition: mcxt.c:950
int errmsg(const char *fmt,...)
Definition: elog.c:902
#define NameStr(name)
Definition: c.h:677
int get_func_input_arg_names(char prokind, Datum proargnames, Datum proargmodes, char ***arg_names)
Definition: funcapi.c:1237

◆ sql_fn_parser_setup()

void sql_fn_parser_setup ( struct ParseState pstate,
SQLFunctionParseInfoPtr  pinfo 
)

Definition at line 280 of file functions.c.

References ParseState::p_paramref_hook, ParseState::p_post_columnref_hook, ParseState::p_pre_columnref_hook, ParseState::p_ref_hook_state, sql_fn_param_ref(), and sql_fn_post_column_ref().

Referenced by fmgr_sql_validator(), init_sql_fcache(), inline_function(), and inline_set_returning_function().

281 {
282  pstate->p_pre_columnref_hook = NULL;
285  /* no need to use p_coerce_param_hook */
286  pstate->p_ref_hook_state = (void *) pinfo;
287 }
PostParseColumnRefHook p_post_columnref_hook
Definition: parse_node.h:219
ParseParamRefHook p_paramref_hook
Definition: parse_node.h:220
static Node * sql_fn_post_column_ref(ParseState *pstate, ColumnRef *cref, Node *var)
Definition: functions.c:293
void * p_ref_hook_state
Definition: parse_node.h:222
static Node * sql_fn_param_ref(ParseState *pstate, ParamRef *pref)
Definition: functions.c:411
PreParseColumnRefHook p_pre_columnref_hook
Definition: parse_node.h:218