PostgreSQL Source Code  git master
functions.c File Reference
#include "postgres.h"
#include "access/htup_details.h"
#include "access/xact.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "executor/functions.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "parser/parse_coerce.h"
#include "parser/parse_func.h"
#include "storage/proc.h"
#include "tcop/utility.h"
#include "utils/builtins.h"
#include "utils/datum.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
Include dependency graph for functions.c:

Go to the source code of this file.

Data Structures

struct  DR_sqlfunction
 
struct  execution_state
 
struct  SQLFunctionCache
 
struct  SQLFunctionParseInfo
 

Typedefs

typedef struct execution_state execution_state
 
typedef SQLFunctionCacheSQLFunctionCachePtr
 
typedef struct SQLFunctionParseInfo SQLFunctionParseInfo
 

Enumerations

enum  ExecStatus { F_EXEC_START, F_EXEC_RUN, F_EXEC_DONE }
 

Functions

static Nodesql_fn_param_ref (ParseState *pstate, ParamRef *pref)
 
static Nodesql_fn_post_column_ref (ParseState *pstate, ColumnRef *cref, Node *var)
 
static Nodesql_fn_make_param (SQLFunctionParseInfoPtr pinfo, int paramno, int location)
 
static Nodesql_fn_resolve_param_name (SQLFunctionParseInfoPtr pinfo, const char *paramname, int location)
 
static Listinit_execution_state (List *queryTree_list, SQLFunctionCachePtr fcache, bool lazyEvalOK)
 
static void init_sql_fcache (FmgrInfo *finfo, Oid collation, bool lazyEvalOK)
 
static void postquel_start (execution_state *es, SQLFunctionCachePtr fcache)
 
static bool postquel_getnext (execution_state *es, SQLFunctionCachePtr fcache)
 
static void postquel_end (execution_state *es)
 
static void postquel_sub_params (SQLFunctionCachePtr fcache, FunctionCallInfo fcinfo)
 
static Datum postquel_get_single_result (TupleTableSlot *slot, FunctionCallInfo fcinfo, SQLFunctionCachePtr fcache, MemoryContext resultcontext)
 
static void sql_exec_error_callback (void *arg)
 
static void ShutdownSQLFunction (Datum arg)
 
static void sqlfunction_startup (DestReceiver *self, int operation, TupleDesc typeinfo)
 
static bool sqlfunction_receive (TupleTableSlot *slot, DestReceiver *self)
 
static void sqlfunction_shutdown (DestReceiver *self)
 
static void sqlfunction_destroy (DestReceiver *self)
 
SQLFunctionParseInfoPtr prepare_sql_fn_parse_info (HeapTuple procedureTuple, Node *call_expr, Oid inputCollation)
 
void sql_fn_parser_setup (struct ParseState *pstate, SQLFunctionParseInfoPtr pinfo)
 
Datum fmgr_sql (PG_FUNCTION_ARGS)
 
bool check_sql_fn_retval (Oid func_id, Oid rettype, List *queryTreeList, bool *modifyTargetList, JunkFilter **junkFilter)
 
DestReceiverCreateSQLFunctionDestReceiver (void)
 

Typedef Documentation

◆ execution_state

◆ SQLFunctionCachePtr

◆ SQLFunctionParseInfo

Enumeration Type Documentation

◆ ExecStatus

enum ExecStatus
Enumerator
F_EXEC_START 
F_EXEC_RUN 
F_EXEC_DONE 

Definition at line 58 of file functions.c.

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

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

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

Referenced by CreateDestReceiver().

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

◆ fmgr_sql()

Datum fmgr_sql ( PG_FUNCTION_ARGS  )

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

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

◆ init_execution_state()

static List * init_execution_state ( List queryTree_list,
SQLFunctionCachePtr  fcache,
bool  lazyEvalOK 
)
static

Definition at line 474 of file functions.c.

References PlannedStmt::canSetTag, Query::canSetTag, CMD_SELECT, CMD_UTILITY, CommandIsReadOnly(), PlannedStmt::commandType, Query::commandType, CreateCommandTag(), CURSOR_OPT_PARALLEL_OK, ereport, errcode(), errmsg(), ERROR, F_EXEC_START, PlannedStmt::hasModifyingCTE, IsA, IsInParallelMode(), SQLFunctionCache::junkFilter, lappend(), execution_state::lazyEval, SQLFunctionCache::lazyEval, lfirst_node, makeNode, execution_state::next, NIL, palloc(), pg_plan_query(), PreventCommandIfParallelMode(), execution_state::qd, SQLFunctionCache::readonly_func, execution_state::setsResult, execution_state::status, execution_state::stmt, PlannedStmt::stmt_len, Query::stmt_len, PlannedStmt::stmt_location, Query::stmt_location, PlannedStmt::utilityStmt, and Query::utilityStmt.

Referenced by init_sql_fcache().

477 {
478  List *eslist = NIL;
479  execution_state *lasttages = NULL;
480  ListCell *lc1;
481 
482  foreach(lc1, queryTree_list)
483  {
484  List *qtlist = lfirst_node(List, lc1);
485  execution_state *firstes = NULL;
486  execution_state *preves = NULL;
487  ListCell *lc2;
488 
489  foreach(lc2, qtlist)
490  {
491  Query *queryTree = lfirst_node(Query, lc2);
492  PlannedStmt *stmt;
493  execution_state *newes;
494 
495  /* Plan the query if needed */
496  if (queryTree->commandType == CMD_UTILITY)
497  {
498  /* Utility commands require no planning. */
499  stmt = makeNode(PlannedStmt);
500  stmt->commandType = CMD_UTILITY;
501  stmt->canSetTag = queryTree->canSetTag;
502  stmt->utilityStmt = queryTree->utilityStmt;
503  stmt->stmt_location = queryTree->stmt_location;
504  stmt->stmt_len = queryTree->stmt_len;
505  }
506  else
507  stmt = pg_plan_query(queryTree,
509  NULL);
510 
511  /*
512  * Precheck all commands for validity in a function. This should
513  * generally match the restrictions spi.c applies.
514  */
515  if (stmt->commandType == CMD_UTILITY)
516  {
517  if (IsA(stmt->utilityStmt, CopyStmt) &&
518  ((CopyStmt *) stmt->utilityStmt)->filename == NULL)
519  ereport(ERROR,
520  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
521  errmsg("cannot COPY to/from client in a SQL function")));
522 
523  if (IsA(stmt->utilityStmt, TransactionStmt))
524  ereport(ERROR,
525  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
526  /* translator: %s is a SQL statement name */
527  errmsg("%s is not allowed in a SQL function",
528  CreateCommandTag(stmt->utilityStmt))));
529  }
530 
531  if (fcache->readonly_func && !CommandIsReadOnly(stmt))
532  ereport(ERROR,
533  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
534  /* translator: %s is a SQL statement name */
535  errmsg("%s is not allowed in a non-volatile function",
536  CreateCommandTag((Node *) stmt))));
537 
538  if (IsInParallelMode() && !CommandIsReadOnly(stmt))
540 
541  /* OK, build the execution_state for this query */
542  newes = (execution_state *) palloc(sizeof(execution_state));
543  if (preves)
544  preves->next = newes;
545  else
546  firstes = newes;
547 
548  newes->next = NULL;
549  newes->status = F_EXEC_START;
550  newes->setsResult = false; /* might change below */
551  newes->lazyEval = false; /* might change below */
552  newes->stmt = stmt;
553  newes->qd = NULL;
554 
555  if (queryTree->canSetTag)
556  lasttages = newes;
557 
558  preves = newes;
559  }
560 
561  eslist = lappend(eslist, firstes);
562  }
563 
564  /*
565  * Mark the last canSetTag query as delivering the function result; then,
566  * if it is a plain SELECT, mark it for lazy evaluation. If it's not a
567  * SELECT we must always run it to completion.
568  *
569  * Note: at some point we might add additional criteria for whether to use
570  * lazy eval. However, we should prefer to use it whenever the function
571  * doesn't return set, since fetching more than one row is useless in that
572  * case.
573  *
574  * Note: don't set setsResult if the function returns VOID, as evidenced
575  * by not having made a junkfilter. This ensures we'll throw away any
576  * output from a utility statement that check_sql_fn_retval deemed to not
577  * have output.
578  */
579  if (lasttages && fcache->junkFilter)
580  {
581  lasttages->setsResult = true;
582  if (lazyEvalOK &&
583  lasttages->stmt->commandType == CMD_SELECT &&
584  !lasttages->stmt->hasModifyingCTE)
585  fcache->lazyEval = lasttages->lazyEval = true;
586  }
587 
588  return eslist;
589 }
#define NIL
Definition: pg_list.h:69
bool CommandIsReadOnly(PlannedStmt *pstmt)
Definition: utility.c:97
#define IsA(nodeptr, _type_)
Definition: nodes.h:563
int stmt_location
Definition: parsenodes.h:179
void PreventCommandIfParallelMode(const char *cmdname)
Definition: utility.c:254
Definition: nodes.h:512
ExecStatus status
Definition: functions.c:66
int errcode(int sqlerrcode)
Definition: elog.c:575
JunkFilter * junkFilter
Definition: functions.c:111
Node * utilityStmt
Definition: parsenodes.h:118
int stmt_len
Definition: plannodes.h:98
bool IsInParallelMode(void)
Definition: xact.c:906
#define ERROR
Definition: elog.h:43
#define lfirst_node(type, lc)
Definition: pg_list.h:109
int stmt_location
Definition: plannodes.h:97
Node * utilityStmt
Definition: plannodes.h:94
#define ereport(elevel, rest)
Definition: elog.h:122
const char * CreateCommandTag(Node *parsetree)
Definition: utility.c:2046
List * lappend(List *list, void *datum)
Definition: list.c:128
bool canSetTag
Definition: plannodes.h:53
CmdType commandType
Definition: plannodes.h:45
QueryDesc * qd
Definition: functions.c:70
CmdType commandType
Definition: parsenodes.h:110
#define makeNode(_type_)
Definition: nodes.h:560
bool hasModifyingCTE
Definition: plannodes.h:51
bool canSetTag
Definition: parsenodes.h:116
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2650
void * palloc(Size size)
Definition: mcxt.c:835
int errmsg(const char *fmt,...)
Definition: elog.c:797
struct execution_state * next
Definition: functions.c:65
PlannedStmt * stmt
Definition: functions.c:69
Definition: pg_list.h:45
int stmt_len
Definition: parsenodes.h:180
PlannedStmt * pg_plan_query(Query *querytree, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:790

◆ init_sql_fcache()

static void init_sql_fcache ( FmgrInfo finfo,
Oid  collation,
bool  lazyEvalOK 
)
static

Definition at line 595 of file functions.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Anum_pg_proc_prosrc, BlessTupleDesc(), check_sql_fn_retval(), elog, ereport, errcode(), errmsg(), ERROR, SQLFunctionCache::fcontext, FmgrInfo::fn_expr, FmgrInfo::fn_extra, FmgrInfo::fn_mcxt, FmgrInfo::fn_oid, SQLFunctionCache::fname, format_type_be(), SQLFunctionCache::func_state, get_fn_expr_rettype(), get_typlenbyval(), GetCurrentSubTransactionId(), GETSTRUCT, HeapTupleIsValid, init_execution_state(), InvalidOid, IsPolymorphicType, JunkFilter::jf_resultSlot, SQLFunctionCache::junkFilter, lappend(), lfirst_node, list_concat(), list_copy(), PGPROC::lxid, SQLFunctionCache::lxid, MemoryContextSwitchTo(), MyProc, NameStr, NIL, ObjectIdGetDatum, palloc0(), pg_analyze_and_rewrite_params(), pg_parse_query(), SQLFunctionCache::pinfo, prepare_sql_fn_parse_info(), PROCOID, PROVOLATILE_VOLATILE, pstrdup(), SQLFunctionCache::readonly_func, ReleaseSysCache(), SQLFunctionCache::rettype, SQLFunctionCache::returnsSet, SQLFunctionCache::returnsTuple, SearchSysCache1(), sql_fn_parser_setup(), SQLFunctionCache::src, SQLFunctionCache::subxid, SysCacheGetAttr(), TextDatumGetCString, TupleTableSlot::tts_tupleDescriptor, SQLFunctionCache::typbyval, type_is_rowtype(), and SQLFunctionCache::typlen.

Referenced by fmgr_sql().

596 {
597  Oid foid = finfo->fn_oid;
598  MemoryContext fcontext;
599  MemoryContext oldcontext;
600  Oid rettype;
601  HeapTuple procedureTuple;
602  Form_pg_proc procedureStruct;
603  SQLFunctionCachePtr fcache;
604  List *raw_parsetree_list;
605  List *queryTree_list;
606  List *flat_query_list;
607  ListCell *lc;
608  Datum tmp;
609  bool isNull;
610 
611  /*
612  * Create memory context that holds all the SQLFunctionCache data. It
613  * must be a child of whatever context holds the FmgrInfo.
614  */
615  fcontext = AllocSetContextCreate(finfo->fn_mcxt,
616  "SQL function data",
618 
619  oldcontext = MemoryContextSwitchTo(fcontext);
620 
621  /*
622  * Create the struct proper, link it to fcontext and fn_extra. Once this
623  * is done, we'll be able to recover the memory after failure, even if the
624  * FmgrInfo is long-lived.
625  */
626  fcache = (SQLFunctionCachePtr) palloc0(sizeof(SQLFunctionCache));
627  fcache->fcontext = fcontext;
628  finfo->fn_extra = (void *) fcache;
629 
630  /*
631  * get the procedure tuple corresponding to the given function Oid
632  */
633  procedureTuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(foid));
634  if (!HeapTupleIsValid(procedureTuple))
635  elog(ERROR, "cache lookup failed for function %u", foid);
636  procedureStruct = (Form_pg_proc) GETSTRUCT(procedureTuple);
637 
638  /*
639  * copy function name immediately for use by error reporting callback
640  */
641  fcache->fname = pstrdup(NameStr(procedureStruct->proname));
642 
643  /*
644  * get the result type from the procedure tuple, and check for polymorphic
645  * result type; if so, find out the actual result type.
646  */
647  rettype = procedureStruct->prorettype;
648 
649  if (IsPolymorphicType(rettype))
650  {
651  rettype = get_fn_expr_rettype(finfo);
652  if (rettype == InvalidOid) /* this probably should not happen */
653  ereport(ERROR,
654  (errcode(ERRCODE_DATATYPE_MISMATCH),
655  errmsg("could not determine actual result type for function declared to return type %s",
656  format_type_be(procedureStruct->prorettype))));
657  }
658 
659  fcache->rettype = rettype;
660 
661  /* Fetch the typlen and byval info for the result type */
662  if (rettype)
663  get_typlenbyval(rettype, &fcache->typlen, &fcache->typbyval);
664 
665  /* Remember whether we're returning setof something */
666  fcache->returnsSet = procedureStruct->proretset;
667 
668  /* Remember if function is STABLE/IMMUTABLE */
669  fcache->readonly_func =
670  (procedureStruct->provolatile != PROVOLATILE_VOLATILE);
671 
672  /*
673  * We need the actual argument types to pass to the parser. Also make
674  * sure that parameter symbols are considered to have the function's
675  * resolved input collation.
676  */
677  fcache->pinfo = prepare_sql_fn_parse_info(procedureTuple,
678  finfo->fn_expr,
679  collation);
680 
681  /*
682  * And of course we need the function body text.
683  */
684  tmp = SysCacheGetAttr(PROCOID,
685  procedureTuple,
687  &isNull);
688  if (isNull)
689  elog(ERROR, "null prosrc for function %u", foid);
690  fcache->src = TextDatumGetCString(tmp);
691 
692  /*
693  * Parse and rewrite the queries in the function text. Use sublists to
694  * keep track of the original query boundaries. But we also build a
695  * "flat" list of the rewritten queries to pass to check_sql_fn_retval.
696  * This is because the last canSetTag query determines the result type
697  * independently of query boundaries --- and it might not be in the last
698  * sublist, for example if the last query rewrites to DO INSTEAD NOTHING.
699  * (It might not be unreasonable to throw an error in such a case, but
700  * this is the historical behavior and it doesn't seem worth changing.)
701  *
702  * Note: since parsing and planning is done in fcontext, we will generate
703  * a lot of cruft that lives as long as the fcache does. This is annoying
704  * but we'll not worry about it until the module is rewritten to use
705  * plancache.c.
706  */
707  raw_parsetree_list = pg_parse_query(fcache->src);
708 
709  queryTree_list = NIL;
710  flat_query_list = NIL;
711  foreach(lc, raw_parsetree_list)
712  {
713  RawStmt *parsetree = lfirst_node(RawStmt, lc);
714  List *queryTree_sublist;
715 
716  queryTree_sublist = pg_analyze_and_rewrite_params(parsetree,
717  fcache->src,
719  fcache->pinfo,
720  NULL);
721  queryTree_list = lappend(queryTree_list, queryTree_sublist);
722  flat_query_list = list_concat(flat_query_list,
723  list_copy(queryTree_sublist));
724  }
725 
726  /*
727  * Check that the function returns the type it claims to. Although in
728  * simple cases this was already done when the function was defined, we
729  * have to recheck because database objects used in the function's queries
730  * might have changed type. We'd have to do it anyway if the function had
731  * any polymorphic arguments.
732  *
733  * Note: we set fcache->returnsTuple according to whether we are returning
734  * the whole tuple result or just a single column. In the latter case we
735  * clear returnsTuple because we need not act different from the scalar
736  * result case, even if it's a rowtype column. (However, we have to force
737  * lazy eval mode in that case; otherwise we'd need extra code to expand
738  * the rowtype column into multiple columns, since we have no way to
739  * notify the caller that it should do that.)
740  *
741  * check_sql_fn_retval will also construct a JunkFilter we can use to
742  * coerce the returned rowtype to the desired form (unless the result type
743  * is VOID, in which case there's nothing to coerce to).
744  */
745  fcache->returnsTuple = check_sql_fn_retval(foid,
746  rettype,
747  flat_query_list,
748  NULL,
749  &fcache->junkFilter);
750 
751  if (fcache->returnsTuple)
752  {
753  /* Make sure output rowtype is properly blessed */
755  }
756  else if (fcache->returnsSet && type_is_rowtype(fcache->rettype))
757  {
758  /*
759  * Returning rowtype as if it were scalar --- materialize won't work.
760  * Right now it's sufficient to override any caller preference for
761  * materialize mode, but to add more smarts in init_execution_state
762  * about this, we'd probably need a three-way flag instead of bool.
763  */
764  lazyEvalOK = true;
765  }
766 
767  /* Finally, plan the queries */
768  fcache->func_state = init_execution_state(queryTree_list,
769  fcache,
770  lazyEvalOK);
771 
772  /* Mark fcache with time of creation to show it's valid */
773  fcache->lxid = MyProc->lxid;
775 
776  ReleaseSysCache(procedureTuple);
777 
778  MemoryContextSwitchTo(oldcontext);
779 }
#define NIL
Definition: pg_list.h:69
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
MemoryContext fn_mcxt
Definition: fmgr.h:65
MemoryContext fcontext
Definition: functions.c:121
PGPROC * MyProc
Definition: proc.c:67
char * pstrdup(const char *in)
Definition: mcxt.c:1063
void sql_fn_parser_setup(struct ParseState *pstate, SQLFunctionParseInfoPtr pinfo)
Definition: functions.c:273
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define Anum_pg_proc_prosrc
Definition: pg_proc.h:115
List * list_copy(const List *oldlist)
Definition: list.c:1160
int errcode(int sqlerrcode)
Definition: elog.c:575
TupleTableSlot * jf_resultSlot
Definition: execnodes.h:336
bool check_sql_fn_retval(Oid func_id, Oid rettype, List *queryTreeList, bool *modifyTargetList, JunkFilter **junkFilter)
Definition: functions.c:1534
JunkFilter * junkFilter
Definition: functions.c:111
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
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define IsPolymorphicType(typid)
Definition: pg_type.h:745
List * pg_parse_query(const char *query_string)
Definition: postgres.c:607
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:197
#define lfirst_node(type, lc)
Definition: pg_list.h:109
TupleDesc BlessTupleDesc(TupleDesc tupdesc)
Definition: execTuples.c:1032
void(* ParserSetupHook)(struct ParseState *pstate, void *arg)
Definition: params.h:66
List * func_state
Definition: functions.c:119
LocalTransactionId lxid
Definition: functions.c:124
static List * init_execution_state(List *queryTree_list, SQLFunctionCachePtr fcache, bool lazyEvalOK)
Definition: functions.c:474
bool type_is_rowtype(Oid typid)
Definition: lsyscache.c:2424
#define ereport(elevel, rest)
Definition: elog.h:122
SQLFunctionParseInfoPtr pinfo
Definition: functions.c:96
#define PROVOLATILE_VOLATILE
Definition: pg_proc.h:5539
List * lappend(List *list, void *datum)
Definition: list.c:128
#define AllocSetContextCreate(parent, name, allocparams)
Definition: memutils.h:165
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:121
#define TextDatumGetCString(d)
Definition: builtins.h:92
void * palloc0(Size size)
Definition: mcxt.c:864
uintptr_t Datum
Definition: postgres.h:372
Oid get_fn_expr_rettype(FmgrInfo *flinfo)
Definition: fmgr.c:1882
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
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
Oid fn_oid
Definition: fmgr.h:59
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:642
fmNodePtr fn_expr
Definition: fmgr.h:66
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2020
void * fn_extra
Definition: fmgr.h:64
List * pg_analyze_and_rewrite_params(RawStmt *parsetree, const char *query_string, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
Definition: postgres.c:686
SQLFunctionCache * SQLFunctionCachePtr
Definition: functions.c:128
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define NameStr(name)
Definition: c.h:557
#define elog
Definition: elog.h:219
SQLFunctionParseInfoPtr prepare_sql_fn_parse_info(HeapTuple procedureTuple, Node *call_expr, Oid inputCollation)
Definition: functions.c:184
SubTransactionId subxid
Definition: functions.c:125
Definition: pg_list.h:45
LocalTransactionId lxid
Definition: proc.h:106

◆ postquel_end()

static void postquel_end ( execution_state es)
static

Definition at line 879 of file functions.c.

References CMD_UTILITY, QueryDesc::dest, ExecutorEnd(), ExecutorFinish(), F_EXEC_DONE, FreeQueryDesc(), QueryDesc::operation, execution_state::qd, _DestReceiver::rDestroy, and execution_state::status.

Referenced by fmgr_sql(), and ShutdownSQLFunction().

880 {
881  /* mark status done to ensure we don't do ExecutorEnd twice */
882  es->status = F_EXEC_DONE;
883 
884  /* Utility commands don't need Executor. */
885  if (es->qd->operation != CMD_UTILITY)
886  {
887  ExecutorFinish(es->qd);
888  ExecutorEnd(es->qd);
889  }
890 
891  es->qd->dest->rDestroy(es->qd->dest);
892 
893  FreeQueryDesc(es->qd);
894  es->qd = NULL;
895 }
void FreeQueryDesc(QueryDesc *qdesc)
Definition: pquery.c:105
ExecStatus status
Definition: functions.c:66
void ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:459
void ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:399
CmdType operation
Definition: execdesc.h:36
QueryDesc * qd
Definition: functions.c:70
void(* rDestroy)(DestReceiver *self)
Definition: dest.h:126
DestReceiver * dest
Definition: execdesc.h:41

◆ postquel_get_single_result()

static Datum postquel_get_single_result ( TupleTableSlot slot,
FunctionCallInfo  fcinfo,
SQLFunctionCachePtr  fcache,
MemoryContext  resultcontext 
)
static

Definition at line 949 of file functions.c.

References datumCopy(), ExecFetchSlotTupleDatum(), FunctionCallInfoData::isnull, MemoryContextSwitchTo(), SQLFunctionCache::returnsTuple, slot_getattr(), SQLFunctionCache::typbyval, SQLFunctionCache::typlen, and value.

Referenced by fmgr_sql().

953 {
954  Datum value;
955  MemoryContext oldcontext;
956 
957  /*
958  * Set up to return the function value. For pass-by-reference datatypes,
959  * be sure to allocate the result in resultcontext, not the current memory
960  * context (which has query lifespan). We can't leave the data in the
961  * TupleTableSlot because we intend to clear the slot before returning.
962  */
963  oldcontext = MemoryContextSwitchTo(resultcontext);
964 
965  if (fcache->returnsTuple)
966  {
967  /* We must return the whole tuple as a Datum. */
968  fcinfo->isnull = false;
969  value = ExecFetchSlotTupleDatum(slot);
970  }
971  else
972  {
973  /*
974  * Returning a scalar, which we have to extract from the first column
975  * of the SELECT result, and then copy into result context if needed.
976  */
977  value = slot_getattr(slot, 1, &(fcinfo->isnull));
978 
979  if (!fcinfo->isnull)
980  value = datumCopy(value, fcache->typbyval, fcache->typlen);
981  }
982 
983  MemoryContextSwitchTo(oldcontext);
984 
985  return value;
986 }
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static struct @121 value
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:128
uintptr_t Datum
Definition: postgres.h:372
Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: heaptuple.c:1142
Datum ExecFetchSlotTupleDatum(TupleTableSlot *slot)
Definition: execTuples.c:698

◆ postquel_getnext()

static bool postquel_getnext ( execution_state es,
SQLFunctionCachePtr  fcache 
)
static

Definition at line 845 of file functions.c.

References CMD_UTILITY, QueryDesc::dest, EState::es_processed, QueryDesc::estate, ExecutorRun(), ForwardScanDirection, execution_state::lazyEval, QueryDesc::operation, QueryDesc::params, QueryDesc::plannedstmt, PROCESS_UTILITY_QUERY, ProcessUtility(), execution_state::qd, QueryDesc::queryEnv, SQLFunctionCache::returnsSet, and SQLFunctionCache::src.

Referenced by fmgr_sql().

846 {
847  bool result;
848 
849  if (es->qd->operation == CMD_UTILITY)
850  {
852  fcache->src,
854  es->qd->params,
855  es->qd->queryEnv,
856  es->qd->dest,
857  NULL);
858  result = true; /* never stops early */
859  }
860  else
861  {
862  /* Run regular commands to completion unless lazyEval */
863  uint64 count = (es->lazyEval) ? 1 : 0;
864 
865  ExecutorRun(es->qd, ForwardScanDirection, count, !fcache->returnsSet || !es->lazyEval);
866 
867  /*
868  * If we requested run to completion OR there was no tuple returned,
869  * command must be complete.
870  */
871  result = (count == 0 || es->qd->estate->es_processed == 0);
872  }
873 
874  return result;
875 }
EState * estate
Definition: execdesc.h:48
void ProcessUtility(PlannedStmt *pstmt, const char *queryString, ProcessUtilityContext context, ParamListInfo params, QueryEnvironment *queryEnv, DestReceiver *dest, char *completionTag)
Definition: utility.c:335
QueryEnvironment * queryEnv
Definition: execdesc.h:43
void ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
Definition: execMain.c:297
ParamListInfo params
Definition: execdesc.h:42
CmdType operation
Definition: execdesc.h:36
QueryDesc * qd
Definition: functions.c:70
uint64 es_processed
Definition: execnodes.h:478
DestReceiver * dest
Definition: execdesc.h:41
PlannedStmt * plannedstmt
Definition: execdesc.h:37

◆ postquel_start()

static void postquel_start ( execution_state es,
SQLFunctionCachePtr  fcache 
)
static

Definition at line 783 of file functions.c.

References ActiveSnapshotSet(), Assert, CMD_UTILITY, CreateDestReceiver(), CreateQueryDesc(), CurrentMemoryContext, DR_sqlfunction::cxt, generate_unaccent_rules::dest, DestSQLFunction, EXEC_FLAG_SKIP_TRIGGERS, ExecutorStart(), F_EXEC_RUN, DR_sqlfunction::filter, GetActiveSnapshot(), InvalidSnapshot, SQLFunctionCache::junkFilter, execution_state::lazyEval, _DestReceiver::mydest, None_Receiver, QueryDesc::operation, SQLFunctionCache::paramLI, DR_sqlfunction::pub, execution_state::qd, QueryDesc::queryEnv, execution_state::setsResult, SQLFunctionCache::src, execution_state::status, execution_state::stmt, DR_sqlfunction::tstore, and SQLFunctionCache::tstore.

Referenced by fmgr_sql().

784 {
786 
787  Assert(es->qd == NULL);
788 
789  /* Caller should have ensured a suitable snapshot is active */
791 
792  /*
793  * If this query produces the function result, send its output to the
794  * tuplestore; else discard any output.
795  */
796  if (es->setsResult)
797  {
798  DR_sqlfunction *myState;
799 
801  /* pass down the needed info to the dest receiver routines */
802  myState = (DR_sqlfunction *) dest;
803  Assert(myState->pub.mydest == DestSQLFunction);
804  myState->tstore = fcache->tstore;
805  myState->cxt = CurrentMemoryContext;
806  myState->filter = fcache->junkFilter;
807  }
808  else
809  dest = None_Receiver;
810 
811  es->qd = CreateQueryDesc(es->stmt,
812  fcache->src,
815  dest,
816  fcache->paramLI,
817  es->qd ? es->qd->queryEnv : NULL,
818  0);
819 
820  /* Utility commands don't need Executor. */
821  if (es->qd->operation != CMD_UTILITY)
822  {
823  /*
824  * In lazyEval mode, do not let the executor set up an AfterTrigger
825  * context. This is necessary not just an optimization, because we
826  * mustn't exit from the function execution with a stacked
827  * AfterTrigger level still active. We are careful not to select
828  * lazyEval mode for any statement that could possibly queue triggers.
829  */
830  int eflags;
831 
832  if (es->lazyEval)
833  eflags = EXEC_FLAG_SKIP_TRIGGERS;
834  else
835  eflags = 0; /* default run-to-completion flags */
836  ExecutorStart(es->qd, eflags);
837  }
838 
839  es->status = F_EXEC_RUN;
840 }
DestReceiver pub
Definition: functions.c:43
CommandDest mydest
Definition: dest.h:128
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:140
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:839
ExecStatus status
Definition: functions.c:66
JunkFilter * junkFilter
Definition: functions.c:111
Tuplestorestate * tstore
Definition: functions.c:109
DestReceiver * None_Receiver
Definition: dest.c:91
QueryEnvironment * queryEnv
Definition: execdesc.h:43
QueryDesc * CreateQueryDesc(PlannedStmt *plannedstmt, const char *sourceText, Snapshot snapshot, Snapshot crosscheck_snapshot, DestReceiver *dest, ParamListInfo params, QueryEnvironment *queryEnv, int instrument_options)
Definition: pquery.c:67
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:109
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:851
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
CmdType operation
Definition: execdesc.h:36
#define InvalidSnapshot
Definition: snapshot.h:25
QueryDesc * qd
Definition: functions.c:70
#define Assert(condition)
Definition: c.h:680
ParamListInfo paramLI
Definition: functions.c:107
MemoryContext cxt
Definition: functions.c:45
#define EXEC_FLAG_SKIP_TRIGGERS
Definition: executor.h:62
JunkFilter * filter
Definition: functions.c:46
PlannedStmt * stmt
Definition: functions.c:69
Tuplestorestate * tstore
Definition: functions.c:44

◆ postquel_sub_params()

static void postquel_sub_params ( SQLFunctionCachePtr  fcache,
FunctionCallInfo  fcinfo 
)
static

Definition at line 899 of file functions.c.

References FunctionCallInfoData::arg, FunctionCallInfoData::argnull, SQLFunctionParseInfo::argtypes, Assert, i, ParamExternData::isnull, FunctionCallInfoData::nargs, ParamListInfoData::numParams, offsetof, palloc(), ParamListInfoData::paramFetch, ParamListInfoData::paramFetchArg, SQLFunctionCache::paramLI, ParamListInfoData::paramMask, ParamListInfoData::params, ParamListInfoData::parserSetup, ParamListInfoData::parserSetupArg, ParamExternData::pflags, SQLFunctionCache::pinfo, ParamExternData::ptype, and ParamExternData::value.

Referenced by fmgr_sql().

901 {
902  int nargs = fcinfo->nargs;
903 
904  if (nargs > 0)
905  {
906  ParamListInfo paramLI;
907  int i;
908 
909  if (fcache->paramLI == NULL)
910  {
911  paramLI = (ParamListInfo)
913  nargs * sizeof(ParamExternData));
914  /* we have static list of params, so no hooks needed */
915  paramLI->paramFetch = NULL;
916  paramLI->paramFetchArg = NULL;
917  paramLI->parserSetup = NULL;
918  paramLI->parserSetupArg = NULL;
919  paramLI->numParams = nargs;
920  paramLI->paramMask = NULL;
921  fcache->paramLI = paramLI;
922  }
923  else
924  {
925  paramLI = fcache->paramLI;
926  Assert(paramLI->numParams == nargs);
927  }
928 
929  for (i = 0; i < nargs; i++)
930  {
931  ParamExternData *prm = &paramLI->params[i];
932 
933  prm->value = fcinfo->arg[i];
934  prm->isnull = fcinfo->argnull[i];
935  prm->pflags = 0;
936  prm->ptype = fcache->pinfo->argtypes[i];
937  }
938  }
939  else
940  fcache->paramLI = NULL;
941 }
ParamExternData params[FLEXIBLE_ARRAY_MEMBER]
Definition: params.h:76
Datum value
Definition: params.h:56
void * parserSetupArg
Definition: params.h:73
ParserSetupHook parserSetup
Definition: params.h:72
struct ParamListInfoData * ParamListInfo
Definition: params.h:62
void * paramFetchArg
Definition: params.h:71
ParamFetchHook paramFetch
Definition: params.h:70
struct Bitmapset * paramMask
Definition: params.h:75
bool argnull[FUNC_MAX_ARGS]
Definition: fmgr.h:86
SQLFunctionParseInfoPtr pinfo
Definition: functions.c:96
struct ParamExternData ParamExternData
Datum arg[FUNC_MAX_ARGS]
Definition: fmgr.h:85
#define Assert(condition)
Definition: c.h:680
ParamListInfo paramLI
Definition: functions.c:107
uint16 pflags
Definition: params.h:58
void * palloc(Size size)
Definition: mcxt.c:835
int i
bool isnull
Definition: params.h:57
#define offsetof(type, field)
Definition: c.h:603

◆ 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:562
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: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:988
void * palloc0(Size size)
Definition: mcxt.c:864
uintptr_t Datum
Definition: postgres.h:372
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:557

◆ ShutdownSQLFunction()

static void ShutdownSQLFunction ( Datum  arg)
static

Definition at line 1451 of file functions.c.

References DatumGetPointer, F_EXEC_RUN, F_EXEC_START, SQLFunctionCache::func_state, lfirst, execution_state::next, PopActiveSnapshot(), postquel_end(), PushActiveSnapshot(), execution_state::qd, SQLFunctionCache::readonly_func, SQLFunctionCache::shutdown_reg, QueryDesc::snapshot, execution_state::status, SQLFunctionCache::tstore, and tuplestore_end().

Referenced by fmgr_sql().

1452 {
1454  execution_state *es;
1455  ListCell *lc;
1456 
1457  foreach(lc, fcache->func_state)
1458  {
1459  es = (execution_state *) lfirst(lc);
1460  while (es)
1461  {
1462  /* Shut down anything still running */
1463  if (es->status == F_EXEC_RUN)
1464  {
1465  /* Re-establish active snapshot for any called functions */
1466  if (!fcache->readonly_func)
1468 
1469  postquel_end(es);
1470 
1471  if (!fcache->readonly_func)
1473  }
1474 
1475  /* Reset states to START in case we're called again */
1476  es->status = F_EXEC_START;
1477  es = es->next;
1478  }
1479  }
1480 
1481  /* Release tuplestore if we have one */
1482  if (fcache->tstore)
1483  tuplestore_end(fcache->tstore);
1484  fcache->tstore = NULL;
1485 
1486  /* execUtils will deregister the callback... */
1487  fcache->shutdown_reg = false;
1488 }
ExecStatus status
Definition: functions.c:66
void PopActiveSnapshot(void)
Definition: snapmgr.c:812
Tuplestorestate * tstore
Definition: functions.c:109
Snapshot snapshot
Definition: execdesc.h:39
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
QueryDesc * qd
Definition: functions.c:70
#define lfirst(lc)
Definition: pg_list.h:106
void tuplestore_end(Tuplestorestate *state)
Definition: tuplestore.c:453
#define DatumGetPointer(X)
Definition: postgres.h:555
SQLFunctionCache * SQLFunctionCachePtr
Definition: functions.c:128
void * arg
struct execution_state * next
Definition: functions.c:65

◆ sql_exec_error_callback()

static void sql_exec_error_callback ( void *  arg)
static

Definition at line 1369 of file functions.c.

References errcontext, errposition(), FmgrInfo::fn_extra, SQLFunctionCache::fname, SQLFunctionCache::func_state, geterrposition(), internalerrposition(), internalerrquery(), lfirst, execution_state::next, execution_state::qd, and SQLFunctionCache::src.

Referenced by fmgr_sql().

1370 {
1371  FmgrInfo *flinfo = (FmgrInfo *) arg;
1373  int syntaxerrposition;
1374 
1375  /*
1376  * We can do nothing useful if init_sql_fcache() didn't get as far as
1377  * saving the function name
1378  */
1379  if (fcache == NULL || fcache->fname == NULL)
1380  return;
1381 
1382  /*
1383  * If there is a syntax error position, convert to internal syntax error
1384  */
1385  syntaxerrposition = geterrposition();
1386  if (syntaxerrposition > 0 && fcache->src != NULL)
1387  {
1388  errposition(0);
1389  internalerrposition(syntaxerrposition);
1390  internalerrquery(fcache->src);
1391  }
1392 
1393  /*
1394  * Try to determine where in the function we failed. If there is a query
1395  * with non-null QueryDesc, finger it. (We check this rather than looking
1396  * for F_EXEC_RUN state, so that errors during ExecutorStart or
1397  * ExecutorEnd are blamed on the appropriate query; see postquel_start and
1398  * postquel_end.)
1399  */
1400  if (fcache->func_state)
1401  {
1402  execution_state *es;
1403  int query_num;
1404  ListCell *lc;
1405 
1406  es = NULL;
1407  query_num = 1;
1408  foreach(lc, fcache->func_state)
1409  {
1410  es = (execution_state *) lfirst(lc);
1411  while (es)
1412  {
1413  if (es->qd)
1414  {
1415  errcontext("SQL function \"%s\" statement %d",
1416  fcache->fname, query_num);
1417  break;
1418  }
1419  es = es->next;
1420  }
1421  if (es)
1422  break;
1423  query_num++;
1424  }
1425  if (es == NULL)
1426  {
1427  /*
1428  * couldn't identify a running query; might be function entry,
1429  * function exit, or between queries.
1430  */
1431  errcontext("SQL function \"%s\"", fcache->fname);
1432  }
1433  }
1434  else
1435  {
1436  /*
1437  * Assume we failed during init_sql_fcache(). (It's possible that the
1438  * function actually has an empty body, but in that case we may as
1439  * well report all errors as being "during startup".)
1440  */
1441  errcontext("SQL function \"%s\" during startup", fcache->fname);
1442  }
1443 }
Definition: fmgr.h:56
List * func_state
Definition: functions.c:119
int geterrposition(void)
Definition: elog.c:1257
QueryDesc * qd
Definition: functions.c:70
int internalerrquery(const char *query)
Definition: elog.c:1161
#define lfirst(lc)
Definition: pg_list.h:106
void * fn_extra
Definition: fmgr.h:64
SQLFunctionCache * SQLFunctionCachePtr
Definition: functions.c:128
#define errcontext
Definition: elog.h:164
void * arg
struct execution_state * next
Definition: functions.c:65
int errposition(int cursorpos)
Definition: elog.c:1125
int internalerrposition(int cursorpos)
Definition: elog.c:1141

◆ sql_fn_make_param()

static Node * sql_fn_make_param ( SQLFunctionParseInfoPtr  pinfo,
int  paramno,
int  location 
)
static

Definition at line 420 of file functions.c.

References SQLFunctionParseInfo::argtypes, SQLFunctionParseInfo::collation, get_typcollation(), Param::location, makeNode, OidIsValid, PARAM_EXTERN, Param::paramcollid, Param::paramid, Param::paramkind, Param::paramtype, and Param::paramtypmod.

Referenced by sql_fn_param_ref(), and sql_fn_resolve_param_name().

422 {
423  Param *param;
424 
425  param = makeNode(Param);
426  param->paramkind = PARAM_EXTERN;
427  param->paramid = paramno;
428  param->paramtype = pinfo->argtypes[paramno - 1];
429  param->paramtypmod = -1;
430  param->paramcollid = get_typcollation(param->paramtype);
431  param->location = location;
432 
433  /*
434  * If we have a function input collation, allow it to override the
435  * type-derived collation for parameter symbols. (XXX perhaps this should
436  * not happen if the type collation is not default?)
437  */
438  if (OidIsValid(pinfo->collation) && OidIsValid(param->paramcollid))
439  param->paramcollid = pinfo->collation;
440 
441  return (Node *) param;
442 }
ParamKind paramkind
Definition: primnodes.h:244
Definition: nodes.h:512
#define OidIsValid(objectId)
Definition: c.h:586
Oid paramcollid
Definition: primnodes.h:248
int location
Definition: primnodes.h:249
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:2814
int32 paramtypmod
Definition: primnodes.h:247
#define makeNode(_type_)
Definition: nodes.h:560
int paramid
Definition: primnodes.h:245
Oid paramtype
Definition: primnodes.h:246

◆ sql_fn_param_ref()

static Node * sql_fn_param_ref ( ParseState pstate,
ParamRef pref 
)
static

Definition at line 404 of file functions.c.

References ParamRef::location, SQLFunctionParseInfo::nargs, ParamRef::number, ParseState::p_ref_hook_state, and sql_fn_make_param().

Referenced by sql_fn_parser_setup().

405 {
407  int paramno = pref->number;
408 
409  /* Check parameter number is valid */
410  if (paramno <= 0 || paramno > pinfo->nargs)
411  return NULL; /* unknown parameter number */
412 
413  return sql_fn_make_param(pinfo, paramno, pref->location);
414 }
struct SQLFunctionParseInfo * SQLFunctionParseInfoPtr
Definition: functions.h:21
int number
Definition: parsenodes.h:244
int location
Definition: parsenodes.h:245
void * p_ref_hook_state
Definition: parse_node.h:215
static Node * sql_fn_make_param(SQLFunctionParseInfoPtr pinfo, int paramno, int location)
Definition: functions.c:420

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

◆ sql_fn_post_column_ref()

static Node * sql_fn_post_column_ref ( ParseState pstate,
ColumnRef cref,
Node var 
)
static

Definition at line 286 of file functions.c.

References Assert, ColumnRef::fields, SQLFunctionParseInfo::fname, IsA, linitial, list_length(), list_make1, llast, ColumnRef::location, lsecond, lthird, ParseState::p_last_srf, ParseState::p_ref_hook_state, ParseFuncOrColumn(), sql_fn_resolve_param_name(), and strVal.

Referenced by sql_fn_parser_setup().

287 {
289  int nnames;
290  Node *field1;
291  Node *subfield = NULL;
292  const char *name1;
293  const char *name2 = NULL;
294  Node *param;
295 
296  /*
297  * Never override a table-column reference. This corresponds to
298  * considering the parameter names to appear in a scope outside the
299  * individual SQL commands, which is what we want.
300  */
301  if (var != NULL)
302  return NULL;
303 
304  /*----------
305  * The allowed syntaxes are:
306  *
307  * A A = parameter name
308  * A.B A = function name, B = parameter name
309  * OR: A = record-typed parameter name, B = field name
310  * (the first possibility takes precedence)
311  * A.B.C A = function name, B = record-typed parameter name,
312  * C = field name
313  * A.* Whole-row reference to composite parameter A.
314  * A.B.* Same, with A = function name, B = parameter name
315  *
316  * Here, it's sufficient to ignore the "*" in the last two cases --- the
317  * main parser will take care of expanding the whole-row reference.
318  *----------
319  */
320  nnames = list_length(cref->fields);
321 
322  if (nnames > 3)
323  return NULL;
324 
325  if (IsA(llast(cref->fields), A_Star))
326  nnames--;
327 
328  field1 = (Node *) linitial(cref->fields);
329  Assert(IsA(field1, String));
330  name1 = strVal(field1);
331  if (nnames > 1)
332  {
333  subfield = (Node *) lsecond(cref->fields);
334  Assert(IsA(subfield, String));
335  name2 = strVal(subfield);
336  }
337 
338  if (nnames == 3)
339  {
340  /*
341  * Three-part name: if the first part doesn't match the function name,
342  * we can fail immediately. Otherwise, look up the second part, and
343  * take the third part to be a field reference.
344  */
345  if (strcmp(name1, pinfo->fname) != 0)
346  return NULL;
347 
348  param = sql_fn_resolve_param_name(pinfo, name2, cref->location);
349 
350  subfield = (Node *) lthird(cref->fields);
351  Assert(IsA(subfield, String));
352  }
353  else if (nnames == 2 && strcmp(name1, pinfo->fname) == 0)
354  {
355  /*
356  * Two-part name with first part matching function name: first see if
357  * second part matches any parameter name.
358  */
359  param = sql_fn_resolve_param_name(pinfo, name2, cref->location);
360 
361  if (param)
362  {
363  /* Yes, so this is a parameter reference, no subfield */
364  subfield = NULL;
365  }
366  else
367  {
368  /* No, so try to match as parameter name and subfield */
369  param = sql_fn_resolve_param_name(pinfo, name1, cref->location);
370  }
371  }
372  else
373  {
374  /* Single name, or parameter name followed by subfield */
375  param = sql_fn_resolve_param_name(pinfo, name1, cref->location);
376  }
377 
378  if (!param)
379  return NULL; /* No match */
380 
381  if (subfield)
382  {
383  /*
384  * Must be a reference to a field of a composite parameter; otherwise
385  * ParseFuncOrColumn will return NULL, and we'll fail back at the
386  * caller.
387  */
388  param = ParseFuncOrColumn(pstate,
389  list_make1(subfield),
390  list_make1(param),
391  pstate->p_last_srf,
392  NULL,
393  false,
394  cref->location);
395  }
396 
397  return param;
398 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:563
struct SQLFunctionParseInfo * SQLFunctionParseInfoPtr
Definition: functions.h:21
#define llast(l)
Definition: pg_list.h:131
Definition: nodes.h:512
#define strVal(v)
Definition: value.h:54
static Node * sql_fn_resolve_param_name(SQLFunctionParseInfoPtr pinfo, const char *paramname, int location)
Definition: functions.c:450
#define lsecond(l)
Definition: pg_list.h:116
int location
Definition: parsenodes.h:235
#define list_make1(x1)
Definition: pg_list.h:139
#define linitial(l)
Definition: pg_list.h:111
Node * ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs, Node *last_srf, FuncCall *fn, bool proc_call, int location)
Definition: parse_func.c:73
Node * p_last_srf
Definition: parse_node.h:205
#define Assert(condition)
Definition: c.h:680
void * p_ref_hook_state
Definition: parse_node.h:215
static int list_length(const List *l)
Definition: pg_list.h:89
#define lthird(l)
Definition: pg_list.h:121
List * fields
Definition: parsenodes.h:234

◆ sql_fn_resolve_param_name()

static Node * sql_fn_resolve_param_name ( SQLFunctionParseInfoPtr  pinfo,
const char *  paramname,
int  location 
)
static

Definition at line 450 of file functions.c.

References SQLFunctionParseInfo::argnames, i, SQLFunctionParseInfo::nargs, and sql_fn_make_param().

Referenced by sql_fn_post_column_ref().

452 {
453  int i;
454 
455  if (pinfo->argnames == NULL)
456  return NULL;
457 
458  for (i = 0; i < pinfo->nargs; i++)
459  {
460  if (pinfo->argnames[i] && strcmp(pinfo->argnames[i], paramname) == 0)
461  return sql_fn_make_param(pinfo, i + 1, location);
462  }
463 
464  return NULL;
465 }
int i
static Node * sql_fn_make_param(SQLFunctionParseInfoPtr pinfo, int paramno, int location)
Definition: functions.c:420

◆ sqlfunction_destroy()

static void sqlfunction_destroy ( DestReceiver self)
static

Definition at line 1954 of file functions.c.

References pfree().

Referenced by CreateSQLFunctionDestReceiver().

1955 {
1956  pfree(self);
1957 }
void pfree(void *pointer)
Definition: mcxt.c:936

◆ sqlfunction_receive()

static bool sqlfunction_receive ( TupleTableSlot slot,
DestReceiver self 
)
static

Definition at line 1928 of file functions.c.

References ExecFilterJunk(), DR_sqlfunction::filter, DR_sqlfunction::tstore, and tuplestore_puttupleslot().

Referenced by CreateSQLFunctionDestReceiver().

1929 {
1930  DR_sqlfunction *myState = (DR_sqlfunction *) self;
1931 
1932  /* Filter tuple as needed */
1933  slot = ExecFilterJunk(myState->filter, slot);
1934 
1935  /* Store the filtered tuple into the tuplestore */
1936  tuplestore_puttupleslot(myState->tstore, slot);
1937 
1938  return true;
1939 }
void tuplestore_puttupleslot(Tuplestorestate *state, TupleTableSlot *slot)
Definition: tuplestore.c:708
TupleTableSlot * ExecFilterJunk(JunkFilter *junkfilter, TupleTableSlot *slot)
Definition: execJunk.c:262
JunkFilter * filter
Definition: functions.c:46
Tuplestorestate * tstore
Definition: functions.c:44

◆ sqlfunction_shutdown()

static void sqlfunction_shutdown ( DestReceiver self)
static

Definition at line 1945 of file functions.c.

Referenced by CreateSQLFunctionDestReceiver().

1946 {
1947  /* no-op */
1948 }

◆ sqlfunction_startup()

static void sqlfunction_startup ( DestReceiver self,
int  operation,
TupleDesc  typeinfo 
)
static

Definition at line 1919 of file functions.c.

Referenced by CreateSQLFunctionDestReceiver().

1920 {
1921  /* no-op */
1922 }