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.

Data Structures

struct  SQLFunctionParseInfo
 

Typedefs

typedef struct SQLFunctionParseInfo SQLFunctionParseInfo
 
typedef 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

◆ SQLFunctionParseInfo

◆ SQLFunctionParseInfoPtr

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

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

◆ check_sql_fn_statements()

void check_sql_fn_statements ( List queryTreeLists)

Definition at line 1524 of file functions.c.

References CMD_UTILITY, Query::commandType, ereport, errcode(), errmsg(), ERROR, IsA, lfirst_node, NIL, CallStmt::outargs, execution_state::stmt, and Query::utilityStmt.

Referenced by fmgr_sql_validator(), and init_sql_fcache().

1525 {
1526  ListCell *lc;
1527 
1528  /* We are given a list of sublists of Queries */
1529  foreach(lc, queryTreeLists)
1530  {
1531  List *sublist = lfirst_node(List, lc);
1532  ListCell *lc2;
1533 
1534  foreach(lc2, sublist)
1535  {
1536  Query *query = lfirst_node(Query, lc2);
1537 
1538  /*
1539  * Disallow calling procedures with output arguments. The current
1540  * implementation would just throw the output values away, unless
1541  * the statement is the last one. Per SQL standard, we should
1542  * assign the output values by name. By disallowing this here, we
1543  * preserve an opportunity for future improvement.
1544  */
1545  if (query->commandType == CMD_UTILITY &&
1546  IsA(query->utilityStmt, CallStmt))
1547  {
1548  CallStmt *stmt = (CallStmt *) query->utilityStmt;
1549 
1550  if (stmt->outargs != NIL)
1551  ereport(ERROR,
1552  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1553  errmsg("calling procedures with output arguments is not supported in SQL functions")));
1554  }
1555  }
1556  }
1557 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:587
int errcode(int sqlerrcode)
Definition: elog.c:698
Node * utilityStmt
Definition: parsenodes.h:128
#define ERROR
Definition: elog.h:46
#define lfirst_node(type, lc)
Definition: pg_list.h:172
List * outargs
Definition: parsenodes.h:3039
#define ereport(elevel,...)
Definition: elog.h:157
CmdType commandType
Definition: parsenodes.h:120
int errmsg(const char *fmt,...)
Definition: elog.c:909
Definition: pg_list.h:50

◆ CreateSQLFunctionDestReceiver()

DestReceiver* CreateSQLFunctionDestReceiver ( void  )

Definition at line 2046 of file functions.c.

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

Referenced by CreateDestReceiver().

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

◆ fmgr_sql()

Datum fmgr_sql ( PG_FUNCTION_ARGS  )

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

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

◆ prepare_sql_fn_parse_info()

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

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

179 {
181  Form_pg_proc procedureStruct = (Form_pg_proc) GETSTRUCT(procedureTuple);
182  int nargs;
183 
185 
186  /* Function's name (only) can be used to qualify argument names */
187  pinfo->fname = pstrdup(NameStr(procedureStruct->proname));
188 
189  /* Save the function's input collation */
190  pinfo->collation = inputCollation;
191 
192  /*
193  * Copy input argument types from the pg_proc entry, then resolve any
194  * polymorphic types.
195  */
196  pinfo->nargs = nargs = procedureStruct->pronargs;
197  if (nargs > 0)
198  {
199  Oid *argOidVect;
200  int argnum;
201 
202  argOidVect = (Oid *) palloc(nargs * sizeof(Oid));
203  memcpy(argOidVect,
204  procedureStruct->proargtypes.values,
205  nargs * sizeof(Oid));
206 
207  for (argnum = 0; argnum < nargs; argnum++)
208  {
209  Oid argtype = argOidVect[argnum];
210 
211  if (IsPolymorphicType(argtype))
212  {
213  argtype = get_call_expr_argtype(call_expr, argnum);
214  if (argtype == InvalidOid)
215  ereport(ERROR,
216  (errcode(ERRCODE_DATATYPE_MISMATCH),
217  errmsg("could not determine actual type of argument declared %s",
218  format_type_be(argOidVect[argnum]))));
219  argOidVect[argnum] = argtype;
220  }
221  }
222 
223  pinfo->argtypes = argOidVect;
224  }
225 
226  /*
227  * Collect names of arguments, too, if any
228  */
229  if (nargs > 0)
230  {
231  Datum proargnames;
232  Datum proargmodes;
233  int n_arg_names;
234  bool isNull;
235 
236  proargnames = SysCacheGetAttr(PROCNAMEARGSNSP, procedureTuple,
237  Anum_pg_proc_proargnames,
238  &isNull);
239  if (isNull)
240  proargnames = PointerGetDatum(NULL); /* just to be sure */
241 
242  proargmodes = SysCacheGetAttr(PROCNAMEARGSNSP, procedureTuple,
243  Anum_pg_proc_proargmodes,
244  &isNull);
245  if (isNull)
246  proargmodes = PointerGetDatum(NULL); /* just to be sure */
247 
248  n_arg_names = get_func_input_arg_names(proargnames, proargmodes,
249  &pinfo->argnames);
250 
251  /* Paranoia: ignore the result if too few array entries */
252  if (n_arg_names < nargs)
253  pinfo->argnames = NULL;
254  }
255  else
256  pinfo->argnames = NULL;
257 
258  return pinfo;
259 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
#define PointerGetDatum(X)
Definition: postgres.h:600
char * pstrdup(const char *in)
Definition: mcxt.c:1299
int errcode(int sqlerrcode)
Definition: elog.c:698
Oid get_call_expr_argtype(Node *expr, int argnum)
Definition: fmgr.c:1819
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:46
int get_func_input_arg_names(Datum proargnames, Datum proargmodes, char ***arg_names)
Definition: funcapi.c:1412
void * palloc0(Size size)
Definition: mcxt.c:1093
uintptr_t Datum
Definition: postgres.h:411
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1388
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:136
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
SQLFunctionParseInfo * SQLFunctionParseInfoPtr
Definition: functions.h:35
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define NameStr(name)
Definition: c.h:681

◆ sql_fn_parser_setup()

void sql_fn_parser_setup ( struct ParseState pstate,
SQLFunctionParseInfoPtr  pinfo 
)

Definition at line 265 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(), inline_set_returning_function(), and interpret_AS_clause().

266 {
267  pstate->p_pre_columnref_hook = NULL;
270  /* no need to use p_coerce_param_hook */
271  pstate->p_ref_hook_state = (void *) pinfo;
272 }
PostParseColumnRefHook p_post_columnref_hook
Definition: parse_node.h:221
ParseParamRefHook p_paramref_hook
Definition: parse_node.h:222
static Node * sql_fn_post_column_ref(ParseState *pstate, ColumnRef *cref, Node *var)
Definition: functions.c:278
void * p_ref_hook_state
Definition: parse_node.h:224
static Node * sql_fn_param_ref(ParseState *pstate, ParamRef *pref)
Definition: functions.c:396
PreParseColumnRefHook p_pre_columnref_hook
Definition: parse_node.h:220