PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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
SQLFunctionParseInfo
SQLFunctionParseInfoPtr
 

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

Definition at line 21 of file functions.h.

Function Documentation

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

Definition at line 1531 of file functions.c.

References Assert, AssertArg, tupleDesc::attrs, 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, NULL, parse(), RECORDOID, TargetEntry::resjunk, TargetEntry::resno, TargetEntry::ressortgroupref, Query::returningList, Query::setOperations, Query::targetList, 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().

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

Definition at line 1883 of file functions.c.

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

Referenced by CreateDestReceiver().

1884 {
1885  DR_sqlfunction *self = (DR_sqlfunction *) palloc0(sizeof(DR_sqlfunction));
1886 
1887  self->pub.receiveSlot = sqlfunction_receive;
1888  self->pub.rStartup = sqlfunction_startup;
1889  self->pub.rShutdown = sqlfunction_shutdown;
1890  self->pub.rDestroy = sqlfunction_destroy;
1891  self->pub.mydest = DestSQLFunction;
1892 
1893  /* private fields will be set by postquel_start */
1894 
1895  return (DestReceiver *) self;
1896 }
static void sqlfunction_destroy(DestReceiver *self)
Definition: functions.c:1937
static void sqlfunction_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: functions.c:1902
static bool sqlfunction_receive(TupleTableSlot *slot, DestReceiver *self)
Definition: functions.c:1911
void * palloc0(Size size)
Definition: mcxt.c:878
static void sqlfunction_shutdown(DestReceiver *self)
Definition: functions.c:1928
Datum fmgr_sql ( PG_FUNCTION_ARGS  )

Definition at line 989 of file functions.c.

References ReturnSetInfo::allowedModes, ErrorContextCallback::arg, Assert, ErrorContextCallback::callback, CommandCounterIncrement(), CreateTupleDescCopy(), ReturnSetInfo::econtext, elog, ereport, errcode(), errmsg(), ERROR, error_context_stack, ExprEndResult, ExprMultipleResult, F_EXEC_DONE, F_EXEC_START, SQLFunctionCache::fcontext, SQLFunctionCache::func_state, GetTransactionSnapshot(), init_sql_fcache(), IsA, ReturnSetInfo::isDone, JunkFilter::jf_cleanTupType, JunkFilter::jf_resultSlot, SQLFunctionCache::junkFilter, execution_state::lazyEval, SQLFunctionCache::lazyEval, lfirst, lnext, PGPROC::lxid, SQLFunctionCache::lxid, MemoryContextDelete(), MemoryContextSwitchTo(), MyProc, execution_state::next, NULL, 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(), result, 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().

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

Definition at line 273 of file functions.c.

References NULL, 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:206
ParseParamRefHook p_paramref_hook
Definition: parse_node.h:207
static Node * sql_fn_post_column_ref(ParseState *pstate, ColumnRef *cref, Node *var)
Definition: functions.c:286
#define NULL
Definition: c.h:229
void * p_ref_hook_state
Definition: parse_node.h:209
static Node * sql_fn_param_ref(ParseState *pstate, ParamRef *pref)
Definition: functions.c:402
PreParseColumnRefHook p_pre_columnref_hook
Definition: parse_node.h:205