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)
 
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 1535 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(), INT4OID, InvalidOid, IsBinaryCoercible(), IsPolymorphicType, lappend(), lfirst, lfirst_node, linitial, list_concat(), makeConst(), makeRelabelType(), makeTargetEntry(), tupleDesc::natts, NIL, parse(), RECORDOID, TargetEntry::resjunk, TargetEntry::resno, TargetEntry::ressortgroupref, Query::returningList, Query::setOperations, Query::targetList, TupleDescAttr, TYPEFUNC_COMPOSITE, TYPTYPE_BASE, TYPTYPE_COMPOSITE, TYPTYPE_DOMAIN, TYPTYPE_ENUM, TYPTYPE_RANGE, and VOIDOID.

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

1538 {
1539  Query *parse;
1540  List **tlist_ptr;
1541  List *tlist;
1542  int tlistlen;
1543  char fn_typtype;
1544  Oid restype;
1545  ListCell *lc;
1546 
1547  AssertArg(!IsPolymorphicType(rettype));
1548 
1549  if (modifyTargetList)
1550  *modifyTargetList = false; /* initialize for no change */
1551  if (junkFilter)
1552  *junkFilter = NULL; /* initialize in case of procedure/VOID result */
1553 
1554  if (!rettype)
1555  return false;
1556 
1557  /*
1558  * Find the last canSetTag query in the list. This isn't necessarily the
1559  * last parsetree, because rule rewriting can insert queries after what
1560  * the user wrote.
1561  */
1562  parse = NULL;
1563  foreach(lc, queryTreeList)
1564  {
1565  Query *q = lfirst_node(Query, lc);
1566 
1567  if (q->canSetTag)
1568  parse = q;
1569  }
1570 
1571  /*
1572  * If it's a plain SELECT, it returns whatever the targetlist says.
1573  * Otherwise, if it's INSERT/UPDATE/DELETE with RETURNING, it returns
1574  * that. Otherwise, the function return type must be VOID.
1575  *
1576  * Note: eventually replace this test with QueryReturnsTuples? We'd need
1577  * a more general method of determining the output type, though. Also, it
1578  * seems too dangerous to consider FETCH or EXECUTE as returning a
1579  * determinable rowtype, since they depend on relatively short-lived
1580  * entities.
1581  */
1582  if (parse &&
1583  parse->commandType == CMD_SELECT)
1584  {
1585  tlist_ptr = &parse->targetList;
1586  tlist = parse->targetList;
1587  }
1588  else if (parse &&
1589  (parse->commandType == CMD_INSERT ||
1590  parse->commandType == CMD_UPDATE ||
1591  parse->commandType == CMD_DELETE) &&
1592  parse->returningList)
1593  {
1594  tlist_ptr = &parse->returningList;
1595  tlist = parse->returningList;
1596  }
1597  else
1598  {
1599  /* Empty function body, or last statement is a utility command */
1600  if (rettype && rettype != VOIDOID)
1601  ereport(ERROR,
1602  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1603  errmsg("return type mismatch in function declared to return %s",
1604  format_type_be(rettype)),
1605  errdetail("Function's final statement must be SELECT or INSERT/UPDATE/DELETE RETURNING.")));
1606  return false;
1607  }
1608 
1609  /*
1610  * OK, check that the targetlist returns something matching the declared
1611  * type. (We used to insist that the declared type not be VOID in this
1612  * case, but that makes it hard to write a void function that exits after
1613  * calling another void function. Instead, we insist that the tlist
1614  * return void ... so void is treated as if it were a scalar type below.)
1615  */
1616 
1617  /*
1618  * Count the non-junk entries in the result targetlist.
1619  */
1620  tlistlen = ExecCleanTargetListLength(tlist);
1621 
1622  fn_typtype = get_typtype(rettype);
1623 
1624  if (fn_typtype == TYPTYPE_BASE ||
1625  fn_typtype == TYPTYPE_DOMAIN ||
1626  fn_typtype == TYPTYPE_ENUM ||
1627  fn_typtype == TYPTYPE_RANGE ||
1628  rettype == VOIDOID)
1629  {
1630  /*
1631  * For scalar-type returns, the target list must have exactly one
1632  * non-junk entry, and its type must agree with what the user
1633  * declared; except we allow binary-compatible types too.
1634  */
1635  TargetEntry *tle;
1636 
1637  if (tlistlen != 1)
1638  ereport(ERROR,
1639  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1640  errmsg("return type mismatch in function declared to return %s",
1641  format_type_be(rettype)),
1642  errdetail("Final statement must return exactly one column.")));
1643 
1644  /* We assume here that non-junk TLEs must come first in tlists */
1645  tle = (TargetEntry *) linitial(tlist);
1646  Assert(!tle->resjunk);
1647 
1648  restype = exprType((Node *) tle->expr);
1649  if (!IsBinaryCoercible(restype, rettype))
1650  ereport(ERROR,
1651  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1652  errmsg("return type mismatch in function declared to return %s",
1653  format_type_be(rettype)),
1654  errdetail("Actual return type is %s.",
1655  format_type_be(restype))));
1656  if (modifyTargetList && restype != rettype)
1657  {
1658  tle->expr = (Expr *) makeRelabelType(tle->expr,
1659  rettype,
1660  -1,
1661  get_typcollation(rettype),
1663  /* Relabel is dangerous if TLE is a sort/group or setop column */
1664  if (tle->ressortgroupref != 0 || parse->setOperations)
1665  *modifyTargetList = true;
1666  }
1667 
1668  /* Set up junk filter if needed */
1669  if (junkFilter)
1670  *junkFilter = ExecInitJunkFilter(tlist, false, NULL);
1671  }
1672  else if (fn_typtype == TYPTYPE_COMPOSITE || rettype == RECORDOID)
1673  {
1674  /*
1675  * Returns a rowtype.
1676  *
1677  * Note that we will not consider a domain over composite to be a
1678  * "rowtype" return type; it goes through the scalar case above. This
1679  * is because SQL functions don't provide any implicit casting to the
1680  * result type, so there is no way to produce a domain-over-composite
1681  * result except by computing it as an explicit single-column result.
1682  */
1683  TupleDesc tupdesc;
1684  int tupnatts; /* physical number of columns in tuple */
1685  int tuplogcols; /* # of nondeleted columns in tuple */
1686  int colindex; /* physical column index */
1687  List *newtlist; /* new non-junk tlist entries */
1688  List *junkattrs; /* new junk tlist entries */
1689 
1690  /*
1691  * If the target list is of length 1, and the type of the varnode in
1692  * the target list matches the declared return type, this is okay.
1693  * This can happen, for example, where the body of the function is
1694  * 'SELECT func2()', where func2 has the same composite return type as
1695  * the function that's calling it.
1696  *
1697  * XXX Note that if rettype is RECORD, the IsBinaryCoercible check
1698  * will succeed for any composite restype. For the moment we rely on
1699  * runtime type checking to catch any discrepancy, but it'd be nice to
1700  * do better at parse time.
1701  */
1702  if (tlistlen == 1)
1703  {
1704  TargetEntry *tle = (TargetEntry *) linitial(tlist);
1705 
1706  Assert(!tle->resjunk);
1707  restype = exprType((Node *) tle->expr);
1708  if (IsBinaryCoercible(restype, rettype))
1709  {
1710  if (modifyTargetList && restype != rettype)
1711  {
1712  tle->expr = (Expr *) makeRelabelType(tle->expr,
1713  rettype,
1714  -1,
1715  get_typcollation(rettype),
1717  /* Relabel is dangerous if sort/group or setop column */
1718  if (tle->ressortgroupref != 0 || parse->setOperations)
1719  *modifyTargetList = true;
1720  }
1721  /* Set up junk filter if needed */
1722  if (junkFilter)
1723  *junkFilter = ExecInitJunkFilter(tlist, false, NULL);
1724  return false; /* NOT returning whole tuple */
1725  }
1726  }
1727 
1728  /*
1729  * Is the rowtype fixed, or determined only at runtime? (Note we
1730  * cannot see TYPEFUNC_COMPOSITE_DOMAIN here.)
1731  */
1732  if (get_func_result_type(func_id, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
1733  {
1734  /*
1735  * Assume we are returning the whole tuple. Crosschecking against
1736  * what the caller expects will happen at runtime.
1737  */
1738  if (junkFilter)
1739  *junkFilter = ExecInitJunkFilter(tlist, false, NULL);
1740  return true;
1741  }
1742  Assert(tupdesc);
1743 
1744  /*
1745  * Verify that the targetlist matches the return tuple type. We scan
1746  * the non-deleted attributes to ensure that they match the datatypes
1747  * of the non-resjunk columns. For deleted attributes, insert NULL
1748  * result columns if the caller asked for that.
1749  */
1750  tupnatts = tupdesc->natts;
1751  tuplogcols = 0; /* we'll count nondeleted cols as we go */
1752  colindex = 0;
1753  newtlist = NIL; /* these are only used if modifyTargetList */
1754  junkattrs = NIL;
1755 
1756  foreach(lc, tlist)
1757  {
1758  TargetEntry *tle = (TargetEntry *) lfirst(lc);
1759  Form_pg_attribute attr;
1760  Oid tletype;
1761  Oid atttype;
1762 
1763  if (tle->resjunk)
1764  {
1765  if (modifyTargetList)
1766  junkattrs = lappend(junkattrs, tle);
1767  continue;
1768  }
1769 
1770  do
1771  {
1772  colindex++;
1773  if (colindex > tupnatts)
1774  ereport(ERROR,
1775  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1776  errmsg("return type mismatch in function declared to return %s",
1777  format_type_be(rettype)),
1778  errdetail("Final statement returns too many columns.")));
1779  attr = TupleDescAttr(tupdesc, colindex - 1);
1780  if (attr->attisdropped && modifyTargetList)
1781  {
1782  Expr *null_expr;
1783 
1784  /* The type of the null we insert isn't important */
1785  null_expr = (Expr *) makeConst(INT4OID,
1786  -1,
1787  InvalidOid,
1788  sizeof(int32),
1789  (Datum) 0,
1790  true, /* isnull */
1791  true /* byval */ );
1792  newtlist = lappend(newtlist,
1793  makeTargetEntry(null_expr,
1794  colindex,
1795  NULL,
1796  false));
1797  /* NULL insertion is dangerous in a setop */
1798  if (parse->setOperations)
1799  *modifyTargetList = true;
1800  }
1801  } while (attr->attisdropped);
1802  tuplogcols++;
1803 
1804  tletype = exprType((Node *) tle->expr);
1805  atttype = attr->atttypid;
1806  if (!IsBinaryCoercible(tletype, atttype))
1807  ereport(ERROR,
1808  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1809  errmsg("return type mismatch in function declared to return %s",
1810  format_type_be(rettype)),
1811  errdetail("Final statement returns %s instead of %s at column %d.",
1812  format_type_be(tletype),
1813  format_type_be(atttype),
1814  tuplogcols)));
1815  if (modifyTargetList)
1816  {
1817  if (tletype != atttype)
1818  {
1819  tle->expr = (Expr *) makeRelabelType(tle->expr,
1820  atttype,
1821  -1,
1822  get_typcollation(atttype),
1824  /* Relabel is dangerous if sort/group or setop column */
1825  if (tle->ressortgroupref != 0 || parse->setOperations)
1826  *modifyTargetList = true;
1827  }
1828  tle->resno = colindex;
1829  newtlist = lappend(newtlist, tle);
1830  }
1831  }
1832 
1833  /* remaining columns in tupdesc had better all be dropped */
1834  for (colindex++; colindex <= tupnatts; colindex++)
1835  {
1836  if (!TupleDescAttr(tupdesc, colindex - 1)->attisdropped)
1837  ereport(ERROR,
1838  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1839  errmsg("return type mismatch in function declared to return %s",
1840  format_type_be(rettype)),
1841  errdetail("Final statement returns too few columns.")));
1842  if (modifyTargetList)
1843  {
1844  Expr *null_expr;
1845 
1846  /* The type of the null we insert isn't important */
1847  null_expr = (Expr *) makeConst(INT4OID,
1848  -1,
1849  InvalidOid,
1850  sizeof(int32),
1851  (Datum) 0,
1852  true, /* isnull */
1853  true /* byval */ );
1854  newtlist = lappend(newtlist,
1855  makeTargetEntry(null_expr,
1856  colindex,
1857  NULL,
1858  false));
1859  /* NULL insertion is dangerous in a setop */
1860  if (parse->setOperations)
1861  *modifyTargetList = true;
1862  }
1863  }
1864 
1865  if (modifyTargetList)
1866  {
1867  /* ensure resjunk columns are numbered correctly */
1868  foreach(lc, junkattrs)
1869  {
1870  TargetEntry *tle = (TargetEntry *) lfirst(lc);
1871 
1872  tle->resno = colindex++;
1873  }
1874  /* replace the tlist with the modified one */
1875  *tlist_ptr = list_concat(newtlist, junkattrs);
1876  }
1877 
1878  /* Set up junk filter if needed */
1879  if (junkFilter)
1880  *junkFilter = ExecInitJunkFilterConversion(tlist,
1881  CreateTupleDescCopy(tupdesc),
1882  NULL);
1883 
1884  /* Report that we are returning entire tuple result */
1885  return true;
1886  }
1887  else
1888  ereport(ERROR,
1889  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1890  errmsg("return type %s is not supported for SQL functions",
1891  format_type_be(rettype))));
1892 
1893  return false;
1894 }
#define NIL
Definition: pg_list.h:69
#define TYPTYPE_DOMAIN
Definition: pg_type.h:722
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:110
#define TYPTYPE_BASE
Definition: pg_type.h:720
#define TYPTYPE_COMPOSITE
Definition: pg_type.h:721
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:90
JunkFilter * ExecInitJunkFilterConversion(List *targetList, TupleDesc cleanTupType, TupleTableSlot *slot)
Definition: execJunk.c:136
#define INT4OID
Definition: pg_type.h:316
Definition: nodes.h:513
int errcode(int sqlerrcode)
Definition: elog.c:575
char get_typtype(Oid typid)
Definition: lsyscache.c:2383
char * format_type_be(Oid type_oid)
Definition: format_type.c:320
List * list_concat(List *list1, List *list2)
Definition: list.c:321
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:298
int natts
Definition: tupdesc.h:79
signed int int32
Definition: c.h:302
List * targetList
Definition: parsenodes.h:138
bool resjunk
Definition: primnodes.h:1382
#define linitial(l)
Definition: pg_list.h:111
#define VOIDOID
Definition: pg_type.h:690
#define ERROR
Definition: elog.h:43
#define IsPolymorphicType(typid)
Definition: pg_type.h:745
#define lfirst_node(type, lc)
Definition: pg_list.h:109
RelabelType * makeRelabelType(Expr *arg, Oid rtype, int32 rtypmod, Oid rcollid, CoercionForm rformat)
Definition: makefuncs.c:401
JunkFilter * ExecInitJunkFilter(List *targetList, bool hasoid, TupleTableSlot *slot)
Definition: execJunk.c:61
int errdetail(const char *fmt,...)
Definition: elog.c:873
AttrNumber resno
Definition: primnodes.h:1376
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
#define RECORDOID
Definition: pg_type.h:680
List * returningList
Definition: parsenodes.h:144
#define ereport(elevel, rest)
Definition: elog.h:122
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:237
#define AssertArg(condition)
Definition: c.h:690
bool IsBinaryCoercible(Oid srctype, Oid targettype)
List * lappend(List *list, void *datum)
Definition: list.c:128
int ExecCleanTargetListLength(List *targetlist)
Definition: execUtils.c:1044
TypeFuncClass get_func_result_type(Oid functionId, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:272
#define TYPTYPE_RANGE
Definition: pg_type.h:725
uintptr_t Datum
Definition: postgres.h:365
#define InvalidOid
Definition: postgres_ext.h:36
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:2799
CmdType commandType
Definition: parsenodes.h:110
#define Assert(condition)
Definition: c.h:688
#define lfirst(lc)
Definition: pg_list.h:106
Expr * expr
Definition: primnodes.h:1375
bool canSetTag
Definition: parsenodes.h:116
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
Node * setOperations
Definition: parsenodes.h:163
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define TYPTYPE_ENUM
Definition: pg_type.h:723
Index ressortgroupref
Definition: primnodes.h:1378
Definition: pg_list.h:45
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649

◆ CreateSQLFunctionDestReceiver()

DestReceiver* CreateSQLFunctionDestReceiver ( void  )

Definition at line 1901 of file functions.c.

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

Referenced by CreateDestReceiver().

1902 {
1903  DR_sqlfunction *self = (DR_sqlfunction *) palloc0(sizeof(DR_sqlfunction));
1904 
1905  self->pub.receiveSlot = sqlfunction_receive;
1906  self->pub.rStartup = sqlfunction_startup;
1907  self->pub.rShutdown = sqlfunction_shutdown;
1908  self->pub.rDestroy = sqlfunction_destroy;
1909  self->pub.mydest = DestSQLFunction;
1910 
1911  /* private fields will be set by postquel_start */
1912 
1913  return (DestReceiver *) self;
1914 }
static void sqlfunction_destroy(DestReceiver *self)
Definition: functions.c:1955
static void sqlfunction_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: functions.c:1920
static bool sqlfunction_receive(TupleTableSlot *slot, DestReceiver *self)
Definition: functions.c:1929
void * palloc0(Size size)
Definition: mcxt.c:864
static void sqlfunction_shutdown(DestReceiver *self)
Definition: functions.c:1946

◆ fmgr_sql()

Datum fmgr_sql ( PG_FUNCTION_ARGS  )

Definition at line 993 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(), InvalidOid, 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(), VOIDOID, and work_mem.

Referenced by fmgr_info_cxt_security().

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

◆ 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:213
ParseParamRefHook p_paramref_hook
Definition: parse_node.h:214
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:216
static Node * sql_fn_param_ref(ParseState *pstate, ParamRef *pref)
Definition: functions.c:404
PreParseColumnRefHook p_pre_columnref_hook
Definition: parse_node.h:212