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

Go to the source code of this file.

Data Structures

struct  SQLFunctionParseInfo
 

Typedefs

typedef struct SQLFunctionParseInfo SQLFunctionParseInfo
 
typedef SQLFunctionParseInfoSQLFunctionParseInfoPtr
 

Functions

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

Typedef Documentation

◆ SQLFunctionParseInfo

◆ SQLFunctionParseInfoPtr

Definition at line 35 of file functions.h.

Function Documentation

◆ check_sql_fn_retval()

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

Definition at line 1608 of file functions.c.

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

References RangeTblEntry::alias, Assert(), CMD_DELETE, CMD_INSERT, CMD_MERGE, 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::rtable, RTE_SUBQUERY, RangeTblEntry::rtekind, RangeTblRef::rtindex, RangeTblEntry::subquery, Query::targetList, and TupleDescAttr.

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

◆ check_sql_fn_statements()

void check_sql_fn_statements ( List queryTreeLists)

Definition at line 1533 of file functions.c.

1534 {
1535  ListCell *lc;
1536 
1537  /* We are given a list of sublists of Queries */
1538  foreach(lc, queryTreeLists)
1539  {
1540  List *sublist = lfirst_node(List, lc);
1541  ListCell *lc2;
1542 
1543  foreach(lc2, sublist)
1544  {
1545  Query *query = lfirst_node(Query, lc2);
1546 
1547  /*
1548  * Disallow calling procedures with output arguments. The current
1549  * implementation would just throw the output values away, unless
1550  * the statement is the last one. Per SQL standard, we should
1551  * assign the output values by name. By disallowing this here, we
1552  * preserve an opportunity for future improvement.
1553  */
1554  if (query->commandType == CMD_UTILITY &&
1555  IsA(query->utilityStmt, CallStmt))
1556  {
1557  CallStmt *stmt = (CallStmt *) query->utilityStmt;
1558 
1559  if (stmt->outargs != NIL)
1560  ereport(ERROR,
1561  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1562  errmsg("calling procedures with output arguments is not supported in SQL functions")));
1563  }
1564  }
1565  }
1566 }
#define stmt
Definition: indent_codes.h:59
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
@ CMD_UTILITY
Definition: nodes.h:260
Node * utilityStmt
Definition: parsenodes.h:136

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

Referenced by fmgr_sql_validator(), and init_sql_fcache().

◆ CreateSQLFunctionDestReceiver()

DestReceiver* CreateSQLFunctionDestReceiver ( void  )

Definition at line 2062 of file functions.c.

2063 {
2064  DR_sqlfunction *self = (DR_sqlfunction *) palloc0(sizeof(DR_sqlfunction));
2065 
2066  self->pub.receiveSlot = sqlfunction_receive;
2067  self->pub.rStartup = sqlfunction_startup;
2068  self->pub.rShutdown = sqlfunction_shutdown;
2069  self->pub.rDestroy = sqlfunction_destroy;
2070  self->pub.mydest = DestSQLFunction;
2071 
2072  /* private fields will be set by postquel_start */
2073 
2074  return (DestReceiver *) self;
2075 }
@ DestSQLFunction
Definition: dest.h:96
static void sqlfunction_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: functions.c:2081
static bool sqlfunction_receive(TupleTableSlot *slot, DestReceiver *self)
Definition: functions.c:2090
static void sqlfunction_destroy(DestReceiver *self)
Definition: functions.c:2116
static void sqlfunction_shutdown(DestReceiver *self)
Definition: functions.c:2107
void * palloc0(Size size)
Definition: mcxt.c:1334

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

Referenced by CreateDestReceiver().

◆ fmgr_sql()

Datum fmgr_sql ( PG_FUNCTION_ARGS  )

Definition at line 1028 of file functions.c.

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

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(), if(), 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(), PGPROC::vxid, and work_mem.

Referenced by fmgr_info_cxt_security().

◆ prepare_sql_fn_parse_info()

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

Definition at line 176 of file functions.c.

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

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(), pstrdup(), and SysCacheGetAttr().

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

◆ sql_fn_parser_setup()

void sql_fn_parser_setup ( struct ParseState pstate,
SQLFunctionParseInfoPtr  pinfo 
)

Definition at line 265 of file functions.c.

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

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

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