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 1589 of file functions.c.

References RangeTblEntry::alias, Assert, AssertArg, 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().

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

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

◆ CreateSQLFunctionDestReceiver()

DestReceiver* CreateSQLFunctionDestReceiver ( void  )

Definition at line 2026 of file functions.c.

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

Referenced by CreateDestReceiver().

2027 {
2028  DR_sqlfunction *self = (DR_sqlfunction *) palloc0(sizeof(DR_sqlfunction));
2029 
2030  self->pub.receiveSlot = sqlfunction_receive;
2031  self->pub.rStartup = sqlfunction_startup;
2032  self->pub.rShutdown = sqlfunction_shutdown;
2033  self->pub.rDestroy = sqlfunction_destroy;
2034  self->pub.mydest = DestSQLFunction;
2035 
2036  /* private fields will be set by postquel_start */
2037 
2038  return (DestReceiver *) self;
2039 }
static void sqlfunction_destroy(DestReceiver *self)
Definition: functions.c:2080
static void sqlfunction_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: functions.c:2045
static bool sqlfunction_receive(TupleTableSlot *slot, DestReceiver *self)
Definition: functions.c:2054
void * palloc0(Size size)
Definition: mcxt.c:980
static void sqlfunction_shutdown(DestReceiver *self)
Definition: functions.c:2071

◆ fmgr_sql()

Datum fmgr_sql ( PG_FUNCTION_ARGS  )

Definition at line 1005 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(), PGPROC::lxid, SQLFunctionCache::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().

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

◆ prepare_sql_fn_parse_info()

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

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

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

◆ sql_fn_parser_setup()

void sql_fn_parser_setup ( struct ParseState pstate,
SQLFunctionParseInfoPtr  pinfo 
)

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

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