PostgreSQL Source Code git master
Loading...
Searching...
No Matches
parse_func.c File Reference
#include "postgres.h"
#include "access/htup_details.h"
#include "catalog/pg_aggregate.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "funcapi.h"
#include "lib/stringinfo.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "parser/parse_agg.h"
#include "parser/parse_clause.h"
#include "parser/parse_coerce.h"
#include "parser/parse_expr.h"
#include "parser/parse_func.h"
#include "parser/parse_relation.h"
#include "parser/parse_target.h"
#include "parser/parse_type.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/syscache.h"
Include dependency graph for parse_func.c:

Go to the source code of this file.

Enumerations

enum  FuncLookupError { FUNCLOOKUP_NOSUCHFUNC , FUNCLOOKUP_AMBIGUOUS }
 

Functions

static int func_lookup_failure_details (int fgc_flags, List *argnames, bool proc_call)
 
static void unify_hypothetical_args (ParseState *pstate, List *fargs, int numAggregatedArgs, Oid *actual_arg_types, Oid *declared_arg_types)
 
static Oid FuncNameAsType (List *funcname)
 
static NodeParseComplexProjection (ParseState *pstate, const char *funcname, Node *first_arg, int location)
 
static Oid LookupFuncNameInternal (ObjectType objtype, List *funcname, int nargs, const Oid *argtypes, bool include_out_arguments, bool missing_ok, FuncLookupError *lookupError)
 
NodeParseFuncOrColumn (ParseState *pstate, List *funcname, List *fargs, Node *last_srf, FuncCall *fn, bool proc_call, int location)
 
int func_match_argtypes (int nargs, Oid *input_typeids, FuncCandidateList raw_candidates, FuncCandidateList *candidates)
 
FuncCandidateList func_select_candidate (int nargs, Oid *input_typeids, FuncCandidateList candidates)
 
FuncDetailCode func_get_detail (List *funcname, List *fargs, List *fargnames, int nargs, Oid *argtypes, bool expand_variadic, bool expand_defaults, bool include_out_arguments, int *fgc_flags, Oid *funcid, Oid *rettype, bool *retset, int *nvargs, Oid *vatype, Oid **true_typeids, List **argdefaults)
 
void make_fn_arguments (ParseState *pstate, List *fargs, Oid *actual_arg_types, Oid *declared_arg_types)
 
const charfuncname_signature_string (const char *funcname, int nargs, List *argnames, const Oid *argtypes)
 
const charfunc_signature_string (List *funcname, int nargs, List *argnames, const Oid *argtypes)
 
Oid LookupFuncName (List *funcname, int nargs, const Oid *argtypes, bool missing_ok)
 
Oid LookupFuncWithArgs (ObjectType objtype, ObjectWithArgs *func, bool missing_ok)
 
void check_srf_call_placement (ParseState *pstate, Node *last_srf, int location)
 

Enumeration Type Documentation

◆ FuncLookupError

Enumerator
FUNCLOOKUP_NOSUCHFUNC 
FUNCLOOKUP_AMBIGUOUS 

Definition at line 39 of file parse_func.c.

40{
FuncLookupError
Definition parse_func.c:40
@ FUNCLOOKUP_NOSUCHFUNC
Definition parse_func.c:41
@ FUNCLOOKUP_AMBIGUOUS
Definition parse_func.c:42

Function Documentation

◆ check_srf_call_placement()

void check_srf_call_placement ( ParseState pstate,
Node last_srf,
int  location 
)

Definition at line 2639 of file parse_func.c.

2640{
2641 const char *err;
2642 bool errkind;
2643
2644 /*
2645 * Check to see if the set-returning function is in an invalid place
2646 * within the query. Basically, we don't allow SRFs anywhere except in
2647 * the targetlist (which includes GROUP BY/ORDER BY expressions), VALUES,
2648 * and functions in FROM.
2649 *
2650 * For brevity we support two schemes for reporting an error here: set
2651 * "err" to a custom message, or set "errkind" true if the error context
2652 * is sufficiently identified by what ParseExprKindName will return, *and*
2653 * what it will return is just a SQL keyword. (Otherwise, use a custom
2654 * message to avoid creating translation problems.)
2655 */
2656 err = NULL;
2657 errkind = false;
2658 switch (pstate->p_expr_kind)
2659 {
2660 case EXPR_KIND_NONE:
2661 Assert(false); /* can't happen */
2662 break;
2663 case EXPR_KIND_OTHER:
2664 /* Accept SRF here; caller must throw error if wanted */
2665 break;
2666 case EXPR_KIND_JOIN_ON:
2668 err = _("set-returning functions are not allowed in JOIN conditions");
2669 break;
2671 /* can't get here, but just in case, throw an error */
2672 errkind = true;
2673 break;
2675 /* okay, but we don't allow nested SRFs here */
2676 /* errmsg is chosen to match transformRangeFunction() */
2677 /* errposition should point to the inner SRF */
2678 if (pstate->p_last_srf != last_srf)
2679 ereport(ERROR,
2681 errmsg("set-returning functions must appear at top level of FROM"),
2682 parser_errposition(pstate,
2683 exprLocation(pstate->p_last_srf))));
2684 break;
2685 case EXPR_KIND_WHERE:
2686 errkind = true;
2687 break;
2688 case EXPR_KIND_POLICY:
2689 err = _("set-returning functions are not allowed in policy expressions");
2690 break;
2691 case EXPR_KIND_HAVING:
2692 errkind = true;
2693 break;
2694 case EXPR_KIND_FILTER:
2695 errkind = true;
2696 break;
2699 /* okay, these are effectively GROUP BY/ORDER BY */
2700 pstate->p_hasTargetSRFs = true;
2701 break;
2705 err = _("set-returning functions are not allowed in window definitions");
2706 break;
2709 /* okay */
2710 pstate->p_hasTargetSRFs = true;
2711 break;
2714 /* disallowed because it would be ambiguous what to do */
2715 errkind = true;
2716 break;
2717 case EXPR_KIND_GROUP_BY:
2718 case EXPR_KIND_ORDER_BY:
2719 /* okay */
2720 pstate->p_hasTargetSRFs = true;
2721 break;
2723 /* okay */
2724 pstate->p_hasTargetSRFs = true;
2725 break;
2726 case EXPR_KIND_LIMIT:
2727 case EXPR_KIND_OFFSET:
2728 errkind = true;
2729 break;
2732 errkind = true;
2733 break;
2734 case EXPR_KIND_VALUES:
2735 /* SRFs are presently not supported by nodeValuesscan.c */
2736 errkind = true;
2737 break;
2739 /* okay, since we process this like a SELECT tlist */
2740 pstate->p_hasTargetSRFs = true;
2741 break;
2743 err = _("set-returning functions are not allowed in MERGE WHEN conditions");
2744 break;
2747 err = _("set-returning functions are not allowed in check constraints");
2748 break;
2751 err = _("set-returning functions are not allowed in DEFAULT expressions");
2752 break;
2754 err = _("set-returning functions are not allowed in index expressions");
2755 break;
2757 err = _("set-returning functions are not allowed in index predicates");
2758 break;
2760 err = _("set-returning functions are not allowed in statistics expressions");
2761 break;
2763 err = _("set-returning functions are not allowed in transform expressions");
2764 break;
2766 err = _("set-returning functions are not allowed in EXECUTE parameters");
2767 break;
2769 err = _("set-returning functions are not allowed in trigger WHEN conditions");
2770 break;
2772 err = _("set-returning functions are not allowed in partition bound");
2773 break;
2775 err = _("set-returning functions are not allowed in partition key expressions");
2776 break;
2778 err = _("set-returning functions are not allowed in CALL arguments");
2779 break;
2781 err = _("set-returning functions are not allowed in COPY FROM WHERE conditions");
2782 break;
2784 err = _("set-returning functions are not allowed in column generation expressions");
2785 break;
2787 errkind = true;
2788 break;
2790 err = _("set-returning functions are not allowed in property definition expressions");
2791 break;
2793 err = _("set-returning functions are not allowed in FOR PORTION OF expressions");
2794 break;
2795
2796 /*
2797 * There is intentionally no default: case here, so that the
2798 * compiler will warn if we add a new ParseExprKind without
2799 * extending this switch. If we do see an unrecognized value at
2800 * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
2801 * which is sane anyway.
2802 */
2803 }
2804 if (err)
2805 ereport(ERROR,
2807 errmsg_internal("%s", err),
2808 parser_errposition(pstate, location)));
2809 if (errkind)
2810 ereport(ERROR,
2812 /* translator: %s is name of a SQL construct, eg GROUP BY */
2813 errmsg("set-returning functions are not allowed in %s",
2815 parser_errposition(pstate, location)));
2816}
#define Assert(condition)
Definition c.h:943
int errcode(int sqlerrcode)
Definition elog.c:875
#define _(x)
Definition elog.c:96
int int errmsg_internal(const char *fmt,...) pg_attribute_printf(1
#define ERROR
Definition elog.h:40
#define ereport(elevel,...)
Definition elog.h:152
void err(int eval, const char *fmt,...)
Definition err.c:43
int exprLocation(const Node *expr)
Definition nodeFuncs.c:1403
static char * errmsg
const char * ParseExprKindName(ParseExprKind exprKind)
int parser_errposition(ParseState *pstate, int location)
Definition parse_node.c:106
@ EXPR_KIND_EXECUTE_PARAMETER
Definition parse_node.h:77
@ EXPR_KIND_DOMAIN_CHECK
Definition parse_node.h:70
@ EXPR_KIND_COPY_WHERE
Definition parse_node.h:83
@ EXPR_KIND_COLUMN_DEFAULT
Definition parse_node.h:71
@ EXPR_KIND_DISTINCT_ON
Definition parse_node.h:62
@ EXPR_KIND_MERGE_WHEN
Definition parse_node.h:58
@ EXPR_KIND_STATS_EXPRESSION
Definition parse_node.h:75
@ EXPR_KIND_INDEX_EXPRESSION
Definition parse_node.h:73
@ EXPR_KIND_MERGE_RETURNING
Definition parse_node.h:66
@ EXPR_KIND_PROPGRAPH_PROPERTY
Definition parse_node.h:86
@ EXPR_KIND_PARTITION_BOUND
Definition parse_node.h:80
@ EXPR_KIND_FUNCTION_DEFAULT
Definition parse_node.h:72
@ EXPR_KIND_WINDOW_FRAME_RANGE
Definition parse_node.h:51
@ EXPR_KIND_VALUES
Definition parse_node.h:67
@ EXPR_KIND_FROM_SUBSELECT
Definition parse_node.h:44
@ EXPR_KIND_POLICY
Definition parse_node.h:79
@ EXPR_KIND_WINDOW_FRAME_GROUPS
Definition parse_node.h:53
@ EXPR_KIND_PARTITION_EXPRESSION
Definition parse_node.h:81
@ EXPR_KIND_JOIN_USING
Definition parse_node.h:43
@ EXPR_KIND_INDEX_PREDICATE
Definition parse_node.h:74
@ EXPR_KIND_ORDER_BY
Definition parse_node.h:61
@ EXPR_KIND_OFFSET
Definition parse_node.h:64
@ EXPR_KIND_JOIN_ON
Definition parse_node.h:42
@ EXPR_KIND_HAVING
Definition parse_node.h:47
@ EXPR_KIND_INSERT_TARGET
Definition parse_node.h:55
@ EXPR_KIND_ALTER_COL_TRANSFORM
Definition parse_node.h:76
@ EXPR_KIND_LIMIT
Definition parse_node.h:63
@ EXPR_KIND_WHERE
Definition parse_node.h:46
@ EXPR_KIND_UPDATE_TARGET
Definition parse_node.h:57
@ EXPR_KIND_SELECT_TARGET
Definition parse_node.h:54
@ EXPR_KIND_RETURNING
Definition parse_node.h:65
@ EXPR_KIND_GENERATED_COLUMN
Definition parse_node.h:84
@ EXPR_KIND_NONE
Definition parse_node.h:40
@ EXPR_KIND_CALL_ARGUMENT
Definition parse_node.h:82
@ EXPR_KIND_GROUP_BY
Definition parse_node.h:60
@ EXPR_KIND_FOR_PORTION
Definition parse_node.h:59
@ EXPR_KIND_OTHER
Definition parse_node.h:41
@ EXPR_KIND_FROM_FUNCTION
Definition parse_node.h:45
@ EXPR_KIND_TRIGGER_WHEN
Definition parse_node.h:78
@ EXPR_KIND_FILTER
Definition parse_node.h:48
@ EXPR_KIND_UPDATE_SOURCE
Definition parse_node.h:56
@ EXPR_KIND_CHECK_CONSTRAINT
Definition parse_node.h:69
@ EXPR_KIND_WINDOW_PARTITION
Definition parse_node.h:49
@ EXPR_KIND_CYCLE_MARK
Definition parse_node.h:85
@ EXPR_KIND_WINDOW_FRAME_ROWS
Definition parse_node.h:52
@ EXPR_KIND_WINDOW_ORDER
Definition parse_node.h:50
@ EXPR_KIND_VALUES_SINGLE
Definition parse_node.h:68
static int fb(int x)
bool p_hasTargetSRFs
Definition parse_node.h:248
ParseExprKind p_expr_kind
Definition parse_node.h:232
Node * p_last_srf
Definition parse_node.h:252

References _, Assert, ereport, err(), errcode(), errmsg, errmsg_internal(), ERROR, EXPR_KIND_ALTER_COL_TRANSFORM, EXPR_KIND_CALL_ARGUMENT, EXPR_KIND_CHECK_CONSTRAINT, EXPR_KIND_COLUMN_DEFAULT, EXPR_KIND_COPY_WHERE, EXPR_KIND_CYCLE_MARK, EXPR_KIND_DISTINCT_ON, EXPR_KIND_DOMAIN_CHECK, EXPR_KIND_EXECUTE_PARAMETER, EXPR_KIND_FILTER, EXPR_KIND_FOR_PORTION, EXPR_KIND_FROM_FUNCTION, EXPR_KIND_FROM_SUBSELECT, EXPR_KIND_FUNCTION_DEFAULT, EXPR_KIND_GENERATED_COLUMN, EXPR_KIND_GROUP_BY, EXPR_KIND_HAVING, EXPR_KIND_INDEX_EXPRESSION, EXPR_KIND_INDEX_PREDICATE, EXPR_KIND_INSERT_TARGET, EXPR_KIND_JOIN_ON, EXPR_KIND_JOIN_USING, EXPR_KIND_LIMIT, EXPR_KIND_MERGE_RETURNING, EXPR_KIND_MERGE_WHEN, EXPR_KIND_NONE, EXPR_KIND_OFFSET, EXPR_KIND_ORDER_BY, EXPR_KIND_OTHER, EXPR_KIND_PARTITION_BOUND, EXPR_KIND_PARTITION_EXPRESSION, EXPR_KIND_POLICY, EXPR_KIND_PROPGRAPH_PROPERTY, EXPR_KIND_RETURNING, EXPR_KIND_SELECT_TARGET, EXPR_KIND_STATS_EXPRESSION, EXPR_KIND_TRIGGER_WHEN, EXPR_KIND_UPDATE_SOURCE, EXPR_KIND_UPDATE_TARGET, EXPR_KIND_VALUES, EXPR_KIND_VALUES_SINGLE, EXPR_KIND_WHERE, EXPR_KIND_WINDOW_FRAME_GROUPS, EXPR_KIND_WINDOW_FRAME_RANGE, EXPR_KIND_WINDOW_FRAME_ROWS, EXPR_KIND_WINDOW_ORDER, EXPR_KIND_WINDOW_PARTITION, exprLocation(), fb(), ParseState::p_expr_kind, ParseState::p_hasTargetSRFs, ParseState::p_last_srf, ParseExprKindName(), and parser_errposition().

Referenced by make_op(), and ParseFuncOrColumn().

◆ func_get_detail()

FuncDetailCode func_get_detail ( List funcname,
List fargs,
List fargnames,
int  nargs,
Oid argtypes,
bool  expand_variadic,
bool  expand_defaults,
bool  include_out_arguments,
int fgc_flags,
Oid funcid,
Oid rettype,
bool retset,
int nvargs,
Oid vatype,
Oid **  true_typeids,
List **  argdefaults 
)

Definition at line 1516 of file parse_func.c.

1532{
1535
1536 /* initialize output arguments to silence compiler warnings */
1537 *funcid = InvalidOid;
1538 *rettype = InvalidOid;
1539 *retset = false;
1540 *nvargs = 0;
1541 *vatype = InvalidOid;
1542 *true_typeids = NULL;
1543 if (argdefaults)
1544 *argdefaults = NIL;
1545
1546 /* Get list of possible candidates from namespace search */
1549 include_out_arguments, false,
1550 fgc_flags);
1551
1552 /*
1553 * Quickly check if there is an exact match to the input datatypes (there
1554 * can be only one)
1555 */
1559 {
1560 /* if nargs==0, argtypes can be null; don't pass that to memcmp */
1561 if (nargs == 0 ||
1562 memcmp(argtypes, best_candidate->args, nargs * sizeof(Oid)) == 0)
1563 break;
1564 }
1565
1566 if (best_candidate == NULL)
1567 {
1568 /*
1569 * If we didn't find an exact match, next consider the possibility
1570 * that this is really a type-coercion request: a single-argument
1571 * function call where the function name is a type name. If so, and
1572 * if the coercion path is RELABELTYPE or COERCEVIAIO, then go ahead
1573 * and treat the "function call" as a coercion.
1574 *
1575 * This interpretation needs to be given higher priority than
1576 * interpretations involving a type coercion followed by a function
1577 * call, otherwise we can produce surprising results. For example, we
1578 * want "text(varchar)" to be interpreted as a simple coercion, not as
1579 * "text(name(varchar))" which the code below this point is entirely
1580 * capable of selecting.
1581 *
1582 * We also treat a coercion of a previously-unknown-type literal
1583 * constant to a specific type this way.
1584 *
1585 * The reason we reject COERCION_PATH_FUNC here is that we expect the
1586 * cast implementation function to be named after the target type.
1587 * Thus the function will be found by normal lookup if appropriate.
1588 *
1589 * The reason we reject COERCION_PATH_ARRAYCOERCE is mainly that you
1590 * can't write "foo[] (something)" as a function call. In theory
1591 * someone might want to invoke it as "_foo (something)" but we have
1592 * never supported that historically, so we can insist that people
1593 * write it as a normal cast instead.
1594 *
1595 * We also reject the specific case of COERCEVIAIO for a composite
1596 * source type and a string-category target type. This is a case that
1597 * find_coercion_pathway() allows by default, but experience has shown
1598 * that it's too commonly invoked by mistake. So, again, insist that
1599 * people use cast syntax if they want to do that.
1600 *
1601 * NB: it's important that this code does not exceed what coerce_type
1602 * can do, because the caller will try to apply coerce_type if we
1603 * return FUNCDETAIL_COERCION. If we return that result for something
1604 * coerce_type can't handle, we'll cause infinite recursion between
1605 * this module and coerce_type!
1606 */
1607 if (nargs == 1 && fargs != NIL && fargnames == NIL)
1608 {
1610
1612 {
1613 Oid sourceType = argtypes[0];
1614 Node *arg1 = linitial(fargs);
1615 bool iscoercion;
1616
1617 if (sourceType == UNKNOWNOID && IsA(arg1, Const))
1618 {
1619 /* always treat typename('literal') as coercion */
1620 iscoercion = true;
1621 }
1622 else
1623 {
1625 Oid cfuncid;
1626
1629 &cfuncid);
1630 switch (cpathtype)
1631 {
1633 iscoercion = true;
1634 break;
1636 if ((sourceType == RECORDOID ||
1639 iscoercion = false;
1640 else
1641 iscoercion = true;
1642 break;
1643 default:
1644 iscoercion = false;
1645 break;
1646 }
1647 }
1648
1649 if (iscoercion)
1650 {
1651 /* Treat it as a type coercion */
1652 *funcid = InvalidOid;
1653 *rettype = targetType;
1654 *retset = false;
1655 *nvargs = 0;
1656 *vatype = InvalidOid;
1657 *true_typeids = argtypes;
1658 return FUNCDETAIL_COERCION;
1659 }
1660 }
1661 }
1662
1663 /*
1664 * didn't find an exact match, so now try to match up candidates...
1665 */
1666 if (raw_candidates != NULL)
1667 {
1669 int ncandidates;
1670
1672 argtypes,
1675
1676 /* one match only? then run with it... */
1677 if (ncandidates == 1)
1679
1680 /*
1681 * multiple candidates? then better decide or throw an error...
1682 */
1683 else if (ncandidates > 1)
1684 {
1686 argtypes,
1688
1689 /*
1690 * If we were able to choose a best candidate, we're done.
1691 * Otherwise, ambiguous function call.
1692 */
1693 if (!best_candidate)
1694 return FUNCDETAIL_MULTIPLE;
1695 }
1696 }
1697 }
1698
1699 if (best_candidate)
1700 {
1704
1705 /*
1706 * If processing named args or expanding variadics or defaults, the
1707 * "best candidate" might represent multiple equivalently good
1708 * functions; treat this case as ambiguous.
1709 */
1710 if (!OidIsValid(best_candidate->oid))
1711 return FUNCDETAIL_MULTIPLE;
1712
1713 /*
1714 * We disallow VARIADIC with named arguments unless the last argument
1715 * (the one with VARIADIC attached) actually matched the variadic
1716 * parameter. This is mere pedantry, really, but some folks insisted.
1717 */
1718 if (fargnames != NIL && !expand_variadic && nargs > 0 &&
1719 best_candidate->argnumbers[nargs - 1] != nargs - 1)
1720 {
1722 return FUNCDETAIL_NOTFOUND;
1723 }
1724
1725 *funcid = best_candidate->oid;
1726 *nvargs = best_candidate->nvargs;
1728
1729 /*
1730 * If processing named args, return actual argument positions into
1731 * NamedArgExpr nodes in the fargs list. This is a bit ugly but not
1732 * worth the extra notation needed to do it differently.
1733 */
1734 if (best_candidate->argnumbers != NULL)
1735 {
1736 int i = 0;
1737 ListCell *lc;
1738
1739 foreach(lc, fargs)
1740 {
1742
1743 if (IsA(na, NamedArgExpr))
1744 na->argnumber = best_candidate->argnumbers[i];
1745 i++;
1746 }
1747 }
1748
1751 if (!HeapTupleIsValid(ftup)) /* should not happen */
1752 elog(ERROR, "cache lookup failed for function %u",
1753 best_candidate->oid);
1755 *rettype = pform->prorettype;
1756 *retset = pform->proretset;
1757 *vatype = pform->provariadic;
1758 /* fetch default args if caller wants 'em */
1759 if (argdefaults && best_candidate->ndargs > 0)
1760 {
1762 char *str;
1763 List *defaults;
1764
1765 /* shouldn't happen, FuncnameGetCandidates messed up */
1766 if (best_candidate->ndargs > pform->pronargdefaults)
1767 elog(ERROR, "not enough default arguments");
1768
1772 defaults = castNode(List, stringToNode(str));
1773 pfree(str);
1774
1775 /* Delete any unused defaults from the returned list */
1776 if (best_candidate->argnumbers != NULL)
1777 {
1778 /*
1779 * This is a bit tricky in named notation, since the supplied
1780 * arguments could replace any subset of the defaults. We
1781 * work by making a bitmapset of the argnumbers of defaulted
1782 * arguments, then scanning the defaults list and selecting
1783 * the needed items. (This assumes that defaulted arguments
1784 * should be supplied in their positional order.)
1785 */
1787 int *firstdefarg;
1789 ListCell *lc;
1790 int i;
1791
1793 firstdefarg = &best_candidate->argnumbers[best_candidate->nargs - best_candidate->ndargs];
1794 for (i = 0; i < best_candidate->ndargs; i++)
1796 firstdefarg[i]);
1797 newdefaults = NIL;
1798 i = best_candidate->nominalnargs - pform->pronargdefaults;
1799 foreach(lc, defaults)
1800 {
1803 i++;
1804 }
1808 }
1809 else
1810 {
1811 /*
1812 * Defaults for positional notation are lots easier; just
1813 * remove any unwanted ones from the front.
1814 */
1815 int ndelete;
1816
1817 ndelete = list_length(defaults) - best_candidate->ndargs;
1818 if (ndelete > 0)
1819 defaults = list_delete_first_n(defaults, ndelete);
1820 *argdefaults = defaults;
1821 }
1822 }
1823
1824 switch (pform->prokind)
1825 {
1826 case PROKIND_AGGREGATE:
1828 break;
1829 case PROKIND_FUNCTION:
1831 break;
1832 case PROKIND_PROCEDURE:
1834 break;
1835 case PROKIND_WINDOW:
1837 break;
1838 default:
1839 elog(ERROR, "unrecognized prokind: %c", pform->prokind);
1840 result = FUNCDETAIL_NORMAL; /* keep compiler quiet */
1841 break;
1842 }
1843
1845 return result;
1846 }
1847
1848 return FUNCDETAIL_NOTFOUND;
1849}
void bms_free(Bitmapset *a)
Definition bitmapset.c:239
bool bms_is_member(int x, const Bitmapset *a)
Definition bitmapset.c:510
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition bitmapset.c:799
#define TextDatumGetCString(d)
Definition builtins.h:99
#define OidIsValid(objectId)
Definition c.h:858
uint32 result
#define elog(elevel,...)
Definition elog.h:228
const char * str
#define HeapTupleIsValid(tuple)
Definition htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
#define funcname
int i
Definition isn.c:77
List * lappend(List *list, void *datum)
Definition list.c:339
List * list_delete_first_n(List *list, int n)
Definition list.c:983
void pfree(void *pointer)
Definition mcxt.c:1619
FuncCandidateList FuncnameGetCandidates(List *names, int nargs, List *argnames, bool expand_variadic, bool expand_defaults, bool include_out_arguments, bool missing_ok, int *fgc_flags)
Definition namespace.c:1199
#define FGC_VARIADIC_FAIL
Definition namespace.h:58
#define IsA(nodeptr, _type_)
Definition nodes.h:164
#define castNode(_type_, nodeptr)
Definition nodes.h:182
TYPCATEGORY TypeCategory(Oid type)
CoercionPathType find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId, CoercionContext ccontext, Oid *funcid)
CoercionPathType
@ COERCION_PATH_COERCEVIAIO
@ COERCION_PATH_RELABELTYPE
FuncCandidateList func_select_candidate(int nargs, Oid *input_typeids, FuncCandidateList candidates)
static Oid FuncNameAsType(List *funcname)
int func_match_argtypes(int nargs, Oid *input_typeids, FuncCandidateList raw_candidates, FuncCandidateList *candidates)
FuncDetailCode
Definition parse_func.h:23
@ FUNCDETAIL_MULTIPLE
Definition parse_func.h:25
@ FUNCDETAIL_NORMAL
Definition parse_func.h:26
@ FUNCDETAIL_PROCEDURE
Definition parse_func.h:27
@ FUNCDETAIL_WINDOWFUNC
Definition parse_func.h:29
@ FUNCDETAIL_NOTFOUND
Definition parse_func.h:24
@ FUNCDETAIL_COERCION
Definition parse_func.h:30
@ FUNCDETAIL_AGGREGATE
Definition parse_func.h:28
#define ISCOMPLEX(typeid)
Definition parse_type.h:59
#define lfirst(lc)
Definition pg_list.h:172
static int list_length(const List *l)
Definition pg_list.h:152
#define NIL
Definition pg_list.h:68
#define linitial(l)
Definition pg_list.h:178
END_CATALOG_STRUCT typedef FormData_pg_proc * Form_pg_proc
Definition pg_proc.h:140
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:252
uint64_t Datum
Definition postgres.h:70
#define InvalidOid
unsigned int Oid
@ COERCION_EXPLICIT
Definition primnodes.h:750
void * stringToNode(const char *str)
Definition read.c:90
Definition pg_list.h:54
Definition nodes.h:135
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:265
Datum SysCacheGetAttrNotNull(SysCacheIdentifier cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition syscache.c:626
HeapTuple SearchSysCache1(SysCacheIdentifier cacheId, Datum key1)
Definition syscache.c:221

References NamedArgExpr::argnumber, Assert, bms_add_member(), bms_free(), bms_is_member(), castNode, COERCION_EXPLICIT, COERCION_PATH_COERCEVIAIO, COERCION_PATH_RELABELTYPE, elog, ERROR, fb(), FGC_VARIADIC_FAIL, find_coercion_pathway(), Form_pg_proc, func_match_argtypes(), func_select_candidate(), FUNCDETAIL_AGGREGATE, FUNCDETAIL_COERCION, FUNCDETAIL_MULTIPLE, FUNCDETAIL_NORMAL, FUNCDETAIL_NOTFOUND, FUNCDETAIL_PROCEDURE, FUNCDETAIL_WINDOWFUNC, funcname, FuncNameAsType(), FuncnameGetCandidates(), GETSTRUCT(), HeapTupleIsValid, i, InvalidOid, IsA, ISCOMPLEX, lappend(), lfirst, linitial, list_delete_first_n(), list_length(), NIL, ObjectIdGetDatum(), OidIsValid, pfree(), ReleaseSysCache(), result, SearchSysCache1(), str, stringToNode(), SysCacheGetAttrNotNull(), TextDatumGetCString, and TypeCategory().

Referenced by generate_function_name(), lookup_agg_function(), and ParseFuncOrColumn().

◆ func_lookup_failure_details()

static int func_lookup_failure_details ( int  fgc_flags,
List argnames,
bool  proc_call 
)
static

Definition at line 930 of file parse_func.c.

931{
932 /*
933 * If not FGC_NAME_VISIBLE, we shouldn't raise the question of whether the
934 * arguments are wrong. If the function name was not schema-qualified,
935 * it's helpful to distinguish between doesn't-exist-anywhere and
936 * not-in-search-path; but if it was, there's really nothing to add to the
937 * basic "function/procedure %s does not exist" message.
938 *
939 * Note: we passed missing_ok = false to FuncnameGetCandidates, so there's
940 * no need to consider FGC_SCHEMA_EXISTS here: we'd have already thrown an
941 * error if an explicitly-given schema doesn't exist.
942 */
944 {
946 return 0; /* schema-qualified name */
947 else if (!(fgc_flags & FGC_NAME_EXISTS))
948 {
949 if (proc_call)
950 return errdetail("There is no procedure of that name.");
951 else
952 return errdetail("There is no function of that name.");
953 }
954 else
955 {
956 if (proc_call)
957 return errdetail("A procedure of that name exists, but it is not in the search_path.");
958 else
959 return errdetail("A function of that name exists, but it is not in the search_path.");
960 }
961 }
962
963 /*
964 * Next, complain if nothing had the right number of arguments. (This
965 * takes precedence over wrong-argnames cases because we won't even look
966 * at the argnames unless there's a workable number of arguments.)
967 */
969 {
970 if (proc_call)
971 return errdetail("No procedure of that name accepts the given number of arguments.");
972 else
973 return errdetail("No function of that name accepts the given number of arguments.");
974 }
975
976 /*
977 * If there are argnames, and we failed to match them, again we should
978 * mention that and not bring up the argument types.
979 */
980 if (argnames != NIL && !(fgc_flags & FGC_ARGNAMES_MATCH))
981 {
982 if (proc_call)
983 return errdetail("No procedure of that name accepts the given argument names.");
984 else
985 return errdetail("No function of that name accepts the given argument names.");
986 }
987
988 /*
989 * We could have matched all the given argnames and still not have had a
990 * valid call, either because of improper use of mixed notation, or
991 * because of missing arguments, or because the user misused VARIADIC. The
992 * rules about named-argument matching are finicky enough that it's worth
993 * trying to be specific about the problem. (The messages here are chosen
994 * with full knowledge of the steps that namespace.c uses while checking a
995 * potential match.)
996 */
997 if (argnames != NIL && !(fgc_flags & FGC_ARGNAMES_NONDUP))
998 return errdetail("In the closest available match, "
999 "an argument was specified both positionally and by name.");
1000
1001 if (argnames != NIL && !(fgc_flags & FGC_ARGNAMES_ALL))
1002 return errdetail("In the closest available match, "
1003 "not all required arguments were supplied.");
1004
1005 if (argnames != NIL && !(fgc_flags & FGC_ARGNAMES_VALID))
1006 return errhint("This call would be correct if the variadic array were labeled VARIADIC and placed last.");
1007
1009 return errhint("The VARIADIC parameter must be placed last, even when using argument names.");
1010
1011 /*
1012 * Otherwise, the problem must be incorrect argument types.
1013 */
1014 if (proc_call)
1015 (void) errdetail("No procedure of that name accepts the given argument types.");
1016 else
1017 (void) errdetail("No function of that name accepts the given argument types.");
1018 return errhint("You might need to add explicit type casts.");
1019}
int errhint(const char *fmt,...) pg_attribute_printf(1
int errdetail(const char *fmt,...) pg_attribute_printf(1
#define FGC_ARGNAMES_ALL
Definition namespace.h:55
#define FGC_NAME_EXISTS
Definition namespace.h:49
#define FGC_ARGNAMES_VALID
Definition namespace.h:56
#define FGC_ARGNAMES_MATCH
Definition namespace.h:53
#define FGC_SCHEMA_GIVEN
Definition namespace.h:47
#define FGC_ARGCOUNT_MATCH
Definition namespace.h:51
#define FGC_NAME_VISIBLE
Definition namespace.h:50
#define FGC_ARGNAMES_NONDUP
Definition namespace.h:54

References errdetail(), errhint(), fb(), FGC_ARGCOUNT_MATCH, FGC_ARGNAMES_ALL, FGC_ARGNAMES_MATCH, FGC_ARGNAMES_NONDUP, FGC_ARGNAMES_VALID, FGC_NAME_EXISTS, FGC_NAME_VISIBLE, FGC_SCHEMA_GIVEN, FGC_VARIADIC_FAIL, and NIL.

Referenced by ParseFuncOrColumn().

◆ func_match_argtypes()

int func_match_argtypes ( int  nargs,
Oid input_typeids,
FuncCandidateList  raw_candidates,
FuncCandidateList candidates 
)

Definition at line 1037 of file parse_func.c.

1041{
1044 int ncandidates = 0;
1045
1046 *candidates = NULL;
1047
1051 {
1055 {
1058 ncandidates++;
1059 }
1060 }
1061
1062 return ncandidates;
1063} /* func_match_argtypes() */
bool can_coerce_type(int nargs, const Oid *input_typeids, const Oid *target_typeids, CoercionContext ccontext)
@ COERCION_IMPLICIT
Definition primnodes.h:747
struct _FuncCandidateList * next
Definition namespace.h:31

References can_coerce_type(), COERCION_IMPLICIT, fb(), and _FuncCandidateList::next.

Referenced by func_get_detail(), and oper_select_candidate().

◆ func_select_candidate()

FuncCandidateList func_select_candidate ( int  nargs,
Oid input_typeids,
FuncCandidateList  candidates 
)

Definition at line 1123 of file parse_func.c.

1126{
1132 int i;
1133 int ncandidates;
1134 int nbestMatch,
1135 nmatch,
1136 nunknowns;
1142 bool resolved_unknowns;
1143
1144 /* protect local fixed-size arrays */
1145 if (nargs > FUNC_MAX_ARGS)
1146 ereport(ERROR,
1148 errmsg_plural("cannot pass more than %d argument to a function",
1149 "cannot pass more than %d arguments to a function",
1151 FUNC_MAX_ARGS)));
1152
1153 /*
1154 * If any input types are domains, reduce them to their base types. This
1155 * ensures that we will consider functions on the base type to be "exact
1156 * matches" in the exact-match heuristic; it also makes it possible to do
1157 * something useful with the type-category heuristics. Note that this
1158 * makes it difficult, but not impossible, to use functions declared to
1159 * take a domain as an input datatype. Such a function will be selected
1160 * over the base-type function only if it is an exact match at all
1161 * argument positions, and so was already chosen by our caller.
1162 *
1163 * While we're at it, count the number of unknown-type arguments for use
1164 * later.
1165 */
1166 nunknowns = 0;
1167 for (i = 0; i < nargs; i++)
1168 {
1169 if (input_typeids[i] != UNKNOWNOID)
1171 else
1172 {
1173 /* no need to call getBaseType on UNKNOWNOID */
1175 nunknowns++;
1176 }
1177 }
1178
1179 /*
1180 * Run through all candidates and keep those with the most matches on
1181 * exact types. Keep all candidates if none match.
1182 */
1183 ncandidates = 0;
1184 nbestMatch = 0;
1189 {
1191 nmatch = 0;
1192 for (i = 0; i < nargs; i++)
1193 {
1196 nmatch++;
1197 }
1198
1199 /* take this one as the best choice so far? */
1200 if ((nmatch > nbestMatch) || (last_candidate == NULL))
1201 {
1202 nbestMatch = nmatch;
1205 ncandidates = 1;
1206 }
1207 /* no worse than the last choice, so keep this one too? */
1208 else if (nmatch == nbestMatch)
1209 {
1212 ncandidates++;
1213 }
1214 /* otherwise, don't bother keeping this one... */
1215 }
1216
1217 if (last_candidate) /* terminate rebuilt list */
1218 last_candidate->next = NULL;
1219
1220 if (ncandidates == 1)
1221 return candidates;
1222
1223 /*
1224 * Still too many candidates? Now look for candidates which have either
1225 * exact matches or preferred types at the args that will require
1226 * coercion. (Restriction added in 7.4: preferred type must be of same
1227 * category as input type; give no preference to cross-category
1228 * conversions to preferred types.) Keep all candidates if none match.
1229 */
1230 for (i = 0; i < nargs; i++) /* avoid multiple lookups */
1232 ncandidates = 0;
1233 nbestMatch = 0;
1238 {
1240 nmatch = 0;
1241 for (i = 0; i < nargs; i++)
1242 {
1244 {
1247 nmatch++;
1248 }
1249 }
1250
1251 if ((nmatch > nbestMatch) || (last_candidate == NULL))
1252 {
1253 nbestMatch = nmatch;
1256 ncandidates = 1;
1257 }
1258 else if (nmatch == nbestMatch)
1259 {
1262 ncandidates++;
1263 }
1264 }
1265
1266 if (last_candidate) /* terminate rebuilt list */
1267 last_candidate->next = NULL;
1268
1269 if (ncandidates == 1)
1270 return candidates;
1271
1272 /*
1273 * Still too many candidates? Try assigning types for the unknown inputs.
1274 *
1275 * If there are no unknown inputs, we have no more heuristics that apply,
1276 * and must fail.
1277 */
1278 if (nunknowns == 0)
1279 return NULL; /* failed to select a best candidate */
1280
1281 /*
1282 * The next step examines each unknown argument position to see if we can
1283 * determine a "type category" for it. If any candidate has an input
1284 * datatype of STRING category, use STRING category (this bias towards
1285 * STRING is appropriate since unknown-type literals look like strings).
1286 * Otherwise, if all the candidates agree on the type category of this
1287 * argument position, use that category. Otherwise, fail because we
1288 * cannot determine a category.
1289 *
1290 * If we are able to determine a type category, also notice whether any of
1291 * the candidates takes a preferred datatype within the category.
1292 *
1293 * Having completed this examination, remove candidates that accept the
1294 * wrong category at any unknown position. Also, if at least one
1295 * candidate accepted a preferred type at a position, remove candidates
1296 * that accept non-preferred types. If just one candidate remains, return
1297 * that one. However, if this rule turns out to reject all candidates,
1298 * keep them all instead.
1299 */
1300 resolved_unknowns = false;
1301 for (i = 0; i < nargs; i++)
1302 {
1303 bool have_conflict;
1304
1306 continue;
1307 resolved_unknowns = true; /* assume we can do it */
1309 slot_has_preferred_type[i] = false;
1310 have_conflict = false;
1314 {
1321 {
1322 /* first candidate */
1325 }
1326 else if (current_category == slot_category[i])
1327 {
1328 /* more candidates in same category */
1330 }
1331 else
1332 {
1333 /* category conflict! */
1335 {
1336 /* STRING always wins if available */
1339 }
1340 else
1341 {
1342 /*
1343 * Remember conflict, but keep going (might find STRING)
1344 */
1345 have_conflict = true;
1346 }
1347 }
1348 }
1350 {
1351 /* Failed to resolve category conflict at this position */
1352 resolved_unknowns = false;
1353 break;
1354 }
1355 }
1356
1358 {
1359 /* Strip non-matching candidates */
1360 ncandidates = 0;
1366 {
1367 bool keepit = true;
1368
1370 for (i = 0; i < nargs; i++)
1371 {
1373 continue;
1379 {
1380 keepit = false;
1381 break;
1382 }
1384 {
1385 keepit = false;
1386 break;
1387 }
1388 }
1389 if (keepit)
1390 {
1391 /* keep this candidate */
1393 ncandidates++;
1394 }
1395 else
1396 {
1397 /* forget this candidate */
1398 if (last_candidate)
1399 last_candidate->next = current_candidate->next;
1400 else
1402 }
1403 }
1404
1405 /* if we found any matches, restrict our attention to those */
1406 if (last_candidate)
1407 {
1409 /* terminate rebuilt list */
1410 last_candidate->next = NULL;
1411 }
1412
1413 if (ncandidates == 1)
1414 return candidates;
1415 }
1416
1417 /*
1418 * Last gasp: if there are both known- and unknown-type inputs, and all
1419 * the known types are the same, assume the unknown inputs are also that
1420 * type, and see if that gives us a unique match. If so, use that match.
1421 *
1422 * NOTE: for a binary operator with one unknown and one non-unknown input,
1423 * we already tried this heuristic in binary_oper_exact(). However, that
1424 * code only finds exact matches, whereas here we will handle matches that
1425 * involve coercion, polymorphic type resolution, etc.
1426 */
1427 if (nunknowns < nargs)
1428 {
1430
1431 for (i = 0; i < nargs; i++)
1432 {
1434 continue;
1435 if (known_type == UNKNOWNOID) /* first known arg? */
1437 else if (known_type != input_base_typeids[i])
1438 {
1439 /* oops, not all match */
1441 break;
1442 }
1443 }
1444
1445 if (known_type != UNKNOWNOID)
1446 {
1447 /* okay, just one known type, apply the heuristic */
1448 for (i = 0; i < nargs; i++)
1450 ncandidates = 0;
1455 {
1459 {
1460 if (++ncandidates > 1)
1461 break; /* not unique, give up */
1463 }
1464 }
1465 if (ncandidates == 1)
1466 {
1467 /* successfully identified a unique match */
1468 last_candidate->next = NULL;
1469 return last_candidate;
1470 }
1471 }
1472 }
1473
1474 return NULL; /* failed to select a best candidate */
1475} /* func_select_candidate() */
int int int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...) pg_attribute_printf(1
Oid getBaseType(Oid typid)
Definition lsyscache.c:2754
void get_type_category_preferred(Oid typid, char *typcategory, bool *typispreferred)
Definition lsyscache.c:2943
bool IsPreferredType(TYPCATEGORY category, Oid type)
char TYPCATEGORY
#define FUNC_MAX_ARGS

References can_coerce_type(), COERCION_IMPLICIT, ereport, errcode(), errmsg_plural(), ERROR, fb(), FUNC_MAX_ARGS, get_type_category_preferred(), getBaseType(), i, IsPreferredType(), and TypeCategory().

Referenced by func_get_detail(), and oper_select_candidate().

◆ func_signature_string()

const char * func_signature_string ( List funcname,
int  nargs,
List argnames,
const Oid argtypes 
)

◆ funcname_signature_string()

const char * funcname_signature_string ( const char funcname,
int  nargs,
List argnames,
const Oid argtypes 
)

Definition at line 2119 of file parse_func.c.

2121{
2123 int numposargs;
2124 ListCell *lc;
2125 int i;
2126
2128
2130
2131 numposargs = nargs - list_length(argnames);
2132 lc = list_head(argnames);
2133
2134 for (i = 0; i < nargs; i++)
2135 {
2136 if (i)
2138 if (i >= numposargs)
2139 {
2140 appendStringInfo(&argbuf, "%s => ", (char *) lfirst(lc));
2141 lc = lnext(argnames, lc);
2142 }
2144 }
2145
2147
2148 return argbuf.data; /* return palloc'd string buffer */
2149}
char * format_type_be(Oid type_oid)
static ListCell * list_head(const List *l)
Definition pg_list.h:128
static ListCell * lnext(const List *l, const ListCell *c)
Definition pg_list.h:375
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition stringinfo.c:145
void appendStringInfoString(StringInfo str, const char *s)
Definition stringinfo.c:230
void appendStringInfoChar(StringInfo str, char ch)
Definition stringinfo.c:242
void initStringInfo(StringInfo str)
Definition stringinfo.c:97

References appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), fb(), format_type_be(), funcname, i, initStringInfo(), lfirst, list_head(), list_length(), and lnext().

Referenced by func_signature_string(), and IsThereFunctionInNamespace().

◆ FuncNameAsType()

static Oid FuncNameAsType ( List funcname)
static

Definition at line 2007 of file parse_func.c.

2008{
2009 Oid result;
2010 Type typtup;
2011
2012 /*
2013 * temp_ok=false protects the <refsect1 id="sql-createfunction-security">
2014 * contract for writing SECURITY DEFINER functions safely.
2015 */
2017 NULL, false, false);
2018 if (typtup == NULL)
2019 return InvalidOid;
2020
2024 else
2026
2028 return result;
2029}
TypeName * makeTypeNameFromNameList(List *names)
Definition makefuncs.c:531
Oid typeTypeRelid(Type typ)
Definition parse_type.c:630
Type LookupTypeNameExtended(ParseState *pstate, const TypeName *typeName, int32 *typmod_p, bool temp_ok, bool missing_ok)
Definition parse_type.c:73
Oid typeTypeId(Type tp)
Definition parse_type.c:590
END_CATALOG_STRUCT typedef FormData_pg_type * Form_pg_type
Definition pg_type.h:265

References fb(), Form_pg_type, funcname, GETSTRUCT(), InvalidOid, LookupTypeNameExtended(), makeTypeNameFromNameList(), OidIsValid, ReleaseSysCache(), result, typeTypeId(), and typeTypeRelid().

Referenced by func_get_detail().

◆ LookupFuncName()

Oid LookupFuncName ( List funcname,
int  nargs,
const Oid argtypes,
bool  missing_ok 
)

Definition at line 2272 of file parse_func.c.

2273{
2274 Oid funcoid;
2276
2278 funcname, nargs, argtypes,
2279 false, missing_ok,
2280 &lookupError);
2281
2282 if (OidIsValid(funcoid))
2283 return funcoid;
2284
2285 switch (lookupError)
2286 {
2288 /* Let the caller deal with it when missing_ok is true */
2289 if (missing_ok)
2290 return InvalidOid;
2291
2292 if (nargs < 0)
2293 ereport(ERROR,
2295 errmsg("could not find a function named \"%s\"",
2297 else
2298 ereport(ERROR,
2300 errmsg("function %s does not exist",
2302 NIL, argtypes))));
2303 break;
2304
2306 /* Raise an error regardless of missing_ok */
2307 ereport(ERROR,
2309 errmsg("function name \"%s\" is not unique",
2311 errhint("Specify the argument list to select the function unambiguously.")));
2312 break;
2313 }
2314
2315 return InvalidOid; /* Keep compiler quiet */
2316}
static Oid LookupFuncNameInternal(ObjectType objtype, List *funcname, int nargs, const Oid *argtypes, bool include_out_arguments, bool missing_ok, FuncLookupError *lookupError)
const char * func_signature_string(List *funcname, int nargs, List *argnames, const Oid *argtypes)
@ OBJECT_FUNCTION

References ereport, errcode(), errhint(), errmsg, ERROR, fb(), func_signature_string(), FUNCLOOKUP_AMBIGUOUS, FUNCLOOKUP_NOSUCHFUNC, funcname, InvalidOid, LookupFuncNameInternal(), NameListToString(), NIL, OBJECT_FUNCTION, and OidIsValid.

Referenced by call_pltcl_start_proc(), CreateConversionCommand(), CreateEventTrigger(), CreateProceduralLanguage(), CreateTriggerFiringOn(), DefineOperator(), findRangeCanonicalFunction(), findRangeSubtypeDiffFunction(), findTypeAnalyzeFunction(), findTypeInputFunction(), findTypeOutputFunction(), findTypeReceiveFunction(), findTypeSendFunction(), findTypeSubscriptingFunction(), findTypeTypmodinFunction(), findTypeTypmodoutFunction(), get_ts_parser_func(), get_ts_template_func(), interpret_func_support(), lookup_am_handler_func(), lookup_fdw_connection_func(), lookup_fdw_handler_func(), lookup_fdw_validator_func(), transformRangeTableSample(), ValidateJoinEstimator(), and ValidateRestrictionEstimator().

◆ LookupFuncNameInternal()

static Oid LookupFuncNameInternal ( ObjectType  objtype,
List funcname,
int  nargs,
const Oid argtypes,
bool  include_out_arguments,
bool  missing_ok,
FuncLookupError lookupError 
)
static

Definition at line 2175 of file parse_func.c.

2179{
2182 int fgc_flags;
2183
2184 /* NULL argtypes allowed for nullary functions only */
2185 Assert(argtypes != NULL || nargs == 0);
2186
2187 /* Always set *lookupError, to forestall uninitialized-variable warnings */
2189
2190 /* Get list of candidate objects */
2191 clist = FuncnameGetCandidates(funcname, nargs, NIL, false, false,
2192 include_out_arguments, missing_ok,
2193 &fgc_flags);
2194
2195 /* Scan list for a match to the arg types (if specified) and the objtype */
2196 for (; clist != NULL; clist = clist->next)
2197 {
2198 /* Check arg type match, if specified */
2199 if (nargs >= 0)
2200 {
2201 /* if nargs==0, argtypes can be null; don't pass that to memcmp */
2202 if (nargs > 0 &&
2203 memcmp(argtypes, clist->args, nargs * sizeof(Oid)) != 0)
2204 continue;
2205 }
2206
2207 /* Check for duplicates reported by FuncnameGetCandidates */
2208 if (!OidIsValid(clist->oid))
2209 {
2211 return InvalidOid;
2212 }
2213
2214 /* Check objtype match, if specified */
2215 switch (objtype)
2216 {
2217 case OBJECT_FUNCTION:
2218 case OBJECT_AGGREGATE:
2219 /* Ignore procedures */
2221 continue;
2222 break;
2223 case OBJECT_PROCEDURE:
2224 /* Ignore non-procedures */
2226 continue;
2227 break;
2228 case OBJECT_ROUTINE:
2229 /* no restriction */
2230 break;
2231 default:
2232 Assert(false);
2233 }
2234
2235 /* Check for multiple matches */
2236 if (OidIsValid(result))
2237 {
2239 return InvalidOid;
2240 }
2241
2242 /* OK, we have a candidate */
2243 result = clist->oid;
2244 }
2245
2246 return result;
2247}
char get_func_prokind(Oid funcid)
Definition lsyscache.c:2049
@ OBJECT_AGGREGATE
@ OBJECT_ROUTINE
@ OBJECT_PROCEDURE

References Assert, fb(), FUNCLOOKUP_AMBIGUOUS, FUNCLOOKUP_NOSUCHFUNC, funcname, FuncnameGetCandidates(), get_func_prokind(), InvalidOid, NIL, OBJECT_AGGREGATE, OBJECT_FUNCTION, OBJECT_PROCEDURE, OBJECT_ROUTINE, OidIsValid, and result.

Referenced by LookupFuncName(), and LookupFuncWithArgs().

◆ LookupFuncWithArgs()

Oid LookupFuncWithArgs ( ObjectType  objtype,
ObjectWithArgs func,
bool  missing_ok 
)

Definition at line 2334 of file parse_func.c.

2335{
2337 int argcount;
2338 int nargs;
2339 int i;
2341 Oid oid;
2343
2344 Assert(objtype == OBJECT_AGGREGATE ||
2345 objtype == OBJECT_FUNCTION ||
2346 objtype == OBJECT_PROCEDURE ||
2347 objtype == OBJECT_ROUTINE);
2348
2349 argcount = list_length(func->objargs);
2350 if (argcount > FUNC_MAX_ARGS)
2351 {
2352 if (objtype == OBJECT_PROCEDURE)
2353 ereport(ERROR,
2355 errmsg_plural("procedures cannot have more than %d argument",
2356 "procedures cannot have more than %d arguments",
2358 FUNC_MAX_ARGS)));
2359 else
2360 ereport(ERROR,
2362 errmsg_plural("functions cannot have more than %d argument",
2363 "functions cannot have more than %d arguments",
2365 FUNC_MAX_ARGS)));
2366 }
2367
2368 /*
2369 * First, perform a lookup considering only input arguments (traditional
2370 * Postgres rules).
2371 */
2372 i = 0;
2373 foreach(args_item, func->objargs)
2374 {
2376
2377 argoids[i] = LookupTypeNameOid(NULL, t, missing_ok);
2378 if (!OidIsValid(argoids[i]))
2379 return InvalidOid; /* missing_ok must be true */
2380 i++;
2381 }
2382
2383 /*
2384 * Set nargs for LookupFuncNameInternal. It expects -1 to mean no args
2385 * were specified.
2386 */
2387 nargs = func->args_unspecified ? -1 : argcount;
2388
2389 /*
2390 * In args_unspecified mode, also tell LookupFuncNameInternal to consider
2391 * the object type, since there seems no reason not to. However, if we
2392 * have an argument list, disable the objtype check, because we'd rather
2393 * complain about "object is of wrong type" than "object doesn't exist".
2394 * (Note that with args, FuncnameGetCandidates will have ensured there's
2395 * only one argtype match, so we're not risking an ambiguity failure via
2396 * this choice.)
2397 */
2399 func->objname, nargs, argoids,
2400 false, missing_ok,
2401 &lookupError);
2402
2403 /*
2404 * If PROCEDURE or ROUTINE was specified, and we have an argument list
2405 * that contains no parameter mode markers, and we didn't already discover
2406 * that there's ambiguity, perform a lookup considering all arguments.
2407 * (Note: for a zero-argument procedure, or in args_unspecified mode, the
2408 * normal lookup is sufficient; so it's OK to require non-NIL objfuncargs
2409 * to perform this lookup.)
2410 */
2411 if ((objtype == OBJECT_PROCEDURE || objtype == OBJECT_ROUTINE) &&
2412 func->objfuncargs != NIL &&
2414 {
2415 bool have_param_mode = false;
2416
2417 /*
2418 * Check for non-default parameter mode markers. If there are any,
2419 * then the command does not conform to SQL-spec syntax, so we may
2420 * assume that the traditional Postgres lookup method of considering
2421 * only input parameters is sufficient. (Note that because the spec
2422 * doesn't have OUT arguments for functions, we also don't need this
2423 * hack in FUNCTION or AGGREGATE mode.)
2424 */
2425 foreach(args_item, func->objfuncargs)
2426 {
2428
2429 if (fp->mode != FUNC_PARAM_DEFAULT)
2430 {
2431 have_param_mode = true;
2432 break;
2433 }
2434 }
2435
2436 if (!have_param_mode)
2437 {
2438 Oid poid;
2439
2440 /* Without mode marks, objargs surely includes all params */
2442
2443 /* For objtype == OBJECT_PROCEDURE, we can ignore non-procedures */
2444 poid = LookupFuncNameInternal(objtype, func->objname,
2446 true, missing_ok,
2447 &lookupError);
2448
2449 /* Combine results, handling ambiguity */
2450 if (OidIsValid(poid))
2451 {
2452 if (OidIsValid(oid) && oid != poid)
2453 {
2454 /* oops, we got hits both ways, on different objects */
2455 oid = InvalidOid;
2457 }
2458 else
2459 oid = poid;
2460 }
2462 oid = InvalidOid;
2463 }
2464 }
2465
2466 if (OidIsValid(oid))
2467 {
2468 /*
2469 * Even if we found the function, perform validation that the objtype
2470 * matches the prokind of the found function. For historical reasons
2471 * we allow the objtype of FUNCTION to include aggregates and window
2472 * functions; but we draw the line if the object is a procedure. That
2473 * is a new enough feature that this historical rule does not apply.
2474 *
2475 * (This check is partially redundant with the objtype check in
2476 * LookupFuncNameInternal; but not entirely, since we often don't tell
2477 * LookupFuncNameInternal to apply that check at all.)
2478 */
2479 switch (objtype)
2480 {
2481 case OBJECT_FUNCTION:
2482 /* Only complain if it's a procedure. */
2484 ereport(ERROR,
2486 errmsg("%s is not a function",
2488 NIL, argoids))));
2489 break;
2490
2491 case OBJECT_PROCEDURE:
2492 /* Reject if found object is not a procedure. */
2494 ereport(ERROR,
2496 errmsg("%s is not a procedure",
2498 NIL, argoids))));
2499 break;
2500
2501 case OBJECT_AGGREGATE:
2502 /* Reject if found object is not an aggregate. */
2504 ereport(ERROR,
2506 errmsg("function %s is not an aggregate",
2508 NIL, argoids))));
2509 break;
2510
2511 default:
2512 /* OBJECT_ROUTINE accepts anything. */
2513 break;
2514 }
2515
2516 return oid; /* All good */
2517 }
2518 else
2519 {
2520 /* Deal with cases where the lookup failed */
2521 switch (lookupError)
2522 {
2524 /* Suppress no-such-func errors when missing_ok is true */
2525 if (missing_ok)
2526 break;
2527
2528 switch (objtype)
2529 {
2530 case OBJECT_PROCEDURE:
2531 if (func->args_unspecified)
2532 ereport(ERROR,
2534 errmsg("could not find a procedure named \"%s\"",
2535 NameListToString(func->objname))));
2536 else
2537 ereport(ERROR,
2539 errmsg("procedure %s does not exist",
2541 NIL, argoids))));
2542 break;
2543
2544 case OBJECT_AGGREGATE:
2545 if (func->args_unspecified)
2546 ereport(ERROR,
2548 errmsg("could not find an aggregate named \"%s\"",
2549 NameListToString(func->objname))));
2550 else if (argcount == 0)
2551 ereport(ERROR,
2553 errmsg("aggregate %s(*) does not exist",
2554 NameListToString(func->objname))));
2555 else
2556 ereport(ERROR,
2558 errmsg("aggregate %s does not exist",
2560 NIL, argoids))));
2561 break;
2562
2563 default:
2564 /* FUNCTION and ROUTINE */
2565 if (func->args_unspecified)
2566 ereport(ERROR,
2568 errmsg("could not find a function named \"%s\"",
2569 NameListToString(func->objname))));
2570 else
2571 ereport(ERROR,
2573 errmsg("function %s does not exist",
2575 NIL, argoids))));
2576 break;
2577 }
2578 break;
2579
2581 switch (objtype)
2582 {
2583 case OBJECT_FUNCTION:
2584 ereport(ERROR,
2586 errmsg("function name \"%s\" is not unique",
2587 NameListToString(func->objname)),
2588 func->args_unspecified ?
2589 errhint("Specify the argument list to select the function unambiguously.") : 0));
2590 break;
2591 case OBJECT_PROCEDURE:
2592 ereport(ERROR,
2594 errmsg("procedure name \"%s\" is not unique",
2595 NameListToString(func->objname)),
2596 func->args_unspecified ?
2597 errhint("Specify the argument list to select the procedure unambiguously.") : 0));
2598 break;
2599 case OBJECT_AGGREGATE:
2600 ereport(ERROR,
2602 errmsg("aggregate name \"%s\" is not unique",
2603 NameListToString(func->objname)),
2604 func->args_unspecified ?
2605 errhint("Specify the argument list to select the aggregate unambiguously.") : 0));
2606 break;
2607 case OBJECT_ROUTINE:
2608 ereport(ERROR,
2610 errmsg("routine name \"%s\" is not unique",
2611 NameListToString(func->objname)),
2612 func->args_unspecified ?
2613 errhint("Specify the argument list to select the routine unambiguously.") : 0));
2614 break;
2615
2616 default:
2617 Assert(false); /* Disallowed by Assert above */
2618 break;
2619 }
2620 break;
2621 }
2622
2623 return InvalidOid;
2624 }
2625}
#define false
Oid LookupTypeNameOid(ParseState *pstate, const TypeName *typeName, bool missing_ok)
Definition parse_type.c:232
@ FUNC_PARAM_DEFAULT
#define lfirst_node(type, lc)
Definition pg_list.h:176
FunctionParameterMode mode

References ObjectWithArgs::args_unspecified, Assert, ereport, errcode(), errhint(), errmsg, errmsg_plural(), ERROR, fb(), FUNC_MAX_ARGS, FUNC_PARAM_DEFAULT, func_signature_string(), FUNCLOOKUP_AMBIGUOUS, FUNCLOOKUP_NOSUCHFUNC, get_func_prokind(), i, InvalidOid, lfirst_node, list_length(), LookupFuncNameInternal(), LookupTypeNameOid(), FunctionParameter::mode, NameListToString(), NIL, ObjectWithArgs::objargs, OBJECT_AGGREGATE, OBJECT_FUNCTION, OBJECT_PROCEDURE, OBJECT_ROUTINE, ObjectWithArgs::objfuncargs, ObjectWithArgs::objname, and OidIsValid.

Referenced by AlterFunction(), AlterOpFamilyAdd(), CreateCast(), CreateTransform(), DefineOpClass(), and get_object_address().

◆ make_fn_arguments()

void make_fn_arguments ( ParseState pstate,
List fargs,
Oid actual_arg_types,
Oid declared_arg_types 
)

Definition at line 1951 of file parse_func.c.

1955{
1957 int i = 0;
1958
1959 foreach(current_fargs, fargs)
1960 {
1961 /* types don't match? then force coercion using a function call... */
1963 {
1964 Node *node = (Node *) lfirst(current_fargs);
1965
1966 /*
1967 * If arg is a NamedArgExpr, coerce its input expr instead --- we
1968 * want the NamedArgExpr to stay at the top level of the list.
1969 */
1970 if (IsA(node, NamedArgExpr))
1971 {
1972 NamedArgExpr *na = (NamedArgExpr *) node;
1973
1974 node = coerce_type(pstate,
1975 (Node *) na->arg,
1977 declared_arg_types[i], -1,
1980 -1);
1981 na->arg = (Expr *) node;
1982 }
1983 else
1984 {
1985 node = coerce_type(pstate,
1986 node,
1988 declared_arg_types[i], -1,
1991 -1);
1992 lfirst(current_fargs) = node;
1993 }
1994 }
1995 i++;
1996 }
1997}
Node * coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod, CoercionContext ccontext, CoercionForm cformat, int location)
@ COERCE_IMPLICIT_CAST
Definition primnodes.h:769

References COERCE_IMPLICIT_CAST, coerce_type(), COERCION_IMPLICIT, fb(), i, IsA, and lfirst.

Referenced by build_edge_vertex_link_quals(), make_op(), make_scalar_array_op(), ParseFuncOrColumn(), recheck_cast_function_args(), and transformForPortionOfClause().

◆ ParseComplexProjection()

static Node * ParseComplexProjection ( ParseState pstate,
const char funcname,
Node first_arg,
int  location 
)
static

Definition at line 2038 of file parse_func.c.

2040{
2041 TupleDesc tupdesc;
2042 int i;
2043
2044 /*
2045 * Special case for whole-row Vars so that we can resolve (foo.*).bar even
2046 * when foo is a reference to a subselect, join, or RECORD function. A
2047 * bonus is that we avoid generating an unnecessary FieldSelect; our
2048 * result can omit the whole-row Var and just be a Var for the selected
2049 * field.
2050 *
2051 * This case could be handled by expandRecordVariable, but it's more
2052 * efficient to do it this way when possible.
2053 */
2054 if (IsA(first_arg, Var) &&
2055 ((Var *) first_arg)->varattno == InvalidAttrNumber)
2056 {
2058
2060 ((Var *) first_arg)->varno,
2061 ((Var *) first_arg)->varlevelsup);
2062 /* Return a Var if funcname matches a column, else NULL */
2063 return scanNSItemForColumn(pstate, nsitem,
2064 ((Var *) first_arg)->varlevelsup,
2065 funcname, location);
2066 }
2067
2068 /*
2069 * Else do it the hard way with get_expr_result_tupdesc().
2070 *
2071 * If it's a Var of type RECORD, we have to work even harder: we have to
2072 * find what the Var refers to, and pass that to get_expr_result_tupdesc.
2073 * That task is handled by expandRecordVariable().
2074 */
2075 if (IsA(first_arg, Var) &&
2076 ((Var *) first_arg)->vartype == RECORDOID)
2077 tupdesc = expandRecordVariable(pstate, (Var *) first_arg, 0);
2078 else
2079 tupdesc = get_expr_result_tupdesc(first_arg, true);
2080 if (!tupdesc)
2081 return NULL; /* unresolvable RECORD type */
2082
2083 for (i = 0; i < tupdesc->natts; i++)
2084 {
2085 Form_pg_attribute att = TupleDescAttr(tupdesc, i);
2086
2087 if (strcmp(funcname, NameStr(att->attname)) == 0 &&
2088 !att->attisdropped)
2089 {
2090 /* Success, so generate a FieldSelect expression */
2092
2093 fselect->arg = (Expr *) first_arg;
2094 fselect->fieldnum = i + 1;
2095 fselect->resulttype = att->atttypid;
2096 fselect->resulttypmod = att->atttypmod;
2097 /* save attribute's collation for parse_collate.c */
2098 fselect->resultcollid = att->attcollation;
2099 return (Node *) fselect;
2100 }
2101 }
2102
2103 return NULL; /* funcname does not match any column */
2104}
#define InvalidAttrNumber
Definition attnum.h:23
#define NameStr(name)
Definition c.h:835
TupleDesc get_expr_result_tupdesc(Node *expr, bool noError)
Definition funcapi.c:553
#define makeNode(_type_)
Definition nodes.h:161
ParseNamespaceItem * GetNSItemByRangeTablePosn(ParseState *pstate, int varno, int sublevels_up)
Node * scanNSItemForColumn(ParseState *pstate, ParseNamespaceItem *nsitem, int sublevels_up, const char *colname, int location)
TupleDesc expandRecordVariable(ParseState *pstate, Var *var, int levelsup)
FormData_pg_attribute * Form_pg_attribute
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition tupdesc.h:178

References expandRecordVariable(), fb(), funcname, get_expr_result_tupdesc(), GetNSItemByRangeTablePosn(), i, InvalidAttrNumber, IsA, makeNode, NameStr, TupleDescData::natts, scanNSItemForColumn(), and TupleDescAttr().

Referenced by ParseFuncOrColumn().

◆ ParseFuncOrColumn()

Node * ParseFuncOrColumn ( ParseState pstate,
List funcname,
List fargs,
Node last_srf,
FuncCall fn,
bool  proc_call,
int  location 
)

Definition at line 92 of file parse_func.c.

94{
95 bool is_column = (fn == NULL);
96 List *agg_order = (fn ? fn->agg_order : NIL);
97 Expr *agg_filter = NULL;
98 WindowDef *over = (fn ? fn->over : NULL);
99 bool agg_within_group = (fn ? fn->agg_within_group : false);
100 bool agg_star = (fn ? fn->agg_star : false);
101 bool agg_distinct = (fn ? fn->agg_distinct : false);
102 bool func_variadic = (fn ? fn->func_variadic : false);
103 int ignore_nulls = (fn ? fn->ignore_nulls : NO_NULLTREATMENT);
104 CoercionForm funcformat = (fn ? fn->funcformat : COERCE_EXPLICIT_CALL);
106 Oid rettype;
107 Oid funcid;
108 ListCell *l;
110 int nargs;
111 int nargsplusdefs;
114 List *argnames;
116 Node *retval;
117 bool retset;
118 int nvargs;
119 Oid vatype;
121 int fgc_flags;
122 char aggkind = 0;
124
125 /*
126 * If there's an aggregate filter, transform it using transformWhereClause
127 */
128 if (fn && fn->agg_filter != NULL)
129 agg_filter = (Expr *) transformWhereClause(pstate, fn->agg_filter,
131 "FILTER");
132
133 /*
134 * Most of the rest of the parser just assumes that functions do not have
135 * more than FUNC_MAX_ARGS parameters. We have to test here to protect
136 * against array overruns, etc. Of course, this may not be a function,
137 * but the test doesn't hurt.
138 */
142 errmsg_plural("cannot pass more than %d argument to a function",
143 "cannot pass more than %d arguments to a function",
146 parser_errposition(pstate, location)));
147
148 /*
149 * Extract arg type info in preparation for function lookup.
150 *
151 * If any arguments are Param markers of type VOID, we discard them from
152 * the parameter list. This is a hack to allow the JDBC driver to not have
153 * to distinguish "input" and "output" parameter symbols while parsing
154 * function-call constructs. Don't do this if dealing with column syntax,
155 * nor if we had WITHIN GROUP (because in that case it's critical to keep
156 * the argument count unchanged).
157 */
158 nargs = 0;
159 foreach(l, fargs)
160 {
161 Node *arg = lfirst(l);
162 Oid argtype = exprType(arg);
163
164 if (argtype == VOIDOID && IsA(arg, Param) &&
165 !is_column && !agg_within_group)
166 {
168 continue;
169 }
170
171 actual_arg_types[nargs++] = argtype;
172 }
173
174 /*
175 * Check for named arguments; if there are any, build a list of names.
176 *
177 * We allow mixed notation (some named and some not), but only with all
178 * the named parameters after all the unnamed ones. So the name list
179 * corresponds to the last N actual parameters and we don't need any extra
180 * bookkeeping to match things up.
181 */
182 argnames = NIL;
183 foreach(l, fargs)
184 {
185 Node *arg = lfirst(l);
186
187 if (IsA(arg, NamedArgExpr))
188 {
190 ListCell *lc;
191
192 /* Reject duplicate arg names */
193 foreach(lc, argnames)
194 {
195 if (strcmp(na->name, (char *) lfirst(lc)) == 0)
198 errmsg("argument name \"%s\" used more than once",
199 na->name),
200 parser_errposition(pstate, na->location)));
201 }
202 argnames = lappend(argnames, na->name);
203 }
204 else
205 {
206 if (argnames != NIL)
209 errmsg("positional argument cannot follow named argument"),
211 }
212 }
213
214 if (fargs)
215 {
218 }
219
220 /*
221 * Decide whether it's legitimate to consider the construct to be a column
222 * projection. For that, there has to be a single argument of complex
223 * type, the function name must not be qualified, and there cannot be any
224 * syntactic decoration that'd require it to be a function (such as
225 * aggregate or variadic decoration, or named arguments).
226 */
227 could_be_projection = (nargs == 1 && !proc_call &&
228 agg_order == NIL && agg_filter == NULL &&
229 !agg_star && !agg_distinct && over == NULL &&
230 !func_variadic && argnames == NIL &&
231 list_length(funcname) == 1 &&
234
235 /*
236 * If it's column syntax, check for column projection case first.
237 */
239 {
240 retval = ParseComplexProjection(pstate,
242 first_arg,
243 location);
244 if (retval)
245 return retval;
246
247 /*
248 * If ParseComplexProjection doesn't recognize it as a projection,
249 * just press on.
250 */
251 }
252
253 /*
254 * func_get_detail looks up the function in the catalogs, does
255 * disambiguation for polymorphic functions, handles inheritance, and
256 * returns the funcid and type and set or singleton status of the
257 * function's return value. It also returns the true argument types to
258 * the function.
259 *
260 * Note: for a named-notation or variadic function call, the reported
261 * "true" types aren't really what is in pg_proc: the types are reordered
262 * to match the given argument order of named arguments, and a variadic
263 * argument is replaced by a suitable number of copies of its element
264 * type. We'll fix up the variadic case below. We may also have to deal
265 * with default arguments.
266 */
267
269
270 fdresult = func_get_detail(funcname, fargs, argnames, nargs,
272 !func_variadic, true, proc_call,
273 &fgc_flags,
274 &funcid, &rettype, &retset,
275 &nvargs, &vatype,
277
279
280 /*
281 * Check for various wrong-kind-of-routine cases.
282 */
283
284 /* If this is a CALL, reject things that aren't procedures */
285 if (proc_call &&
292 errmsg("%s is not a procedure",
294 argnames,
296 errhint("To call a function, use SELECT."),
297 parser_errposition(pstate, location)));
298 /* Conversely, if not a CALL, reject procedures */
302 errmsg("%s is a procedure",
304 argnames,
306 errhint("To call a procedure, use CALL."),
307 parser_errposition(pstate, location)));
308
312 {
313 /*
314 * In these cases, complain if there was anything indicating it must
315 * be an aggregate or window function.
316 */
317 if (agg_star)
320 errmsg("%s(*) specified, but %s is not an aggregate function",
323 parser_errposition(pstate, location)));
324 if (agg_distinct)
327 errmsg("DISTINCT specified, but %s is not an aggregate function",
329 parser_errposition(pstate, location)));
330 if (agg_within_group)
333 errmsg("WITHIN GROUP specified, but %s is not an aggregate function",
335 parser_errposition(pstate, location)));
336 if (agg_order != NIL)
339 errmsg("ORDER BY specified, but %s is not an aggregate function",
341 parser_errposition(pstate, location)));
342 if (agg_filter)
345 errmsg("FILTER specified, but %s is not an aggregate function",
347 parser_errposition(pstate, location)));
348 if (over)
351 errmsg("OVER specified, but %s is not a window function nor an aggregate function",
353 parser_errposition(pstate, location)));
354 }
355
356 /*
357 * So far so good, so do some fdresult-type-specific processing.
358 */
360 {
361 /* Nothing special to do for these cases. */
362 }
363 else if (fdresult == FUNCDETAIL_AGGREGATE)
364 {
365 /*
366 * It's an aggregate; fetch needed info from the pg_aggregate entry.
367 */
370 int catDirectArgs;
371
373 if (!HeapTupleIsValid(tup)) /* should not happen */
374 elog(ERROR, "cache lookup failed for aggregate %u", funcid);
376 aggkind = classForm->aggkind;
377 catDirectArgs = classForm->aggnumdirectargs;
379
380 /* Now check various disallowed cases. */
382 {
384 int numDirectArgs;
385
386 if (!agg_within_group)
389 errmsg("WITHIN GROUP is required for ordered-set aggregate %s",
391 parser_errposition(pstate, location)));
392 if (over)
395 errmsg("OVER is not supported for ordered-set aggregate %s",
397 parser_errposition(pstate, location)));
398 /* gram.y rejects DISTINCT + WITHIN GROUP */
399 Assert(!agg_distinct);
400 /* gram.y rejects VARIADIC + WITHIN GROUP */
401 Assert(!func_variadic);
402
403 /*
404 * Since func_get_detail was working with an undifferentiated list
405 * of arguments, it might have selected an aggregate that doesn't
406 * really match because it requires a different division of direct
407 * and aggregated arguments. Check that the number of direct
408 * arguments is actually OK; if not, throw an "undefined function"
409 * error, similarly to the case where a misplaced ORDER BY is used
410 * in a regular aggregate call.
411 */
412 numAggregatedArgs = list_length(agg_order);
414 Assert(numDirectArgs >= 0);
415
416 if (!OidIsValid(vatype))
417 {
418 /* Test is simple if aggregate isn't variadic */
422 errmsg("function %s does not exist",
424 argnames,
426 errhint_plural("There is an ordered-set aggregate %s, but it requires %d direct argument, not %d.",
427 "There is an ordered-set aggregate %s, but it requires %d direct arguments, not %d.",
431 parser_errposition(pstate, location)));
432 }
433 else
434 {
435 /*
436 * If it's variadic, we have two cases depending on whether
437 * the agg was "... ORDER BY VARIADIC" or "..., VARIADIC ORDER
438 * BY VARIADIC". It's the latter if catDirectArgs equals
439 * pronargs; to save a catalog lookup, we reverse-engineer
440 * pronargs from the info we got from func_get_detail.
441 */
442 int pronargs;
443
444 pronargs = nargs;
445 if (nvargs > 1)
446 pronargs -= nvargs - 1;
448 {
449 /* VARIADIC isn't part of direct args, so still easy */
453 errmsg("function %s does not exist",
455 argnames,
457 errhint_plural("There is an ordered-set aggregate %s, but it requires %d direct argument, not %d.",
458 "There is an ordered-set aggregate %s, but it requires %d direct arguments, not %d.",
462 parser_errposition(pstate, location)));
463 }
464 else
465 {
466 /*
467 * Both direct and aggregated args were declared variadic.
468 * For a standard ordered-set aggregate, it's okay as long
469 * as there aren't too few direct args. For a
470 * hypothetical-set aggregate, we assume that the
471 * hypothetical arguments are those that matched the
472 * variadic parameter; there must be just as many of them
473 * as there are aggregated arguments.
474 */
476 {
477 if (nvargs != 2 * numAggregatedArgs)
480 errmsg("function %s does not exist",
482 argnames,
484 errhint("To use the hypothetical-set aggregate %s, the number of hypothetical direct arguments (here %d) must match the number of ordering columns (here %d).",
487 parser_errposition(pstate, location)));
488 }
489 else
490 {
491 if (nvargs <= numAggregatedArgs)
494 errmsg("function %s does not exist",
496 argnames,
498 errhint_plural("There is an ordered-set aggregate %s, but it requires at least %d direct argument.",
499 "There is an ordered-set aggregate %s, but it requires at least %d direct arguments.",
503 parser_errposition(pstate, location)));
504 }
505 }
506 }
507
508 /* Check type matching of hypothetical arguments */
512 }
513 else
514 {
515 /* Normal aggregate, so it can't have WITHIN GROUP */
516 if (agg_within_group)
519 errmsg("%s is not an ordered-set aggregate, so it cannot have WITHIN GROUP",
521 parser_errposition(pstate, location)));
522
523 /* It also can't treat nulls as a window function */
524 if (ignore_nulls != NO_NULLTREATMENT)
527 errmsg("aggregate functions do not accept RESPECT/IGNORE NULLS"),
528 parser_errposition(pstate, location)));
529 }
530 }
532 {
533 /*
534 * True window functions must be called with a window definition.
535 */
536 if (!over)
539 errmsg("window function %s requires an OVER clause",
541 parser_errposition(pstate, location)));
542 /* And, per spec, WITHIN GROUP isn't allowed */
543 if (agg_within_group)
546 errmsg("window function %s cannot have WITHIN GROUP",
548 parser_errposition(pstate, location)));
549 }
550 else if (fdresult == FUNCDETAIL_COERCION)
551 {
552 /*
553 * We interpreted it as a type coercion. coerce_type can handle these
554 * cases, so why duplicate code...
555 */
556 return coerce_type(pstate, linitial(fargs),
557 actual_arg_types[0], rettype, -1,
559 }
560 else if (fdresult == FUNCDETAIL_MULTIPLE)
561 {
562 /*
563 * We found multiple possible functional matches. If we are dealing
564 * with attribute notation, return failure, letting the caller report
565 * "no such column" (we already determined there wasn't one). If
566 * dealing with function notation, report "ambiguous function",
567 * regardless of whether there's also a column by this name.
568 */
569 if (is_column)
570 return NULL;
571
572 if (proc_call)
575 errmsg("procedure %s is not unique",
576 func_signature_string(funcname, nargs, argnames,
578 errdetail("Could not choose a best candidate procedure."),
579 errhint("You might need to add explicit type casts."),
580 parser_errposition(pstate, location)));
581 else
584 errmsg("function %s is not unique",
585 func_signature_string(funcname, nargs, argnames,
587 errdetail("Could not choose a best candidate function."),
588 errhint("You might need to add explicit type casts."),
589 parser_errposition(pstate, location)));
590 }
591 else
592 {
593 /*
594 * Not found as a function. If we are dealing with attribute
595 * notation, return failure, letting the caller report "no such
596 * column" (we already determined there wasn't one).
597 */
598 if (is_column)
599 return NULL;
600
601 /*
602 * Check for column projection interpretation, since we didn't before.
603 */
605 {
606 retval = ParseComplexProjection(pstate,
608 first_arg,
609 location);
610 if (retval)
611 return retval;
612 }
613
614 /*
615 * No function, and no column either. Since we're dealing with
616 * function notation, report "function/procedure does not exist".
617 * Depending on what was returned in fgc_flags, we can add some color
618 * to that with detail or hint messages.
619 */
620 if (list_length(agg_order) > 1 && !agg_within_group)
621 {
622 /* It's agg(x, ORDER BY y,z) ... perhaps misplaced ORDER BY */
625 errmsg("function %s does not exist",
626 func_signature_string(funcname, nargs, argnames,
628 errdetail("No aggregate function matches the given name and argument types."),
629 errhint("Perhaps you misplaced ORDER BY; ORDER BY must appear "
630 "after all regular arguments of the aggregate."),
631 parser_errposition(pstate, location)));
632 }
633 else if (proc_call)
636 errmsg("procedure %s does not exist",
637 func_signature_string(funcname, nargs, argnames,
640 proc_call),
641 parser_errposition(pstate, location)));
642 else
645 errmsg("function %s does not exist",
646 func_signature_string(funcname, nargs, argnames,
649 proc_call),
650 parser_errposition(pstate, location)));
651 }
652
653 /*
654 * If there are default arguments, we have to include their types in
655 * actual_arg_types for the purpose of checking generic type consistency.
656 * However, we do NOT put them into the generated parse node, because
657 * their actual values might change before the query gets run. The
658 * planner has to insert the up-to-date values at plan time.
659 */
660 nargsplusdefs = nargs;
661 foreach(l, argdefaults)
662 {
663 Node *expr = (Node *) lfirst(l);
664
665 /* probably shouldn't happen ... */
669 errmsg_plural("cannot pass more than %d argument to a function",
670 "cannot pass more than %d arguments to a function",
673 parser_errposition(pstate, location)));
674
676 }
677
678 /*
679 * enforce consistency with polymorphic argument and return types,
680 * possibly adjusting return type or declared_arg_types (which will be
681 * used as the cast destination by make_fn_arguments)
682 */
686 rettype,
687 false);
688
689 /* perform the necessary typecasting of arguments */
691
692 /*
693 * If the function isn't actually variadic, forget any VARIADIC decoration
694 * on the call. (Perhaps we should throw an error instead, but
695 * historically we've allowed people to write that.)
696 */
697 if (!OidIsValid(vatype))
698 {
699 Assert(nvargs == 0);
700 func_variadic = false;
701 }
702
703 /*
704 * If it's a variadic function call, transform the last nvargs arguments
705 * into an array --- unless it's an "any" variadic.
706 */
707 if (nvargs > 0 && vatype != ANYOID)
708 {
710 int non_var_args = nargs - nvargs;
711 List *vargs;
712
713 Assert(non_var_args >= 0);
716
717 newa->elements = vargs;
718 /* assume all the variadic arguments were coerced to the same type */
719 newa->element_typeid = exprType((Node *) linitial(vargs));
720 newa->array_typeid = get_array_type(newa->element_typeid);
721 if (!OidIsValid(newa->array_typeid))
724 errmsg("could not find array type for data type %s",
725 format_type_be(newa->element_typeid)),
727 /* array_collid will be set by parse_collate.c */
728 newa->multidims = false;
729 newa->location = exprLocation((Node *) vargs);
730
732
733 /* We could not have had VARIADIC marking before ... */
734 Assert(!func_variadic);
735 /* ... but now, it's a VARIADIC call */
736 func_variadic = true;
737 }
738
739 /*
740 * If an "any" variadic is called with explicit VARIADIC marking, insist
741 * that the variadic parameter be of some array type.
742 */
743 if (nargs > 0 && vatype == ANYOID && func_variadic)
744 {
745 Oid va_arr_typid = actual_arg_types[nargs - 1];
746
750 errmsg("VARIADIC argument must be an array"),
751 parser_errposition(pstate,
752 exprLocation((Node *) llast(fargs)))));
753 }
754
755 /* if it returns a set, check that's OK */
756 if (retset)
757 check_srf_call_placement(pstate, last_srf, location);
758
759 /* build the appropriate output structure */
761 {
762 FuncExpr *funcexpr = makeNode(FuncExpr);
763
764 funcexpr->funcid = funcid;
765 funcexpr->funcresulttype = rettype;
766 funcexpr->funcretset = retset;
767 funcexpr->funcvariadic = func_variadic;
768 funcexpr->funcformat = funcformat;
769 /* funccollid and inputcollid will be set by parse_collate.c */
770 funcexpr->args = fargs;
771 funcexpr->location = location;
772
773 retval = (Node *) funcexpr;
774 }
775 else if (fdresult == FUNCDETAIL_AGGREGATE && !over)
776 {
777 /* aggregate function */
778 Aggref *aggref = makeNode(Aggref);
779
780 aggref->aggfnoid = funcid;
781 aggref->aggtype = rettype;
782 /* aggcollid and inputcollid will be set by parse_collate.c */
783 aggref->aggtranstype = InvalidOid; /* will be set by planner */
784 /* aggargtypes will be set by transformAggregateCall */
785 /* aggdirectargs and args will be set by transformAggregateCall */
786 /* aggorder and aggdistinct will be set by transformAggregateCall */
787 aggref->aggfilter = agg_filter;
788 aggref->aggstar = agg_star;
789 aggref->aggvariadic = func_variadic;
790 aggref->aggkind = aggkind;
791 aggref->aggpresorted = false;
792 /* agglevelsup will be set by transformAggregateCall */
793 aggref->aggsplit = AGGSPLIT_SIMPLE; /* planner might change this */
794 aggref->aggno = -1; /* planner will set aggno and aggtransno */
795 aggref->aggtransno = -1;
796 aggref->location = location;
797
798 /*
799 * Reject attempt to call a parameterless aggregate without (*)
800 * syntax. This is mere pedantry but some folks insisted ...
801 */
802 if (fargs == NIL && !agg_star && !agg_within_group)
805 errmsg("%s(*) must be used to call a parameterless aggregate function",
807 parser_errposition(pstate, location)));
808
809 if (retset)
812 errmsg("aggregates cannot return sets"),
813 parser_errposition(pstate, location)));
814
815 /*
816 * We might want to support named arguments later, but disallow it for
817 * now. We'd need to figure out the parsed representation (should the
818 * NamedArgExprs go above or below the TargetEntry nodes?) and then
819 * teach the planner to reorder the list properly. Or maybe we could
820 * make transformAggregateCall do that? However, if you'd also like
821 * to allow default arguments for aggregates, we'd need to do it in
822 * planning to avoid semantic problems.
823 */
824 if (argnames != NIL)
827 errmsg("aggregates cannot use named arguments"),
828 parser_errposition(pstate, location)));
829
830 /* parse_agg.c does additional aggregate-specific processing */
831 transformAggregateCall(pstate, aggref, fargs, agg_order, agg_distinct);
832
833 retval = (Node *) aggref;
834 }
835 else
836 {
837 /* window function */
839
840 Assert(over); /* lack of this was checked above */
841 Assert(!agg_within_group); /* also checked above */
842
843 wfunc->winfnoid = funcid;
844 wfunc->wintype = rettype;
845 /* wincollid and inputcollid will be set by parse_collate.c */
846 wfunc->args = fargs;
847 /* winref will be set by transformWindowFuncCall */
848 wfunc->winstar = agg_star;
849 wfunc->winagg = (fdresult == FUNCDETAIL_AGGREGATE);
850 wfunc->aggfilter = agg_filter;
851 wfunc->ignore_nulls = ignore_nulls;
852 wfunc->runCondition = NIL;
853 wfunc->location = location;
854
855 /*
856 * agg_star is allowed for aggregate functions but distinct isn't
857 */
858 if (agg_distinct)
861 errmsg("DISTINCT is not implemented for window functions"),
862 parser_errposition(pstate, location)));
863
864 /*
865 * Reject attempt to call a parameterless aggregate without (*)
866 * syntax. This is mere pedantry but some folks insisted ...
867 */
868 if (wfunc->winagg && fargs == NIL && !agg_star)
871 errmsg("%s(*) must be used to call a parameterless aggregate function",
873 parser_errposition(pstate, location)));
874
875 /*
876 * ordered aggs not allowed in windows yet
877 */
878 if (agg_order != NIL)
881 errmsg("aggregate ORDER BY is not implemented for window functions"),
882 parser_errposition(pstate, location)));
883
884 /*
885 * FILTER is not yet supported with true window functions
886 */
887 if (!wfunc->winagg && agg_filter)
890 errmsg("FILTER is not implemented for non-aggregate window functions"),
891 parser_errposition(pstate, location)));
892
893 /*
894 * Window functions can't either take or return sets
895 */
896 if (pstate->p_last_srf != last_srf)
899 errmsg("window function calls cannot contain set-returning function calls"),
900 errhint("You might be able to move the set-returning function into a LATERAL FROM item."),
901 parser_errposition(pstate,
902 exprLocation(pstate->p_last_srf))));
903
904 if (retset)
907 errmsg("window functions cannot return sets"),
908 parser_errposition(pstate, location)));
909
910 /* parse_agg.c does additional window-func-specific processing */
911 transformWindowFuncCall(pstate, wfunc, over);
912
913 retval = (Node *) wfunc;
914 }
915
916 /* if it returns a set, remember it for error checks at higher levels */
917 if (retset)
918 pstate->p_last_srf = retval;
919
920 return retval;
921}
Datum arg
Definition elog.c:1323
int int int errhint_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...) pg_attribute_printf(1
List * list_copy_tail(const List *oldlist, int nskip)
Definition list.c:1613
List * list_truncate(List *list, int new_size)
Definition list.c:631
Oid get_base_element_type(Oid typid)
Definition lsyscache.c:3065
Oid get_array_type(Oid typid)
Definition lsyscache.c:3020
Oid exprType(const Node *expr)
Definition nodeFuncs.c:42
@ AGGSPLIT_SIMPLE
Definition nodes.h:387
void transformWindowFuncCall(ParseState *pstate, WindowFunc *wfunc, WindowDef *windef)
Definition parse_agg.c:894
void transformAggregateCall(ParseState *pstate, Aggref *agg, List *args, List *aggorder, bool agg_distinct)
Definition parse_agg.c:113
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
Oid enforce_generic_type_consistency(const Oid *actual_arg_types, Oid *declared_arg_types, int nargs, Oid rettype, bool allow_poly)
FuncDetailCode func_get_detail(List *funcname, List *fargs, List *fargnames, int nargs, Oid *argtypes, bool expand_variadic, bool expand_defaults, bool include_out_arguments, int *fgc_flags, Oid *funcid, Oid *rettype, bool *retset, int *nvargs, Oid *vatype, Oid **true_typeids, List **argdefaults)
static Node * ParseComplexProjection(ParseState *pstate, const char *funcname, Node *first_arg, int location)
void make_fn_arguments(ParseState *pstate, List *fargs, Oid *actual_arg_types, Oid *declared_arg_types)
static void unify_hypothetical_args(ParseState *pstate, List *fargs, int numAggregatedArgs, Oid *actual_arg_types, Oid *declared_arg_types)
void check_srf_call_placement(ParseState *pstate, Node *last_srf, int location)
static int func_lookup_failure_details(int fgc_flags, List *argnames, bool proc_call)
Definition parse_func.c:930
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition parse_node.c:156
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition parse_node.c:140
END_CATALOG_STRUCT typedef FormData_pg_aggregate * Form_pg_aggregate
#define llast(l)
Definition pg_list.h:198
#define foreach_delete_current(lst, var_or_cell)
Definition pg_list.h:423
int16 pronargs
Definition pg_proc.h:83
CoercionForm
Definition primnodes.h:766
@ COERCE_EXPLICIT_CALL
Definition primnodes.h:767
#define NO_NULLTREATMENT
Definition primnodes.h:589
Oid aggfnoid
Definition primnodes.h:464
Expr * aggfilter
Definition primnodes.h:497
ParseLoc location
Definition primnodes.h:527
ParseLoc location
Definition primnodes.h:803
Oid funcid
Definition primnodes.h:783
List * args
Definition primnodes.h:801
List * args
Definition primnodes.h:606
Expr * aggfilter
Definition primnodes.h:608
ParseLoc location
Definition primnodes.h:620
int ignore_nulls
Definition primnodes.h:618
static void * fn(void *arg)
#define strVal(v)
Definition value.h:82

References Aggref::aggfilter, WindowFunc::aggfilter, Aggref::aggfnoid, AGGSPLIT_SIMPLE, arg, WindowFunc::args, FuncExpr::args, Assert, cancel_parser_errposition_callback(), check_srf_call_placement(), COERCE_EXPLICIT_CALL, coerce_type(), COERCION_EXPLICIT, elog, enforce_generic_type_consistency(), ereport, errcode(), errdetail(), errhint(), errhint_plural(), errmsg, errmsg_plural(), ERROR, EXPR_KIND_FILTER, exprLocation(), exprType(), fb(), fn(), foreach_delete_current, Form_pg_aggregate, format_type_be(), func_get_detail(), func_lookup_failure_details(), FUNC_MAX_ARGS, func_signature_string(), FUNCDETAIL_AGGREGATE, FUNCDETAIL_COERCION, FUNCDETAIL_MULTIPLE, FUNCDETAIL_NORMAL, FUNCDETAIL_PROCEDURE, FUNCDETAIL_WINDOWFUNC, FuncExpr::funcid, funcname, get_array_type(), get_base_element_type(), GETSTRUCT(), HeapTupleIsValid, WindowFunc::ignore_nulls, InvalidOid, IsA, ISCOMPLEX, lappend(), lfirst, linitial, list_copy_tail(), list_length(), list_truncate(), llast, Aggref::location, WindowFunc::location, FuncExpr::location, make_fn_arguments(), makeNode, NameListToString(), NIL, NO_NULLTREATMENT, ObjectIdGetDatum(), OidIsValid, ParseState::p_last_srf, ParseComplexProjection(), parser_errposition(), pronargs, ReleaseSysCache(), SearchSysCache1(), setup_parser_errposition_callback(), strVal, transformAggregateCall(), transformWhereClause(), transformWindowFuncCall(), unify_hypothetical_args(), and WindowFunc::winfnoid.

Referenced by sql_fn_post_column_ref(), transformCallStmt(), transformColumnRef(), transformFuncCall(), and transformIndirection().

◆ unify_hypothetical_args()

static void unify_hypothetical_args ( ParseState pstate,
List fargs,
int  numAggregatedArgs,
Oid actual_arg_types,
Oid declared_arg_types 
)
static

Definition at line 1867 of file parse_func.c.

1872{
1873 int numDirectArgs,
1875 int hargpos;
1876
1879 /* safety check (should only trigger with a misdeclared agg) */
1880 if (numNonHypotheticalArgs < 0)
1881 elog(ERROR, "incorrect number of arguments to hypothetical-set aggregate");
1882
1883 /* Check each hypothetical arg and corresponding aggregated arg */
1885 {
1891
1892 /* A mismatch means AggregateCreate didn't check properly ... */
1894 elog(ERROR, "hypothetical-set aggregate has inconsistent declared argument types");
1895
1896 /* No need to unify if make_fn_arguments will coerce */
1898 continue;
1899
1900 /*
1901 * Select common type, giving preference to the aggregated argument's
1902 * type (we'd rather coerce the direct argument once than coerce all
1903 * the aggregated values).
1904 */
1907 "WITHIN GROUP",
1908 NULL);
1911 commontype);
1912
1913 /*
1914 * Perform the coercions. We don't need to worry about NamedArgExprs
1915 * here because they aren't supported with aggregates.
1916 */
1917 lfirst(harg) = coerce_type(pstate,
1918 (Node *) lfirst(harg),
1923 -1);
1925 lfirst(aarg) = coerce_type(pstate,
1926 (Node *) lfirst(aarg),
1931 -1);
1933 }
1934}
int32_t int32
Definition c.h:620
int32 select_common_typmod(ParseState *pstate, List *exprs, Oid common_type)
Oid select_common_type(ParseState *pstate, List *exprs, const char *context, Node **which_expr)
static ListCell * list_nth_cell(const List *list, int n)
Definition pg_list.h:309
#define list_make2(x1, x2)
Definition pg_list.h:246

References COERCE_IMPLICIT_CAST, coerce_type(), COERCION_IMPLICIT, elog, ERROR, fb(), lfirst, list_length(), list_make2, list_nth_cell(), select_common_type(), and select_common_typmod().

Referenced by ParseFuncOrColumn().