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 "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 (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 129 of file functions.c.

◆ SQLFunctionParseInfo

Enumeration Type Documentation

◆ ExecStatus

enum ExecStatus
Enumerator
F_EXEC_START 
F_EXEC_RUN 
F_EXEC_DONE 

Definition at line 59 of file functions.c.

Function Documentation

◆ check_sql_fn_retval()

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

Definition at line 1601 of file functions.c.

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::returningList, Query::rtable, RTE_SUBQUERY, RangeTblEntry::rtekind, RangeTblRef::rtindex, Query::setOperations, RangeTblEntry::subquery, Query::targetList, and TupleDescAttr.

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

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

◆ check_sql_fn_statements()

void check_sql_fn_statements ( List queryTreeLists)

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

1508 {
1509  ListCell *lc;
1510 
1511  /* We are given a list of sublists of Queries */
1512  foreach(lc, queryTreeLists)
1513  {
1514  List *sublist = lfirst_node(List, lc);
1515  ListCell *lc2;
1516 
1517  foreach(lc2, sublist)
1518  {
1519  Query *query = lfirst_node(Query, lc2);
1520 
1521  /*
1522  * Disallow procedures with output arguments. The current
1523  * implementation would just throw the output values away, unless
1524  * the statement is the last one. Per SQL standard, we should
1525  * assign the output values by name. By disallowing this here, we
1526  * preserve an opportunity for future improvement.
1527  */
1528  if (query->commandType == CMD_UTILITY &&
1529  IsA(query->utilityStmt, CallStmt))
1530  {
1531  CallStmt *stmt = castNode(CallStmt, query->utilityStmt);
1532  HeapTuple tuple;
1533  int numargs;
1534  Oid *argtypes;
1535  char **argnames;
1536  char *argmodes;
1537  int i;
1538 
1539  tuple = SearchSysCache1(PROCOID,
1540  ObjectIdGetDatum(stmt->funcexpr->funcid));
1541  if (!HeapTupleIsValid(tuple))
1542  elog(ERROR, "cache lookup failed for function %u",
1543  stmt->funcexpr->funcid);
1544  numargs = get_func_arg_info(tuple,
1545  &argtypes, &argnames, &argmodes);
1546  ReleaseSysCache(tuple);
1547 
1548  for (i = 0; i < numargs; i++)
1549  {
1550  if (argmodes && (argmodes[i] == PROARGMODE_INOUT ||
1551  argmodes[i] == PROARGMODE_OUT))
1552  ereport(ERROR,
1553  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1554  errmsg("calling procedures with output arguments is not supported in SQL functions")));
1555  }
1556  }
1557  }
1558  }
1559 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
FuncExpr * funcexpr
Definition: parsenodes.h:2903
#define castNode(_type_, nodeptr)
Definition: nodes.h:597
int get_func_arg_info(HeapTuple procTup, Oid **p_argtypes, char ***p_argnames, char **p_argmodes)
Definition: funcapi.c:1094
int errcode(int sqlerrcode)
Definition: elog.c:610
unsigned int Oid
Definition: postgres_ext.h:31
Node * utilityStmt
Definition: parsenodes.h:120
Oid funcid
Definition: primnodes.h:469
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
#define lfirst_node(type, lc)
Definition: pg_list.h:172
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define ereport(elevel,...)
Definition: elog.h:144
CmdType commandType
Definition: parsenodes.h:112
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
int errmsg(const char *fmt,...)
Definition: elog.c:821
#define elog(elevel,...)
Definition: elog.h:214
int i
Definition: pg_list.h:50

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

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

Referenced by check_sql_fn_retval().

1987 {
1988  TargetEntry *new_tle;
1989  Expr *new_tle_expr;
1990  Node *cast_result;
1991 
1992  /*
1993  * If the TLE has a sortgroupref marking, don't change it, as it probably
1994  * is referenced by ORDER BY, DISTINCT, etc, and changing its type would
1995  * break query semantics. Otherwise, it's safe to modify in-place unless
1996  * the query as a whole has issues with that.
1997  */
1998  if (tlist_is_modifiable && src_tle->ressortgroupref == 0)
1999  {
2000  /* OK to modify src_tle in place, if necessary */
2001  cast_result = coerce_to_target_type(NULL,
2002  (Node *) src_tle->expr,
2003  exprType((Node *) src_tle->expr),
2004  res_type, res_typmod,
2007  -1);
2008  if (cast_result == NULL)
2009  return false;
2010  assign_expr_collations(NULL, cast_result);
2011  src_tle->expr = (Expr *) cast_result;
2012  /* Make a Var referencing the possibly-modified TLE */
2013  new_tle_expr = (Expr *) makeVarFromTargetEntry(1, src_tle);
2014  }
2015  else
2016  {
2017  /* Any casting must happen in the upper tlist */
2018  Var *var = makeVarFromTargetEntry(1, src_tle);
2019 
2020  cast_result = coerce_to_target_type(NULL,
2021  (Node *) var,
2022  var->vartype,
2023  res_type, res_typmod,
2026  -1);
2027  if (cast_result == NULL)
2028  return false;
2029  assign_expr_collations(NULL, cast_result);
2030  /* Did the coercion actually do anything? */
2031  if (cast_result != (Node *) var)
2032  *upper_tlist_nontrivial = true;
2033  new_tle_expr = (Expr *) cast_result;
2034  }
2035  new_tle = makeTargetEntry(new_tle_expr,
2036  list_length(*upper_tlist) + 1,
2037  src_tle->resname, false);
2038  *upper_tlist = lappend(*upper_tlist, new_tle);
2039  return true;
2040 }
Var * makeVarFromTargetEntry(Index varno, TargetEntry *tle)
Definition: makefuncs.c:103
Definition: nodes.h:528
char * resname
Definition: primnodes.h:1412
Definition: primnodes.h:181
void assign_expr_collations(ParseState *pstate, Node *expr)
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:77
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:238
List * lappend(List *list, void *datum)
Definition: list.c:321
Expr * expr
Definition: primnodes.h:1410
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
static int list_length(const List *l)
Definition: pg_list.h:149
Index ressortgroupref
Definition: primnodes.h:1413

◆ CreateSQLFunctionDestReceiver()

DestReceiver* CreateSQLFunctionDestReceiver ( void  )

Definition at line 2047 of file functions.c.

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

Referenced by CreateDestReceiver().

2048 {
2049  DR_sqlfunction *self = (DR_sqlfunction *) palloc0(sizeof(DR_sqlfunction));
2050 
2051  self->pub.receiveSlot = sqlfunction_receive;
2052  self->pub.rStartup = sqlfunction_startup;
2053  self->pub.rShutdown = sqlfunction_shutdown;
2054  self->pub.rDestroy = sqlfunction_destroy;
2055  self->pub.mydest = DestSQLFunction;
2056 
2057  /* private fields will be set by postquel_start */
2058 
2059  return (DestReceiver *) self;
2060 }
static void sqlfunction_destroy(DestReceiver *self)
Definition: functions.c:2101
static void sqlfunction_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: functions.c:2066
static bool sqlfunction_receive(TupleTableSlot *slot, DestReceiver *self)
Definition: functions.c:2075
void * palloc0(Size size)
Definition: mcxt.c:981
static void sqlfunction_shutdown(DestReceiver *self)
Definition: functions.c:2092

◆ fmgr_sql()

Datum fmgr_sql ( PG_FUNCTION_ARGS  )

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

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

◆ init_execution_state()

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

Definition at line 481 of file functions.c.

References PlannedStmt::canSetTag, Query::canSetTag, CMD_SELECT, CMD_UTILITY, CommandIsReadOnly(), PlannedStmt::commandType, Query::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, PlannedStmt::stmt_len, Query::stmt_len, PlannedStmt::stmt_location, Query::stmt_location, PlannedStmt::utilityStmt, and Query::utilityStmt.

Referenced by init_sql_fcache().

484 {
485  List *eslist = NIL;
486  execution_state *lasttages = NULL;
487  ListCell *lc1;
488 
489  foreach(lc1, queryTree_list)
490  {
491  List *qtlist = lfirst_node(List, lc1);
492  execution_state *firstes = NULL;
493  execution_state *preves = NULL;
494  ListCell *lc2;
495 
496  foreach(lc2, qtlist)
497  {
498  Query *queryTree = lfirst_node(Query, lc2);
499  PlannedStmt *stmt;
500  execution_state *newes;
501 
502  /* Plan the query if needed */
503  if (queryTree->commandType == CMD_UTILITY)
504  {
505  /* Utility commands require no planning. */
506  stmt = makeNode(PlannedStmt);
507  stmt->commandType = CMD_UTILITY;
508  stmt->canSetTag = queryTree->canSetTag;
509  stmt->utilityStmt = queryTree->utilityStmt;
510  stmt->stmt_location = queryTree->stmt_location;
511  stmt->stmt_len = queryTree->stmt_len;
512  }
513  else
514  stmt = pg_plan_query(queryTree,
515  fcache->src,
517  NULL);
518 
519  /*
520  * Precheck all commands for validity in a function. This should
521  * generally match the restrictions spi.c applies.
522  */
523  if (stmt->commandType == CMD_UTILITY)
524  {
525  if (IsA(stmt->utilityStmt, CopyStmt) &&
526  ((CopyStmt *) stmt->utilityStmt)->filename == NULL)
527  ereport(ERROR,
528  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
529  errmsg("cannot COPY to/from client in a SQL function")));
530 
531  if (IsA(stmt->utilityStmt, TransactionStmt))
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 SQL function",
536  CreateCommandName(stmt->utilityStmt))));
537  }
538 
539  if (fcache->readonly_func && !CommandIsReadOnly(stmt))
540  ereport(ERROR,
541  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
542  /* translator: %s is a SQL statement name */
543  errmsg("%s is not allowed in a non-volatile function",
544  CreateCommandName((Node *) stmt))));
545 
546  /* OK, build the execution_state for this query */
547  newes = (execution_state *) palloc(sizeof(execution_state));
548  if (preves)
549  preves->next = newes;
550  else
551  firstes = newes;
552 
553  newes->next = NULL;
554  newes->status = F_EXEC_START;
555  newes->setsResult = false; /* might change below */
556  newes->lazyEval = false; /* might change below */
557  newes->stmt = stmt;
558  newes->qd = NULL;
559 
560  if (queryTree->canSetTag)
561  lasttages = newes;
562 
563  preves = newes;
564  }
565 
566  eslist = lappend(eslist, firstes);
567  }
568 
569  /*
570  * Mark the last canSetTag query as delivering the function result; then,
571  * if it is a plain SELECT, mark it for lazy evaluation. If it's not a
572  * SELECT we must always run it to completion.
573  *
574  * Note: at some point we might add additional criteria for whether to use
575  * lazy eval. However, we should prefer to use it whenever the function
576  * doesn't return set, since fetching more than one row is useless in that
577  * case.
578  *
579  * Note: don't set setsResult if the function returns VOID, as evidenced
580  * by not having made a junkfilter. This ensures we'll throw away any
581  * output from the last statement in such a function.
582  */
583  if (lasttages && fcache->junkFilter)
584  {
585  lasttages->setsResult = true;
586  if (lazyEvalOK &&
587  lasttages->stmt->commandType == CMD_SELECT &&
588  !lasttages->stmt->hasModifyingCTE)
589  fcache->lazyEval = lasttages->lazyEval = true;
590  }
591 
592  return eslist;
593 }
#define NIL
Definition: pg_list.h:65
bool CommandIsReadOnly(PlannedStmt *pstmt)
Definition: utility.c:99
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
int stmt_location
Definition: parsenodes.h:181
static const char * CreateCommandName(Node *parsetree)
Definition: utility.h:99
Definition: nodes.h:528
ExecStatus status
Definition: functions.c:67
int errcode(int sqlerrcode)
Definition: elog.c:610
JunkFilter * junkFilter
Definition: functions.c:112
Node * utilityStmt
Definition: parsenodes.h:120
int stmt_len
Definition: plannodes.h:90
#define ERROR
Definition: elog.h:43
#define lfirst_node(type, lc)
Definition: pg_list.h:172
int stmt_location
Definition: plannodes.h:89
Node * utilityStmt
Definition: plannodes.h:86
List * lappend(List *list, void *datum)
Definition: list.c:321
bool canSetTag
Definition: plannodes.h:54
CmdType commandType
Definition: plannodes.h:46
QueryDesc * qd
Definition: functions.c:71
#define ereport(elevel,...)
Definition: elog.h:144
CmdType commandType
Definition: parsenodes.h:112
#define makeNode(_type_)
Definition: nodes.h:576
bool hasModifyingCTE
Definition: plannodes.h:52
bool canSetTag
Definition: parsenodes.h:118
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2717
void * palloc(Size size)
Definition: mcxt.c:950
int errmsg(const char *fmt,...)
Definition: elog.c:821
PlannedStmt * pg_plan_query(Query *querytree, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:857
struct execution_state * next
Definition: functions.c:66
PlannedStmt * stmt
Definition: functions.c:70
Definition: pg_list.h:50
int stmt_len
Definition: parsenodes.h:182

◆ init_sql_fcache()

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

Definition at line 599 of file functions.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, BlessTupleDesc(), 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(), JunkFilter::jf_resultSlot, SQLFunctionCache::junkFilter, lappend(), lfirst_node, SQLFunctionCache::lxid, PGPROC::lxid, MakeSingleTupleTableSlot(), 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, TTSOpsMinimalTuple, SQLFunctionCache::typbyval, type_is_rowtype(), and SQLFunctionCache::typlen.

Referenced by fmgr_sql().

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

◆ postquel_end()

static void postquel_end ( execution_state es)
static

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

900 {
901  /* mark status done to ensure we don't do ExecutorEnd twice */
902  es->status = F_EXEC_DONE;
903 
904  /* Utility commands don't need Executor. */
905  if (es->qd->operation != CMD_UTILITY)
906  {
907  ExecutorFinish(es->qd);
908  ExecutorEnd(es->qd);
909  }
910 
911  es->qd->dest->rDestroy(es->qd->dest);
912 
913  FreeQueryDesc(es->qd);
914  es->qd = NULL;
915 }
void FreeQueryDesc(QueryDesc *qdesc)
Definition: pquery.c:105
ExecStatus status
Definition: functions.c:67
void ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:462
void ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:402
CmdType operation
Definition: execdesc.h:36
QueryDesc * qd
Definition: functions.c:71
void(* rDestroy)(DestReceiver *self)
Definition: dest.h:127
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 959 of file functions.c.

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

Referenced by fmgr_sql().

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

◆ postquel_getnext()

static bool postquel_getnext ( execution_state es,
SQLFunctionCachePtr  fcache 
)
static

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

866 {
867  bool result;
868 
869  if (es->qd->operation == CMD_UTILITY)
870  {
872  fcache->src,
874  es->qd->params,
875  es->qd->queryEnv,
876  es->qd->dest,
877  NULL);
878  result = true; /* never stops early */
879  }
880  else
881  {
882  /* Run regular commands to completion unless lazyEval */
883  uint64 count = (es->lazyEval) ? 1 : 0;
884 
885  ExecutorRun(es->qd, ForwardScanDirection, count, !fcache->returnsSet || !es->lazyEval);
886 
887  /*
888  * If we requested run to completion OR there was no tuple returned,
889  * command must be complete.
890  */
891  result = (count == 0 || es->qd->estate->es_processed == 0);
892  }
893 
894  return result;
895 }
EState * estate
Definition: execdesc.h:48
QueryEnvironment * queryEnv
Definition: execdesc.h:43
void ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
Definition: execMain.c:301
ParamListInfo params
Definition: execdesc.h:42
CmdType operation
Definition: execdesc.h:36
QueryDesc * qd
Definition: functions.c:71
uint64 es_processed
Definition: execnodes.h:563
DestReceiver * dest
Definition: execdesc.h:41
PlannedStmt * plannedstmt
Definition: execdesc.h:37
void ProcessUtility(PlannedStmt *pstmt, const char *queryString, ProcessUtilityContext context, ParamListInfo params, QueryEnvironment *queryEnv, DestReceiver *dest, QueryCompletion *qc)
Definition: utility.c:501

◆ postquel_start()

static void postquel_start ( execution_state es,
SQLFunctionCachePtr  fcache 
)
static

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

804 {
806 
807  Assert(es->qd == NULL);
808 
809  /* Caller should have ensured a suitable snapshot is active */
811 
812  /*
813  * If this query produces the function result, send its output to the
814  * tuplestore; else discard any output.
815  */
816  if (es->setsResult)
817  {
818  DR_sqlfunction *myState;
819 
821  /* pass down the needed info to the dest receiver routines */
822  myState = (DR_sqlfunction *) dest;
823  Assert(myState->pub.mydest == DestSQLFunction);
824  myState->tstore = fcache->tstore;
825  myState->cxt = CurrentMemoryContext;
826  myState->filter = fcache->junkFilter;
827  }
828  else
829  dest = None_Receiver;
830 
831  es->qd = CreateQueryDesc(es->stmt,
832  fcache->src,
835  dest,
836  fcache->paramLI,
837  es->qd ? es->qd->queryEnv : NULL,
838  0);
839 
840  /* Utility commands don't need Executor. */
841  if (es->qd->operation != CMD_UTILITY)
842  {
843  /*
844  * In lazyEval mode, do not let the executor set up an AfterTrigger
845  * context. This is necessary not just an optimization, because we
846  * mustn't exit from the function execution with a stacked
847  * AfterTrigger level still active. We are careful not to select
848  * lazyEval mode for any statement that could possibly queue triggers.
849  */
850  int eflags;
851 
852  if (es->lazyEval)
853  eflags = EXEC_FLAG_SKIP_TRIGGERS;
854  else
855  eflags = 0; /* default run-to-completion flags */
856  ExecutorStart(es->qd, eflags);
857  }
858 
859  es->status = F_EXEC_RUN;
860 }
DestReceiver pub
Definition: functions.c:44
CommandDest mydest
Definition: dest.h:129
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:143
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:786
ExecStatus status
Definition: functions.c:67
JunkFilter * junkFilter
Definition: functions.c:112
Tuplestorestate * tstore
Definition: functions.c:110
DestReceiver * None_Receiver
Definition: dest.c:96
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:113
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:798
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
CmdType operation
Definition: execdesc.h:36
#define InvalidSnapshot
Definition: snapshot.h:123
QueryDesc * qd
Definition: functions.c:71
#define Assert(condition)
Definition: c.h:746
ParamListInfo paramLI
Definition: functions.c:108
MemoryContext cxt
Definition: functions.c:46
#define EXEC_FLAG_SKIP_TRIGGERS
Definition: executor.h:60
JunkFilter * filter
Definition: functions.c:47
PlannedStmt * stmt
Definition: functions.c:70
Tuplestorestate * tstore
Definition: functions.c:45

◆ postquel_sub_params()

static void postquel_sub_params ( SQLFunctionCachePtr  fcache,
FunctionCallInfo  fcinfo 
)
static

Definition at line 919 of file functions.c.

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

Referenced by fmgr_sql().

921 {
922  int nargs = fcinfo->nargs;
923 
924  if (nargs > 0)
925  {
926  ParamListInfo paramLI;
927 
928  if (fcache->paramLI == NULL)
929  {
930  paramLI = makeParamList(nargs);
931  fcache->paramLI = paramLI;
932  }
933  else
934  {
935  paramLI = fcache->paramLI;
936  Assert(paramLI->numParams == nargs);
937  }
938 
939  for (int i = 0; i < nargs; i++)
940  {
941  ParamExternData *prm = &paramLI->params[i];
942 
943  prm->value = fcinfo->args[i].value;
944  prm->isnull = fcinfo->args[i].isnull;
945  prm->pflags = 0;
946  prm->ptype = fcache->pinfo->argtypes[i];
947  }
948  }
949  else
950  fcache->paramLI = NULL;
951 }
ParamExternData params[FLEXIBLE_ARRAY_MEMBER]
Definition: params.h:125
Datum value
Definition: params.h:92
ParamListInfo makeParamList(int numParams)
Definition: params.c:44
NullableDatum args[FLEXIBLE_ARRAY_MEMBER]
Definition: fmgr.h:95
Datum value
Definition: postgres.h:378
SQLFunctionParseInfoPtr pinfo
Definition: functions.c:97
#define Assert(condition)
Definition: c.h:746
ParamListInfo paramLI
Definition: functions.c:108
uint16 pflags
Definition: params.h:94
int i
bool isnull
Definition: params.h:93

◆ prepare_sql_fn_parse_info()

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

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

193 {
195  Form_pg_proc procedureStruct = (Form_pg_proc) GETSTRUCT(procedureTuple);
196  int nargs;
197 
199 
200  /* Function's name (only) can be used to qualify argument names */
201  pinfo->fname = pstrdup(NameStr(procedureStruct->proname));
202 
203  /* Save the function's input collation */
204  pinfo->collation = inputCollation;
205 
206  /*
207  * Copy input argument types from the pg_proc entry, then resolve any
208  * polymorphic types.
209  */
210  pinfo->nargs = nargs = procedureStruct->pronargs;
211  if (nargs > 0)
212  {
213  Oid *argOidVect;
214  int argnum;
215 
216  argOidVect = (Oid *) palloc(nargs * sizeof(Oid));
217  memcpy(argOidVect,
218  procedureStruct->proargtypes.values,
219  nargs * sizeof(Oid));
220 
221  for (argnum = 0; argnum < nargs; argnum++)
222  {
223  Oid argtype = argOidVect[argnum];
224 
225  if (IsPolymorphicType(argtype))
226  {
227  argtype = get_call_expr_argtype(call_expr, argnum);
228  if (argtype == InvalidOid)
229  ereport(ERROR,
230  (errcode(ERRCODE_DATATYPE_MISMATCH),
231  errmsg("could not determine actual type of argument declared %s",
232  format_type_be(argOidVect[argnum]))));
233  argOidVect[argnum] = argtype;
234  }
235  }
236 
237  pinfo->argtypes = argOidVect;
238  }
239 
240  /*
241  * Collect names of arguments, too, if any
242  */
243  if (nargs > 0)
244  {
245  Datum proargnames;
246  Datum proargmodes;
247  int n_arg_names;
248  bool isNull;
249 
250  proargnames = SysCacheGetAttr(PROCNAMEARGSNSP, procedureTuple,
251  Anum_pg_proc_proargnames,
252  &isNull);
253  if (isNull)
254  proargnames = PointerGetDatum(NULL); /* just to be sure */
255 
256  proargmodes = SysCacheGetAttr(PROCNAMEARGSNSP, procedureTuple,
257  Anum_pg_proc_proargmodes,
258  &isNull);
259  if (isNull)
260  proargmodes = PointerGetDatum(NULL); /* just to be sure */
261 
262  n_arg_names = get_func_input_arg_names(procedureStruct->prokind,
263  proargnames, proargmodes,
264  &pinfo->argnames);
265 
266  /* Paranoia: ignore the result if too few array entries */
267  if (n_arg_names < nargs)
268  pinfo->argnames = NULL;
269  }
270  else
271  pinfo->argnames = NULL;
272 
273  return pinfo;
274 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define PointerGetDatum(X)
Definition: postgres.h:556
char * pstrdup(const char *in)
Definition: mcxt.c:1187
struct SQLFunctionParseInfo * SQLFunctionParseInfoPtr
Definition: functions.h:21
int errcode(int sqlerrcode)
Definition: elog.c:610
Oid get_call_expr_argtype(Node *expr, int argnum)
Definition: fmgr.c:1823
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
unsigned int Oid
Definition: postgres_ext.h:31
#define ERROR
Definition: elog.h:43
void * palloc0(Size size)
Definition: mcxt.c:981
uintptr_t Datum
Definition: postgres.h:367
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1377
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:133
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:144
void * palloc(Size size)
Definition: mcxt.c:950
int errmsg(const char *fmt,...)
Definition: elog.c:821
#define NameStr(name)
Definition: c.h:623
int get_func_input_arg_names(char prokind, Datum proargnames, Datum proargmodes, char ***arg_names)
Definition: funcapi.c:1236

◆ ShutdownSQLFunction()

static void ShutdownSQLFunction ( Datum  arg)
static

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

1462 {
1464  execution_state *es;
1465  ListCell *lc;
1466 
1467  foreach(lc, fcache->func_state)
1468  {
1469  es = (execution_state *) lfirst(lc);
1470  while (es)
1471  {
1472  /* Shut down anything still running */
1473  if (es->status == F_EXEC_RUN)
1474  {
1475  /* Re-establish active snapshot for any called functions */
1476  if (!fcache->readonly_func)
1478 
1479  postquel_end(es);
1480 
1481  if (!fcache->readonly_func)
1483  }
1484 
1485  /* Reset states to START in case we're called again */
1486  es->status = F_EXEC_START;
1487  es = es->next;
1488  }
1489  }
1490 
1491  /* Release tuplestore if we have one */
1492  if (fcache->tstore)
1493  tuplestore_end(fcache->tstore);
1494  fcache->tstore = NULL;
1495 
1496  /* execUtils will deregister the callback... */
1497  fcache->shutdown_reg = false;
1498 }
ExecStatus status
Definition: functions.c:67
void PopActiveSnapshot(void)
Definition: snapmgr.c:759
Tuplestorestate * tstore
Definition: functions.c:110
Snapshot snapshot
Definition: execdesc.h:39
static void postquel_end(execution_state *es)
Definition: functions.c:899
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:680
List * func_state
Definition: functions.c:120
QueryDesc * qd
Definition: functions.c:71
#define lfirst(lc)
Definition: pg_list.h:169
void tuplestore_end(Tuplestorestate *state)
Definition: tuplestore.c:453
#define DatumGetPointer(X)
Definition: postgres.h:549
SQLFunctionCache * SQLFunctionCachePtr
Definition: functions.c:129
void * arg
struct execution_state * next
Definition: functions.c:66

◆ sql_exec_error_callback()

static void sql_exec_error_callback ( void *  arg)
static

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

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

◆ sql_fn_make_param()

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

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

429 {
430  Param *param;
431 
432  param = makeNode(Param);
433  param->paramkind = PARAM_EXTERN;
434  param->paramid = paramno;
435  param->paramtype = pinfo->argtypes[paramno - 1];
436  param->paramtypmod = -1;
437  param->paramcollid = get_typcollation(param->paramtype);
438  param->location = location;
439 
440  /*
441  * If we have a function input collation, allow it to override the
442  * type-derived collation for parameter symbols. (XXX perhaps this should
443  * not happen if the type collation is not default?)
444  */
445  if (OidIsValid(pinfo->collation) && OidIsValid(param->paramcollid))
446  param->paramcollid = pinfo->collation;
447 
448  return (Node *) param;
449 }
ParamKind paramkind
Definition: primnodes.h:262
Definition: nodes.h:528
#define OidIsValid(objectId)
Definition: c.h:652
Oid paramcollid
Definition: primnodes.h:266
int location
Definition: primnodes.h:267
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:2933
int32 paramtypmod
Definition: primnodes.h:265
#define makeNode(_type_)
Definition: nodes.h:576
int paramid
Definition: primnodes.h:263
Oid paramtype
Definition: primnodes.h:264

◆ sql_fn_param_ref()

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

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

412 {
414  int paramno = pref->number;
415 
416  /* Check parameter number is valid */
417  if (paramno <= 0 || paramno > pinfo->nargs)
418  return NULL; /* unknown parameter number */
419 
420  return sql_fn_make_param(pinfo, paramno, pref->location);
421 }
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:222
static Node * sql_fn_make_param(SQLFunctionParseInfoPtr pinfo, int paramno, int location)
Definition: functions.c:427

◆ sql_fn_parser_setup()

void sql_fn_parser_setup ( struct ParseState pstate,
SQLFunctionParseInfoPtr  pinfo 
)

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

281 {
282  pstate->p_pre_columnref_hook = NULL;
285  /* no need to use p_coerce_param_hook */
286  pstate->p_ref_hook_state = (void *) pinfo;
287 }
PostParseColumnRefHook p_post_columnref_hook
Definition: parse_node.h:219
ParseParamRefHook p_paramref_hook
Definition: parse_node.h:220
static Node * sql_fn_post_column_ref(ParseState *pstate, ColumnRef *cref, Node *var)
Definition: functions.c:293
void * p_ref_hook_state
Definition: parse_node.h:222
static Node * sql_fn_param_ref(ParseState *pstate, ParamRef *pref)
Definition: functions.c:411
PreParseColumnRefHook p_pre_columnref_hook
Definition: parse_node.h:218

◆ sql_fn_post_column_ref()

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

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

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

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

Referenced by sql_fn_post_column_ref().

459 {
460  int i;
461 
462  if (pinfo->argnames == NULL)
463  return NULL;
464 
465  for (i = 0; i < pinfo->nargs; i++)
466  {
467  if (pinfo->argnames[i] && strcmp(pinfo->argnames[i], paramname) == 0)
468  return sql_fn_make_param(pinfo, i + 1, location);
469  }
470 
471  return NULL;
472 }
int i
static Node * sql_fn_make_param(SQLFunctionParseInfoPtr pinfo, int paramno, int location)
Definition: functions.c:427

◆ sqlfunction_destroy()

static void sqlfunction_destroy ( DestReceiver self)
static

Definition at line 2101 of file functions.c.

References pfree().

Referenced by CreateSQLFunctionDestReceiver().

2102 {
2103  pfree(self);
2104 }
void pfree(void *pointer)
Definition: mcxt.c:1057

◆ sqlfunction_receive()

static bool sqlfunction_receive ( TupleTableSlot slot,
DestReceiver self 
)
static

Definition at line 2075 of file functions.c.

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

Referenced by CreateSQLFunctionDestReceiver().

2076 {
2077  DR_sqlfunction *myState = (DR_sqlfunction *) self;
2078 
2079  /* Filter tuple as needed */
2080  slot = ExecFilterJunk(myState->filter, slot);
2081 
2082  /* Store the filtered tuple into the tuplestore */
2083  tuplestore_puttupleslot(myState->tstore, slot);
2084 
2085  return true;
2086 }
void tuplestore_puttupleslot(Tuplestorestate *state, TupleTableSlot *slot)
Definition: tuplestore.c:708
TupleTableSlot * ExecFilterJunk(JunkFilter *junkfilter, TupleTableSlot *slot)
Definition: execJunk.c:261
JunkFilter * filter
Definition: functions.c:47
Tuplestorestate * tstore
Definition: functions.c:45

◆ sqlfunction_shutdown()

static void sqlfunction_shutdown ( DestReceiver self)
static

Definition at line 2092 of file functions.c.

Referenced by CreateSQLFunctionDestReceiver().

2093 {
2094  /* no-op */
2095 }

◆ sqlfunction_startup()

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

Definition at line 2066 of file functions.c.

Referenced by CreateSQLFunctionDestReceiver().

2067 {
2068  /* no-op */
2069 }