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 (Oid func_id, Oid rettype, List *queryTreeList, bool *modifyTargetList, JunkFilter **junkFilter)
 
DestReceiverCreateSQLFunctionDestReceiver (void)
 

Typedef Documentation

◆ SQLFunctionParseInfoPtr

Definition at line 21 of file functions.h.

Function Documentation

◆ check_sql_fn_retval()

bool check_sql_fn_retval ( Oid  func_id,
Oid  rettype,
List queryTreeList,
bool modifyTargetList,
JunkFilter **  junkFilter 
)

Definition at line 1574 of file functions.c.

References Assert, AssertArg, Query::canSetTag, CMD_DELETE, CMD_INSERT, CMD_SELECT, CMD_UPDATE, COERCE_IMPLICIT_CAST, Query::commandType, CreateTupleDescCopy(), ereport, errcode(), errdetail(), errmsg(), ERROR, ExecCleanTargetListLength(), ExecInitJunkFilter(), ExecInitJunkFilterConversion(), TargetEntry::expr, exprType(), format_type_be(), get_func_result_type(), get_typcollation(), get_typtype(), InvalidOid, IsBinaryCoercible(), lappend(), lfirst, lfirst_node, linitial, list_concat(), makeConst(), makeRelabelType(), MakeSingleTupleTableSlot(), makeTargetEntry(), TupleDescData::natts, NIL, parse(), TargetEntry::resjunk, TargetEntry::resno, TargetEntry::ressortgroupref, Query::returningList, Query::setOperations, Query::targetList, TTSOpsMinimalTuple, TupleDescAttr, and TYPEFUNC_COMPOSITE.

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

1577 {
1578  Query *parse;
1579  List **tlist_ptr;
1580  List *tlist;
1581  int tlistlen;
1582  char fn_typtype;
1583  Oid restype;
1584  ListCell *lc;
1585 
1586  AssertArg(!IsPolymorphicType(rettype));
1587 
1588  if (modifyTargetList)
1589  *modifyTargetList = false; /* initialize for no change */
1590  if (junkFilter)
1591  *junkFilter = NULL; /* initialize in case of VOID result */
1592 
1593  /*
1594  * If it's declared to return VOID, we don't care what's in the function.
1595  * (This takes care of the procedure case, as well.)
1596  */
1597  if (rettype == VOIDOID)
1598  return false;
1599 
1600  /*
1601  * Find the last canSetTag query in the list. This isn't necessarily the
1602  * last parsetree, because rule rewriting can insert queries after what
1603  * the user wrote.
1604  */
1605  parse = NULL;
1606  foreach(lc, queryTreeList)
1607  {
1608  Query *q = lfirst_node(Query, lc);
1609 
1610  if (q->canSetTag)
1611  parse = q;
1612  }
1613 
1614  /*
1615  * If it's a plain SELECT, it returns whatever the targetlist says.
1616  * Otherwise, if it's INSERT/UPDATE/DELETE with RETURNING, it returns
1617  * that. Otherwise, the function return type must be VOID.
1618  *
1619  * Note: eventually replace this test with QueryReturnsTuples? We'd need
1620  * a more general method of determining the output type, though. Also, it
1621  * seems too dangerous to consider FETCH or EXECUTE as returning a
1622  * determinable rowtype, since they depend on relatively short-lived
1623  * entities.
1624  */
1625  if (parse &&
1626  parse->commandType == CMD_SELECT)
1627  {
1628  tlist_ptr = &parse->targetList;
1629  tlist = parse->targetList;
1630  }
1631  else if (parse &&
1632  (parse->commandType == CMD_INSERT ||
1633  parse->commandType == CMD_UPDATE ||
1634  parse->commandType == CMD_DELETE) &&
1635  parse->returningList)
1636  {
1637  tlist_ptr = &parse->returningList;
1638  tlist = parse->returningList;
1639  }
1640  else
1641  {
1642  /* Empty function body, or last statement is a utility command */
1643  ereport(ERROR,
1644  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1645  errmsg("return type mismatch in function declared to return %s",
1646  format_type_be(rettype)),
1647  errdetail("Function's final statement must be SELECT or INSERT/UPDATE/DELETE RETURNING.")));
1648  return false; /* keep compiler quiet */
1649  }
1650 
1651  /*
1652  * OK, check that the targetlist returns something matching the declared
1653  * type.
1654  */
1655 
1656  /*
1657  * Count the non-junk entries in the result targetlist.
1658  */
1659  tlistlen = ExecCleanTargetListLength(tlist);
1660 
1661  fn_typtype = get_typtype(rettype);
1662 
1663  if (fn_typtype == TYPTYPE_BASE ||
1664  fn_typtype == TYPTYPE_DOMAIN ||
1665  fn_typtype == TYPTYPE_ENUM ||
1666  fn_typtype == TYPTYPE_RANGE)
1667  {
1668  /*
1669  * For scalar-type returns, the target list must have exactly one
1670  * non-junk entry, and its type must agree with what the user
1671  * declared; except we allow binary-compatible types too.
1672  */
1673  TargetEntry *tle;
1674 
1675  if (tlistlen != 1)
1676  ereport(ERROR,
1677  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1678  errmsg("return type mismatch in function declared to return %s",
1679  format_type_be(rettype)),
1680  errdetail("Final statement must return exactly one column.")));
1681 
1682  /* We assume here that non-junk TLEs must come first in tlists */
1683  tle = (TargetEntry *) linitial(tlist);
1684  Assert(!tle->resjunk);
1685 
1686  restype = exprType((Node *) tle->expr);
1687  if (!IsBinaryCoercible(restype, rettype))
1688  ereport(ERROR,
1689  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1690  errmsg("return type mismatch in function declared to return %s",
1691  format_type_be(rettype)),
1692  errdetail("Actual return type is %s.",
1693  format_type_be(restype))));
1694  if (modifyTargetList && restype != rettype)
1695  {
1696  tle->expr = (Expr *) makeRelabelType(tle->expr,
1697  rettype,
1698  -1,
1699  get_typcollation(rettype),
1701  /* Relabel is dangerous if TLE is a sort/group or setop column */
1702  if (tle->ressortgroupref != 0 || parse->setOperations)
1703  *modifyTargetList = true;
1704  }
1705 
1706  /* Set up junk filter if needed */
1707  if (junkFilter)
1708  *junkFilter = ExecInitJunkFilter(tlist,
1710  }
1711  else if (fn_typtype == TYPTYPE_COMPOSITE || rettype == RECORDOID)
1712  {
1713  /*
1714  * Returns a rowtype.
1715  *
1716  * Note that we will not consider a domain over composite to be a
1717  * "rowtype" return type; it goes through the scalar case above. This
1718  * is because SQL functions don't provide any implicit casting to the
1719  * result type, so there is no way to produce a domain-over-composite
1720  * result except by computing it as an explicit single-column result.
1721  */
1722  TupleDesc tupdesc;
1723  int tupnatts; /* physical number of columns in tuple */
1724  int tuplogcols; /* # of nondeleted columns in tuple */
1725  int colindex; /* physical column index */
1726  List *newtlist; /* new non-junk tlist entries */
1727  List *junkattrs; /* new junk tlist entries */
1728 
1729  /*
1730  * If the target list is of length 1, and the type of the varnode in
1731  * the target list matches the declared return type, this is okay.
1732  * This can happen, for example, where the body of the function is
1733  * 'SELECT func2()', where func2 has the same composite return type as
1734  * the function that's calling it.
1735  *
1736  * XXX Note that if rettype is RECORD, the IsBinaryCoercible check
1737  * will succeed for any composite restype. For the moment we rely on
1738  * runtime type checking to catch any discrepancy, but it'd be nice to
1739  * do better at parse time.
1740  */
1741  if (tlistlen == 1)
1742  {
1743  TargetEntry *tle = (TargetEntry *) linitial(tlist);
1744 
1745  Assert(!tle->resjunk);
1746  restype = exprType((Node *) tle->expr);
1747  if (IsBinaryCoercible(restype, rettype))
1748  {
1749  if (modifyTargetList && restype != rettype)
1750  {
1751  tle->expr = (Expr *) makeRelabelType(tle->expr,
1752  rettype,
1753  -1,
1754  get_typcollation(rettype),
1756  /* Relabel is dangerous if sort/group or setop column */
1757  if (tle->ressortgroupref != 0 || parse->setOperations)
1758  *modifyTargetList = true;
1759  }
1760  /* Set up junk filter if needed */
1761  if (junkFilter)
1762  {
1763  TupleTableSlot *slot =
1765 
1766  *junkFilter = ExecInitJunkFilter(tlist, slot);
1767  }
1768  return false; /* NOT returning whole tuple */
1769  }
1770  }
1771 
1772  /*
1773  * Is the rowtype fixed, or determined only at runtime? (Note we
1774  * cannot see TYPEFUNC_COMPOSITE_DOMAIN here.)
1775  */
1776  if (get_func_result_type(func_id, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
1777  {
1778  /*
1779  * Assume we are returning the whole tuple. Crosschecking against
1780  * what the caller expects will happen at runtime.
1781  */
1782  if (junkFilter)
1783  {
1784  TupleTableSlot *slot;
1785 
1787  *junkFilter = ExecInitJunkFilter(tlist, slot);
1788  }
1789  return true;
1790  }
1791  Assert(tupdesc);
1792 
1793  /*
1794  * Verify that the targetlist matches the return tuple type. We scan
1795  * the non-deleted attributes to ensure that they match the datatypes
1796  * of the non-resjunk columns. For deleted attributes, insert NULL
1797  * result columns if the caller asked for that.
1798  */
1799  tupnatts = tupdesc->natts;
1800  tuplogcols = 0; /* we'll count nondeleted cols as we go */
1801  colindex = 0;
1802  newtlist = NIL; /* these are only used if modifyTargetList */
1803  junkattrs = NIL;
1804 
1805  foreach(lc, tlist)
1806  {
1807  TargetEntry *tle = (TargetEntry *) lfirst(lc);
1808  Form_pg_attribute attr;
1809  Oid tletype;
1810  Oid atttype;
1811 
1812  if (tle->resjunk)
1813  {
1814  if (modifyTargetList)
1815  junkattrs = lappend(junkattrs, tle);
1816  continue;
1817  }
1818 
1819  do
1820  {
1821  colindex++;
1822  if (colindex > tupnatts)
1823  ereport(ERROR,
1824  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1825  errmsg("return type mismatch in function declared to return %s",
1826  format_type_be(rettype)),
1827  errdetail("Final statement returns too many columns.")));
1828  attr = TupleDescAttr(tupdesc, colindex - 1);
1829  if (attr->attisdropped && modifyTargetList)
1830  {
1831  Expr *null_expr;
1832 
1833  /* The type of the null we insert isn't important */
1834  null_expr = (Expr *) makeConst(INT4OID,
1835  -1,
1836  InvalidOid,
1837  sizeof(int32),
1838  (Datum) 0,
1839  true, /* isnull */
1840  true /* byval */ );
1841  newtlist = lappend(newtlist,
1842  makeTargetEntry(null_expr,
1843  colindex,
1844  NULL,
1845  false));
1846  /* NULL insertion is dangerous in a setop */
1847  if (parse->setOperations)
1848  *modifyTargetList = true;
1849  }
1850  } while (attr->attisdropped);
1851  tuplogcols++;
1852 
1853  tletype = exprType((Node *) tle->expr);
1854  atttype = attr->atttypid;
1855  if (!IsBinaryCoercible(tletype, atttype))
1856  ereport(ERROR,
1857  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1858  errmsg("return type mismatch in function declared to return %s",
1859  format_type_be(rettype)),
1860  errdetail("Final statement returns %s instead of %s at column %d.",
1861  format_type_be(tletype),
1862  format_type_be(atttype),
1863  tuplogcols)));
1864  if (modifyTargetList)
1865  {
1866  if (tletype != atttype)
1867  {
1868  tle->expr = (Expr *) makeRelabelType(tle->expr,
1869  atttype,
1870  -1,
1871  get_typcollation(atttype),
1873  /* Relabel is dangerous if sort/group or setop column */
1874  if (tle->ressortgroupref != 0 || parse->setOperations)
1875  *modifyTargetList = true;
1876  }
1877  tle->resno = colindex;
1878  newtlist = lappend(newtlist, tle);
1879  }
1880  }
1881 
1882  /* remaining columns in tupdesc had better all be dropped */
1883  for (colindex++; colindex <= tupnatts; colindex++)
1884  {
1885  if (!TupleDescAttr(tupdesc, colindex - 1)->attisdropped)
1886  ereport(ERROR,
1887  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1888  errmsg("return type mismatch in function declared to return %s",
1889  format_type_be(rettype)),
1890  errdetail("Final statement returns too few columns.")));
1891  if (modifyTargetList)
1892  {
1893  Expr *null_expr;
1894 
1895  /* The type of the null we insert isn't important */
1896  null_expr = (Expr *) makeConst(INT4OID,
1897  -1,
1898  InvalidOid,
1899  sizeof(int32),
1900  (Datum) 0,
1901  true, /* isnull */
1902  true /* byval */ );
1903  newtlist = lappend(newtlist,
1904  makeTargetEntry(null_expr,
1905  colindex,
1906  NULL,
1907  false));
1908  /* NULL insertion is dangerous in a setop */
1909  if (parse->setOperations)
1910  *modifyTargetList = true;
1911  }
1912  }
1913 
1914  if (modifyTargetList)
1915  {
1916  /* ensure resjunk columns are numbered correctly */
1917  foreach(lc, junkattrs)
1918  {
1919  TargetEntry *tle = (TargetEntry *) lfirst(lc);
1920 
1921  tle->resno = colindex++;
1922  }
1923  /* replace the tlist with the modified one */
1924  *tlist_ptr = list_concat(newtlist, junkattrs);
1925  }
1926 
1927  /* Set up junk filter if needed */
1928  if (junkFilter)
1929  {
1930  TupleTableSlot *slot =
1932 
1933  *junkFilter = ExecInitJunkFilterConversion(tlist,
1934  CreateTupleDescCopy(tupdesc),
1935  slot);
1936  }
1937 
1938  /* Report that we are returning entire tuple result */
1939  return true;
1940  }
1941  else
1942  ereport(ERROR,
1943  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1944  errmsg("return type %s is not supported for SQL functions",
1945  format_type_be(rettype))));
1946 
1947  return false;
1948 }
#define NIL
Definition: pg_list.h:65
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:110
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1208
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
JunkFilter * ExecInitJunkFilterConversion(List *targetList, TupleDesc cleanTupType, TupleTableSlot *slot)
Definition: execJunk.c:135
Definition: nodes.h:525
List * list_concat(List *list1, const List *list2)
Definition: list.c:516
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
unsigned int Oid
Definition: postgres_ext.h:31
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
bool resjunk
Definition: primnodes.h:1400
#define linitial(l)
Definition: pg_list.h:195
#define ERROR
Definition: elog.h:43
#define lfirst_node(type, lc)
Definition: pg_list.h:193
RelabelType * makeRelabelType(Expr *arg, Oid rtype, int32 rtypmod, Oid rcollid, CoercionForm rformat)
Definition: makefuncs.c:400
int errdetail(const char *fmt,...)
Definition: elog.c:955
AttrNumber resno
Definition: primnodes.h:1394
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
bool IsBinaryCoercible(Oid srctype, Oid targettype)
List * lappend(List *list, void *datum)
Definition: list.c:322
int ExecCleanTargetListLength(List *targetlist)
Definition: execUtils.c:1085
TypeFuncClass get_func_result_type(Oid functionId, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:289
uintptr_t Datum
Definition: postgres.h:367
#define InvalidOid
Definition: postgres_ext.h:36
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:2823
CmdType commandType
Definition: parsenodes.h:112
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
Expr * expr
Definition: primnodes.h:1393
bool canSetTag
Definition: parsenodes.h:118
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
Node * setOperations
Definition: parsenodes.h:165
int errmsg(const char *fmt,...)
Definition: elog.c:822
Index ressortgroupref
Definition: primnodes.h:1396
Definition: pg_list.h:50
JunkFilter * ExecInitJunkFilter(List *targetList, TupleTableSlot *slot)
Definition: execJunk.c:60
const TupleTableSlotOps TTSOpsMinimalTuple
Definition: execTuples.c:85
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 1488 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().

1489 {
1490  ListCell *lc;
1491 
1492  foreach(lc, queryTreeList)
1493  {
1494  Query *query = lfirst_node(Query, lc);
1495 
1496  /*
1497  * Disallow procedures with output arguments. The current
1498  * implementation would just throw the output values away, unless the
1499  * statement is the last one. Per SQL standard, we should assign the
1500  * output values by name. By disallowing this here, we preserve an
1501  * opportunity for future improvement.
1502  */
1503  if (query->commandType == CMD_UTILITY &&
1504  IsA(query->utilityStmt, CallStmt))
1505  {
1506  CallStmt *stmt = castNode(CallStmt, query->utilityStmt);
1507  HeapTuple tuple;
1508  int numargs;
1509  Oid *argtypes;
1510  char **argnames;
1511  char *argmodes;
1512  int i;
1513 
1515  if (!HeapTupleIsValid(tuple))
1516  elog(ERROR, "cache lookup failed for function %u", stmt->funcexpr->funcid);
1517  numargs = get_func_arg_info(tuple, &argtypes, &argnames, &argmodes);
1518  ReleaseSysCache(tuple);
1519 
1520  for (i = 0; i < numargs; i++)
1521  {
1522  if (argmodes && (argmodes[i] == PROARGMODE_INOUT || argmodes[i] == PROARGMODE_OUT))
1523  ereport(ERROR,
1524  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1525  errmsg("calling procedures with output arguments is not supported in SQL functions")));
1526  }
1527  }
1528  }
1529 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
FuncExpr * funcexpr
Definition: parsenodes.h:2875
#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:455
#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 1955 of file functions.c.

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

Referenced by CreateDestReceiver().

1956 {
1957  DR_sqlfunction *self = (DR_sqlfunction *) palloc0(sizeof(DR_sqlfunction));
1958 
1959  self->pub.receiveSlot = sqlfunction_receive;
1960  self->pub.rStartup = sqlfunction_startup;
1961  self->pub.rShutdown = sqlfunction_shutdown;
1962  self->pub.rDestroy = sqlfunction_destroy;
1963  self->pub.mydest = DestSQLFunction;
1964 
1965  /* private fields will be set by postquel_start */
1966 
1967  return (DestReceiver *) self;
1968 }
static void sqlfunction_destroy(DestReceiver *self)
Definition: functions.c:2009
static void sqlfunction_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: functions.c:1974
static bool sqlfunction_receive(TupleTableSlot *slot, DestReceiver *self)
Definition: functions.c:1983
void * palloc0(Size size)
Definition: mcxt.c:980
static void sqlfunction_shutdown(DestReceiver *self)
Definition: functions.c:2000

◆ fmgr_sql()

Datum fmgr_sql ( PG_FUNCTION_ARGS  )

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

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

187 {
189  Form_pg_proc procedureStruct = (Form_pg_proc) GETSTRUCT(procedureTuple);
190  int nargs;
191 
193 
194  /* Function's name (only) can be used to qualify argument names */
195  pinfo->fname = pstrdup(NameStr(procedureStruct->proname));
196 
197  /* Save the function's input collation */
198  pinfo->collation = inputCollation;
199 
200  /*
201  * Copy input argument types from the pg_proc entry, then resolve any
202  * polymorphic types.
203  */
204  pinfo->nargs = nargs = procedureStruct->pronargs;
205  if (nargs > 0)
206  {
207  Oid *argOidVect;
208  int argnum;
209 
210  argOidVect = (Oid *) palloc(nargs * sizeof(Oid));
211  memcpy(argOidVect,
212  procedureStruct->proargtypes.values,
213  nargs * sizeof(Oid));
214 
215  for (argnum = 0; argnum < nargs; argnum++)
216  {
217  Oid argtype = argOidVect[argnum];
218 
219  if (IsPolymorphicType(argtype))
220  {
221  argtype = get_call_expr_argtype(call_expr, argnum);
222  if (argtype == InvalidOid)
223  ereport(ERROR,
224  (errcode(ERRCODE_DATATYPE_MISMATCH),
225  errmsg("could not determine actual type of argument declared %s",
226  format_type_be(argOidVect[argnum]))));
227  argOidVect[argnum] = argtype;
228  }
229  }
230 
231  pinfo->argtypes = argOidVect;
232  }
233 
234  /*
235  * Collect names of arguments, too, if any
236  */
237  if (nargs > 0)
238  {
239  Datum proargnames;
240  Datum proargmodes;
241  int n_arg_names;
242  bool isNull;
243 
244  proargnames = SysCacheGetAttr(PROCNAMEARGSNSP, procedureTuple,
245  Anum_pg_proc_proargnames,
246  &isNull);
247  if (isNull)
248  proargnames = PointerGetDatum(NULL); /* just to be sure */
249 
250  proargmodes = SysCacheGetAttr(PROCNAMEARGSNSP, procedureTuple,
251  Anum_pg_proc_proargmodes,
252  &isNull);
253  if (isNull)
254  proargmodes = PointerGetDatum(NULL); /* just to be sure */
255 
256  n_arg_names = get_func_input_arg_names(proargnames, proargmodes,
257  &pinfo->argnames);
258 
259  /* Paranoia: ignore the result if too few array entries */
260  if (n_arg_names < nargs)
261  pinfo->argnames = NULL;
262  }
263  else
264  pinfo->argnames = NULL;
265 
266  return pinfo;
267 }
#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 273 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().

274 {
275  pstate->p_pre_columnref_hook = NULL;
278  /* no need to use p_coerce_param_hook */
279  pstate->p_ref_hook_state = (void *) pinfo;
280 }
PostParseColumnRefHook p_post_columnref_hook
Definition: parse_node.h:216
ParseParamRefHook p_paramref_hook
Definition: parse_node.h:217
static Node * sql_fn_post_column_ref(ParseState *pstate, ColumnRef *cref, Node *var)
Definition: functions.c:286
void * p_ref_hook_state
Definition: parse_node.h:219
static Node * sql_fn_param_ref(ParseState *pstate, ParamRef *pref)
Definition: functions.c:404
PreParseColumnRefHook p_pre_columnref_hook
Definition: parse_node.h:215