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 *queryTreeList)
 
bool check_sql_fn_retval (List *queryTreeList, 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 queryTreeList,
Oid  rettype,
TupleDesc  rettupdesc,
bool  insertDroppedCols,
List **  resultTargetList 
)

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

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

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

1513 {
1514  ListCell *lc;
1515 
1516  foreach(lc, queryTreeList)
1517  {
1518  Query *query = lfirst_node(Query, lc);
1519 
1520  /*
1521  * Disallow procedures with output arguments. The current
1522  * implementation would just throw the output values away, unless the
1523  * statement is the last one. Per SQL standard, we should assign the
1524  * output values by name. By disallowing this here, we preserve an
1525  * opportunity for future improvement.
1526  */
1527  if (query->commandType == CMD_UTILITY &&
1528  IsA(query->utilityStmt, CallStmt))
1529  {
1530  CallStmt *stmt = castNode(CallStmt, query->utilityStmt);
1531  HeapTuple tuple;
1532  int numargs;
1533  Oid *argtypes;
1534  char **argnames;
1535  char *argmodes;
1536  int i;
1537 
1539  if (!HeapTupleIsValid(tuple))
1540  elog(ERROR, "cache lookup failed for function %u", stmt->funcexpr->funcid);
1541  numargs = get_func_arg_info(tuple, &argtypes, &argnames, &argmodes);
1542  ReleaseSysCache(tuple);
1543 
1544  for (i = 0; i < numargs; i++)
1545  {
1546  if (argmodes && (argmodes[i] == PROARGMODE_INOUT || argmodes[i] == PROARGMODE_OUT))
1547  ereport(ERROR,
1548  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1549  errmsg("calling procedures with output arguments is not supported in SQL functions")));
1550  }
1551  }
1552  }
1553 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
FuncExpr * funcexpr
Definition: parsenodes.h:2903
#define castNode(_type_, nodeptr)
Definition: nodes.h:598
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:610
unsigned int Oid
Definition: postgres_ext.h:31
Node * utilityStmt
Definition: parsenodes.h:120
Oid funcid
Definition: primnodes.h:469
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
#define lfirst_node(type, lc)
Definition: pg_list.h:193
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define ereport(elevel,...)
Definition: elog.h:144
CmdType commandType
Definition: parsenodes.h:112
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define elog(elevel,...)
Definition: elog.h:214
int i

◆ CreateSQLFunctionDestReceiver()

DestReceiver* CreateSQLFunctionDestReceiver ( void  )

Definition at line 2030 of file functions.c.

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

Referenced by CreateDestReceiver().

2031 {
2032  DR_sqlfunction *self = (DR_sqlfunction *) palloc0(sizeof(DR_sqlfunction));
2033 
2034  self->pub.receiveSlot = sqlfunction_receive;
2035  self->pub.rStartup = sqlfunction_startup;
2036  self->pub.rShutdown = sqlfunction_shutdown;
2037  self->pub.rDestroy = sqlfunction_destroy;
2038  self->pub.mydest = DestSQLFunction;
2039 
2040  /* private fields will be set by postquel_start */
2041 
2042  return (DestReceiver *) self;
2043 }
static void sqlfunction_destroy(DestReceiver *self)
Definition: functions.c:2084
static void sqlfunction_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: functions.c:2049
static bool sqlfunction_receive(TupleTableSlot *slot, DestReceiver *self)
Definition: functions.c:2058
void * palloc0(Size size)
Definition: mcxt.c:981
static void sqlfunction_shutdown(DestReceiver *self)
Definition: functions.c:2075

◆ fmgr_sql()

Datum fmgr_sql ( PG_FUNCTION_ARGS  )

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

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

◆ 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(proargnames, proargmodes,
263  &pinfo->argnames);
264 
265  /* Paranoia: ignore the result if too few array entries */
266  if (n_arg_names < nargs)
267  pinfo->argnames = NULL;
268  }
269  else
270  pinfo->argnames = NULL;
271 
272  return pinfo;
273 }
#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:610
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
int get_func_input_arg_names(Datum proargnames, Datum proargmodes, char ***arg_names)
Definition: funcapi.c:1236
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:1377
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:133
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:144
void * palloc(Size size)
Definition: mcxt.c:950
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define NameStr(name)
Definition: c.h:622

◆ sql_fn_parser_setup()

void sql_fn_parser_setup ( struct ParseState pstate,
SQLFunctionParseInfoPtr  pinfo 
)

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

280 {
281  pstate->p_pre_columnref_hook = NULL;
284  /* no need to use p_coerce_param_hook */
285  pstate->p_ref_hook_state = (void *) pinfo;
286 }
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:292
void * p_ref_hook_state
Definition: parse_node.h:222
static Node * sql_fn_param_ref(ParseState *pstate, ParamRef *pref)
Definition: functions.c:410
PreParseColumnRefHook p_pre_columnref_hook
Definition: parse_node.h:218