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

Go to the source code of this file.

Data Structures

struct  SQLFunctionParseInfo
 

Typedefs

typedef struct SQLFunctionParseInfo SQLFunctionParseInfo
 
typedef SQLFunctionParseInfoSQLFunctionParseInfoPtr
 

Functions

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

Typedef Documentation

◆ SQLFunctionParseInfo

◆ SQLFunctionParseInfoPtr

Definition at line 35 of file functions.h.

Function Documentation

◆ check_sql_fn_retval()

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

Definition at line 1607 of file functions.c.

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

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

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

2055 {
2056  DR_sqlfunction *self = (DR_sqlfunction *) palloc0(sizeof(DR_sqlfunction));
2057 
2058  self->pub.receiveSlot = sqlfunction_receive;
2059  self->pub.rStartup = sqlfunction_startup;
2060  self->pub.rShutdown = sqlfunction_shutdown;
2061  self->pub.rDestroy = sqlfunction_destroy;
2062  self->pub.mydest = DestSQLFunction;
2063 
2064  /* private fields will be set by postquel_start */
2065 
2066  return (DestReceiver *) self;
2067 }
@ DestSQLFunction
Definition: dest.h:96
static void sqlfunction_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: functions.c:2073
static bool sqlfunction_receive(TupleTableSlot *slot, DestReceiver *self)
Definition: functions.c:2082
static void sqlfunction_destroy(DestReceiver *self)
Definition: functions.c:2108
static void sqlfunction_shutdown(DestReceiver *self)
Definition: functions.c:2099
void * palloc0(Size size)
Definition: mcxt.c:1257

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

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

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(), 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:735
Oid get_call_expr_argtype(Node *expr, int argnum)
Definition: fmgr.c:1912
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:1644
void * palloc(Size size)
Definition: mcxt.c:1226
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:1081
@ PROCNAMEARGSNSP
Definition: syscache.h:78

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().

◆ 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:238
ParseParamRefHook p_paramref_hook
Definition: parse_node.h:236
PreParseColumnRefHook p_pre_columnref_hook
Definition: parse_node.h:234
PostParseColumnRefHook p_post_columnref_hook
Definition: parse_node.h:235

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().