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 1532 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, NULL, 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().

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

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

Referenced by CreateDestReceiver().

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

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

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