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)
 
void check_sql_fn_statements (List *queryTreeList)
 
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 1586 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(), InvalidOid, IsBinaryCoercible(), lappend(), lfirst, lfirst_node, linitial, list_concat(), makeConst(), makeRelabelType(), makeTargetEntry(), tupleDesc::natts, NIL, parse(), TargetEntry::resjunk, TargetEntry::resno, TargetEntry::ressortgroupref, Query::returningList, Query::setOperations, Query::targetList, TupleDescAttr, and TYPEFUNC_COMPOSITE.

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

1589 {
1590  Query *parse;
1591  List **tlist_ptr;
1592  List *tlist;
1593  int tlistlen;
1594  char fn_typtype;
1595  Oid restype;
1596  ListCell *lc;
1597 
1598  AssertArg(!IsPolymorphicType(rettype));
1599 
1600  if (modifyTargetList)
1601  *modifyTargetList = false; /* initialize for no change */
1602  if (junkFilter)
1603  *junkFilter = NULL; /* initialize in case of VOID result */
1604 
1605  /*
1606  * If it's declared to return VOID, we don't care what's in the function.
1607  * (This takes care of the procedure case, as well.)
1608  */
1609  if (rettype == VOIDOID)
1610  return false;
1611 
1612  /*
1613  * Find the last canSetTag query in the list. This isn't necessarily the
1614  * last parsetree, because rule rewriting can insert queries after what
1615  * the user wrote.
1616  */
1617  parse = NULL;
1618  foreach(lc, queryTreeList)
1619  {
1620  Query *q = lfirst_node(Query, lc);
1621 
1622  if (q->canSetTag)
1623  parse = q;
1624  }
1625 
1626  /*
1627  * If it's a plain SELECT, it returns whatever the targetlist says.
1628  * Otherwise, if it's INSERT/UPDATE/DELETE with RETURNING, it returns
1629  * that. Otherwise, the function return type must be VOID.
1630  *
1631  * Note: eventually replace this test with QueryReturnsTuples? We'd need
1632  * a more general method of determining the output type, though. Also, it
1633  * seems too dangerous to consider FETCH or EXECUTE as returning a
1634  * determinable rowtype, since they depend on relatively short-lived
1635  * entities.
1636  */
1637  if (parse &&
1638  parse->commandType == CMD_SELECT)
1639  {
1640  tlist_ptr = &parse->targetList;
1641  tlist = parse->targetList;
1642  }
1643  else if (parse &&
1644  (parse->commandType == CMD_INSERT ||
1645  parse->commandType == CMD_UPDATE ||
1646  parse->commandType == CMD_DELETE) &&
1647  parse->returningList)
1648  {
1649  tlist_ptr = &parse->returningList;
1650  tlist = parse->returningList;
1651  }
1652  else
1653  {
1654  /* Empty function body, or last statement is a utility command */
1655  ereport(ERROR,
1656  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1657  errmsg("return type mismatch in function declared to return %s",
1658  format_type_be(rettype)),
1659  errdetail("Function's final statement must be SELECT or INSERT/UPDATE/DELETE RETURNING.")));
1660  return false; /* keep compiler quiet */
1661  }
1662 
1663  /*
1664  * OK, check that the targetlist returns something matching the declared
1665  * type.
1666  */
1667 
1668  /*
1669  * Count the non-junk entries in the result targetlist.
1670  */
1671  tlistlen = ExecCleanTargetListLength(tlist);
1672 
1673  fn_typtype = get_typtype(rettype);
1674 
1675  if (fn_typtype == TYPTYPE_BASE ||
1676  fn_typtype == TYPTYPE_DOMAIN ||
1677  fn_typtype == TYPTYPE_ENUM ||
1678  fn_typtype == TYPTYPE_RANGE)
1679  {
1680  /*
1681  * For scalar-type returns, the target list must have exactly one
1682  * non-junk entry, and its type must agree with what the user
1683  * declared; except we allow binary-compatible types too.
1684  */
1685  TargetEntry *tle;
1686 
1687  if (tlistlen != 1)
1688  ereport(ERROR,
1689  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1690  errmsg("return type mismatch in function declared to return %s",
1691  format_type_be(rettype)),
1692  errdetail("Final statement must return exactly one column.")));
1693 
1694  /* We assume here that non-junk TLEs must come first in tlists */
1695  tle = (TargetEntry *) linitial(tlist);
1696  Assert(!tle->resjunk);
1697 
1698  restype = exprType((Node *) tle->expr);
1699  if (!IsBinaryCoercible(restype, rettype))
1700  ereport(ERROR,
1701  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1702  errmsg("return type mismatch in function declared to return %s",
1703  format_type_be(rettype)),
1704  errdetail("Actual return type is %s.",
1705  format_type_be(restype))));
1706  if (modifyTargetList && restype != rettype)
1707  {
1708  tle->expr = (Expr *) makeRelabelType(tle->expr,
1709  rettype,
1710  -1,
1711  get_typcollation(rettype),
1713  /* Relabel is dangerous if TLE is a sort/group or setop column */
1714  if (tle->ressortgroupref != 0 || parse->setOperations)
1715  *modifyTargetList = true;
1716  }
1717 
1718  /* Set up junk filter if needed */
1719  if (junkFilter)
1720  *junkFilter = ExecInitJunkFilter(tlist, false, NULL);
1721  }
1722  else if (fn_typtype == TYPTYPE_COMPOSITE || rettype == RECORDOID)
1723  {
1724  /*
1725  * Returns a rowtype.
1726  *
1727  * Note that we will not consider a domain over composite to be a
1728  * "rowtype" return type; it goes through the scalar case above. This
1729  * is because SQL functions don't provide any implicit casting to the
1730  * result type, so there is no way to produce a domain-over-composite
1731  * result except by computing it as an explicit single-column result.
1732  */
1733  TupleDesc tupdesc;
1734  int tupnatts; /* physical number of columns in tuple */
1735  int tuplogcols; /* # of nondeleted columns in tuple */
1736  int colindex; /* physical column index */
1737  List *newtlist; /* new non-junk tlist entries */
1738  List *junkattrs; /* new junk tlist entries */
1739 
1740  /*
1741  * If the target list is of length 1, and the type of the varnode in
1742  * the target list matches the declared return type, this is okay.
1743  * This can happen, for example, where the body of the function is
1744  * 'SELECT func2()', where func2 has the same composite return type as
1745  * the function that's calling it.
1746  *
1747  * XXX Note that if rettype is RECORD, the IsBinaryCoercible check
1748  * will succeed for any composite restype. For the moment we rely on
1749  * runtime type checking to catch any discrepancy, but it'd be nice to
1750  * do better at parse time.
1751  */
1752  if (tlistlen == 1)
1753  {
1754  TargetEntry *tle = (TargetEntry *) linitial(tlist);
1755 
1756  Assert(!tle->resjunk);
1757  restype = exprType((Node *) tle->expr);
1758  if (IsBinaryCoercible(restype, rettype))
1759  {
1760  if (modifyTargetList && restype != rettype)
1761  {
1762  tle->expr = (Expr *) makeRelabelType(tle->expr,
1763  rettype,
1764  -1,
1765  get_typcollation(rettype),
1767  /* Relabel is dangerous if sort/group or setop column */
1768  if (tle->ressortgroupref != 0 || parse->setOperations)
1769  *modifyTargetList = true;
1770  }
1771  /* Set up junk filter if needed */
1772  if (junkFilter)
1773  *junkFilter = ExecInitJunkFilter(tlist, false, NULL);
1774  return false; /* NOT returning whole tuple */
1775  }
1776  }
1777 
1778  /*
1779  * Is the rowtype fixed, or determined only at runtime? (Note we
1780  * cannot see TYPEFUNC_COMPOSITE_DOMAIN here.)
1781  */
1782  if (get_func_result_type(func_id, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
1783  {
1784  /*
1785  * Assume we are returning the whole tuple. Crosschecking against
1786  * what the caller expects will happen at runtime.
1787  */
1788  if (junkFilter)
1789  *junkFilter = ExecInitJunkFilter(tlist, false, NULL);
1790  return true;
1791  }
1792  Assert(tupdesc);
1793 
1794  /*
1795  * Verify that the targetlist matches the return tuple type. We scan
1796  * the non-deleted attributes to ensure that they match the datatypes
1797  * of the non-resjunk columns. For deleted attributes, insert NULL
1798  * result columns if the caller asked for that.
1799  */
1800  tupnatts = tupdesc->natts;
1801  tuplogcols = 0; /* we'll count nondeleted cols as we go */
1802  colindex = 0;
1803  newtlist = NIL; /* these are only used if modifyTargetList */
1804  junkattrs = NIL;
1805 
1806  foreach(lc, tlist)
1807  {
1808  TargetEntry *tle = (TargetEntry *) lfirst(lc);
1809  Form_pg_attribute attr;
1810  Oid tletype;
1811  Oid atttype;
1812 
1813  if (tle->resjunk)
1814  {
1815  if (modifyTargetList)
1816  junkattrs = lappend(junkattrs, tle);
1817  continue;
1818  }
1819 
1820  do
1821  {
1822  colindex++;
1823  if (colindex > tupnatts)
1824  ereport(ERROR,
1825  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1826  errmsg("return type mismatch in function declared to return %s",
1827  format_type_be(rettype)),
1828  errdetail("Final statement returns too many columns.")));
1829  attr = TupleDescAttr(tupdesc, colindex - 1);
1830  if (attr->attisdropped && modifyTargetList)
1831  {
1832  Expr *null_expr;
1833 
1834  /* The type of the null we insert isn't important */
1835  null_expr = (Expr *) makeConst(INT4OID,
1836  -1,
1837  InvalidOid,
1838  sizeof(int32),
1839  (Datum) 0,
1840  true, /* isnull */
1841  true /* byval */ );
1842  newtlist = lappend(newtlist,
1843  makeTargetEntry(null_expr,
1844  colindex,
1845  NULL,
1846  false));
1847  /* NULL insertion is dangerous in a setop */
1848  if (parse->setOperations)
1849  *modifyTargetList = true;
1850  }
1851  } while (attr->attisdropped);
1852  tuplogcols++;
1853 
1854  tletype = exprType((Node *) tle->expr);
1855  atttype = attr->atttypid;
1856  if (!IsBinaryCoercible(tletype, atttype))
1857  ereport(ERROR,
1858  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1859  errmsg("return type mismatch in function declared to return %s",
1860  format_type_be(rettype)),
1861  errdetail("Final statement returns %s instead of %s at column %d.",
1862  format_type_be(tletype),
1863  format_type_be(atttype),
1864  tuplogcols)));
1865  if (modifyTargetList)
1866  {
1867  if (tletype != atttype)
1868  {
1869  tle->expr = (Expr *) makeRelabelType(tle->expr,
1870  atttype,
1871  -1,
1872  get_typcollation(atttype),
1874  /* Relabel is dangerous if sort/group or setop column */
1875  if (tle->ressortgroupref != 0 || parse->setOperations)
1876  *modifyTargetList = true;
1877  }
1878  tle->resno = colindex;
1879  newtlist = lappend(newtlist, tle);
1880  }
1881  }
1882 
1883  /* remaining columns in tupdesc had better all be dropped */
1884  for (colindex++; colindex <= tupnatts; colindex++)
1885  {
1886  if (!TupleDescAttr(tupdesc, colindex - 1)->attisdropped)
1887  ereport(ERROR,
1888  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1889  errmsg("return type mismatch in function declared to return %s",
1890  format_type_be(rettype)),
1891  errdetail("Final statement returns too few columns.")));
1892  if (modifyTargetList)
1893  {
1894  Expr *null_expr;
1895 
1896  /* The type of the null we insert isn't important */
1897  null_expr = (Expr *) makeConst(INT4OID,
1898  -1,
1899  InvalidOid,
1900  sizeof(int32),
1901  (Datum) 0,
1902  true, /* isnull */
1903  true /* byval */ );
1904  newtlist = lappend(newtlist,
1905  makeTargetEntry(null_expr,
1906  colindex,
1907  NULL,
1908  false));
1909  /* NULL insertion is dangerous in a setop */
1910  if (parse->setOperations)
1911  *modifyTargetList = true;
1912  }
1913  }
1914 
1915  if (modifyTargetList)
1916  {
1917  /* ensure resjunk columns are numbered correctly */
1918  foreach(lc, junkattrs)
1919  {
1920  TargetEntry *tle = (TargetEntry *) lfirst(lc);
1921 
1922  tle->resno = colindex++;
1923  }
1924  /* replace the tlist with the modified one */
1925  *tlist_ptr = list_concat(newtlist, junkattrs);
1926  }
1927 
1928  /* Set up junk filter if needed */
1929  if (junkFilter)
1930  *junkFilter = ExecInitJunkFilterConversion(tlist,
1931  CreateTupleDescCopy(tupdesc),
1932  NULL);
1933 
1934  /* Report that we are returning entire tuple result */
1935  return true;
1936  }
1937  else
1938  ereport(ERROR,
1939  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1940  errmsg("return type %s is not supported for SQL functions",
1941  format_type_be(rettype))));
1942 
1943  return false;
1944 }
#define NIL
Definition: pg_list.h:69
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:112
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:93
JunkFilter * ExecInitJunkFilterConversion(List *targetList, TupleDesc cleanTupType, TupleTableSlot *slot)
Definition: execJunk.c:136
Definition: nodes.h:517
int errcode(int sqlerrcode)
Definition: elog.c:575
char get_typtype(Oid typid)
Definition: lsyscache.c:2383
char * format_type_be(Oid type_oid)
Definition: format_type.c:328
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:82
signed int int32
Definition: c.h:313
List * targetList
Definition: parsenodes.h:140
bool resjunk
Definition: primnodes.h:1383
#define linitial(l)
Definition: pg_list.h:111
#define ERROR
Definition: elog.h:43
#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:1377
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:197
List * returningList
Definition: parsenodes.h:146
#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:701
bool IsBinaryCoercible(Oid srctype, Oid targettype)
List * lappend(List *list, void *datum)
Definition: list.c:128
int ExecCleanTargetListLength(List *targetlist)
Definition: execUtils.c:1049
TypeFuncClass get_func_result_type(Oid functionId, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:272
uintptr_t Datum
Definition: postgres.h:367
#define InvalidOid
Definition: postgres_ext.h:36
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:2799
CmdType commandType
Definition: parsenodes.h:112
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
Expr * expr
Definition: primnodes.h:1376
bool canSetTag
Definition: parsenodes.h:118
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
Node * setOperations
Definition: parsenodes.h:165
int errmsg(const char *fmt,...)
Definition: elog.c:797
Index ressortgroupref
Definition: primnodes.h:1379
Definition: pg_list.h:45
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649

◆ check_sql_fn_statements()

void check_sql_fn_statements ( List queryTreeList)

Definition at line 1500 of file functions.c.

References castNode, CMD_UTILITY, Query::commandType, elog, ereport, errcode(), errmsg(), ERROR, CallStmt::funcexpr, FuncExpr::funcid, get_func_arg_info(), HeapTupleIsValid, i, IsA, lfirst_node, ObjectIdGetDatum, PROCOID, ReleaseSysCache(), SearchSysCache1(), execution_state::stmt, and Query::utilityStmt.

Referenced by fmgr_sql_validator(), and init_sql_fcache().

1501 {
1502  ListCell *lc;
1503 
1504  foreach(lc, queryTreeList)
1505  {
1506  Query *query = lfirst_node(Query, lc);
1507 
1508  /*
1509  * Disallow procedures with output arguments. The current
1510  * implementation would just throw the output values away, unless the
1511  * statement is the last one. Per SQL standard, we should assign the
1512  * output values by name. By disallowing this here, we preserve an
1513  * opportunity for future improvement.
1514  */
1515  if (query->commandType == CMD_UTILITY &&
1516  IsA(query->utilityStmt, CallStmt))
1517  {
1518  CallStmt *stmt = castNode(CallStmt, query->utilityStmt);
1519  HeapTuple tuple;
1520  int numargs;
1521  Oid *argtypes;
1522  char **argnames;
1523  char *argmodes;
1524  int i;
1525 
1527  if (!HeapTupleIsValid(tuple))
1528  elog(ERROR, "cache lookup failed for function %u", stmt->funcexpr->funcid);
1529  numargs = get_func_arg_info(tuple, &argtypes, &argnames, &argmodes);
1530  ReleaseSysCache(tuple);
1531 
1532  for (i = 0; i < numargs; i++)
1533  {
1534  if (argmodes && (argmodes[i] == PROARGMODE_INOUT || argmodes[i] == PROARGMODE_OUT))
1535  ereport(ERROR,
1536  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1537  errmsg("calling procedures with output arguments is not supported in SQL functions")));
1538  }
1539  }
1540  }
1541 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:568
FuncExpr * funcexpr
Definition: parsenodes.h:2827
#define castNode(_type_, nodeptr)
Definition: nodes.h:586
int get_func_arg_info(HeapTuple procTup, Oid **p_argtypes, char ***p_argnames, char **p_argmodes)
Definition: funcapi.c:846
int errcode(int sqlerrcode)
Definition: elog.c:575
unsigned int Oid
Definition: postgres_ext.h:31
Node * utilityStmt
Definition: parsenodes.h:120
Oid funcid
Definition: primnodes.h:450
#define ObjectIdGetDatum(X)
Definition: postgres.h:492
#define ERROR
Definition: elog.h:43
#define lfirst_node(type, lc)
Definition: pg_list.h:109
#define ereport(elevel, rest)
Definition: elog.h:122
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
CmdType commandType
Definition: parsenodes.h:112
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define elog
Definition: elog.h:219

◆ CreateSQLFunctionDestReceiver()

DestReceiver* CreateSQLFunctionDestReceiver ( void  )

Definition at line 1951 of file functions.c.

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

Referenced by CreateDestReceiver().

1952 {
1953  DR_sqlfunction *self = (DR_sqlfunction *) palloc0(sizeof(DR_sqlfunction));
1954 
1955  self->pub.receiveSlot = sqlfunction_receive;
1956  self->pub.rStartup = sqlfunction_startup;
1957  self->pub.rShutdown = sqlfunction_shutdown;
1958  self->pub.rDestroy = sqlfunction_destroy;
1959  self->pub.mydest = DestSQLFunction;
1960 
1961  /* private fields will be set by postquel_start */
1962 
1963  return (DestReceiver *) self;
1964 }
static void sqlfunction_destroy(DestReceiver *self)
Definition: functions.c:2005
static void sqlfunction_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: functions.c:1970
static bool sqlfunction_receive(TupleTableSlot *slot, DestReceiver *self)
Definition: functions.c:1979
void * palloc0(Size size)
Definition: mcxt.c:955
static void sqlfunction_shutdown(DestReceiver *self)
Definition: functions.c:1996

◆ fmgr_sql()

Datum fmgr_sql ( PG_FUNCTION_ARGS  )

Definition at line 995 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, PG_GET_COLLATION, PointerGetDatum, PopActiveSnapshot(), postquel_end(), postquel_get_single_result(), postquel_getnext(), postquel_start(), postquel_sub_params(), ErrorContextCallback::previous, PushActiveSnapshot(), execution_state::qd, SQLFunctionCache::readonly_func, RegisterExprContextCallback(), SQLFunctionCache::rettype, ReturnSetInfo::returnMode, SQLFunctionCache::returnsSet, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, SFRM_Materialize, SFRM_Materialize_Preferred, SFRM_Materialize_Random, SFRM_ValuePerCall, SQLFunctionCache::shutdown_reg, ShutdownSQLFunction(), QueryDesc::snapshot, sql_exec_error_callback(), execution_state::status, SubTransactionIsActive(), SQLFunctionCache::subxid, SQLFunctionCache::tstore, tuplestore_begin_heap(), tuplestore_clear(), tuplestore_gettupleslot(), UnregisterExprContextCallback(), UpdateActiveSnapshotCommandId(), and work_mem.

Referenced by fmgr_info_cxt_security().

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

◆ init_sql_fcache()

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

Definition at line 594 of file functions.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, BlessTupleDesc(), check_sql_fn_retval(), check_sql_fn_statements(), 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, JunkFilter::jf_resultSlot, SQLFunctionCache::junkFilter, lappend(), lfirst_node, list_concat(), list_copy(), PGPROC::lxid, SQLFunctionCache::lxid, MemoryContextSetIdentifier(), MemoryContextSwitchTo(), MyProc, NameStr, NIL, ObjectIdGetDatum, palloc0(), pg_analyze_and_rewrite_params(), pg_parse_query(), SQLFunctionCache::pinfo, prepare_sql_fn_parse_info(), PROCOID, 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().

595 {
596  Oid foid = finfo->fn_oid;
597  MemoryContext fcontext;
598  MemoryContext oldcontext;
599  Oid rettype;
600  HeapTuple procedureTuple;
601  Form_pg_proc procedureStruct;
602  SQLFunctionCachePtr fcache;
603  List *raw_parsetree_list;
604  List *queryTree_list;
605  List *flat_query_list;
606  ListCell *lc;
607  Datum tmp;
608  bool isNull;
609 
610  /*
611  * Create memory context that holds all the SQLFunctionCache data. It
612  * must be a child of whatever context holds the FmgrInfo.
613  */
614  fcontext = AllocSetContextCreate(finfo->fn_mcxt,
615  "SQL function",
617 
618  oldcontext = MemoryContextSwitchTo(fcontext);
619 
620  /*
621  * Create the struct proper, link it to fcontext and fn_extra. Once this
622  * is done, we'll be able to recover the memory after failure, even if the
623  * FmgrInfo is long-lived.
624  */
625  fcache = (SQLFunctionCachePtr) palloc0(sizeof(SQLFunctionCache));
626  fcache->fcontext = fcontext;
627  finfo->fn_extra = (void *) fcache;
628 
629  /*
630  * get the procedure tuple corresponding to the given function Oid
631  */
632  procedureTuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(foid));
633  if (!HeapTupleIsValid(procedureTuple))
634  elog(ERROR, "cache lookup failed for function %u", foid);
635  procedureStruct = (Form_pg_proc) GETSTRUCT(procedureTuple);
636 
637  /*
638  * copy function name immediately for use by error reporting callback, and
639  * for use as memory context identifier
640  */
641  fcache->fname = pstrdup(NameStr(procedureStruct->proname));
642  MemoryContextSetIdentifier(fcontext, fcache->fname);
643 
644  /*
645  * get the result type from the procedure tuple, and check for polymorphic
646  * result type; if so, find out the actual result type.
647  */
648  rettype = procedureStruct->prorettype;
649 
650  if (IsPolymorphicType(rettype))
651  {
652  rettype = get_fn_expr_rettype(finfo);
653  if (rettype == InvalidOid) /* this probably should not happen */
654  ereport(ERROR,
655  (errcode(ERRCODE_DATATYPE_MISMATCH),
656  errmsg("could not determine actual result type for function declared to return type %s",
657  format_type_be(procedureStruct->prorettype))));
658  }
659 
660  fcache->rettype = rettype;
661 
662  /* Fetch the typlen and byval info for the result type */
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,
686  Anum_pg_proc_prosrc,
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  check_sql_fn_statements(flat_query_list);
727 
728  /*
729  * Check that the function returns the type it claims to. Although in
730  * simple cases this was already done when the function was defined, we
731  * have to recheck because database objects used in the function's queries
732  * might have changed type. We'd have to do it anyway if the function had
733  * any polymorphic arguments.
734  *
735  * Note: we set fcache->returnsTuple according to whether we are returning
736  * the whole tuple result or just a single column. In the latter case we
737  * clear returnsTuple because we need not act different from the scalar
738  * result case, even if it's a rowtype column. (However, we have to force
739  * lazy eval mode in that case; otherwise we'd need extra code to expand
740  * the rowtype column into multiple columns, since we have no way to
741  * notify the caller that it should do that.)
742  *
743  * check_sql_fn_retval will also construct a JunkFilter we can use to
744  * coerce the returned rowtype to the desired form (unless the result type
745  * is VOID, in which case there's nothing to coerce to).
746  */
747  fcache->returnsTuple = check_sql_fn_retval(foid,
748  rettype,
749  flat_query_list,
750  NULL,
751  &fcache->junkFilter);
752 
753  if (fcache->returnsTuple)
754  {
755  /* Make sure output rowtype is properly blessed */
757  }
758  else if (fcache->returnsSet && type_is_rowtype(fcache->rettype))
759  {
760  /*
761  * Returning rowtype as if it were scalar --- materialize won't work.
762  * Right now it's sufficient to override any caller preference for
763  * materialize mode, but to add more smarts in init_execution_state
764  * about this, we'd probably need a three-way flag instead of bool.
765  */
766  lazyEvalOK = true;
767  }
768 
769  /* Finally, plan the queries */
770  fcache->func_state = init_execution_state(queryTree_list,
771  fcache,
772  lazyEvalOK);
773 
774  /* Mark fcache with time of creation to show it's valid */
775  fcache->lxid = MyProc->lxid;
777 
778  ReleaseSysCache(procedureTuple);
779 
780  MemoryContextSwitchTo(oldcontext);
781 }
#define NIL
Definition: pg_list.h:69
#define GETSTRUCT(TUP)
Definition: htup_details.h:668
MemoryContext fn_mcxt
Definition: fmgr.h:65
MemoryContext fcontext
Definition: functions.c:121
PGPROC * MyProc
Definition: proc.c:67
void check_sql_fn_statements(List *queryTreeList)
Definition: functions.c:1500
char * pstrdup(const char *in)
Definition: mcxt.c:1161
void sql_fn_parser_setup(struct ParseState *pstate, SQLFunctionParseInfoPtr pinfo)
Definition: functions.c:273
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
List * list_copy(const List *oldlist)
Definition: list.c:1160
int errcode(int sqlerrcode)
Definition: elog.c:575
TupleTableSlot * jf_resultSlot
Definition: execnodes.h:364
bool check_sql_fn_retval(Oid func_id, Oid rettype, List *queryTreeList, bool *modifyTargetList, JunkFilter **junkFilter)
Definition: functions.c:1586
JunkFilter * junkFilter
Definition: functions.c:111
char * format_type_be(Oid type_oid)
Definition: format_type.c:328
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:492
#define ERROR
Definition: elog.h:43
List * pg_parse_query(const char *query_string)
Definition: postgres.c:609
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
#define lfirst_node(type, lc)
Definition: pg_list.h:109
TupleDesc BlessTupleDesc(TupleDesc tupdesc)
Definition: execTuples.c:1109
void(* ParserSetupHook)(struct ParseState *pstate, void *arg)
Definition: params.h:108
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:2409
#define ereport(elevel, rest)
Definition: elog.h:122
SQLFunctionParseInfoPtr pinfo
Definition: functions.c:96
List * lappend(List *list, void *datum)
Definition: list.c:128
#define AllocSetContextCreate(parent, name, allocparams)
Definition: memutils.h:170
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:124
#define TextDatumGetCString(d)
Definition: builtins.h:96
void * palloc0(Size size)
Definition: mcxt.c:955
uintptr_t Datum
Definition: postgres.h:367
Oid get_fn_expr_rettype(FmgrInfo *flinfo)
Definition: fmgr.c:1973
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:132
#define InvalidOid
Definition: postgres_ext.h:36
Oid fn_oid
Definition: fmgr.h:59
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:641
fmNodePtr fn_expr
Definition: fmgr.h:66
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2005
void MemoryContextSetIdentifier(MemoryContext context, const char *id)
Definition: mcxt.c:329
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:688
SQLFunctionCache * SQLFunctionCachePtr
Definition: functions.c:128
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define NameStr(name)
Definition: c.h:576
#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 881 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().

882 {
883  /* mark status done to ensure we don't do ExecutorEnd twice */
884  es->status = F_EXEC_DONE;
885 
886  /* Utility commands don't need Executor. */
887  if (es->qd->operation != CMD_UTILITY)
888  {
889  ExecutorFinish(es->qd);
890  ExecutorEnd(es->qd);
891  }
892 
893  es->qd->dest->rDestroy(es->qd->dest);
894 
895  FreeQueryDesc(es->qd);
896  es->qd = NULL;
897 }
void FreeQueryDesc(QueryDesc *qdesc)
Definition: pquery.c:105
ExecStatus status
Definition: functions.c:66
void ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:461
void ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:401
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 952 of file functions.c.

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

Referenced by fmgr_sql().

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

◆ postquel_getnext()

static bool postquel_getnext ( execution_state es,
SQLFunctionCachePtr  fcache 
)
static

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

848 {
849  bool result;
850 
851  if (es->qd->operation == CMD_UTILITY)
852  {
854  fcache->src,
856  es->qd->params,
857  es->qd->queryEnv,
858  es->qd->dest,
859  NULL);
860  result = true; /* never stops early */
861  }
862  else
863  {
864  /* Run regular commands to completion unless lazyEval */
865  uint64 count = (es->lazyEval) ? 1 : 0;
866 
867  ExecutorRun(es->qd, ForwardScanDirection, count, !fcache->returnsSet || !es->lazyEval);
868 
869  /*
870  * If we requested run to completion OR there was no tuple returned,
871  * command must be complete.
872  */
873  result = (count == 0 || es->qd->estate->es_processed == 0);
874  }
875 
876  return result;
877 }
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:338
QueryEnvironment * queryEnv
Definition: execdesc.h:43
void ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
Definition: execMain.c:299
ParamListInfo params
Definition: execdesc.h:42
CmdType operation
Definition: execdesc.h:36
QueryDesc * qd
Definition: functions.c:70
uint64 es_processed
Definition: execnodes.h:529
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 785 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().

786 {
788 
789  Assert(es->qd == NULL);
790 
791  /* Caller should have ensured a suitable snapshot is active */
793 
794  /*
795  * If this query produces the function result, send its output to the
796  * tuplestore; else discard any output.
797  */
798  if (es->setsResult)
799  {
800  DR_sqlfunction *myState;
801 
803  /* pass down the needed info to the dest receiver routines */
804  myState = (DR_sqlfunction *) dest;
805  Assert(myState->pub.mydest == DestSQLFunction);
806  myState->tstore = fcache->tstore;
807  myState->cxt = CurrentMemoryContext;
808  myState->filter = fcache->junkFilter;
809  }
810  else
811  dest = None_Receiver;
812 
813  es->qd = CreateQueryDesc(es->stmt,
814  fcache->src,
817  dest,
818  fcache->paramLI,
819  es->qd ? es->qd->queryEnv : NULL,
820  0);
821 
822  /* Utility commands don't need Executor. */
823  if (es->qd->operation != CMD_UTILITY)
824  {
825  /*
826  * In lazyEval mode, do not let the executor set up an AfterTrigger
827  * context. This is necessary not just an optimization, because we
828  * mustn't exit from the function execution with a stacked
829  * AfterTrigger level still active. We are careful not to select
830  * lazyEval mode for any statement that could possibly queue triggers.
831  */
832  int eflags;
833 
834  if (es->lazyEval)
835  eflags = EXEC_FLAG_SKIP_TRIGGERS;
836  else
837  eflags = 0; /* default run-to-completion flags */
838  ExecutorStart(es->qd, eflags);
839  }
840 
841  es->status = F_EXEC_RUN;
842 }
DestReceiver pub
Definition: functions.c:43
CommandDest mydest
Definition: dest.h:128
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:141
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:38
CmdType operation
Definition: execdesc.h:36
#define InvalidSnapshot
Definition: snapshot.h:25
QueryDesc * qd
Definition: functions.c:70
#define Assert(condition)
Definition: c.h:699
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 901 of file functions.c.

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

Referenced by fmgr_sql().

903 {
904  int nargs = fcinfo->nargs;
905 
906  if (nargs > 0)
907  {
908  ParamListInfo paramLI;
909  int i;
910 
911  if (fcache->paramLI == NULL)
912  {
913  paramLI = (ParamListInfo)
915  nargs * sizeof(ParamExternData));
916  /* we have static list of params, so no hooks needed */
917  paramLI->paramFetch = NULL;
918  paramLI->paramFetchArg = NULL;
919  paramLI->paramCompile = NULL;
920  paramLI->paramCompileArg = NULL;
921  paramLI->parserSetup = NULL;
922  paramLI->parserSetupArg = NULL;
923  paramLI->numParams = nargs;
924  fcache->paramLI = paramLI;
925  }
926  else
927  {
928  paramLI = fcache->paramLI;
929  Assert(paramLI->numParams == nargs);
930  }
931 
932  for (i = 0; i < nargs; i++)
933  {
934  ParamExternData *prm = &paramLI->params[i];
935 
936  prm->value = fcinfo->arg[i];
937  prm->isnull = fcinfo->argnull[i];
938  prm->pflags = 0;
939  prm->ptype = fcache->pinfo->argtypes[i];
940  }
941  }
942  else
943  fcache->paramLI = NULL;
944 }
ParamExternData params[FLEXIBLE_ARRAY_MEMBER]
Definition: params.h:124
Datum value
Definition: params.h:92
void * parserSetupArg
Definition: params.h:117
ParserSetupHook parserSetup
Definition: params.h:116
struct ParamListInfoData * ParamListInfo
Definition: params.h:98
void * paramFetchArg
Definition: params.h:113
ParamCompileHook paramCompile
Definition: params.h:114
ParamFetchHook paramFetch
Definition: params.h:112
bool argnull[FUNC_MAX_ARGS]
Definition: fmgr.h:89
SQLFunctionParseInfoPtr pinfo
Definition: functions.c:96
struct ParamExternData ParamExternData
Datum arg[FUNC_MAX_ARGS]
Definition: fmgr.h:87
#define Assert(condition)
Definition: c.h:699
ParamListInfo paramLI
Definition: functions.c:107
uint16 pflags
Definition: params.h:94
void * paramCompileArg
Definition: params.h:115
void * palloc(Size size)
Definition: mcxt.c:924
int i
bool isnull
Definition: params.h:93
#define offsetof(type, field)
Definition: c.h:622

◆ 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 SQLFunctionParseInfo::argnames, SQLFunctionParseInfo::argtypes, SQLFunctionParseInfo::collation, ereport, errcode(), errmsg(), ERROR, SQLFunctionParseInfo::fname, format_type_be(), get_call_expr_argtype(), get_func_input_arg_names(), GETSTRUCT, InvalidOid, NameStr, SQLFunctionParseInfo::nargs, palloc(), palloc0(), PointerGetDatum, PROCNAMEARGSNSP, pstrdup(), and SysCacheGetAttr().

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

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,
245  Anum_pg_proc_proargnames,
246  &isNull);
247  if (isNull)
248  proargnames = PointerGetDatum(NULL); /* just to be sure */
249 
250  proargmodes = SysCacheGetAttr(PROCNAMEARGSNSP, procedureTuple,
251  Anum_pg_proc_proargmodes,
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:668
#define PointerGetDatum(X)
Definition: postgres.h:541
char * pstrdup(const char *in)
Definition: mcxt.c:1161
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:2014
char * format_type_be(Oid type_oid)
Definition: format_type.c:328
unsigned int Oid
Definition: postgres_ext.h:31
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
int get_func_input_arg_names(Datum proargnames, Datum proargmodes, char ***arg_names)
Definition: funcapi.c:988
void * palloc0(Size size)
Definition: mcxt.c:955
uintptr_t Datum
Definition: postgres.h:367
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1368
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:132
#define InvalidOid
Definition: postgres_ext.h:36
void * palloc(Size size)
Definition: mcxt.c:924
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define NameStr(name)
Definition: c.h:576

◆ ShutdownSQLFunction()

static void ShutdownSQLFunction ( Datum  arg)
static

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

1455 {
1457  execution_state *es;
1458  ListCell *lc;
1459 
1460  foreach(lc, fcache->func_state)
1461  {
1462  es = (execution_state *) lfirst(lc);
1463  while (es)
1464  {
1465  /* Shut down anything still running */
1466  if (es->status == F_EXEC_RUN)
1467  {
1468  /* Re-establish active snapshot for any called functions */
1469  if (!fcache->readonly_func)
1471 
1472  postquel_end(es);
1473 
1474  if (!fcache->readonly_func)
1476  }
1477 
1478  /* Reset states to START in case we're called again */
1479  es->status = F_EXEC_START;
1480  es = es->next;
1481  }
1482  }
1483 
1484  /* Release tuplestore if we have one */
1485  if (fcache->tstore)
1486  tuplestore_end(fcache->tstore);
1487  fcache->tstore = NULL;
1488 
1489  /* execUtils will deregister the callback... */
1490  fcache->shutdown_reg = false;
1491 }
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:881
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:534
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 1372 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().

1373 {
1374  FmgrInfo *flinfo = (FmgrInfo *) arg;
1376  int syntaxerrposition;
1377 
1378  /*
1379  * We can do nothing useful if init_sql_fcache() didn't get as far as
1380  * saving the function name
1381  */
1382  if (fcache == NULL || fcache->fname == NULL)
1383  return;
1384 
1385  /*
1386  * If there is a syntax error position, convert to internal syntax error
1387  */
1388  syntaxerrposition = geterrposition();
1389  if (syntaxerrposition > 0 && fcache->src != NULL)
1390  {
1391  errposition(0);
1392  internalerrposition(syntaxerrposition);
1393  internalerrquery(fcache->src);
1394  }
1395 
1396  /*
1397  * Try to determine where in the function we failed. If there is a query
1398  * with non-null QueryDesc, finger it. (We check this rather than looking
1399  * for F_EXEC_RUN state, so that errors during ExecutorStart or
1400  * ExecutorEnd are blamed on the appropriate query; see postquel_start and
1401  * postquel_end.)
1402  */
1403  if (fcache->func_state)
1404  {
1405  execution_state *es;
1406  int query_num;
1407  ListCell *lc;
1408 
1409  es = NULL;
1410  query_num = 1;
1411  foreach(lc, fcache->func_state)
1412  {
1413  es = (execution_state *) lfirst(lc);
1414  while (es)
1415  {
1416  if (es->qd)
1417  {
1418  errcontext("SQL function \"%s\" statement %d",
1419  fcache->fname, query_num);
1420  break;
1421  }
1422  es = es->next;
1423  }
1424  if (es)
1425  break;
1426  query_num++;
1427  }
1428  if (es == NULL)
1429  {
1430  /*
1431  * couldn't identify a running query; might be function entry,
1432  * function exit, or between queries.
1433  */
1434  errcontext("SQL function \"%s\"", fcache->fname);
1435  }
1436  }
1437  else
1438  {
1439  /*
1440  * Assume we failed during init_sql_fcache(). (It's possible that the
1441  * function actually has an empty body, but in that case we may as
1442  * well report all errors as being "during startup".)
1443  */
1444  errcontext("SQL function \"%s\" during startup", fcache->fname);
1445  }
1446 }
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:245
Definition: nodes.h:517
#define OidIsValid(objectId)
Definition: c.h:605
Oid paramcollid
Definition: primnodes.h:249
int location
Definition: primnodes.h:250
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:2799
int32 paramtypmod
Definition: primnodes.h:248
#define makeNode(_type_)
Definition: nodes.h:565
int paramid
Definition: primnodes.h:246
Oid paramtype
Definition: primnodes.h:247

◆ 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:246
int location
Definition: parsenodes.h:247
void * p_ref_hook_state
Definition: parse_node.h:216
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:213
ParseParamRefHook p_paramref_hook
Definition: parse_node.h:214
static Node * sql_fn_post_column_ref(ParseState *pstate, ColumnRef *cref, Node *var)
Definition: functions.c:286
void * p_ref_hook_state
Definition: parse_node.h:216
static Node * sql_fn_param_ref(ParseState *pstate, ParamRef *pref)
Definition: functions.c:404
PreParseColumnRefHook p_pre_columnref_hook
Definition: parse_node.h:212

◆ 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:568
struct SQLFunctionParseInfo * SQLFunctionParseInfoPtr
Definition: functions.h:21
#define llast(l)
Definition: pg_list.h:131
Definition: nodes.h:517
#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:237
#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:206
#define Assert(condition)
Definition: c.h:699
void * p_ref_hook_state
Definition: parse_node.h:216
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:236

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

References pfree().

Referenced by CreateSQLFunctionDestReceiver().

2006 {
2007  pfree(self);
2008 }
void pfree(void *pointer)
Definition: mcxt.c:1031

◆ sqlfunction_receive()

static bool sqlfunction_receive ( TupleTableSlot slot,
DestReceiver self 
)
static

Definition at line 1979 of file functions.c.

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

Referenced by CreateSQLFunctionDestReceiver().

1980 {
1981  DR_sqlfunction *myState = (DR_sqlfunction *) self;
1982 
1983  /* Filter tuple as needed */
1984  slot = ExecFilterJunk(myState->filter, slot);
1985 
1986  /* Store the filtered tuple into the tuplestore */
1987  tuplestore_puttupleslot(myState->tstore, slot);
1988 
1989  return true;
1990 }
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 1996 of file functions.c.

Referenced by CreateSQLFunctionDestReceiver().

1997 {
1998  /* no-op */
1999 }

◆ sqlfunction_startup()

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

Definition at line 1970 of file functions.c.

Referenced by CreateSQLFunctionDestReceiver().

1971 {
1972  /* no-op */
1973 }