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

Go to the source code of this file.

Data Structures

struct  DR_sqlfunction
 
struct  execution_state
 
struct  SQLFunctionCache
 

Typedefs

typedef struct execution_state execution_state
 
typedef SQLFunctionCacheSQLFunctionCachePtr
 

Enumerations

enum  ExecStatus { F_EXEC_START, F_EXEC_RUN, F_EXEC_DONE }
 

Functions

static Nodesql_fn_param_ref (ParseState *pstate, ParamRef *pref)
 
static Nodesql_fn_post_column_ref (ParseState *pstate, ColumnRef *cref, Node *var)
 
static Nodesql_fn_make_param (SQLFunctionParseInfoPtr pinfo, int paramno, int location)
 
static Nodesql_fn_resolve_param_name (SQLFunctionParseInfoPtr pinfo, const char *paramname, int location)
 
static Listinit_execution_state (List *queryTree_list, SQLFunctionCachePtr fcache, bool lazyEvalOK)
 
static void init_sql_fcache (FunctionCallInfo fcinfo, Oid collation, bool lazyEvalOK)
 
static void postquel_start (execution_state *es, SQLFunctionCachePtr fcache)
 
static bool postquel_getnext (execution_state *es, SQLFunctionCachePtr fcache)
 
static void postquel_end (execution_state *es)
 
static void postquel_sub_params (SQLFunctionCachePtr fcache, FunctionCallInfo fcinfo)
 
static Datum postquel_get_single_result (TupleTableSlot *slot, FunctionCallInfo fcinfo, SQLFunctionCachePtr fcache, MemoryContext resultcontext)
 
static void sql_exec_error_callback (void *arg)
 
static void ShutdownSQLFunction (Datum arg)
 
static bool coerce_fn_result_column (TargetEntry *src_tle, Oid res_type, int32 res_typmod, bool tlist_is_modifiable, List **upper_tlist, bool *upper_tlist_nontrivial)
 
static void sqlfunction_startup (DestReceiver *self, int operation, TupleDesc typeinfo)
 
static bool sqlfunction_receive (TupleTableSlot *slot, DestReceiver *self)
 
static void sqlfunction_shutdown (DestReceiver *self)
 
static void sqlfunction_destroy (DestReceiver *self)
 
SQLFunctionParseInfoPtr prepare_sql_fn_parse_info (HeapTuple procedureTuple, Node *call_expr, Oid inputCollation)
 
void sql_fn_parser_setup (struct ParseState *pstate, SQLFunctionParseInfoPtr pinfo)
 
Datum fmgr_sql (PG_FUNCTION_ARGS)
 
void check_sql_fn_statements (List *queryTreeLists)
 
bool check_sql_fn_retval (List *queryTreeLists, Oid rettype, TupleDesc rettupdesc, bool insertDroppedCols, List **resultTargetList)
 
DestReceiverCreateSQLFunctionDestReceiver (void)
 

Typedef Documentation

◆ execution_state

◆ SQLFunctionCachePtr

Definition at line 130 of file functions.c.

Enumeration Type Documentation

◆ ExecStatus

enum ExecStatus
Enumerator
F_EXEC_START 
F_EXEC_RUN 
F_EXEC_DONE 

Definition at line 60 of file functions.c.

Function Documentation

◆ check_sql_fn_retval()

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

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

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

◆ check_sql_fn_statements()

void check_sql_fn_statements ( List queryTreeLists)

Definition at line 1524 of file functions.c.

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

Referenced by fmgr_sql_validator(), and init_sql_fcache().

1525 {
1526  ListCell *lc;
1527 
1528  /* We are given a list of sublists of Queries */
1529  foreach(lc, queryTreeLists)
1530  {
1531  List *sublist = lfirst_node(List, lc);
1532  ListCell *lc2;
1533 
1534  foreach(lc2, sublist)
1535  {
1536  Query *query = lfirst_node(Query, lc2);
1537 
1538  /*
1539  * Disallow calling procedures with output arguments. The current
1540  * implementation would just throw the output values away, unless
1541  * the statement is the last one. Per SQL standard, we should
1542  * assign the output values by name. By disallowing this here, we
1543  * preserve an opportunity for future improvement.
1544  */
1545  if (query->commandType == CMD_UTILITY &&
1546  IsA(query->utilityStmt, CallStmt))
1547  {
1548  CallStmt *stmt = (CallStmt *) query->utilityStmt;
1549 
1550  if (stmt->outargs != NIL)
1551  ereport(ERROR,
1552  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1553  errmsg("calling procedures with output arguments is not supported in SQL functions")));
1554  }
1555  }
1556  }
1557 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:587
int errcode(int sqlerrcode)
Definition: elog.c:698
Node * utilityStmt
Definition: parsenodes.h:128
#define ERROR
Definition: elog.h:46
#define lfirst_node(type, lc)
Definition: pg_list.h:172
List * outargs
Definition: parsenodes.h:3039
#define ereport(elevel,...)
Definition: elog.h:157
CmdType commandType
Definition: parsenodes.h:120
int errmsg(const char *fmt,...)
Definition: elog.c:909
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 1980 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().

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

◆ CreateSQLFunctionDestReceiver()

DestReceiver* CreateSQLFunctionDestReceiver ( void  )

Definition at line 2046 of file functions.c.

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

Referenced by CreateDestReceiver().

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

◆ fmgr_sql()

Datum fmgr_sql ( PG_FUNCTION_ARGS  )

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

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

◆ init_execution_state()

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

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

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

◆ init_sql_fcache()

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

Definition at line 584 of file functions.c.

References AcquireRewriteLocks(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, BlessTupleDesc(), castNode, check_sql_fn_retval(), check_sql_fn_statements(), elog, ERROR, ExecInitJunkFilter(), ExecInitJunkFilterConversion(), SQLFunctionCache::fcontext, FunctionCallInfoBaseData::flinfo, FmgrInfo::fn_expr, FmgrInfo::fn_extra, FmgrInfo::fn_mcxt, FmgrInfo::fn_oid, SQLFunctionCache::fname, SQLFunctionCache::func_state, get_call_result_type(), get_typlenbyval(), GetCurrentSubTransactionId(), GETSTRUCT, HeapTupleIsValid, init_execution_state(), IsA, JunkFilter::jf_resultSlot, SQLFunctionCache::junkFilter, lappend(), lfirst_node, linitial_node, list_make1, SQLFunctionCache::lxid, PGPROC::lxid, MakeSingleTupleTableSlot(), MemoryContextSetIdentifier(), MemoryContextSwitchTo(), MyProc, NameStr, NIL, ObjectIdGetDatum, palloc0(), pg_analyze_and_rewrite_params(), pg_parse_query(), pg_rewrite_query(), SQLFunctionCache::pinfo, prepare_sql_fn_parse_info(), PROCOID, pstrdup(), SQLFunctionCache::readonly_func, ReleaseSysCache(), SQLFunctionCache::rettype, SQLFunctionCache::returnsSet, SQLFunctionCache::returnsTuple, SearchSysCache1(), sql_fn_parser_setup(), SQLFunctionCache::src, stringToNode(), SQLFunctionCache::subxid, SysCacheGetAttr(), TextDatumGetCString, TupleTableSlot::tts_tupleDescriptor, TTSOpsMinimalTuple, SQLFunctionCache::typbyval, type_is_rowtype(), and SQLFunctionCache::typlen.

Referenced by fmgr_sql().

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

◆ postquel_end()

static void postquel_end ( execution_state es)
static

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

917 {
918  /* mark status done to ensure we don't do ExecutorEnd twice */
919  es->status = F_EXEC_DONE;
920 
921  /* Utility commands don't need Executor. */
922  if (es->qd->operation != CMD_UTILITY)
923  {
924  ExecutorFinish(es->qd);
925  ExecutorEnd(es->qd);
926  }
927 
928  es->qd->dest->rDestroy(es->qd->dest);
929 
930  FreeQueryDesc(es->qd);
931  es->qd = NULL;
932 }
void FreeQueryDesc(QueryDesc *qdesc)
Definition: pquery.c:105
ExecStatus status
Definition: functions.c:68
void ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:459
void ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:399
CmdType operation
Definition: execdesc.h:36
QueryDesc * qd
Definition: functions.c:72
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 976 of file functions.c.

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

Referenced by fmgr_sql().

980 {
981  Datum value;
982  MemoryContext oldcontext;
983 
984  /*
985  * Set up to return the function value. For pass-by-reference datatypes,
986  * be sure to allocate the result in resultcontext, not the current memory
987  * context (which has query lifespan). We can't leave the data in the
988  * TupleTableSlot because we intend to clear the slot before returning.
989  */
990  oldcontext = MemoryContextSwitchTo(resultcontext);
991 
992  if (fcache->returnsTuple)
993  {
994  /* We must return the whole tuple as a Datum. */
995  fcinfo->isnull = false;
996  value = ExecFetchSlotHeapTupleDatum(slot);
997  }
998  else
999  {
1000  /*
1001  * Returning a scalar, which we have to extract from the first column
1002  * of the SELECT result, and then copy into result context if needed.
1003  */
1004  value = slot_getattr(slot, 1, &(fcinfo->isnull));
1005 
1006  if (!fcinfo->isnull)
1007  value = datumCopy(value, fcache->typbyval, fcache->typlen);
1008  }
1009 
1010  MemoryContextSwitchTo(oldcontext);
1011 
1012  return value;
1013 }
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:411
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:1723

◆ postquel_getnext()

static bool postquel_getnext ( execution_state es,
SQLFunctionCachePtr  fcache 
)
static

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

882 {
883  bool result;
884 
885  if (es->qd->operation == CMD_UTILITY)
886  {
888  fcache->src,
889  false,
891  es->qd->params,
892  es->qd->queryEnv,
893  es->qd->dest,
894  NULL);
895  result = true; /* never stops early */
896  }
897  else
898  {
899  /* Run regular commands to completion unless lazyEval */
900  uint64 count = (es->lazyEval) ? 1 : 0;
901 
902  ExecutorRun(es->qd, ForwardScanDirection, count, !fcache->returnsSet || !es->lazyEval);
903 
904  /*
905  * If we requested run to completion OR there was no tuple returned,
906  * command must be complete.
907  */
908  result = (count == 0 || es->qd->estate->es_processed == 0);
909  }
910 
911  return result;
912 }
EState * estate
Definition: execdesc.h:48
QueryEnvironment * queryEnv
Definition: execdesc.h:43
void ProcessUtility(PlannedStmt *pstmt, const char *queryString, bool readOnlyTree, ProcessUtilityContext context, ParamListInfo params, QueryEnvironment *queryEnv, DestReceiver *dest, QueryCompletion *qc)
Definition: utility.c:503
void ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
Definition: execMain.c:298
ParamListInfo params
Definition: execdesc.h:42
CmdType operation
Definition: execdesc.h:36
QueryDesc * qd
Definition: functions.c:72
uint64 es_processed
Definition: execnodes.h:604
DestReceiver * dest
Definition: execdesc.h:41
PlannedStmt * plannedstmt
Definition: execdesc.h:37

◆ postquel_start()

static void postquel_start ( execution_state es,
SQLFunctionCachePtr  fcache 
)
static

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

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

◆ postquel_sub_params()

static void postquel_sub_params ( SQLFunctionCachePtr  fcache,
FunctionCallInfo  fcinfo 
)
static

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

938 {
939  int nargs = fcinfo->nargs;
940 
941  if (nargs > 0)
942  {
943  ParamListInfo paramLI;
944 
945  if (fcache->paramLI == NULL)
946  {
947  paramLI = makeParamList(nargs);
948  fcache->paramLI = paramLI;
949  }
950  else
951  {
952  paramLI = fcache->paramLI;
953  Assert(paramLI->numParams == nargs);
954  }
955 
956  for (int i = 0; i < nargs; i++)
957  {
958  ParamExternData *prm = &paramLI->params[i];
959 
960  prm->value = fcinfo->args[i].value;
961  prm->isnull = fcinfo->args[i].isnull;
962  prm->pflags = 0;
963  prm->ptype = fcache->pinfo->argtypes[i];
964  }
965  }
966  else
967  fcache->paramLI = NULL;
968 }
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:422
SQLFunctionParseInfoPtr pinfo
Definition: functions.c:98
#define Assert(condition)
Definition: c.h:804
ParamListInfo paramLI
Definition: functions.c:109
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 176 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().

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

◆ ShutdownSQLFunction()

static void ShutdownSQLFunction ( Datum  arg)
static

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

1479 {
1481  execution_state *es;
1482  ListCell *lc;
1483 
1484  foreach(lc, fcache->func_state)
1485  {
1486  es = (execution_state *) lfirst(lc);
1487  while (es)
1488  {
1489  /* Shut down anything still running */
1490  if (es->status == F_EXEC_RUN)
1491  {
1492  /* Re-establish active snapshot for any called functions */
1493  if (!fcache->readonly_func)
1495 
1496  postquel_end(es);
1497 
1498  if (!fcache->readonly_func)
1500  }
1501 
1502  /* Reset states to START in case we're called again */
1503  es->status = F_EXEC_START;
1504  es = es->next;
1505  }
1506  }
1507 
1508  /* Release tuplestore if we have one */
1509  if (fcache->tstore)
1510  tuplestore_end(fcache->tstore);
1511  fcache->tstore = NULL;
1512 
1513  /* execUtils will deregister the callback... */
1514  fcache->shutdown_reg = false;
1515 }
ExecStatus status
Definition: functions.c:68
void PopActiveSnapshot(void)
Definition: snapmgr.c:774
Tuplestorestate * tstore
Definition: functions.c:111
Snapshot snapshot
Definition: execdesc.h:39
static void postquel_end(execution_state *es)
Definition: functions.c:916
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:680
List * func_state
Definition: functions.c:121
QueryDesc * qd
Definition: functions.c:72
#define lfirst(lc)
Definition: pg_list.h:169
void tuplestore_end(Tuplestorestate *state)
Definition: tuplestore.c:453
#define DatumGetPointer(X)
Definition: postgres.h:593
SQLFunctionCache * SQLFunctionCachePtr
Definition: functions.c:130
void * arg
struct execution_state * next
Definition: functions.c:67

◆ sql_exec_error_callback()

static void sql_exec_error_callback ( void *  arg)
static

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

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

◆ sql_fn_make_param()

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

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

414 {
415  Param *param;
416 
417  param = makeNode(Param);
418  param->paramkind = PARAM_EXTERN;
419  param->paramid = paramno;
420  param->paramtype = pinfo->argtypes[paramno - 1];
421  param->paramtypmod = -1;
422  param->paramcollid = get_typcollation(param->paramtype);
423  param->location = location;
424 
425  /*
426  * If we have a function input collation, allow it to override the
427  * type-derived collation for parameter symbols. (XXX perhaps this should
428  * not happen if the type collation is not default?)
429  */
430  if (OidIsValid(pinfo->collation) && OidIsValid(param->paramcollid))
431  param->paramcollid = pinfo->collation;
432 
433  return (Node *) param;
434 }
ParamKind paramkind
Definition: primnodes.h:267
Definition: nodes.h:536
#define OidIsValid(objectId)
Definition: c.h:710
Oid paramcollid
Definition: primnodes.h:271
int location
Definition: primnodes.h:272
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:3003
int32 paramtypmod
Definition: primnodes.h:270
#define makeNode(_type_)
Definition: nodes.h:584
int paramid
Definition: primnodes.h:268
Oid paramtype
Definition: primnodes.h:269

◆ sql_fn_param_ref()

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

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

397 {
399  int paramno = pref->number;
400 
401  /* Check parameter number is valid */
402  if (paramno <= 0 || paramno > pinfo->nargs)
403  return NULL; /* unknown parameter number */
404 
405  return sql_fn_make_param(pinfo, paramno, pref->location);
406 }
int number
Definition: parsenodes.h:257
int location
Definition: parsenodes.h:258
void * p_ref_hook_state
Definition: parse_node.h:224
SQLFunctionParseInfo * SQLFunctionParseInfoPtr
Definition: functions.h:35
static Node * sql_fn_make_param(SQLFunctionParseInfoPtr pinfo, int paramno, int location)
Definition: functions.c:412

◆ sql_fn_parser_setup()

void sql_fn_parser_setup ( struct ParseState pstate,
SQLFunctionParseInfoPtr  pinfo 
)

Definition at line 265 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(), inline_set_returning_function(), and interpret_AS_clause().

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

◆ sql_fn_post_column_ref()

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

Definition at line 278 of file functions.c.

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

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

◆ sql_fn_resolve_param_name()

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

Definition at line 442 of file functions.c.

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

Referenced by sql_fn_post_column_ref().

444 {
445  int i;
446 
447  if (pinfo->argnames == NULL)
448  return NULL;
449 
450  for (i = 0; i < pinfo->nargs; i++)
451  {
452  if (pinfo->argnames[i] && strcmp(pinfo->argnames[i], paramname) == 0)
453  return sql_fn_make_param(pinfo, i + 1, location);
454  }
455 
456  return NULL;
457 }
int i
static Node * sql_fn_make_param(SQLFunctionParseInfoPtr pinfo, int paramno, int location)
Definition: functions.c:412

◆ sqlfunction_destroy()

static void sqlfunction_destroy ( DestReceiver self)
static

Definition at line 2100 of file functions.c.

References pfree().

Referenced by CreateSQLFunctionDestReceiver().

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

◆ sqlfunction_receive()

static bool sqlfunction_receive ( TupleTableSlot slot,
DestReceiver self 
)
static

Definition at line 2074 of file functions.c.

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

Referenced by CreateSQLFunctionDestReceiver().

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

◆ sqlfunction_shutdown()

static void sqlfunction_shutdown ( DestReceiver self)
static

Definition at line 2091 of file functions.c.

Referenced by CreateSQLFunctionDestReceiver().

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

◆ sqlfunction_startup()

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

Definition at line 2065 of file functions.c.

Referenced by CreateSQLFunctionDestReceiver().

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