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_collate.h"
#include "parser/parse_func.h"
#include "rewrite/rewriteHandler.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
 

Typedefs

typedef struct execution_state execution_state
 
typedef SQLFunctionCacheSQLFunctionCachePtr
 

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 (FunctionCallInfo fcinfo, 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 bool coerce_fn_result_column (TargetEntry *src_tle, Oid res_type, int32 res_typmod, bool tlist_is_modifiable, List **upper_tlist, bool *upper_tlist_nontrivial)
 
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 *queryTreeLists)
 
bool check_sql_fn_retval (List *queryTreeLists, Oid rettype, TupleDesc rettupdesc, bool insertDroppedCols, List **resultTargetList)
 
DestReceiverCreateSQLFunctionDestReceiver (void)
 

Typedef Documentation

◆ execution_state

◆ SQLFunctionCachePtr

Definition at line 130 of file functions.c.

Enumeration Type Documentation

◆ ExecStatus

enum ExecStatus
Enumerator
F_EXEC_START 
F_EXEC_RUN 
F_EXEC_DONE 

Definition at line 60 of file functions.c.

61 {
63 } ExecStatus;
ExecStatus
Definition: functions.c:61
@ F_EXEC_START
Definition: functions.c:62
@ F_EXEC_DONE
Definition: functions.c:62
@ F_EXEC_RUN
Definition: functions.c:62

Function Documentation

◆ check_sql_fn_retval()

bool check_sql_fn_retval ( List queryTreeLists,
Oid  rettype,
TupleDesc  rettupdesc,
bool  insertDroppedCols,
List **  resultTargetList 
)

Definition at line 1612 of file functions.c.

1616 {
1617  bool is_tuple_result = false;
1618  Query *parse;
1619  ListCell *parse_cell;
1620  List *tlist;
1621  int tlistlen;
1622  bool tlist_is_modifiable;
1623  char fn_typtype;
1624  List *upper_tlist = NIL;
1625  bool upper_tlist_nontrivial = false;
1626  ListCell *lc;
1627 
1628  if (resultTargetList)
1629  *resultTargetList = NIL; /* initialize in case of VOID result */
1630 
1631  /*
1632  * If it's declared to return VOID, we don't care what's in the function.
1633  * (This takes care of the procedure case, as well.)
1634  */
1635  if (rettype == VOIDOID)
1636  return false;
1637 
1638  /*
1639  * Find the last canSetTag query in the function body (which is presented
1640  * to us as a list of sublists of Query nodes). This isn't necessarily
1641  * the last parsetree, because rule rewriting can insert queries after
1642  * what the user wrote. Note that it might not even be in the last
1643  * sublist, for example if the last query rewrites to DO INSTEAD NOTHING.
1644  * (It might not be unreasonable to throw an error in such a case, but
1645  * this is the historical behavior and it doesn't seem worth changing.)
1646  */
1647  parse = NULL;
1648  parse_cell = NULL;
1649  foreach(lc, queryTreeLists)
1650  {
1651  List *sublist = lfirst_node(List, lc);
1652  ListCell *lc2;
1653 
1654  foreach(lc2, sublist)
1655  {
1656  Query *q = lfirst_node(Query, lc2);
1657 
1658  if (q->canSetTag)
1659  {
1660  parse = q;
1661  parse_cell = lc2;
1662  }
1663  }
1664  }
1665 
1666  /*
1667  * If it's a plain SELECT, it returns whatever the targetlist says.
1668  * Otherwise, if it's INSERT/UPDATE/DELETE with RETURNING, it returns
1669  * that. Otherwise, the function return type must be VOID.
1670  *
1671  * Note: eventually replace this test with QueryReturnsTuples? We'd need
1672  * a more general method of determining the output type, though. Also, it
1673  * seems too dangerous to consider FETCH or EXECUTE as returning a
1674  * determinable rowtype, since they depend on relatively short-lived
1675  * entities.
1676  */
1677  if (parse &&
1678  parse->commandType == CMD_SELECT)
1679  {
1680  tlist = parse->targetList;
1681  /* tlist is modifiable unless it's a dummy in a setop query */
1682  tlist_is_modifiable = (parse->setOperations == NULL);
1683  }
1684  else if (parse &&
1685  (parse->commandType == CMD_INSERT ||
1686  parse->commandType == CMD_UPDATE ||
1687  parse->commandType == CMD_DELETE) &&
1688  parse->returningList)
1689  {
1690  tlist = parse->returningList;
1691  /* returningList can always be modified */
1692  tlist_is_modifiable = true;
1693  }
1694  else
1695  {
1696  /* Empty function body, or last statement is a utility command */
1697  ereport(ERROR,
1698  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1699  errmsg("return type mismatch in function declared to return %s",
1700  format_type_be(rettype)),
1701  errdetail("Function's final statement must be SELECT or INSERT/UPDATE/DELETE RETURNING.")));
1702  return false; /* keep compiler quiet */
1703  }
1704 
1705  /*
1706  * OK, check that the targetlist returns something matching the declared
1707  * type, and modify it if necessary. If possible, we insert any coercion
1708  * steps right into the final statement's targetlist. However, that might
1709  * risk changes in the statement's semantics --- we can't safely change
1710  * the output type of a grouping column, for instance. In such cases we
1711  * handle coercions by inserting an extra level of Query that effectively
1712  * just does a projection.
1713  */
1714 
1715  /*
1716  * Count the non-junk entries in the result targetlist.
1717  */
1718  tlistlen = ExecCleanTargetListLength(tlist);
1719 
1720  fn_typtype = get_typtype(rettype);
1721 
1722  if (fn_typtype == TYPTYPE_BASE ||
1723  fn_typtype == TYPTYPE_DOMAIN ||
1724  fn_typtype == TYPTYPE_ENUM ||
1725  fn_typtype == TYPTYPE_RANGE ||
1726  fn_typtype == TYPTYPE_MULTIRANGE)
1727  {
1728  /*
1729  * For scalar-type returns, the target list must have exactly one
1730  * non-junk entry, and its type must be coercible to rettype.
1731  */
1732  TargetEntry *tle;
1733 
1734  if (tlistlen != 1)
1735  ereport(ERROR,
1736  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1737  errmsg("return type mismatch in function declared to return %s",
1738  format_type_be(rettype)),
1739  errdetail("Final statement must return exactly one column.")));
1740 
1741  /* We assume here that non-junk TLEs must come first in tlists */
1742  tle = (TargetEntry *) linitial(tlist);
1743  Assert(!tle->resjunk);
1744 
1745  if (!coerce_fn_result_column(tle, rettype, -1,
1746  tlist_is_modifiable,
1747  &upper_tlist,
1748  &upper_tlist_nontrivial))
1749  ereport(ERROR,
1750  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1751  errmsg("return type mismatch in function declared to return %s",
1752  format_type_be(rettype)),
1753  errdetail("Actual return type is %s.",
1754  format_type_be(exprType((Node *) tle->expr)))));
1755  }
1756  else if (fn_typtype == TYPTYPE_COMPOSITE || rettype == RECORDOID)
1757  {
1758  /*
1759  * Returns a rowtype.
1760  *
1761  * Note that we will not consider a domain over composite to be a
1762  * "rowtype" return type; it goes through the scalar case above. This
1763  * is because we only provide column-by-column implicit casting, and
1764  * will not cast the complete record result. So the only way to
1765  * produce a domain-over-composite result is to compute it as an
1766  * explicit single-column result. The single-composite-column code
1767  * path just below could handle such cases, but it won't be reached.
1768  */
1769  int tupnatts; /* physical number of columns in tuple */
1770  int tuplogcols; /* # of nondeleted columns in tuple */
1771  int colindex; /* physical column index */
1772 
1773  /*
1774  * If the target list has one non-junk entry, and that expression has
1775  * or can be coerced to the declared return type, take it as the
1776  * result. This allows, for example, 'SELECT func2()', where func2
1777  * has the same composite return type as the function that's calling
1778  * it. This provision creates some ambiguity --- maybe the expression
1779  * was meant to be the lone field of the composite result --- but it
1780  * works well enough as long as we don't get too enthusiastic about
1781  * inventing coercions from scalar to composite types.
1782  *
1783  * XXX Note that if rettype is RECORD and the expression is of a named
1784  * composite type, or vice versa, this coercion will succeed, whether
1785  * or not the record type really matches. For the moment we rely on
1786  * runtime type checking to catch any discrepancy, but it'd be nice to
1787  * do better at parse time.
1788  */
1789  if (tlistlen == 1)
1790  {
1791  TargetEntry *tle = (TargetEntry *) linitial(tlist);
1792 
1793  Assert(!tle->resjunk);
1794  if (coerce_fn_result_column(tle, rettype, -1,
1795  tlist_is_modifiable,
1796  &upper_tlist,
1797  &upper_tlist_nontrivial))
1798  {
1799  /* Note that we're NOT setting is_tuple_result */
1800  goto tlist_coercion_finished;
1801  }
1802  }
1803 
1804  /*
1805  * If the caller didn't provide an expected tupdesc, we can't do any
1806  * further checking. Assume we're returning the whole tuple.
1807  */
1808  if (rettupdesc == NULL)
1809  {
1810  /* Return tlist if requested */
1811  if (resultTargetList)
1812  *resultTargetList = tlist;
1813  return true;
1814  }
1815 
1816  /*
1817  * Verify that the targetlist matches the return tuple type. We scan
1818  * the non-resjunk columns, and coerce them if necessary to match the
1819  * datatypes of the non-deleted attributes. For deleted attributes,
1820  * insert NULL result columns if the caller asked for that.
1821  */
1822  tupnatts = rettupdesc->natts;
1823  tuplogcols = 0; /* we'll count nondeleted cols as we go */
1824  colindex = 0;
1825 
1826  foreach(lc, tlist)
1827  {
1828  TargetEntry *tle = (TargetEntry *) lfirst(lc);
1829  Form_pg_attribute attr;
1830 
1831  /* resjunk columns can simply be ignored */
1832  if (tle->resjunk)
1833  continue;
1834 
1835  do
1836  {
1837  colindex++;
1838  if (colindex > tupnatts)
1839  ereport(ERROR,
1840  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1841  errmsg("return type mismatch in function declared to return %s",
1842  format_type_be(rettype)),
1843  errdetail("Final statement returns too many columns.")));
1844  attr = TupleDescAttr(rettupdesc, colindex - 1);
1845  if (attr->attisdropped && insertDroppedCols)
1846  {
1847  Expr *null_expr;
1848 
1849  /* The type of the null we insert isn't important */
1850  null_expr = (Expr *) makeConst(INT4OID,
1851  -1,
1852  InvalidOid,
1853  sizeof(int32),
1854  (Datum) 0,
1855  true, /* isnull */
1856  true /* byval */ );
1857  upper_tlist = lappend(upper_tlist,
1858  makeTargetEntry(null_expr,
1859  list_length(upper_tlist) + 1,
1860  NULL,
1861  false));
1862  upper_tlist_nontrivial = true;
1863  }
1864  } while (attr->attisdropped);
1865  tuplogcols++;
1866 
1867  if (!coerce_fn_result_column(tle,
1868  attr->atttypid, attr->atttypmod,
1869  tlist_is_modifiable,
1870  &upper_tlist,
1871  &upper_tlist_nontrivial))
1872  ereport(ERROR,
1873  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1874  errmsg("return type mismatch in function declared to return %s",
1875  format_type_be(rettype)),
1876  errdetail("Final statement returns %s instead of %s at column %d.",
1877  format_type_be(exprType((Node *) tle->expr)),
1878  format_type_be(attr->atttypid),
1879  tuplogcols)));
1880  }
1881 
1882  /* remaining columns in rettupdesc had better all be dropped */
1883  for (colindex++; colindex <= tupnatts; colindex++)
1884  {
1885  if (!TupleDescAttr(rettupdesc, colindex - 1)->attisdropped)
1886  ereport(ERROR,
1887  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1888  errmsg("return type mismatch in function declared to return %s",
1889  format_type_be(rettype)),
1890  errdetail("Final statement returns too few columns.")));
1891  if (insertDroppedCols)
1892  {
1893  Expr *null_expr;
1894 
1895  /* The type of the null we insert isn't important */
1896  null_expr = (Expr *) makeConst(INT4OID,
1897  -1,
1898  InvalidOid,
1899  sizeof(int32),
1900  (Datum) 0,
1901  true, /* isnull */
1902  true /* byval */ );
1903  upper_tlist = lappend(upper_tlist,
1904  makeTargetEntry(null_expr,
1905  list_length(upper_tlist) + 1,
1906  NULL,
1907  false));
1908  upper_tlist_nontrivial = true;
1909  }
1910  }
1911 
1912  /* Report that we are returning entire tuple result */
1913  is_tuple_result = true;
1914  }
1915  else
1916  ereport(ERROR,
1917  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1918  errmsg("return type %s is not supported for SQL functions",
1919  format_type_be(rettype))));
1920 
1921 tlist_coercion_finished:
1922 
1923  /*
1924  * If necessary, modify the final Query by injecting an extra Query level
1925  * that just performs a projection. (It'd be dubious to do this to a
1926  * non-SELECT query, but we never have to; RETURNING lists can always be
1927  * modified in-place.)
1928  */
1929  if (upper_tlist_nontrivial)
1930  {
1931  Query *newquery;
1932  List *colnames;
1933  RangeTblEntry *rte;
1934  RangeTblRef *rtr;
1935 
1936  Assert(parse->commandType == CMD_SELECT);
1937 
1938  /* Most of the upper Query struct can be left as zeroes/nulls */
1939  newquery = makeNode(Query);
1940  newquery->commandType = CMD_SELECT;
1941  newquery->querySource = parse->querySource;
1942  newquery->canSetTag = true;
1943  newquery->targetList = upper_tlist;
1944 
1945  /* We need a moderately realistic colnames list for the subquery RTE */
1946  colnames = NIL;
1947  foreach(lc, parse->targetList)
1948  {
1949  TargetEntry *tle = (TargetEntry *) lfirst(lc);
1950 
1951  if (tle->resjunk)
1952  continue;
1953  colnames = lappend(colnames,
1954  makeString(tle->resname ? tle->resname : ""));
1955  }
1956 
1957  /* Build a suitable RTE for the subquery */
1958  rte = makeNode(RangeTblEntry);
1959  rte->rtekind = RTE_SUBQUERY;
1960  rte->subquery = parse;
1961  rte->eref = rte->alias = makeAlias("*SELECT*", colnames);
1962  rte->lateral = false;
1963  rte->inh = false;
1964  rte->inFromCl = true;
1965  newquery->rtable = list_make1(rte);
1966 
1967  rtr = makeNode(RangeTblRef);
1968  rtr->rtindex = 1;
1969  newquery->jointree = makeFromExpr(list_make1(rtr), NULL);
1970 
1971  /* Replace original query in the correct element of the query list */
1972  lfirst(parse_cell) = newquery;
1973  }
1974 
1975  /* Return tlist (possibly modified) if requested */
1976  if (resultTargetList)
1977  *resultTargetList = upper_tlist;
1978 
1979  return is_tuple_result;
1980 }
signed int int32
Definition: c.h:430
int errdetail(const char *fmt,...)
Definition: elog.c:1039
int errcode(int sqlerrcode)
Definition: elog.c:695
int errmsg(const char *fmt,...)
Definition: elog.c:906
#define ERROR
Definition: elog.h:35
#define ereport(elevel,...)
Definition: elog.h:145
int ExecCleanTargetListLength(List *targetlist)
Definition: execUtils.c:1148
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
static bool coerce_fn_result_column(TargetEntry *src_tle, Oid res_type, int32 res_typmod, bool tlist_is_modifiable, List **upper_tlist, bool *upper_tlist_nontrivial)
Definition: functions.c:1993
Assert(fmt[strlen(fmt) - 1] !='\n')
List * lappend(List *list, void *datum)
Definition: list.c:338
char get_typtype(Oid typid)
Definition: lsyscache.c:2587
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:387
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:238
Const * makeConst(Oid consttype, int32 consttypmod, Oid constcollid, int constlen, Datum constvalue, bool constisnull, bool constbyval)
Definition: makefuncs.c:299
FromExpr * makeFromExpr(List *fromlist, Node *quals)
Definition: makefuncs.c:285
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:43
@ CMD_INSERT
Definition: nodes.h:261
@ CMD_DELETE
Definition: nodes.h:262
@ CMD_UPDATE
Definition: nodes.h:260
@ CMD_SELECT
Definition: nodes.h:259
#define makeNode(_type_)
Definition: nodes.h:159
@ RTE_SUBQUERY
Definition: parsenodes.h:1012
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
#define lfirst(lc)
Definition: pg_list.h:170
#define lfirst_node(type, lc)
Definition: pg_list.h:174
static int list_length(const List *l)
Definition: pg_list.h:150
#define NIL
Definition: pg_list.h:66
#define list_make1(x1)
Definition: pg_list.h:210
#define linitial(l)
Definition: pg_list.h:176
uintptr_t Datum
Definition: postgres.h:412
#define InvalidOid
Definition: postgres_ext.h:36
static struct subre * parse(struct vars *v, int stopper, int type, struct state *init, struct state *final)
Definition: regcomp.c:717
Definition: pg_list.h:52
Definition: nodes.h:112
FromExpr * jointree
Definition: parsenodes.h:156
bool canSetTag
Definition: parsenodes.h:134
List * rtable
Definition: parsenodes.h:155
QuerySource querySource
Definition: parsenodes.h:126
CmdType commandType
Definition: parsenodes.h:124
List * targetList
Definition: parsenodes.h:162
Query * subquery
Definition: parsenodes.h:1065
Alias * eref
Definition: parsenodes.h:1176
Alias * alias
Definition: parsenodes.h:1175
RTEKind rtekind
Definition: parsenodes.h:1030
Expr * expr
Definition: primnodes.h:1555
char * resname
Definition: primnodes.h:1557
bool resjunk
Definition: primnodes.h:1562
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
String * makeString(char *str)
Definition: value.c:63

References RangeTblEntry::alias, Assert(), Query::canSetTag, CMD_DELETE, CMD_INSERT, CMD_SELECT, CMD_UPDATE, coerce_fn_result_column(), Query::commandType, RangeTblEntry::eref, ereport, errcode(), errdetail(), errmsg(), ERROR, ExecCleanTargetListLength(), TargetEntry::expr, exprType(), format_type_be(), get_typtype(), RangeTblEntry::inFromCl, RangeTblEntry::inh, InvalidOid, Query::jointree, lappend(), RangeTblEntry::lateral, lfirst, lfirst_node, linitial, list_length(), list_make1, makeAlias(), makeConst(), makeFromExpr(), makeNode, makeString(), makeTargetEntry(), TupleDescData::natts, NIL, parse(), Query::querySource, TargetEntry::resjunk, TargetEntry::resname, Query::rtable, RTE_SUBQUERY, RangeTblEntry::rtekind, RangeTblRef::rtindex, RangeTblEntry::subquery, Query::targetList, and TupleDescAttr.

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

◆ check_sql_fn_statements()

void check_sql_fn_statements ( List queryTreeLists)

Definition at line 1537 of file functions.c.

1538 {
1539  ListCell *lc;
1540 
1541  /* We are given a list of sublists of Queries */
1542  foreach(lc, queryTreeLists)
1543  {
1544  List *sublist = lfirst_node(List, lc);
1545  ListCell *lc2;
1546 
1547  foreach(lc2, sublist)
1548  {
1549  Query *query = lfirst_node(Query, lc2);
1550 
1551  /*
1552  * Disallow calling procedures with output arguments. The current
1553  * implementation would just throw the output values away, unless
1554  * the statement is the last one. Per SQL standard, we should
1555  * assign the output values by name. By disallowing this here, we
1556  * preserve an opportunity for future improvement.
1557  */
1558  if (query->commandType == CMD_UTILITY &&
1559  IsA(query->utilityStmt, CallStmt))
1560  {
1561  CallStmt *stmt = (CallStmt *) query->utilityStmt;
1562 
1563  if (stmt->outargs != NIL)
1564  ereport(ERROR,
1565  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1566  errmsg("calling procedures with output arguments is not supported in SQL functions")));
1567  }
1568  }
1569  }
1570 }
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
#define IsA(nodeptr, _type_)
Definition: nodes.h:162
@ CMD_UTILITY
Definition: nodes.h:264
List * outargs
Definition: parsenodes.h:3122
Node * utilityStmt
Definition: parsenodes.h:136

References CMD_UTILITY, Query::commandType, ereport, errcode(), errmsg(), ERROR, if(), IsA, lfirst_node, NIL, execution_state::stmt, and Query::utilityStmt.

Referenced by fmgr_sql_validator(), and init_sql_fcache().

◆ coerce_fn_result_column()

static bool coerce_fn_result_column ( TargetEntry src_tle,
Oid  res_type,
int32  res_typmod,
bool  tlist_is_modifiable,
List **  upper_tlist,
bool upper_tlist_nontrivial 
)
static

Definition at line 1993 of file functions.c.

1999 {
2000  TargetEntry *new_tle;
2001  Expr *new_tle_expr;
2002  Node *cast_result;
2003 
2004  /*
2005  * If the TLE has a sortgroupref marking, don't change it, as it probably
2006  * is referenced by ORDER BY, DISTINCT, etc, and changing its type would
2007  * break query semantics. Otherwise, it's safe to modify in-place unless
2008  * the query as a whole has issues with that.
2009  */
2010  if (tlist_is_modifiable && src_tle->ressortgroupref == 0)
2011  {
2012  /* OK to modify src_tle in place, if necessary */
2013  cast_result = coerce_to_target_type(NULL,
2014  (Node *) src_tle->expr,
2015  exprType((Node *) src_tle->expr),
2016  res_type, res_typmod,
2019  -1);
2020  if (cast_result == NULL)
2021  return false;
2022  assign_expr_collations(NULL, cast_result);
2023  src_tle->expr = (Expr *) cast_result;
2024  /* Make a Var referencing the possibly-modified TLE */
2025  new_tle_expr = (Expr *) makeVarFromTargetEntry(1, src_tle);
2026  }
2027  else
2028  {
2029  /* Any casting must happen in the upper tlist */
2030  Var *var = makeVarFromTargetEntry(1, src_tle);
2031 
2032  cast_result = coerce_to_target_type(NULL,
2033  (Node *) var,
2034  var->vartype,
2035  res_type, res_typmod,
2038  -1);
2039  if (cast_result == NULL)
2040  return false;
2041  assign_expr_collations(NULL, cast_result);
2042  /* Did the coercion actually do anything? */
2043  if (cast_result != (Node *) var)
2044  *upper_tlist_nontrivial = true;
2045  new_tle_expr = (Expr *) cast_result;
2046  }
2047  new_tle = makeTargetEntry(new_tle_expr,
2048  list_length(*upper_tlist) + 1,
2049  src_tle->resname, false);
2050  *upper_tlist = lappend(*upper_tlist, new_tle);
2051  return true;
2052 }
Var * makeVarFromTargetEntry(int varno, TargetEntry *tle)
Definition: makefuncs.c:103
Node * coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype, Oid targettype, int32 targettypmod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:78
void assign_expr_collations(ParseState *pstate, Node *expr)
@ COERCE_IMPLICIT_CAST
Definition: primnodes.h:588
@ COERCION_ASSIGNMENT
Definition: primnodes.h:567
Index ressortgroupref
Definition: primnodes.h:1558
Definition: primnodes.h:205

References assign_expr_collations(), COERCE_IMPLICIT_CAST, coerce_to_target_type(), COERCION_ASSIGNMENT, TargetEntry::expr, exprType(), lappend(), list_length(), makeTargetEntry(), makeVarFromTargetEntry(), TargetEntry::resname, TargetEntry::ressortgroupref, and Var::vartype.

Referenced by check_sql_fn_retval().

◆ CreateSQLFunctionDestReceiver()

DestReceiver* CreateSQLFunctionDestReceiver ( void  )

Definition at line 2059 of file functions.c.

2060 {
2061  DR_sqlfunction *self = (DR_sqlfunction *) palloc0(sizeof(DR_sqlfunction));
2062 
2063  self->pub.receiveSlot = sqlfunction_receive;
2064  self->pub.rStartup = sqlfunction_startup;
2065  self->pub.rShutdown = sqlfunction_shutdown;
2066  self->pub.rDestroy = sqlfunction_destroy;
2067  self->pub.mydest = DestSQLFunction;
2068 
2069  /* private fields will be set by postquel_start */
2070 
2071  return (DestReceiver *) self;
2072 }
@ DestSQLFunction
Definition: dest.h:98
static void sqlfunction_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: functions.c:2078
static bool sqlfunction_receive(TupleTableSlot *slot, DestReceiver *self)
Definition: functions.c:2087
static void sqlfunction_destroy(DestReceiver *self)
Definition: functions.c:2113
static void sqlfunction_shutdown(DestReceiver *self)
Definition: functions.c:2104
void * palloc0(Size size)
Definition: mcxt.c:1230

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

Referenced by CreateDestReceiver().

◆ fmgr_sql()

Datum fmgr_sql ( PG_FUNCTION_ARGS  )

Definition at line 1032 of file functions.c.

1033 {
1034  SQLFunctionCachePtr fcache;
1035  ErrorContextCallback sqlerrcontext;
1036  MemoryContext oldcontext;
1037  bool randomAccess;
1038  bool lazyEvalOK;
1039  bool is_first;
1040  bool pushed_snapshot;
1041  execution_state *es;
1042  TupleTableSlot *slot;
1043  Datum result;
1044  List *eslist;
1045  ListCell *eslc;
1046 
1047  /*
1048  * Setup error traceback support for ereport()
1049  */
1050  sqlerrcontext.callback = sql_exec_error_callback;
1051  sqlerrcontext.arg = fcinfo->flinfo;
1052  sqlerrcontext.previous = error_context_stack;
1053  error_context_stack = &sqlerrcontext;
1054 
1055  /* Check call context */
1056  if (fcinfo->flinfo->fn_retset)
1057  {
1058  ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
1059 
1060  /*
1061  * For simplicity, we require callers to support both set eval modes.
1062  * There are cases where we must use one or must use the other, and
1063  * it's not really worthwhile to postpone the check till we know. But
1064  * note we do not require caller to provide an expectedDesc.
1065  */
1066  if (!rsi || !IsA(rsi, ReturnSetInfo) ||
1067  (rsi->allowedModes & SFRM_ValuePerCall) == 0 ||
1068  (rsi->allowedModes & SFRM_Materialize) == 0)
1069  ereport(ERROR,
1070  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1071  errmsg("set-valued function called in context that cannot accept a set")));
1072  randomAccess = rsi->allowedModes & SFRM_Materialize_Random;
1073  lazyEvalOK = !(rsi->allowedModes & SFRM_Materialize_Preferred);
1074  }
1075  else
1076  {
1077  randomAccess = false;
1078  lazyEvalOK = true;
1079  }
1080 
1081  /*
1082  * Initialize fcache (build plans) if first time through; or re-initialize
1083  * if the cache is stale.
1084  */
1085  fcache = (SQLFunctionCachePtr) fcinfo->flinfo->fn_extra;
1086 
1087  if (fcache != NULL)
1088  {
1089  if (fcache->lxid != MyProc->lxid ||
1090  !SubTransactionIsActive(fcache->subxid))
1091  {
1092  /* It's stale; unlink and delete */
1093  fcinfo->flinfo->fn_extra = NULL;
1094  MemoryContextDelete(fcache->fcontext);
1095  fcache = NULL;
1096  }
1097  }
1098 
1099  if (fcache == NULL)
1100  {
1101  init_sql_fcache(fcinfo, PG_GET_COLLATION(), lazyEvalOK);
1102  fcache = (SQLFunctionCachePtr) fcinfo->flinfo->fn_extra;
1103  }
1104 
1105  /*
1106  * Switch to context in which the fcache lives. This ensures that our
1107  * tuplestore etc will have sufficient lifetime. The sub-executor is
1108  * responsible for deleting per-tuple information. (XXX in the case of a
1109  * long-lived FmgrInfo, this policy represents more memory leakage, but
1110  * it's not entirely clear where to keep stuff instead.)
1111  */
1112  oldcontext = MemoryContextSwitchTo(fcache->fcontext);
1113 
1114  /*
1115  * Find first unfinished query in function, and note whether it's the
1116  * first query.
1117  */
1118  eslist = fcache->func_state;
1119  es = NULL;
1120  is_first = true;
1121  foreach(eslc, eslist)
1122  {
1123  es = (execution_state *) lfirst(eslc);
1124 
1125  while (es && es->status == F_EXEC_DONE)
1126  {
1127  is_first = false;
1128  es = es->next;
1129  }
1130 
1131  if (es)
1132  break;
1133  }
1134 
1135  /*
1136  * Convert params to appropriate format if starting a fresh execution. (If
1137  * continuing execution, we can re-use prior params.)
1138  */
1139  if (is_first && es && es->status == F_EXEC_START)
1140  postquel_sub_params(fcache, fcinfo);
1141 
1142  /*
1143  * Build tuplestore to hold results, if we don't have one already. Note
1144  * it's in the query-lifespan context.
1145  */
1146  if (!fcache->tstore)
1147  fcache->tstore = tuplestore_begin_heap(randomAccess, false, work_mem);
1148 
1149  /*
1150  * Execute each command in the function one after another until we either
1151  * run out of commands or get a result row from a lazily-evaluated SELECT.
1152  *
1153  * Notes about snapshot management:
1154  *
1155  * In a read-only function, we just use the surrounding query's snapshot.
1156  *
1157  * In a non-read-only function, we rely on the fact that we'll never
1158  * suspend execution between queries of the function: the only reason to
1159  * suspend execution before completion is if we are returning a row from a
1160  * lazily-evaluated SELECT. So, when first entering this loop, we'll
1161  * either start a new query (and push a fresh snapshot) or re-establish
1162  * the active snapshot from the existing query descriptor. If we need to
1163  * start a new query in a subsequent execution of the loop, either we need
1164  * a fresh snapshot (and pushed_snapshot is false) or the existing
1165  * snapshot is on the active stack and we can just bump its command ID.
1166  */
1167  pushed_snapshot = false;
1168  while (es)
1169  {
1170  bool completed;
1171 
1172  if (es->status == F_EXEC_START)
1173  {
1174  /*
1175  * If not read-only, be sure to advance the command counter for
1176  * each command, so that all work to date in this transaction is
1177  * visible. Take a new snapshot if we don't have one yet,
1178  * otherwise just bump the command ID in the existing snapshot.
1179  */
1180  if (!fcache->readonly_func)
1181  {
1183  if (!pushed_snapshot)
1184  {
1186  pushed_snapshot = true;
1187  }
1188  else
1190  }
1191 
1192  postquel_start(es, fcache);
1193  }
1194  else if (!fcache->readonly_func && !pushed_snapshot)
1195  {
1196  /* Re-establish active snapshot when re-entering function */
1198  pushed_snapshot = true;
1199  }
1200 
1201  completed = postquel_getnext(es, fcache);
1202 
1203  /*
1204  * If we ran the command to completion, we can shut it down now. Any
1205  * row(s) we need to return are safely stashed in the tuplestore, and
1206  * we want to be sure that, for example, AFTER triggers get fired
1207  * before we return anything. Also, if the function doesn't return
1208  * set, we can shut it down anyway because it must be a SELECT and we
1209  * don't care about fetching any more result rows.
1210  */
1211  if (completed || !fcache->returnsSet)
1212  postquel_end(es);
1213 
1214  /*
1215  * Break from loop if we didn't shut down (implying we got a
1216  * lazily-evaluated row). Otherwise we'll press on till the whole
1217  * function is done, relying on the tuplestore to keep hold of the
1218  * data to eventually be returned. This is necessary since an
1219  * INSERT/UPDATE/DELETE RETURNING that sets the result might be
1220  * followed by additional rule-inserted commands, and we want to
1221  * finish doing all those commands before we return anything.
1222  */
1223  if (es->status != F_EXEC_DONE)
1224  break;
1225 
1226  /*
1227  * Advance to next execution_state, which might be in the next list.
1228  */
1229  es = es->next;
1230  while (!es)
1231  {
1232  eslc = lnext(eslist, eslc);
1233  if (!eslc)
1234  break; /* end of function */
1235 
1236  es = (execution_state *) lfirst(eslc);
1237 
1238  /*
1239  * Flush the current snapshot so that we will take a new one for
1240  * the new query list. This ensures that new snaps are taken at
1241  * original-query boundaries, matching the behavior of interactive
1242  * execution.
1243  */
1244  if (pushed_snapshot)
1245  {
1247  pushed_snapshot = false;
1248  }
1249  }
1250  }
1251 
1252  /*
1253  * The tuplestore now contains whatever row(s) we are supposed to return.
1254  */
1255  if (fcache->returnsSet)
1256  {
1257  ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
1258 
1259  if (es)
1260  {
1261  /*
1262  * If we stopped short of being done, we must have a lazy-eval
1263  * row.
1264  */
1265  Assert(es->lazyEval);
1266  /* Re-use the junkfilter's output slot to fetch back the tuple */
1267  Assert(fcache->junkFilter);
1268  slot = fcache->junkFilter->jf_resultSlot;
1269  if (!tuplestore_gettupleslot(fcache->tstore, true, false, slot))
1270  elog(ERROR, "failed to fetch lazy-eval tuple");
1271  /* Extract the result as a datum, and copy out from the slot */
1272  result = postquel_get_single_result(slot, fcinfo,
1273  fcache, oldcontext);
1274  /* Clear the tuplestore, but keep it for next time */
1275  /* NB: this might delete the slot's content, but we don't care */
1276  tuplestore_clear(fcache->tstore);
1277 
1278  /*
1279  * Let caller know we're not finished.
1280  */
1281  rsi->isDone = ExprMultipleResult;
1282 
1283  /*
1284  * Ensure we will get shut down cleanly if the exprcontext is not
1285  * run to completion.
1286  */
1287  if (!fcache->shutdown_reg)
1288  {
1291  PointerGetDatum(fcache));
1292  fcache->shutdown_reg = true;
1293  }
1294  }
1295  else if (fcache->lazyEval)
1296  {
1297  /*
1298  * We are done with a lazy evaluation. Clean up.
1299  */
1300  tuplestore_clear(fcache->tstore);
1301 
1302  /*
1303  * Let caller know we're finished.
1304  */
1305  rsi->isDone = ExprEndResult;
1306 
1307  fcinfo->isnull = true;
1308  result = (Datum) 0;
1309 
1310  /* Deregister shutdown callback, if we made one */
1311  if (fcache->shutdown_reg)
1312  {
1315  PointerGetDatum(fcache));
1316  fcache->shutdown_reg = false;
1317  }
1318  }
1319  else
1320  {
1321  /*
1322  * We are done with a non-lazy evaluation. Return whatever is in
1323  * the tuplestore. (It is now caller's responsibility to free the
1324  * tuplestore when done.)
1325  */
1327  rsi->setResult = fcache->tstore;
1328  fcache->tstore = NULL;
1329  /* must copy desc because execSRF.c will free it */
1330  if (fcache->junkFilter)
1332 
1333  fcinfo->isnull = true;
1334  result = (Datum) 0;
1335 
1336  /* Deregister shutdown callback, if we made one */
1337  if (fcache->shutdown_reg)
1338  {
1341  PointerGetDatum(fcache));
1342  fcache->shutdown_reg = false;
1343  }
1344  }
1345  }
1346  else
1347  {
1348  /*
1349  * Non-set function. If we got a row, return it; else return NULL.
1350  */
1351  if (fcache->junkFilter)
1352  {
1353  /* Re-use the junkfilter's output slot to fetch back the tuple */
1354  slot = fcache->junkFilter->jf_resultSlot;
1355  if (tuplestore_gettupleslot(fcache->tstore, true, false, slot))
1356  result = postquel_get_single_result(slot, fcinfo,
1357  fcache, oldcontext);
1358  else
1359  {
1360  fcinfo->isnull = true;
1361  result = (Datum) 0;
1362  }
1363  }
1364  else
1365  {
1366  /* Should only get here for VOID functions and procedures */
1367  Assert(fcache->rettype == VOIDOID);
1368  fcinfo->isnull = true;
1369  result = (Datum) 0;
1370  }
1371 
1372  /* Clear the tuplestore, but keep it for next time */
1373  tuplestore_clear(fcache->tstore);
1374  }
1375 
1376  /* Pop snapshot if we have pushed one */
1377  if (pushed_snapshot)
1379 
1380  /*
1381  * If we've gone through every command in the function, we are done. Reset
1382  * the execution states to start over again on next call.
1383  */
1384  if (es == NULL)
1385  {
1386  foreach(eslc, fcache->func_state)
1387  {
1388  es = (execution_state *) lfirst(eslc);
1389  while (es)
1390  {
1391  es->status = F_EXEC_START;
1392  es = es->next;
1393  }
1394  }
1395  }
1396 
1397  error_context_stack = sqlerrcontext.previous;
1398 
1399  MemoryContextSwitchTo(oldcontext);
1400 
1401  return result;
1402 }
ErrorContextCallback * error_context_stack
Definition: elog.c:94
void UnregisterExprContextCallback(ExprContext *econtext, ExprContextCallbackFunction function, Datum arg)
Definition: execUtils.c:952
void RegisterExprContextCallback(ExprContext *econtext, ExprContextCallbackFunction function, Datum arg)
Definition: execUtils.c:926
@ ExprMultipleResult
Definition: execnodes.h:296
@ ExprEndResult
Definition: execnodes.h:297
@ SFRM_Materialize_Preferred
Definition: execnodes.h:311
@ SFRM_ValuePerCall
Definition: execnodes.h:308
@ SFRM_Materialize_Random
Definition: execnodes.h:310
@ SFRM_Materialize
Definition: execnodes.h:309
#define PG_GET_COLLATION()
Definition: fmgr.h:198
static bool postquel_getnext(execution_state *es, SQLFunctionCachePtr fcache)
Definition: functions.c:879
static void postquel_end(execution_state *es)
Definition: functions.c:914
static void postquel_sub_params(SQLFunctionCachePtr fcache, FunctionCallInfo fcinfo)
Definition: functions.c:934
static void postquel_start(execution_state *es, SQLFunctionCachePtr fcache)
Definition: functions.c:817
static Datum postquel_get_single_result(TupleTableSlot *slot, FunctionCallInfo fcinfo, SQLFunctionCachePtr fcache, MemoryContext resultcontext)
Definition: functions.c:989
static void sql_exec_error_callback(void *arg)
Definition: functions.c:1409
static void init_sql_fcache(FunctionCallInfo fcinfo, Oid collation, bool lazyEvalOK)
Definition: functions.c:582
static void ShutdownSQLFunction(Datum arg)
Definition: functions.c:1491
SQLFunctionCache * SQLFunctionCachePtr
Definition: functions.c:130
int work_mem
Definition: globals.c:125
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:376
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:135
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:341
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:670
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:251
void PushActiveSnapshot(Snapshot snapshot)
Definition: snapmgr.c:683
void UpdateActiveSnapshotCommandId(void)
Definition: snapmgr.c:747
void PopActiveSnapshot(void)
Definition: snapmgr.c:778
PGPROC * MyProc
Definition: proc.c:68
struct ErrorContextCallback * previous
Definition: elog.h:234
void(* callback)(void *arg)
Definition: elog.h:235
TupleDesc jf_cleanTupType
Definition: execnodes.h:387
TupleTableSlot * jf_resultSlot
Definition: execnodes.h:389
LocalTransactionId lxid
Definition: proc.h:183
Snapshot snapshot
Definition: execdesc.h:39
SetFunctionReturnMode returnMode
Definition: execnodes.h:328
ExprContext * econtext
Definition: execnodes.h:324
TupleDesc setDesc
Definition: execnodes.h:332
Tuplestorestate * setResult
Definition: execnodes.h:331
int allowedModes
Definition: execnodes.h:326
ExprDoneCond isDone
Definition: execnodes.h:329
MemoryContext fcontext
Definition: functions.c:123
LocalTransactionId lxid
Definition: functions.c:126
JunkFilter * junkFilter
Definition: functions.c:113
List * func_state
Definition: functions.c:121
Tuplestorestate * tstore
Definition: functions.c:111
SubTransactionId subxid
Definition: functions.c:127
ExecStatus status
Definition: functions.c:68
struct execution_state * next
Definition: functions.c:67
QueryDesc * qd
Definition: functions.c:72
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:111
bool tuplestore_gettupleslot(Tuplestorestate *state, bool forward, bool copy, TupleTableSlot *slot)
Definition: tuplestore.c:1078
void tuplestore_clear(Tuplestorestate *state)
Definition: tuplestore.c:418
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318
void CommandCounterIncrement(void)
Definition: xact.c:1077
bool SubTransactionIsActive(SubTransactionId subxid)
Definition: xact.c:793

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(), if(), init_sql_fcache(), IsA, ReturnSetInfo::isDone, JunkFilter::jf_cleanTupType, JunkFilter::jf_resultSlot, SQLFunctionCache::junkFilter, execution_state::lazyEval, SQLFunctionCache::lazyEval, lfirst, lnext(), SQLFunctionCache::lxid, PGPROC::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().

◆ init_execution_state()

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

Definition at line 464 of file functions.c.

467 {
468  List *eslist = NIL;
469  execution_state *lasttages = NULL;
470  ListCell *lc1;
471 
472  foreach(lc1, queryTree_list)
473  {
474  List *qtlist = lfirst_node(List, lc1);
475  execution_state *firstes = NULL;
476  execution_state *preves = NULL;
477  ListCell *lc2;
478 
479  foreach(lc2, qtlist)
480  {
481  Query *queryTree = lfirst_node(Query, lc2);
482  PlannedStmt *stmt;
483  execution_state *newes;
484 
485  /* Plan the query if needed */
486  if (queryTree->commandType == CMD_UTILITY)
487  {
488  /* Utility commands require no planning. */
489  stmt = makeNode(PlannedStmt);
490  stmt->commandType = CMD_UTILITY;
491  stmt->canSetTag = queryTree->canSetTag;
492  stmt->utilityStmt = queryTree->utilityStmt;
493  stmt->stmt_location = queryTree->stmt_location;
494  stmt->stmt_len = queryTree->stmt_len;
495  }
496  else
497  stmt = pg_plan_query(queryTree,
498  fcache->src,
500  NULL);
501 
502  /*
503  * Precheck all commands for validity in a function. This should
504  * generally match the restrictions spi.c applies.
505  */
506  if (stmt->commandType == CMD_UTILITY)
507  {
508  if (IsA(stmt->utilityStmt, CopyStmt) &&
509  ((CopyStmt *) stmt->utilityStmt)->filename == NULL)
510  ereport(ERROR,
511  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
512  errmsg("cannot COPY to/from client in an SQL function")));
513 
514  if (IsA(stmt->utilityStmt, TransactionStmt))
515  ereport(ERROR,
516  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
517  /* translator: %s is a SQL statement name */
518  errmsg("%s is not allowed in an SQL function",
519  CreateCommandName(stmt->utilityStmt))));
520  }
521 
522  if (fcache->readonly_func && !CommandIsReadOnly(stmt))
523  ereport(ERROR,
524  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
525  /* translator: %s is a SQL statement name */
526  errmsg("%s is not allowed in a non-volatile function",
527  CreateCommandName((Node *) stmt))));
528 
529  /* OK, build the execution_state for this query */
530  newes = (execution_state *) palloc(sizeof(execution_state));
531  if (preves)
532  preves->next = newes;
533  else
534  firstes = newes;
535 
536  newes->next = NULL;
537  newes->status = F_EXEC_START;
538  newes->setsResult = false; /* might change below */
539  newes->lazyEval = false; /* might change below */
540  newes->stmt = stmt;
541  newes->qd = NULL;
542 
543  if (queryTree->canSetTag)
544  lasttages = newes;
545 
546  preves = newes;
547  }
548 
549  eslist = lappend(eslist, firstes);
550  }
551 
552  /*
553  * Mark the last canSetTag query as delivering the function result; then,
554  * if it is a plain SELECT, mark it for lazy evaluation. If it's not a
555  * SELECT we must always run it to completion.
556  *
557  * Note: at some point we might add additional criteria for whether to use
558  * lazy eval. However, we should prefer to use it whenever the function
559  * doesn't return set, since fetching more than one row is useless in that
560  * case.
561  *
562  * Note: don't set setsResult if the function returns VOID, as evidenced
563  * by not having made a junkfilter. This ensures we'll throw away any
564  * output from the last statement in such a function.
565  */
566  if (lasttages && fcache->junkFilter)
567  {
568  lasttages->setsResult = true;
569  if (lazyEvalOK &&
570  lasttages->stmt->commandType == CMD_SELECT &&
571  !lasttages->stmt->hasModifyingCTE)
572  fcache->lazyEval = lasttages->lazyEval = true;
573  }
574 
575  return eslist;
576 }
void * palloc(Size size)
Definition: mcxt.c:1199
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2908
PlannedStmt * pg_plan_query(Query *querytree, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:853
bool hasModifyingCTE
Definition: plannodes.h:59
bool canSetTag
Definition: plannodes.h:61
int stmt_location
Definition: plannodes.h:96
int stmt_len
Definition: plannodes.h:97
CmdType commandType
Definition: plannodes.h:53
Node * utilityStmt
Definition: plannodes.h:93
int stmt_location
Definition: parsenodes.h:204
int stmt_len
Definition: parsenodes.h:205
PlannedStmt * stmt
Definition: functions.c:71
bool CommandIsReadOnly(PlannedStmt *pstmt)
Definition: utility.c:101
static const char * CreateCommandName(Node *parsetree)
Definition: utility.h:103

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

Referenced by init_sql_fcache().

◆ init_sql_fcache()

static void init_sql_fcache ( FunctionCallInfo  fcinfo,
Oid  collation,
bool  lazyEvalOK 
)
static

Definition at line 582 of file functions.c.

583 {
584  FmgrInfo *finfo = fcinfo->flinfo;
585  Oid foid = finfo->fn_oid;
586  MemoryContext fcontext;
587  MemoryContext oldcontext;
588  Oid rettype;
589  TupleDesc rettupdesc;
590  HeapTuple procedureTuple;
591  Form_pg_proc procedureStruct;
592  SQLFunctionCachePtr fcache;
593  List *queryTree_list;
594  List *resulttlist;
595  ListCell *lc;
596  Datum tmp;
597  bool isNull;
598 
599  /*
600  * Create memory context that holds all the SQLFunctionCache data. It
601  * must be a child of whatever context holds the FmgrInfo.
602  */
603  fcontext = AllocSetContextCreate(finfo->fn_mcxt,
604  "SQL function",
606 
607  oldcontext = MemoryContextSwitchTo(fcontext);
608 
609  /*
610  * Create the struct proper, link it to fcontext and fn_extra. Once this
611  * is done, we'll be able to recover the memory after failure, even if the
612  * FmgrInfo is long-lived.
613  */
614  fcache = (SQLFunctionCachePtr) palloc0(sizeof(SQLFunctionCache));
615  fcache->fcontext = fcontext;
616  finfo->fn_extra = (void *) fcache;
617 
618  /*
619  * get the procedure tuple corresponding to the given function Oid
620  */
621  procedureTuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(foid));
622  if (!HeapTupleIsValid(procedureTuple))
623  elog(ERROR, "cache lookup failed for function %u", foid);
624  procedureStruct = (Form_pg_proc) GETSTRUCT(procedureTuple);
625 
626  /*
627  * copy function name immediately for use by error reporting callback, and
628  * for use as memory context identifier
629  */
630  fcache->fname = pstrdup(NameStr(procedureStruct->proname));
631  MemoryContextSetIdentifier(fcontext, fcache->fname);
632 
633  /*
634  * Resolve any polymorphism, obtaining the actual result type, and the
635  * corresponding tupdesc if it's a rowtype.
636  */
637  (void) get_call_result_type(fcinfo, &rettype, &rettupdesc);
638 
639  fcache->rettype = rettype;
640 
641  /* Fetch the typlen and byval info for the result type */
642  get_typlenbyval(rettype, &fcache->typlen, &fcache->typbyval);
643 
644  /* Remember whether we're returning setof something */
645  fcache->returnsSet = procedureStruct->proretset;
646 
647  /* Remember if function is STABLE/IMMUTABLE */
648  fcache->readonly_func =
649  (procedureStruct->provolatile != PROVOLATILE_VOLATILE);
650 
651  /*
652  * We need the actual argument types to pass to the parser. Also make
653  * sure that parameter symbols are considered to have the function's
654  * resolved input collation.
655  */
656  fcache->pinfo = prepare_sql_fn_parse_info(procedureTuple,
657  finfo->fn_expr,
658  collation);
659 
660  /*
661  * And of course we need the function body text.
662  */
663  tmp = SysCacheGetAttr(PROCOID,
664  procedureTuple,
665  Anum_pg_proc_prosrc,
666  &isNull);
667  if (isNull)
668  elog(ERROR, "null prosrc for function %u", foid);
669  fcache->src = TextDatumGetCString(tmp);
670 
671  /* If we have prosqlbody, pay attention to that not prosrc. */
672  tmp = SysCacheGetAttr(PROCOID,
673  procedureTuple,
674  Anum_pg_proc_prosqlbody,
675  &isNull);
676 
677  /*
678  * Parse and rewrite the queries in the function text. Use sublists to
679  * keep track of the original query boundaries.
680  *
681  * Note: since parsing and planning is done in fcontext, we will generate
682  * a lot of cruft that lives as long as the fcache does. This is annoying
683  * but we'll not worry about it until the module is rewritten to use
684  * plancache.c.
685  */
686  queryTree_list = NIL;
687  if (!isNull)
688  {
689  Node *n;
690  List *stored_query_list;
691 
693  if (IsA(n, List))
694  stored_query_list = linitial_node(List, castNode(List, n));
695  else
696  stored_query_list = list_make1(n);
697 
698  foreach(lc, stored_query_list)
699  {
700  Query *parsetree = lfirst_node(Query, lc);
701  List *queryTree_sublist;
702 
703  AcquireRewriteLocks(parsetree, true, false);
704  queryTree_sublist = pg_rewrite_query(parsetree);
705  queryTree_list = lappend(queryTree_list, queryTree_sublist);
706  }
707  }
708  else
709  {
710  List *raw_parsetree_list;
711 
712  raw_parsetree_list = pg_parse_query(fcache->src);
713 
714  foreach(lc, raw_parsetree_list)
715  {
716  RawStmt *parsetree = lfirst_node(RawStmt, lc);
717  List *queryTree_sublist;
718 
719  queryTree_sublist = pg_analyze_and_rewrite_withcb(parsetree,
720  fcache->src,
722  fcache->pinfo,
723  NULL);
724  queryTree_list = lappend(queryTree_list, queryTree_sublist);
725  }
726  }
727 
728  /*
729  * Check that there are no statements we don't want to allow.
730  */
731  check_sql_fn_statements(queryTree_list);
732 
733  /*
734  * Check that the function returns the type it claims to. Although in
735  * simple cases this was already done when the function was defined, we
736  * have to recheck because database objects used in the function's queries
737  * might have changed type. We'd have to recheck anyway if the function
738  * had any polymorphic arguments. Moreover, check_sql_fn_retval takes
739  * care of injecting any required column type coercions. (But we don't
740  * ask it to insert nulls for dropped columns; the junkfilter handles
741  * that.)
742  *
743  * Note: we set fcache->returnsTuple according to whether we are returning
744  * the whole tuple result or just a single column. In the latter case we
745  * clear returnsTuple because we need not act different from the scalar
746  * result case, even if it's a rowtype column. (However, we have to force
747  * lazy eval mode in that case; otherwise we'd need extra code to expand
748  * the rowtype column into multiple columns, since we have no way to
749  * notify the caller that it should do that.)
750  */
751  fcache->returnsTuple = check_sql_fn_retval(queryTree_list,
752  rettype,
753  rettupdesc,
754  false,
755  &resulttlist);
756 
757  /*
758  * Construct a JunkFilter we can use to coerce the returned rowtype to the
759  * desired form, unless the result type is VOID, in which case there's
760  * nothing to coerce to. (XXX Frequently, the JunkFilter isn't doing
761  * anything very interesting, but much of this module expects it to be
762  * there anyway.)
763  */
764  if (rettype != VOIDOID)
765  {
768 
769  /*
770  * If the result is composite, *and* we are returning the whole tuple
771  * result, we need to insert nulls for any dropped columns. In the
772  * single-column-result case, there might be dropped columns within
773  * the composite column value, but it's not our problem here. There
774  * should be no resjunk entries in resulttlist, so in the second case
775  * the JunkFilter is certainly a no-op.
776  */
777  if (rettupdesc && fcache->returnsTuple)
778  fcache->junkFilter = ExecInitJunkFilterConversion(resulttlist,
779  rettupdesc,
780  slot);
781  else
782  fcache->junkFilter = ExecInitJunkFilter(resulttlist, slot);
783  }
784 
785  if (fcache->returnsTuple)
786  {
787  /* Make sure output rowtype is properly blessed */
789  }
790  else if (fcache->returnsSet && type_is_rowtype(fcache->rettype))
791  {
792  /*
793  * Returning rowtype as if it were scalar --- materialize won't work.
794  * Right now it's sufficient to override any caller preference for
795  * materialize mode, but to add more smarts in init_execution_state
796  * about this, we'd probably need a three-way flag instead of bool.
797  */
798  lazyEvalOK = true;
799  }
800 
801  /* Finally, plan the queries */
802  fcache->func_state = init_execution_state(queryTree_list,
803  fcache,
804  lazyEvalOK);
805 
806  /* Mark fcache with time of creation to show it's valid */
807  fcache->lxid = MyProc->lxid;
809 
810  ReleaseSysCache(procedureTuple);
811 
812  MemoryContextSwitchTo(oldcontext);
813 }
#define TextDatumGetCString(d)
Definition: builtins.h:86
#define NameStr(name)
Definition: c.h:682
JunkFilter * ExecInitJunkFilter(List *targetList, TupleTableSlot *slot)
Definition: execJunk.c:60
JunkFilter * ExecInitJunkFilterConversion(List *targetList, TupleDesc cleanTupType, TupleTableSlot *slot)
Definition: execJunk.c:137
TupleDesc BlessTupleDesc(TupleDesc tupdesc)
Definition: execTuples.c:2071
const TupleTableSlotOps TTSOpsMinimalTuple
Definition: execTuples.c:85
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1238
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:276
bool check_sql_fn_retval(List *queryTreeLists, Oid rettype, TupleDesc rettupdesc, bool insertDroppedCols, List **resultTargetList)
Definition: functions.c:1612
static List * init_execution_state(List *queryTree_list, SQLFunctionCachePtr fcache, bool lazyEvalOK)
Definition: functions.c:464
void check_sql_fn_statements(List *queryTreeLists)
Definition: functions.c:1537
void sql_fn_parser_setup(struct ParseState *pstate, SQLFunctionParseInfoPtr pinfo)
Definition: functions.c:265
SQLFunctionParseInfoPtr prepare_sql_fn_parse_info(HeapTuple procedureTuple, Node *call_expr, Oid inputCollation)
Definition: functions.c:176
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:649
bool type_is_rowtype(Oid typid)
Definition: lsyscache.c:2613
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2209
char * pstrdup(const char *in)
Definition: mcxt.c:1483
void MemoryContextSetIdentifier(MemoryContext context, const char *id)
Definition: mcxt.c:494
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:153
#define castNode(_type_, nodeptr)
Definition: nodes.h:180
void(* ParserSetupHook)(struct ParseState *pstate, void *arg)
Definition: params.h:108
#define linitial_node(type, l)
Definition: pg_list.h:179
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:136
List * pg_parse_query(const char *query_string)
Definition: postgres.c:578
List * pg_analyze_and_rewrite_withcb(RawStmt *parsetree, const char *query_string, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
Definition: postgres.c:731
List * pg_rewrite_query(Query *query)
Definition: postgres.c:771
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:600
unsigned int Oid
Definition: postgres_ext.h:31
void * stringToNode(const char *str)
Definition: read.c:90
void AcquireRewriteLocks(Query *parsetree, bool forExecute, bool forUpdatePushedDown)
Definition: fmgr.h:57
void * fn_extra
Definition: fmgr.h:64
fmNodePtr fn_expr
Definition: fmgr.h:66
MemoryContext fn_mcxt
Definition: fmgr.h:65
Oid fn_oid
Definition: fmgr.h:59
FmgrInfo * flinfo
Definition: fmgr.h:87
SQLFunctionParseInfoPtr pinfo
Definition: functions.c:98
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:124
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1221
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1173
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1434
@ PROCOID
Definition: syscache.h:79
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:779

References AcquireRewriteLocks(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, BlessTupleDesc(), castNode, check_sql_fn_retval(), check_sql_fn_statements(), elog(), ERROR, ExecInitJunkFilter(), ExecInitJunkFilterConversion(), SQLFunctionCache::fcontext, FunctionCallInfoBaseData::flinfo, FmgrInfo::fn_expr, FmgrInfo::fn_extra, FmgrInfo::fn_mcxt, FmgrInfo::fn_oid, SQLFunctionCache::fname, SQLFunctionCache::func_state, get_call_result_type(), get_typlenbyval(), GetCurrentSubTransactionId(), GETSTRUCT, HeapTupleIsValid, init_execution_state(), IsA, JunkFilter::jf_resultSlot, SQLFunctionCache::junkFilter, lappend(), lfirst_node, linitial_node, list_make1, SQLFunctionCache::lxid, PGPROC::lxid, MakeSingleTupleTableSlot(), MemoryContextSetIdentifier(), MemoryContextSwitchTo(), MyProc, NameStr, NIL, ObjectIdGetDatum(), palloc0(), pg_analyze_and_rewrite_withcb(), pg_parse_query(), pg_rewrite_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, stringToNode(), SQLFunctionCache::subxid, SysCacheGetAttr(), TextDatumGetCString, TupleTableSlot::tts_tupleDescriptor, TTSOpsMinimalTuple, SQLFunctionCache::typbyval, type_is_rowtype(), and SQLFunctionCache::typlen.

Referenced by fmgr_sql().

◆ postquel_end()

static void postquel_end ( execution_state es)
static

Definition at line 914 of file functions.c.

915 {
916  /* mark status done to ensure we don't do ExecutorEnd twice */
917  es->status = F_EXEC_DONE;
918 
919  /* Utility commands don't need Executor. */
920  if (es->qd->operation != CMD_UTILITY)
921  {
922  ExecutorFinish(es->qd);
923  ExecutorEnd(es->qd);
924  }
925 
926  es->qd->dest->rDestroy(es->qd->dest);
927 
928  FreeQueryDesc(es->qd);
929  es->qd = NULL;
930 }
void ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:461
void ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:401
void FreeQueryDesc(QueryDesc *qdesc)
Definition: pquery.c:105
DestReceiver * dest
Definition: execdesc.h:41
CmdType operation
Definition: execdesc.h:36
void(* rDestroy)(DestReceiver *self)
Definition: dest.h:127

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

◆ postquel_get_single_result()

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

Definition at line 989 of file functions.c.

993 {
994  Datum value;
995  MemoryContext oldcontext;
996 
997  /*
998  * Set up to return the function value. For pass-by-reference datatypes,
999  * be sure to allocate the result in resultcontext, not the current memory
1000  * context (which has query lifespan). We can't leave the data in the
1001  * TupleTableSlot because we intend to clear the slot before returning.
1002  */
1003  oldcontext = MemoryContextSwitchTo(resultcontext);
1004 
1005  if (fcache->returnsTuple)
1006  {
1007  /* We must return the whole tuple as a Datum. */
1008  fcinfo->isnull = false;
1010  }
1011  else
1012  {
1013  /*
1014  * Returning a scalar, which we have to extract from the first column
1015  * of the SELECT result, and then copy into result context if needed.
1016  */
1017  value = slot_getattr(slot, 1, &(fcinfo->isnull));
1018 
1019  if (!fcinfo->isnull)
1020  value = datumCopy(value, fcache->typbyval, fcache->typlen);
1021  }
1022 
1023  MemoryContextSwitchTo(oldcontext);
1024 
1025  return value;
1026 }
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:132
Datum ExecFetchSlotHeapTupleDatum(TupleTableSlot *slot)
Definition: execTuples.c:1723
static struct @143 value
static Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:389

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

Referenced by fmgr_sql().

◆ postquel_getnext()

static bool postquel_getnext ( execution_state es,
SQLFunctionCachePtr  fcache 
)
static

Definition at line 879 of file functions.c.

880 {
881  bool result;
882 
883  if (es->qd->operation == CMD_UTILITY)
884  {
886  fcache->src,
887  true, /* protect function cache's parsetree */
889  es->qd->params,
890  es->qd->queryEnv,
891  es->qd->dest,
892  NULL);
893  result = true; /* never stops early */
894  }
895  else
896  {
897  /* Run regular commands to completion unless lazyEval */
898  uint64 count = (es->lazyEval) ? 1 : 0;
899 
900  ExecutorRun(es->qd, ForwardScanDirection, count, !fcache->returnsSet || !es->lazyEval);
901 
902  /*
903  * If we requested run to completion OR there was no tuple returned,
904  * command must be complete.
905  */
906  result = (count == 0 || es->qd->estate->es_processed == 0);
907  }
908 
909  return result;
910 }
void ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
Definition: execMain.c:300
@ ForwardScanDirection
Definition: sdir.h:26
uint64 es_processed
Definition: execnodes.h:654
ParamListInfo params
Definition: execdesc.h:42
EState * estate
Definition: execdesc.h:48
PlannedStmt * plannedstmt
Definition: execdesc.h:37
QueryEnvironment * queryEnv
Definition: execdesc.h:43
void ProcessUtility(PlannedStmt *pstmt, const char *queryString, bool readOnlyTree, ProcessUtilityContext context, ParamListInfo params, QueryEnvironment *queryEnv, DestReceiver *dest, QueryCompletion *qc)
Definition: utility.c:506
@ PROCESS_UTILITY_QUERY
Definition: utility.h:23

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

◆ postquel_start()

static void postquel_start ( execution_state es,
SQLFunctionCachePtr  fcache 
)
static

Definition at line 817 of file functions.c.

818 {
820 
821  Assert(es->qd == NULL);
822 
823  /* Caller should have ensured a suitable snapshot is active */
825 
826  /*
827  * If this query produces the function result, send its output to the
828  * tuplestore; else discard any output.
829  */
830  if (es->setsResult)
831  {
832  DR_sqlfunction *myState;
833 
835  /* pass down the needed info to the dest receiver routines */
836  myState = (DR_sqlfunction *) dest;
837  Assert(myState->pub.mydest == DestSQLFunction);
838  myState->tstore = fcache->tstore;
839  myState->cxt = CurrentMemoryContext;
840  myState->filter = fcache->junkFilter;
841  }
842  else
844 
845  es->qd = CreateQueryDesc(es->stmt,
846  fcache->src,
849  dest,
850  fcache->paramLI,
851  es->qd ? es->qd->queryEnv : NULL,
852  0);
853 
854  /* Utility commands don't need Executor. */
855  if (es->qd->operation != CMD_UTILITY)
856  {
857  /*
858  * In lazyEval mode, do not let the executor set up an AfterTrigger
859  * context. This is necessary not just an optimization, because we
860  * mustn't exit from the function execution with a stacked
861  * AfterTrigger level still active. We are careful not to select
862  * lazyEval mode for any statement that could possibly queue triggers.
863  */
864  int eflags;
865 
866  if (es->lazyEval)
867  eflags = EXEC_FLAG_SKIP_TRIGGERS;
868  else
869  eflags = 0; /* default run-to-completion flags */
870  ExecutorStart(es->qd, eflags);
871  }
872 
873  es->status = F_EXEC_RUN;
874 }
DestReceiver * None_Receiver
Definition: dest.c:96
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:113
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:131
#define EXEC_FLAG_SKIP_TRIGGERS
Definition: executor.h:60
MemoryContext CurrentMemoryContext
Definition: mcxt.c:124
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
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:817
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:805
#define InvalidSnapshot
Definition: snapshot.h:123
JunkFilter * filter
Definition: functions.c:48
DestReceiver pub
Definition: functions.c:45
MemoryContext cxt
Definition: functions.c:47
Tuplestorestate * tstore
Definition: functions.c:46
ParamListInfo paramLI
Definition: functions.c:109
CommandDest mydest
Definition: dest.h:129

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

◆ postquel_sub_params()

static void postquel_sub_params ( SQLFunctionCachePtr  fcache,
FunctionCallInfo  fcinfo 
)
static

Definition at line 934 of file functions.c.

936 {
937  int nargs = fcinfo->nargs;
938 
939  if (nargs > 0)
940  {
941  ParamListInfo paramLI;
942  Oid *argtypes = fcache->pinfo->argtypes;
943 
944  if (fcache->paramLI == NULL)
945  {
946  paramLI = makeParamList(nargs);
947  fcache->paramLI = paramLI;
948  }
949  else
950  {
951  paramLI = fcache->paramLI;
952  Assert(paramLI->numParams == nargs);
953  }
954 
955  for (int i = 0; i < nargs; i++)
956  {
957  ParamExternData *prm = &paramLI->params[i];
958 
959  /*
960  * If an incoming parameter value is a R/W expanded datum, we
961  * force it to R/O. We'd be perfectly entitled to scribble on it,
962  * but the problem is that if the parameter is referenced more
963  * than once in the function, earlier references might mutate the
964  * value seen by later references, which won't do at all. We
965  * could do better if we could be sure of the number of Param
966  * nodes in the function's plans; but we might not have planned
967  * all the statements yet, nor do we have plan tree walker
968  * infrastructure. (Examining the parse trees is not good enough,
969  * because of possible function inlining during planning.)
970  */
971  prm->isnull = fcinfo->args[i].isnull;
972  prm->value = MakeExpandedObjectReadOnly(fcinfo->args[i].value,
973  prm->isnull,
974  get_typlen(argtypes[i]));
975  prm->pflags = 0;
976  prm->ptype = argtypes[i];
977  }
978  }
979  else
980  fcache->paramLI = NULL;
981 }
#define MakeExpandedObjectReadOnly(d, isnull, typlen)
int i
Definition: isn.c:73
int16 get_typlen(Oid typid)
Definition: lsyscache.c:2155
ParamListInfo makeParamList(int numParams)
Definition: params.c:44
NullableDatum args[FLEXIBLE_ARRAY_MEMBER]
Definition: fmgr.h:95
Datum value
Definition: postgres.h:423
bool isnull
Definition: params.h:93
uint16 pflags
Definition: params.h:94
Datum value
Definition: params.h:92
ParamExternData params[FLEXIBLE_ARRAY_MEMBER]
Definition: params.h:125

References FunctionCallInfoBaseData::args, SQLFunctionParseInfo::argtypes, Assert(), get_typlen(), i, ParamExternData::isnull, NullableDatum::isnull, MakeExpandedObjectReadOnly, makeParamList(), FunctionCallInfoBaseData::nargs, ParamListInfoData::numParams, SQLFunctionCache::paramLI, ParamListInfoData::params, ParamExternData::pflags, SQLFunctionCache::pinfo, ParamExternData::ptype, ParamExternData::value, and NullableDatum::value.

Referenced by fmgr_sql().

◆ prepare_sql_fn_parse_info()

SQLFunctionParseInfoPtr prepare_sql_fn_parse_info ( HeapTuple  procedureTuple,
Node call_expr,
Oid  inputCollation 
)

Definition at line 176 of file functions.c.

179 {
181  Form_pg_proc procedureStruct = (Form_pg_proc) GETSTRUCT(procedureTuple);
182  int nargs;
183 
185 
186  /* Function's name (only) can be used to qualify argument names */
187  pinfo->fname = pstrdup(NameStr(procedureStruct->proname));
188 
189  /* Save the function's input collation */
190  pinfo->collation = inputCollation;
191 
192  /*
193  * Copy input argument types from the pg_proc entry, then resolve any
194  * polymorphic types.
195  */
196  pinfo->nargs = nargs = procedureStruct->pronargs;
197  if (nargs > 0)
198  {
199  Oid *argOidVect;
200  int argnum;
201 
202  argOidVect = (Oid *) palloc(nargs * sizeof(Oid));
203  memcpy(argOidVect,
204  procedureStruct->proargtypes.values,
205  nargs * sizeof(Oid));
206 
207  for (argnum = 0; argnum < nargs; argnum++)
208  {
209  Oid argtype = argOidVect[argnum];
210 
211  if (IsPolymorphicType(argtype))
212  {
213  argtype = get_call_expr_argtype(call_expr, argnum);
214  if (argtype == InvalidOid)
215  ereport(ERROR,
216  (errcode(ERRCODE_DATATYPE_MISMATCH),
217  errmsg("could not determine actual type of argument declared %s",
218  format_type_be(argOidVect[argnum]))));
219  argOidVect[argnum] = argtype;
220  }
221  }
222 
223  pinfo->argtypes = argOidVect;
224  }
225 
226  /*
227  * Collect names of arguments, too, if any
228  */
229  if (nargs > 0)
230  {
231  Datum proargnames;
232  Datum proargmodes;
233  int n_arg_names;
234  bool isNull;
235 
236  proargnames = SysCacheGetAttr(PROCNAMEARGSNSP, procedureTuple,
237  Anum_pg_proc_proargnames,
238  &isNull);
239  if (isNull)
240  proargnames = PointerGetDatum(NULL); /* just to be sure */
241 
242  proargmodes = SysCacheGetAttr(PROCNAMEARGSNSP, procedureTuple,
243  Anum_pg_proc_proargmodes,
244  &isNull);
245  if (isNull)
246  proargmodes = PointerGetDatum(NULL); /* just to be sure */
247 
248  n_arg_names = get_func_input_arg_names(proargnames, proargmodes,
249  &pinfo->argnames);
250 
251  /* Paranoia: ignore the result if too few array entries */
252  if (n_arg_names < nargs)
253  pinfo->argnames = NULL;
254  }
255  else
256  pinfo->argnames = NULL;
257 
258  return pinfo;
259 }
Oid get_call_expr_argtype(Node *expr, int argnum)
Definition: fmgr.c:1805
int get_func_input_arg_names(Datum proargnames, Datum proargmodes, char ***arg_names)
Definition: funcapi.c:1514
SQLFunctionParseInfo * SQLFunctionParseInfoPtr
Definition: functions.h:35
@ PROCNAMEARGSNSP
Definition: syscache.h:78

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

◆ ShutdownSQLFunction()

static void ShutdownSQLFunction ( Datum  arg)
static

Definition at line 1491 of file functions.c.

1492 {
1494  execution_state *es;
1495  ListCell *lc;
1496 
1497  foreach(lc, fcache->func_state)
1498  {
1499  es = (execution_state *) lfirst(lc);
1500  while (es)
1501  {
1502  /* Shut down anything still running */
1503  if (es->status == F_EXEC_RUN)
1504  {
1505  /* Re-establish active snapshot for any called functions */
1506  if (!fcache->readonly_func)
1508 
1509  postquel_end(es);
1510 
1511  if (!fcache->readonly_func)
1513  }
1514 
1515  /* Reset states to START in case we're called again */
1516  es->status = F_EXEC_START;
1517  es = es->next;
1518  }
1519  }
1520 
1521  /* Release tuplestore if we have one */
1522  if (fcache->tstore)
1523  tuplestore_end(fcache->tstore);
1524  fcache->tstore = NULL;
1525 
1526  /* execUtils will deregister the callback... */
1527  fcache->shutdown_reg = false;
1528 }
void * arg
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:660
void tuplestore_end(Tuplestorestate *state)
Definition: tuplestore.c:453

References arg, 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().

◆ sql_exec_error_callback()

static void sql_exec_error_callback ( void *  arg)
static

Definition at line 1409 of file functions.c.

1410 {
1411  FmgrInfo *flinfo = (FmgrInfo *) arg;
1413  int syntaxerrposition;
1414 
1415  /*
1416  * We can do nothing useful if init_sql_fcache() didn't get as far as
1417  * saving the function name
1418  */
1419  if (fcache == NULL || fcache->fname == NULL)
1420  return;
1421 
1422  /*
1423  * If there is a syntax error position, convert to internal syntax error
1424  */
1425  syntaxerrposition = geterrposition();
1426  if (syntaxerrposition > 0 && fcache->src != NULL)
1427  {
1428  errposition(0);
1429  internalerrposition(syntaxerrposition);
1430  internalerrquery(fcache->src);
1431  }
1432 
1433  /*
1434  * Try to determine where in the function we failed. If there is a query
1435  * with non-null QueryDesc, finger it. (We check this rather than looking
1436  * for F_EXEC_RUN state, so that errors during ExecutorStart or
1437  * ExecutorEnd are blamed on the appropriate query; see postquel_start and
1438  * postquel_end.)
1439  */
1440  if (fcache->func_state)
1441  {
1442  execution_state *es;
1443  int query_num;
1444  ListCell *lc;
1445 
1446  es = NULL;
1447  query_num = 1;
1448  foreach(lc, fcache->func_state)
1449  {
1450  es = (execution_state *) lfirst(lc);
1451  while (es)
1452  {
1453  if (es->qd)
1454  {
1455  errcontext("SQL function \"%s\" statement %d",
1456  fcache->fname, query_num);
1457  break;
1458  }
1459  es = es->next;
1460  }
1461  if (es)
1462  break;
1463  query_num++;
1464  }
1465  if (es == NULL)
1466  {
1467  /*
1468  * couldn't identify a running query; might be function entry,
1469  * function exit, or between queries.
1470  */
1471  errcontext("SQL function \"%s\"", fcache->fname);
1472  }
1473  }
1474  else
1475  {
1476  /*
1477  * Assume we failed during init_sql_fcache(). (It's possible that the
1478  * function actually has an empty body, but in that case we may as
1479  * well report all errors as being "during startup".)
1480  */
1481  errcontext("SQL function \"%s\" during startup", fcache->fname);
1482  }
1483 }
int internalerrquery(const char *query)
Definition: elog.c:1318
int internalerrposition(int cursorpos)
Definition: elog.c:1298
int geterrposition(void)
Definition: elog.c:1414
int errposition(int cursorpos)
Definition: elog.c:1282
#define errcontext
Definition: elog.h:192

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

Referenced by fmgr_sql().

◆ sql_fn_make_param()

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

Definition at line 410 of file functions.c.

412 {
413  Param *param;
414 
415  param = makeNode(Param);
416  param->paramkind = PARAM_EXTERN;
417  param->paramid = paramno;
418  param->paramtype = pinfo->argtypes[paramno - 1];
419  param->paramtypmod = -1;
420  param->paramcollid = get_typcollation(param->paramtype);
421  param->location = location;
422 
423  /*
424  * If we have a function input collation, allow it to override the
425  * type-derived collation for parameter symbols. (XXX perhaps this should
426  * not happen if the type collation is not default?)
427  */
428  if (OidIsValid(pinfo->collation) && OidIsValid(param->paramcollid))
429  param->paramcollid = pinfo->collation;
430 
431  return (Node *) param;
432 }
#define OidIsValid(objectId)
Definition: c.h:711
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:3014
@ PARAM_EXTERN
Definition: primnodes.h:302
int32 paramtypmod
Definition: primnodes.h:314
int paramid
Definition: primnodes.h:312
Oid paramtype
Definition: primnodes.h:313
ParamKind paramkind
Definition: primnodes.h:311
int location
Definition: primnodes.h:316
Oid paramcollid
Definition: primnodes.h:315

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

◆ sql_fn_param_ref()

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

Definition at line 394 of file functions.c.

395 {
397  int paramno = pref->number;
398 
399  /* Check parameter number is valid */
400  if (paramno <= 0 || paramno > pinfo->nargs)
401  return NULL; /* unknown parameter number */
402 
403  return sql_fn_make_param(pinfo, paramno, pref->location);
404 }
static Node * sql_fn_make_param(SQLFunctionParseInfoPtr pinfo, int paramno, int location)
Definition: functions.c:410
int location
Definition: parsenodes.h:270
int number
Definition: parsenodes.h:269
void * p_ref_hook_state
Definition: parse_node.h:225

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

Referenced by sql_fn_parser_setup().

◆ sql_fn_parser_setup()

void sql_fn_parser_setup ( struct ParseState pstate,
SQLFunctionParseInfoPtr  pinfo 
)

Definition at line 265 of file functions.c.

266 {
267  pstate->p_pre_columnref_hook = NULL;
270  /* no need to use p_coerce_param_hook */
271  pstate->p_ref_hook_state = (void *) pinfo;
272 }
static Node * sql_fn_param_ref(ParseState *pstate, ParamRef *pref)
Definition: functions.c:394
static Node * sql_fn_post_column_ref(ParseState *pstate, ColumnRef *cref, Node *var)
Definition: functions.c:278
ParseParamRefHook p_paramref_hook
Definition: parse_node.h:223
PreParseColumnRefHook p_pre_columnref_hook
Definition: parse_node.h:221
PostParseColumnRefHook p_post_columnref_hook
Definition: parse_node.h:222

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(), inline_set_returning_function(), and interpret_AS_clause().

◆ sql_fn_post_column_ref()

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

Definition at line 278 of file functions.c.

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

References Assert(), ColumnRef::fields, SQLFunctionParseInfo::fname, if(), 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().

◆ sql_fn_resolve_param_name()

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

Definition at line 440 of file functions.c.

442 {
443  int i;
444 
445  if (pinfo->argnames == NULL)
446  return NULL;
447 
448  for (i = 0; i < pinfo->nargs; i++)
449  {
450  if (pinfo->argnames[i] && strcmp(pinfo->argnames[i], paramname) == 0)
451  return sql_fn_make_param(pinfo, i + 1, location);
452  }
453 
454  return NULL;
455 }

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

Referenced by sql_fn_post_column_ref().

◆ sqlfunction_destroy()

static void sqlfunction_destroy ( DestReceiver self)
static

Definition at line 2113 of file functions.c.

2114 {
2115  pfree(self);
2116 }
void pfree(void *pointer)
Definition: mcxt.c:1306

References pfree().

Referenced by CreateSQLFunctionDestReceiver().

◆ sqlfunction_receive()

static bool sqlfunction_receive ( TupleTableSlot slot,
DestReceiver self 
)
static

Definition at line 2087 of file functions.c.

2088 {
2089  DR_sqlfunction *myState = (DR_sqlfunction *) self;
2090 
2091  /* Filter tuple as needed */
2092  slot = ExecFilterJunk(myState->filter, slot);
2093 
2094  /* Store the filtered tuple into the tuplestore */
2095  tuplestore_puttupleslot(myState->tstore, slot);
2096 
2097  return true;
2098 }
TupleTableSlot * ExecFilterJunk(JunkFilter *junkfilter, TupleTableSlot *slot)
Definition: execJunk.c:247
void tuplestore_puttupleslot(Tuplestorestate *state, TupleTableSlot *slot)
Definition: tuplestore.c:708

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

Referenced by CreateSQLFunctionDestReceiver().

◆ sqlfunction_shutdown()

static void sqlfunction_shutdown ( DestReceiver self)
static

Definition at line 2104 of file functions.c.

2105 {
2106  /* no-op */
2107 }

Referenced by CreateSQLFunctionDestReceiver().

◆ sqlfunction_startup()

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

Definition at line 2078 of file functions.c.

2079 {
2080  /* no-op */
2081 }

Referenced by CreateSQLFunctionDestReceiver().