PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
functions.h File Reference
#include "nodes/execnodes.h"
#include "tcop/dest.h"
Include dependency graph for functions.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  SQLFunctionParseInfo
 

Typedefs

typedef struct SQLFunctionParseInfo SQLFunctionParseInfo
 
typedef SQLFunctionParseInfoSQLFunctionParseInfoPtr
 

Functions

Datum fmgr_sql (PG_FUNCTION_ARGS)
 
SQLFunctionParseInfoPtr prepare_sql_fn_parse_info (HeapTuple procedureTuple, Node *call_expr, Oid inputCollation)
 
void sql_fn_parser_setup (struct ParseState *pstate, SQLFunctionParseInfoPtr pinfo)
 
void check_sql_fn_statements (List *queryTreeLists)
 
bool check_sql_fn_retval (List *queryTreeLists, Oid rettype, TupleDesc rettupdesc, char prokind, bool insertDroppedCols, List **resultTargetList)
 
DestReceiverCreateSQLFunctionDestReceiver (void)
 

Typedef Documentation

◆ SQLFunctionParseInfo

◆ SQLFunctionParseInfoPtr

Definition at line 35 of file functions.h.

Function Documentation

◆ check_sql_fn_retval()

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

Definition at line 1609 of file functions.c.

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

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

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

◆ check_sql_fn_statements()

void check_sql_fn_statements ( List queryTreeLists)

Definition at line 1534 of file functions.c.

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

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

Referenced by fmgr_sql_validator(), and init_sql_fcache().

◆ CreateSQLFunctionDestReceiver()

DestReceiver * CreateSQLFunctionDestReceiver ( void  )

Definition at line 2069 of file functions.c.

2070{
2072
2077 self->pub.mydest = DestSQLFunction;
2078
2079 /* private fields will be set by postquel_start */
2080
2081 return (DestReceiver *) self;
2082}
@ DestSQLFunction
Definition: dest.h:96
static void sqlfunction_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: functions.c:2088
static bool sqlfunction_receive(TupleTableSlot *slot, DestReceiver *self)
Definition: functions.c:2097
static void sqlfunction_destroy(DestReceiver *self)
Definition: functions.c:2123
static void sqlfunction_shutdown(DestReceiver *self)
Definition: functions.c:2114
void * palloc0(Size size)
Definition: mcxt.c:1347
DestReceiver pub
Definition: functions.c:45
void(* rStartup)(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: dest.h:121
void(* rShutdown)(DestReceiver *self)
Definition: dest.h:124
bool(* receiveSlot)(TupleTableSlot *slot, DestReceiver *self)
Definition: dest.h:118
void(* rDestroy)(DestReceiver *self)
Definition: dest.h:126
CommandDest mydest
Definition: dest.h:128

References DestSQLFunction, _DestReceiver::mydest, palloc0(), DR_sqlfunction::pub, _DestReceiver::rDestroy, _DestReceiver::receiveSlot, _DestReceiver::rShutdown, _DestReceiver::rStartup, sqlfunction_destroy(), sqlfunction_receive(), sqlfunction_shutdown(), and sqlfunction_startup().

Referenced by CreateDestReceiver().

◆ fmgr_sql()

Datum fmgr_sql ( PG_FUNCTION_ARGS  )

Definition at line 1029 of file functions.c.

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

References ReturnSetInfo::allowedModes, ErrorContextCallback::arg, Assert, ErrorContextCallback::callback, CommandCounterIncrement(), CreateTupleDescCopy(), ReturnSetInfo::econtext, elog, ereport, errcode(), errmsg(), ERROR, error_context_stack, ExprEndResult, ExprMultipleResult, F_EXEC_DONE, F_EXEC_START, SQLFunctionCache::fcontext, SQLFunctionCache::func_state, GetTransactionSnapshot(), if(), init_sql_fcache(), IsA, ReturnSetInfo::isDone, JunkFilter::jf_cleanTupType, JunkFilter::jf_resultSlot, SQLFunctionCache::junkFilter, execution_state::lazyEval, SQLFunctionCache::lazyEval, lfirst, lnext(), SQLFunctionCache::lxid, PGPROC::lxid, MemoryContextDelete(), MemoryContextSwitchTo(), MyProc, execution_state::next, PG_GET_COLLATION, PointerGetDatum(), PopActiveSnapshot(), postquel_end(), postquel_get_single_result(), postquel_getnext(), postquel_start(), postquel_sub_params(), ErrorContextCallback::previous, PushActiveSnapshot(), execution_state::qd, SQLFunctionCache::readonly_func, RegisterExprContextCallback(), SQLFunctionCache::rettype, ReturnSetInfo::returnMode, SQLFunctionCache::returnsSet, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, SFRM_Materialize, SFRM_Materialize_Preferred, SFRM_Materialize_Random, SFRM_ValuePerCall, SQLFunctionCache::shutdown_reg, ShutdownSQLFunction(), QueryDesc::snapshot, sql_exec_error_callback(), execution_state::status, SubTransactionIsActive(), SQLFunctionCache::subxid, SQLFunctionCache::tstore, tuplestore_begin_heap(), tuplestore_clear(), tuplestore_gettupleslot(), UnregisterExprContextCallback(), UpdateActiveSnapshotCommandId(), PGPROC::vxid, and work_mem.

Referenced by fmgr_info_cxt_security().

◆ prepare_sql_fn_parse_info()

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

Definition at line 176 of file functions.c.

179{
181 Form_pg_proc procedureStruct = (Form_pg_proc) GETSTRUCT(procedureTuple);
182 int nargs;
183
185
186 /* Function's name (only) can be used to qualify argument names */
187 pinfo->fname = pstrdup(NameStr(procedureStruct->proname));
188
189 /* Save the function's input collation */
190 pinfo->collation = inputCollation;
191
192 /*
193 * Copy input argument types from the pg_proc entry, then resolve any
194 * polymorphic types.
195 */
196 pinfo->nargs = nargs = procedureStruct->pronargs;
197 if (nargs > 0)
198 {
199 Oid *argOidVect;
200 int argnum;
201
202 argOidVect = (Oid *) palloc(nargs * sizeof(Oid));
203 memcpy(argOidVect,
204 procedureStruct->proargtypes.values,
205 nargs * sizeof(Oid));
206
207 for (argnum = 0; argnum < nargs; argnum++)
208 {
209 Oid argtype = argOidVect[argnum];
210
211 if (IsPolymorphicType(argtype))
212 {
213 argtype = get_call_expr_argtype(call_expr, argnum);
214 if (argtype == InvalidOid)
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 NameStr(name)
Definition: c.h:700
Oid get_call_expr_argtype(Node *expr, int argnum)
Definition: fmgr.c:1929
int get_func_input_arg_names(Datum proargnames, Datum proargmodes, char ***arg_names)
Definition: funcapi.c:1522
SQLFunctionParseInfo * SQLFunctionParseInfoPtr
Definition: functions.h:35
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
char * pstrdup(const char *in)
Definition: mcxt.c:1696
void * palloc(Size size)
Definition: mcxt.c:1317
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:136
unsigned int Oid
Definition: postgres_ext.h:31
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:600

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(), pstrdup(), and SysCacheGetAttr().

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

◆ sql_fn_parser_setup()

void sql_fn_parser_setup ( struct ParseState pstate,
SQLFunctionParseInfoPtr  pinfo 
)

Definition at line 265 of file functions.c.

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

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