PostgreSQL Source Code  git master
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 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 (List *funcname, int nargs, const Oid *argtypes, 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, 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 char * funcname_signature_string (const char *funcname, int nargs, List *argnames, const Oid *argtypes)
 
const char * func_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.

Function Documentation

◆ check_srf_call_placement()

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

Definition at line 2380 of file parse_func.c.

References _, Assert, ereport, 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_DISTINCT_ON, EXPR_KIND_DOMAIN_CHECK, EXPR_KIND_EXECUTE_PARAMETER, EXPR_KIND_FILTER, 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_NONE, EXPR_KIND_OFFSET, EXPR_KIND_ORDER_BY, EXPR_KIND_OTHER, EXPR_KIND_PARTITION_BOUND, EXPR_KIND_PARTITION_EXPRESSION, EXPR_KIND_POLICY, EXPR_KIND_RETURNING, EXPR_KIND_SELECT_TARGET, 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(), ParseState::p_expr_kind, ParseState::p_hasTargetSRFs, ParseState::p_last_srf, ParseExprKindName(), and parser_errposition().

Referenced by make_op(), and ParseFuncOrColumn().

2381 {
2382  const char *err;
2383  bool errkind;
2384 
2385  /*
2386  * Check to see if the set-returning function is in an invalid place
2387  * within the query. Basically, we don't allow SRFs anywhere except in
2388  * the targetlist (which includes GROUP BY/ORDER BY expressions), VALUES,
2389  * and functions in FROM.
2390  *
2391  * For brevity we support two schemes for reporting an error here: set
2392  * "err" to a custom message, or set "errkind" true if the error context
2393  * is sufficiently identified by what ParseExprKindName will return, *and*
2394  * what it will return is just a SQL keyword. (Otherwise, use a custom
2395  * message to avoid creating translation problems.)
2396  */
2397  err = NULL;
2398  errkind = false;
2399  switch (pstate->p_expr_kind)
2400  {
2401  case EXPR_KIND_NONE:
2402  Assert(false); /* can't happen */
2403  break;
2404  case EXPR_KIND_OTHER:
2405  /* Accept SRF here; caller must throw error if wanted */
2406  break;
2407  case EXPR_KIND_JOIN_ON:
2408  case EXPR_KIND_JOIN_USING:
2409  err = _("set-returning functions are not allowed in JOIN conditions");
2410  break;
2412  /* can't get here, but just in case, throw an error */
2413  errkind = true;
2414  break;
2416  /* okay, but we don't allow nested SRFs here */
2417  /* errmsg is chosen to match transformRangeFunction() */
2418  /* errposition should point to the inner SRF */
2419  if (pstate->p_last_srf != last_srf)
2420  ereport(ERROR,
2421  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2422  errmsg("set-returning functions must appear at top level of FROM"),
2423  parser_errposition(pstate,
2424  exprLocation(pstate->p_last_srf))));
2425  break;
2426  case EXPR_KIND_WHERE:
2427  errkind = true;
2428  break;
2429  case EXPR_KIND_POLICY:
2430  err = _("set-returning functions are not allowed in policy expressions");
2431  break;
2432  case EXPR_KIND_HAVING:
2433  errkind = true;
2434  break;
2435  case EXPR_KIND_FILTER:
2436  errkind = true;
2437  break;
2440  /* okay, these are effectively GROUP BY/ORDER BY */
2441  pstate->p_hasTargetSRFs = true;
2442  break;
2446  err = _("set-returning functions are not allowed in window definitions");
2447  break;
2450  /* okay */
2451  pstate->p_hasTargetSRFs = true;
2452  break;
2455  /* disallowed because it would be ambiguous what to do */
2456  errkind = true;
2457  break;
2458  case EXPR_KIND_GROUP_BY:
2459  case EXPR_KIND_ORDER_BY:
2460  /* okay */
2461  pstate->p_hasTargetSRFs = true;
2462  break;
2463  case EXPR_KIND_DISTINCT_ON:
2464  /* okay */
2465  pstate->p_hasTargetSRFs = true;
2466  break;
2467  case EXPR_KIND_LIMIT:
2468  case EXPR_KIND_OFFSET:
2469  errkind = true;
2470  break;
2471  case EXPR_KIND_RETURNING:
2472  errkind = true;
2473  break;
2474  case EXPR_KIND_VALUES:
2475  /* SRFs are presently not supported by nodeValuesscan.c */
2476  errkind = true;
2477  break;
2479  /* okay, since we process this like a SELECT tlist */
2480  pstate->p_hasTargetSRFs = true;
2481  break;
2484  err = _("set-returning functions are not allowed in check constraints");
2485  break;
2488  err = _("set-returning functions are not allowed in DEFAULT expressions");
2489  break;
2491  err = _("set-returning functions are not allowed in index expressions");
2492  break;
2494  err = _("set-returning functions are not allowed in index predicates");
2495  break;
2497  err = _("set-returning functions are not allowed in transform expressions");
2498  break;
2500  err = _("set-returning functions are not allowed in EXECUTE parameters");
2501  break;
2503  err = _("set-returning functions are not allowed in trigger WHEN conditions");
2504  break;
2506  err = _("set-returning functions are not allowed in partition bound");
2507  break;
2509  err = _("set-returning functions are not allowed in partition key expressions");
2510  break;
2512  err = _("set-returning functions are not allowed in CALL arguments");
2513  break;
2514  case EXPR_KIND_COPY_WHERE:
2515  err = _("set-returning functions are not allowed in COPY FROM WHERE conditions");
2516  break;
2518  err = _("set-returning functions are not allowed in column generation expressions");
2519  break;
2520 
2521  /*
2522  * There is intentionally no default: case here, so that the
2523  * compiler will warn if we add a new ParseExprKind without
2524  * extending this switch. If we do see an unrecognized value at
2525  * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
2526  * which is sane anyway.
2527  */
2528  }
2529  if (err)
2530  ereport(ERROR,
2531  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2532  errmsg_internal("%s", err),
2533  parser_errposition(pstate, location)));
2534  if (errkind)
2535  ereport(ERROR,
2536  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2537  /* translator: %s is name of a SQL construct, eg GROUP BY */
2538  errmsg("set-returning functions are not allowed in %s",
2539  ParseExprKindName(pstate->p_expr_kind)),
2540  parser_errposition(pstate, location)));
2541 }
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1191
bool p_hasTargetSRFs
Definition: parse_node.h:205
int errcode(int sqlerrcode)
Definition: elog.c:608
const char * ParseExprKindName(ParseExprKind exprKind)
Definition: parse_expr.c:3481
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:141
Node * p_last_srf
Definition: parse_node.h:209
ParseExprKind p_expr_kind
Definition: parse_node.h:191
int errmsg_internal(const char *fmt,...)
Definition: elog.c:909
#define Assert(condition)
Definition: c.h:739
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define _(x)
Definition: elog.c:87

◆ func_get_detail()

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

Definition at line 1382 of file parse_func.c.

References NamedArgExpr::argnumber, _FuncCandidateList::argnumbers, _FuncCandidateList::args, Assert, bms_add_member(), bms_free(), bms_is_member(), castNode, COERCION_EXPLICIT, COERCION_PATH_COERCEVIAIO, COERCION_PATH_RELABELTYPE, elog, ERROR, find_coercion_pathway(), func_match_argtypes(), func_select_candidate(), FUNCDETAIL_AGGREGATE, FUNCDETAIL_COERCION, FUNCDETAIL_MULTIPLE, FUNCDETAIL_NORMAL, FUNCDETAIL_NOTFOUND, FUNCDETAIL_PROCEDURE, FUNCDETAIL_WINDOWFUNC, FuncNameAsType(), FuncnameGetCandidates(), GETSTRUCT, HeapTupleIsValid, i, InvalidOid, IsA, ISCOMPLEX, lappend(), lfirst, linitial, list_copy_tail(), list_length(), _FuncCandidateList::nargs, _FuncCandidateList::ndargs, _FuncCandidateList::next, NIL, _FuncCandidateList::nvargs, ObjectIdGetDatum, _FuncCandidateList::oid, OidIsValid, pfree(), PROCOID, ReleaseSysCache(), SearchSysCache1(), generate_unaccent_rules::str, stringToNode(), SysCacheGetAttr(), TextDatumGetCString, and TypeCategory().

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

1396 {
1397  FuncCandidateList raw_candidates;
1398  FuncCandidateList best_candidate;
1399 
1400  /* initialize output arguments to silence compiler warnings */
1401  *funcid = InvalidOid;
1402  *rettype = InvalidOid;
1403  *retset = false;
1404  *nvargs = 0;
1405  *vatype = InvalidOid;
1406  *true_typeids = NULL;
1407  if (argdefaults)
1408  *argdefaults = NIL;
1409 
1410  /* Get list of possible candidates from namespace search */
1411  raw_candidates = FuncnameGetCandidates(funcname, nargs, fargnames,
1412  expand_variadic, expand_defaults,
1413  false);
1414 
1415  /*
1416  * Quickly check if there is an exact match to the input datatypes (there
1417  * can be only one)
1418  */
1419  for (best_candidate = raw_candidates;
1420  best_candidate != NULL;
1421  best_candidate = best_candidate->next)
1422  {
1423  /* if nargs==0, argtypes can be null; don't pass that to memcmp */
1424  if (nargs == 0 ||
1425  memcmp(argtypes, best_candidate->args, nargs * sizeof(Oid)) == 0)
1426  break;
1427  }
1428 
1429  if (best_candidate == NULL)
1430  {
1431  /*
1432  * If we didn't find an exact match, next consider the possibility
1433  * that this is really a type-coercion request: a single-argument
1434  * function call where the function name is a type name. If so, and
1435  * if the coercion path is RELABELTYPE or COERCEVIAIO, then go ahead
1436  * and treat the "function call" as a coercion.
1437  *
1438  * This interpretation needs to be given higher priority than
1439  * interpretations involving a type coercion followed by a function
1440  * call, otherwise we can produce surprising results. For example, we
1441  * want "text(varchar)" to be interpreted as a simple coercion, not as
1442  * "text(name(varchar))" which the code below this point is entirely
1443  * capable of selecting.
1444  *
1445  * We also treat a coercion of a previously-unknown-type literal
1446  * constant to a specific type this way.
1447  *
1448  * The reason we reject COERCION_PATH_FUNC here is that we expect the
1449  * cast implementation function to be named after the target type.
1450  * Thus the function will be found by normal lookup if appropriate.
1451  *
1452  * The reason we reject COERCION_PATH_ARRAYCOERCE is mainly that you
1453  * can't write "foo[] (something)" as a function call. In theory
1454  * someone might want to invoke it as "_foo (something)" but we have
1455  * never supported that historically, so we can insist that people
1456  * write it as a normal cast instead.
1457  *
1458  * We also reject the specific case of COERCEVIAIO for a composite
1459  * source type and a string-category target type. This is a case that
1460  * find_coercion_pathway() allows by default, but experience has shown
1461  * that it's too commonly invoked by mistake. So, again, insist that
1462  * people use cast syntax if they want to do that.
1463  *
1464  * NB: it's important that this code does not exceed what coerce_type
1465  * can do, because the caller will try to apply coerce_type if we
1466  * return FUNCDETAIL_COERCION. If we return that result for something
1467  * coerce_type can't handle, we'll cause infinite recursion between
1468  * this module and coerce_type!
1469  */
1470  if (nargs == 1 && fargs != NIL && fargnames == NIL)
1471  {
1472  Oid targetType = FuncNameAsType(funcname);
1473 
1474  if (OidIsValid(targetType))
1475  {
1476  Oid sourceType = argtypes[0];
1477  Node *arg1 = linitial(fargs);
1478  bool iscoercion;
1479 
1480  if (sourceType == UNKNOWNOID && IsA(arg1, Const))
1481  {
1482  /* always treat typename('literal') as coercion */
1483  iscoercion = true;
1484  }
1485  else
1486  {
1487  CoercionPathType cpathtype;
1488  Oid cfuncid;
1489 
1490  cpathtype = find_coercion_pathway(targetType, sourceType,
1492  &cfuncid);
1493  switch (cpathtype)
1494  {
1496  iscoercion = true;
1497  break;
1499  if ((sourceType == RECORDOID ||
1500  ISCOMPLEX(sourceType)) &&
1501  TypeCategory(targetType) == TYPCATEGORY_STRING)
1502  iscoercion = false;
1503  else
1504  iscoercion = true;
1505  break;
1506  default:
1507  iscoercion = false;
1508  break;
1509  }
1510  }
1511 
1512  if (iscoercion)
1513  {
1514  /* Treat it as a type coercion */
1515  *funcid = InvalidOid;
1516  *rettype = targetType;
1517  *retset = false;
1518  *nvargs = 0;
1519  *vatype = InvalidOid;
1520  *true_typeids = argtypes;
1521  return FUNCDETAIL_COERCION;
1522  }
1523  }
1524  }
1525 
1526  /*
1527  * didn't find an exact match, so now try to match up candidates...
1528  */
1529  if (raw_candidates != NULL)
1530  {
1531  FuncCandidateList current_candidates;
1532  int ncandidates;
1533 
1534  ncandidates = func_match_argtypes(nargs,
1535  argtypes,
1536  raw_candidates,
1537  &current_candidates);
1538 
1539  /* one match only? then run with it... */
1540  if (ncandidates == 1)
1541  best_candidate = current_candidates;
1542 
1543  /*
1544  * multiple candidates? then better decide or throw an error...
1545  */
1546  else if (ncandidates > 1)
1547  {
1548  best_candidate = func_select_candidate(nargs,
1549  argtypes,
1550  current_candidates);
1551 
1552  /*
1553  * If we were able to choose a best candidate, we're done.
1554  * Otherwise, ambiguous function call.
1555  */
1556  if (!best_candidate)
1557  return FUNCDETAIL_MULTIPLE;
1558  }
1559  }
1560  }
1561 
1562  if (best_candidate)
1563  {
1564  HeapTuple ftup;
1565  Form_pg_proc pform;
1566  FuncDetailCode result;
1567 
1568  /*
1569  * If processing named args or expanding variadics or defaults, the
1570  * "best candidate" might represent multiple equivalently good
1571  * functions; treat this case as ambiguous.
1572  */
1573  if (!OidIsValid(best_candidate->oid))
1574  return FUNCDETAIL_MULTIPLE;
1575 
1576  /*
1577  * We disallow VARIADIC with named arguments unless the last argument
1578  * (the one with VARIADIC attached) actually matched the variadic
1579  * parameter. This is mere pedantry, really, but some folks insisted.
1580  */
1581  if (fargnames != NIL && !expand_variadic && nargs > 0 &&
1582  best_candidate->argnumbers[nargs - 1] != nargs - 1)
1583  return FUNCDETAIL_NOTFOUND;
1584 
1585  *funcid = best_candidate->oid;
1586  *nvargs = best_candidate->nvargs;
1587  *true_typeids = best_candidate->args;
1588 
1589  /*
1590  * If processing named args, return actual argument positions into
1591  * NamedArgExpr nodes in the fargs list. This is a bit ugly but not
1592  * worth the extra notation needed to do it differently.
1593  */
1594  if (best_candidate->argnumbers != NULL)
1595  {
1596  int i = 0;
1597  ListCell *lc;
1598 
1599  foreach(lc, fargs)
1600  {
1601  NamedArgExpr *na = (NamedArgExpr *) lfirst(lc);
1602 
1603  if (IsA(na, NamedArgExpr))
1604  na->argnumber = best_candidate->argnumbers[i];
1605  i++;
1606  }
1607  }
1608 
1609  ftup = SearchSysCache1(PROCOID,
1610  ObjectIdGetDatum(best_candidate->oid));
1611  if (!HeapTupleIsValid(ftup)) /* should not happen */
1612  elog(ERROR, "cache lookup failed for function %u",
1613  best_candidate->oid);
1614  pform = (Form_pg_proc) GETSTRUCT(ftup);
1615  *rettype = pform->prorettype;
1616  *retset = pform->proretset;
1617  *vatype = pform->provariadic;
1618  /* fetch default args if caller wants 'em */
1619  if (argdefaults && best_candidate->ndargs > 0)
1620  {
1621  Datum proargdefaults;
1622  bool isnull;
1623  char *str;
1624  List *defaults;
1625 
1626  /* shouldn't happen, FuncnameGetCandidates messed up */
1627  if (best_candidate->ndargs > pform->pronargdefaults)
1628  elog(ERROR, "not enough default arguments");
1629 
1630  proargdefaults = SysCacheGetAttr(PROCOID, ftup,
1631  Anum_pg_proc_proargdefaults,
1632  &isnull);
1633  Assert(!isnull);
1634  str = TextDatumGetCString(proargdefaults);
1635  defaults = castNode(List, stringToNode(str));
1636  pfree(str);
1637 
1638  /* Delete any unused defaults from the returned list */
1639  if (best_candidate->argnumbers != NULL)
1640  {
1641  /*
1642  * This is a bit tricky in named notation, since the supplied
1643  * arguments could replace any subset of the defaults. We
1644  * work by making a bitmapset of the argnumbers of defaulted
1645  * arguments, then scanning the defaults list and selecting
1646  * the needed items. (This assumes that defaulted arguments
1647  * should be supplied in their positional order.)
1648  */
1649  Bitmapset *defargnumbers;
1650  int *firstdefarg;
1651  List *newdefaults;
1652  ListCell *lc;
1653  int i;
1654 
1655  defargnumbers = NULL;
1656  firstdefarg = &best_candidate->argnumbers[best_candidate->nargs - best_candidate->ndargs];
1657  for (i = 0; i < best_candidate->ndargs; i++)
1658  defargnumbers = bms_add_member(defargnumbers,
1659  firstdefarg[i]);
1660  newdefaults = NIL;
1661  i = pform->pronargs - pform->pronargdefaults;
1662  foreach(lc, defaults)
1663  {
1664  if (bms_is_member(i, defargnumbers))
1665  newdefaults = lappend(newdefaults, lfirst(lc));
1666  i++;
1667  }
1668  Assert(list_length(newdefaults) == best_candidate->ndargs);
1669  bms_free(defargnumbers);
1670  *argdefaults = newdefaults;
1671  }
1672  else
1673  {
1674  /*
1675  * Defaults for positional notation are lots easier; just
1676  * remove any unwanted ones from the front.
1677  */
1678  int ndelete;
1679 
1680  ndelete = list_length(defaults) - best_candidate->ndargs;
1681  if (ndelete > 0)
1682  defaults = list_copy_tail(defaults, ndelete);
1683  *argdefaults = defaults;
1684  }
1685  }
1686 
1687  switch (pform->prokind)
1688  {
1689  case PROKIND_AGGREGATE:
1690  result = FUNCDETAIL_AGGREGATE;
1691  break;
1692  case PROKIND_FUNCTION:
1693  result = FUNCDETAIL_NORMAL;
1694  break;
1695  case PROKIND_PROCEDURE:
1696  result = FUNCDETAIL_PROCEDURE;
1697  break;
1698  case PROKIND_WINDOW:
1699  result = FUNCDETAIL_WINDOWFUNC;
1700  break;
1701  default:
1702  elog(ERROR, "unrecognized prokind: %c", pform->prokind);
1703  result = FUNCDETAIL_NORMAL; /* keep compiler quiet */
1704  break;
1705  }
1706 
1707  ReleaseSysCache(ftup);
1708  return result;
1709  }
1710 
1711  return FUNCDETAIL_NOTFOUND;
1712 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
int func_match_argtypes(int nargs, Oid *input_typeids, FuncCandidateList raw_candidates, FuncCandidateList *candidates)
Definition: parse_func.c:910
#define castNode(_type_, nodeptr)
Definition: nodes.h:594
static Oid FuncNameAsType(List *funcname)
Definition: parse_func.c:1866
Definition: nodes.h:525
void * stringToNode(const char *str)
Definition: read.c:89
List * list_copy_tail(const List *oldlist, int nskip)
Definition: list.c:1423
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:645
CoercionPathType
Definition: parse_coerce.h:24
Oid args[FLEXIBLE_ARRAY_MEMBER]
Definition: namespace.h:37
void pfree(void *pointer)
Definition: mcxt.c:1056
#define linitial(l)
Definition: pg_list.h:195
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
FuncCandidateList FuncnameGetCandidates(List *names, int nargs, List *argnames, bool expand_variadic, bool expand_defaults, bool missing_ok)
Definition: namespace.c:934
FuncDetailCode
Definition: parse_func.h:22
struct _FuncCandidateList * next
Definition: namespace.h:30
List * lappend(List *list, void *datum)
Definition: list.c:322
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
#define TextDatumGetCString(d)
Definition: builtins.h:84
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1377
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:133
#define InvalidOid
Definition: postgres_ext.h:36
TYPCATEGORY TypeCategory(Oid type)
void bms_free(Bitmapset *a)
Definition: bitmapset.c:208
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
#define ISCOMPLEX(typeid)
Definition: parse_type.h:58
static int list_length(const List *l)
Definition: pg_list.h:169
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:736
FuncCandidateList func_select_candidate(int nargs, Oid *input_typeids, FuncCandidateList candidates)
Definition: parse_func.c:995
CoercionPathType find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId, CoercionContext ccontext, Oid *funcid)
#define elog(elevel,...)
Definition: elog.h:228
int i
Definition: pg_list.h:50
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427

◆ func_match_argtypes()

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

Definition at line 910 of file parse_func.c.

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

Referenced by func_get_detail(), and oper_select_candidate().

914 {
915  FuncCandidateList current_candidate;
916  FuncCandidateList next_candidate;
917  int ncandidates = 0;
918 
919  *candidates = NULL;
920 
921  for (current_candidate = raw_candidates;
922  current_candidate != NULL;
923  current_candidate = next_candidate)
924  {
925  next_candidate = current_candidate->next;
926  if (can_coerce_type(nargs, input_typeids, current_candidate->args,
928  {
929  current_candidate->next = *candidates;
930  *candidates = current_candidate;
931  ncandidates++;
932  }
933  }
934 
935  return ncandidates;
936 } /* func_match_argtypes() */
bool can_coerce_type(int nargs, const Oid *input_typeids, const Oid *target_typeids, CoercionContext ccontext)
Definition: parse_coerce.c:543
Oid args[FLEXIBLE_ARRAY_MEMBER]
Definition: namespace.h:37
struct _FuncCandidateList * next
Definition: namespace.h:30

◆ func_select_candidate()

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

Definition at line 995 of file parse_func.c.

References _FuncCandidateList::args, can_coerce_type(), COERCION_IMPLICIT, ereport, errcode(), errmsg_plural(), ERROR, FUNC_MAX_ARGS, get_type_category_preferred(), getBaseType(), i, IsPreferredType(), _FuncCandidateList::next, and TypeCategory().

Referenced by func_get_detail(), and oper_select_candidate().

998 {
999  FuncCandidateList current_candidate,
1000  first_candidate,
1001  last_candidate;
1002  Oid *current_typeids;
1003  Oid current_type;
1004  int i;
1005  int ncandidates;
1006  int nbestMatch,
1007  nmatch,
1008  nunknowns;
1009  Oid input_base_typeids[FUNC_MAX_ARGS];
1010  TYPCATEGORY slot_category[FUNC_MAX_ARGS],
1011  current_category;
1012  bool current_is_preferred;
1013  bool slot_has_preferred_type[FUNC_MAX_ARGS];
1014  bool resolved_unknowns;
1015 
1016  /* protect local fixed-size arrays */
1017  if (nargs > FUNC_MAX_ARGS)
1018  ereport(ERROR,
1019  (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
1020  errmsg_plural("cannot pass more than %d argument to a function",
1021  "cannot pass more than %d arguments to a function",
1022  FUNC_MAX_ARGS,
1023  FUNC_MAX_ARGS)));
1024 
1025  /*
1026  * If any input types are domains, reduce them to their base types. This
1027  * ensures that we will consider functions on the base type to be "exact
1028  * matches" in the exact-match heuristic; it also makes it possible to do
1029  * something useful with the type-category heuristics. Note that this
1030  * makes it difficult, but not impossible, to use functions declared to
1031  * take a domain as an input datatype. Such a function will be selected
1032  * over the base-type function only if it is an exact match at all
1033  * argument positions, and so was already chosen by our caller.
1034  *
1035  * While we're at it, count the number of unknown-type arguments for use
1036  * later.
1037  */
1038  nunknowns = 0;
1039  for (i = 0; i < nargs; i++)
1040  {
1041  if (input_typeids[i] != UNKNOWNOID)
1042  input_base_typeids[i] = getBaseType(input_typeids[i]);
1043  else
1044  {
1045  /* no need to call getBaseType on UNKNOWNOID */
1046  input_base_typeids[i] = UNKNOWNOID;
1047  nunknowns++;
1048  }
1049  }
1050 
1051  /*
1052  * Run through all candidates and keep those with the most matches on
1053  * exact types. Keep all candidates if none match.
1054  */
1055  ncandidates = 0;
1056  nbestMatch = 0;
1057  last_candidate = NULL;
1058  for (current_candidate = candidates;
1059  current_candidate != NULL;
1060  current_candidate = current_candidate->next)
1061  {
1062  current_typeids = current_candidate->args;
1063  nmatch = 0;
1064  for (i = 0; i < nargs; i++)
1065  {
1066  if (input_base_typeids[i] != UNKNOWNOID &&
1067  current_typeids[i] == input_base_typeids[i])
1068  nmatch++;
1069  }
1070 
1071  /* take this one as the best choice so far? */
1072  if ((nmatch > nbestMatch) || (last_candidate == NULL))
1073  {
1074  nbestMatch = nmatch;
1075  candidates = current_candidate;
1076  last_candidate = current_candidate;
1077  ncandidates = 1;
1078  }
1079  /* no worse than the last choice, so keep this one too? */
1080  else if (nmatch == nbestMatch)
1081  {
1082  last_candidate->next = current_candidate;
1083  last_candidate = current_candidate;
1084  ncandidates++;
1085  }
1086  /* otherwise, don't bother keeping this one... */
1087  }
1088 
1089  if (last_candidate) /* terminate rebuilt list */
1090  last_candidate->next = NULL;
1091 
1092  if (ncandidates == 1)
1093  return candidates;
1094 
1095  /*
1096  * Still too many candidates? Now look for candidates which have either
1097  * exact matches or preferred types at the args that will require
1098  * coercion. (Restriction added in 7.4: preferred type must be of same
1099  * category as input type; give no preference to cross-category
1100  * conversions to preferred types.) Keep all candidates if none match.
1101  */
1102  for (i = 0; i < nargs; i++) /* avoid multiple lookups */
1103  slot_category[i] = TypeCategory(input_base_typeids[i]);
1104  ncandidates = 0;
1105  nbestMatch = 0;
1106  last_candidate = NULL;
1107  for (current_candidate = candidates;
1108  current_candidate != NULL;
1109  current_candidate = current_candidate->next)
1110  {
1111  current_typeids = current_candidate->args;
1112  nmatch = 0;
1113  for (i = 0; i < nargs; i++)
1114  {
1115  if (input_base_typeids[i] != UNKNOWNOID)
1116  {
1117  if (current_typeids[i] == input_base_typeids[i] ||
1118  IsPreferredType(slot_category[i], current_typeids[i]))
1119  nmatch++;
1120  }
1121  }
1122 
1123  if ((nmatch > nbestMatch) || (last_candidate == NULL))
1124  {
1125  nbestMatch = nmatch;
1126  candidates = current_candidate;
1127  last_candidate = current_candidate;
1128  ncandidates = 1;
1129  }
1130  else if (nmatch == nbestMatch)
1131  {
1132  last_candidate->next = current_candidate;
1133  last_candidate = current_candidate;
1134  ncandidates++;
1135  }
1136  }
1137 
1138  if (last_candidate) /* terminate rebuilt list */
1139  last_candidate->next = NULL;
1140 
1141  if (ncandidates == 1)
1142  return candidates;
1143 
1144  /*
1145  * Still too many candidates? Try assigning types for the unknown inputs.
1146  *
1147  * If there are no unknown inputs, we have no more heuristics that apply,
1148  * and must fail.
1149  */
1150  if (nunknowns == 0)
1151  return NULL; /* failed to select a best candidate */
1152 
1153  /*
1154  * The next step examines each unknown argument position to see if we can
1155  * determine a "type category" for it. If any candidate has an input
1156  * datatype of STRING category, use STRING category (this bias towards
1157  * STRING is appropriate since unknown-type literals look like strings).
1158  * Otherwise, if all the candidates agree on the type category of this
1159  * argument position, use that category. Otherwise, fail because we
1160  * cannot determine a category.
1161  *
1162  * If we are able to determine a type category, also notice whether any of
1163  * the candidates takes a preferred datatype within the category.
1164  *
1165  * Having completed this examination, remove candidates that accept the
1166  * wrong category at any unknown position. Also, if at least one
1167  * candidate accepted a preferred type at a position, remove candidates
1168  * that accept non-preferred types. If just one candidate remains, return
1169  * that one. However, if this rule turns out to reject all candidates,
1170  * keep them all instead.
1171  */
1172  resolved_unknowns = false;
1173  for (i = 0; i < nargs; i++)
1174  {
1175  bool have_conflict;
1176 
1177  if (input_base_typeids[i] != UNKNOWNOID)
1178  continue;
1179  resolved_unknowns = true; /* assume we can do it */
1180  slot_category[i] = TYPCATEGORY_INVALID;
1181  slot_has_preferred_type[i] = false;
1182  have_conflict = false;
1183  for (current_candidate = candidates;
1184  current_candidate != NULL;
1185  current_candidate = current_candidate->next)
1186  {
1187  current_typeids = current_candidate->args;
1188  current_type = current_typeids[i];
1189  get_type_category_preferred(current_type,
1190  &current_category,
1191  &current_is_preferred);
1192  if (slot_category[i] == TYPCATEGORY_INVALID)
1193  {
1194  /* first candidate */
1195  slot_category[i] = current_category;
1196  slot_has_preferred_type[i] = current_is_preferred;
1197  }
1198  else if (current_category == slot_category[i])
1199  {
1200  /* more candidates in same category */
1201  slot_has_preferred_type[i] |= current_is_preferred;
1202  }
1203  else
1204  {
1205  /* category conflict! */
1206  if (current_category == TYPCATEGORY_STRING)
1207  {
1208  /* STRING always wins if available */
1209  slot_category[i] = current_category;
1210  slot_has_preferred_type[i] = current_is_preferred;
1211  }
1212  else
1213  {
1214  /*
1215  * Remember conflict, but keep going (might find STRING)
1216  */
1217  have_conflict = true;
1218  }
1219  }
1220  }
1221  if (have_conflict && slot_category[i] != TYPCATEGORY_STRING)
1222  {
1223  /* Failed to resolve category conflict at this position */
1224  resolved_unknowns = false;
1225  break;
1226  }
1227  }
1228 
1229  if (resolved_unknowns)
1230  {
1231  /* Strip non-matching candidates */
1232  ncandidates = 0;
1233  first_candidate = candidates;
1234  last_candidate = NULL;
1235  for (current_candidate = candidates;
1236  current_candidate != NULL;
1237  current_candidate = current_candidate->next)
1238  {
1239  bool keepit = true;
1240 
1241  current_typeids = current_candidate->args;
1242  for (i = 0; i < nargs; i++)
1243  {
1244  if (input_base_typeids[i] != UNKNOWNOID)
1245  continue;
1246  current_type = current_typeids[i];
1247  get_type_category_preferred(current_type,
1248  &current_category,
1249  &current_is_preferred);
1250  if (current_category != slot_category[i])
1251  {
1252  keepit = false;
1253  break;
1254  }
1255  if (slot_has_preferred_type[i] && !current_is_preferred)
1256  {
1257  keepit = false;
1258  break;
1259  }
1260  }
1261  if (keepit)
1262  {
1263  /* keep this candidate */
1264  last_candidate = current_candidate;
1265  ncandidates++;
1266  }
1267  else
1268  {
1269  /* forget this candidate */
1270  if (last_candidate)
1271  last_candidate->next = current_candidate->next;
1272  else
1273  first_candidate = current_candidate->next;
1274  }
1275  }
1276 
1277  /* if we found any matches, restrict our attention to those */
1278  if (last_candidate)
1279  {
1280  candidates = first_candidate;
1281  /* terminate rebuilt list */
1282  last_candidate->next = NULL;
1283  }
1284 
1285  if (ncandidates == 1)
1286  return candidates;
1287  }
1288 
1289  /*
1290  * Last gasp: if there are both known- and unknown-type inputs, and all
1291  * the known types are the same, assume the unknown inputs are also that
1292  * type, and see if that gives us a unique match. If so, use that match.
1293  *
1294  * NOTE: for a binary operator with one unknown and one non-unknown input,
1295  * we already tried this heuristic in binary_oper_exact(). However, that
1296  * code only finds exact matches, whereas here we will handle matches that
1297  * involve coercion, polymorphic type resolution, etc.
1298  */
1299  if (nunknowns < nargs)
1300  {
1301  Oid known_type = UNKNOWNOID;
1302 
1303  for (i = 0; i < nargs; i++)
1304  {
1305  if (input_base_typeids[i] == UNKNOWNOID)
1306  continue;
1307  if (known_type == UNKNOWNOID) /* first known arg? */
1308  known_type = input_base_typeids[i];
1309  else if (known_type != input_base_typeids[i])
1310  {
1311  /* oops, not all match */
1312  known_type = UNKNOWNOID;
1313  break;
1314  }
1315  }
1316 
1317  if (known_type != UNKNOWNOID)
1318  {
1319  /* okay, just one known type, apply the heuristic */
1320  for (i = 0; i < nargs; i++)
1321  input_base_typeids[i] = known_type;
1322  ncandidates = 0;
1323  last_candidate = NULL;
1324  for (current_candidate = candidates;
1325  current_candidate != NULL;
1326  current_candidate = current_candidate->next)
1327  {
1328  current_typeids = current_candidate->args;
1329  if (can_coerce_type(nargs, input_base_typeids, current_typeids,
1331  {
1332  if (++ncandidates > 1)
1333  break; /* not unique, give up */
1334  last_candidate = current_candidate;
1335  }
1336  }
1337  if (ncandidates == 1)
1338  {
1339  /* successfully identified a unique match */
1340  last_candidate->next = NULL;
1341  return last_candidate;
1342  }
1343  }
1344  }
1345 
1346  return NULL; /* failed to select a best candidate */
1347 } /* func_select_candidate() */
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:932
bool can_coerce_type(int nargs, const Oid *input_typeids, const Oid *target_typeids, CoercionContext ccontext)
Definition: parse_coerce.c:543
int errcode(int sqlerrcode)
Definition: elog.c:608
unsigned int Oid
Definition: postgres_ext.h:31
bool IsPreferredType(TYPCATEGORY category, Oid type)
#define FUNC_MAX_ARGS
char TYPCATEGORY
Definition: parse_coerce.h:21
Oid args[FLEXIBLE_ARRAY_MEMBER]
Definition: namespace.h:37
#define ERROR
Definition: elog.h:43
struct _FuncCandidateList * next
Definition: namespace.h:30
#define ereport(elevel, rest)
Definition: elog.h:141
TYPCATEGORY TypeCategory(Oid type)
int i
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2299
void get_type_category_preferred(Oid typid, char *typcategory, bool *typispreferred)
Definition: lsyscache.c:2478

◆ 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 1976 of file parse_func.c.

References appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), StringInfoData::data, format_type_be(), i, initStringInfo(), lfirst, list_head(), list_length(), and lnext().

Referenced by func_signature_string(), and IsThereFunctionInNamespace().

1978 {
1979  StringInfoData argbuf;
1980  int numposargs;
1981  ListCell *lc;
1982  int i;
1983 
1984  initStringInfo(&argbuf);
1985 
1986  appendStringInfo(&argbuf, "%s(", funcname);
1987 
1988  numposargs = nargs - list_length(argnames);
1989  lc = list_head(argnames);
1990 
1991  for (i = 0; i < nargs; i++)
1992  {
1993  if (i)
1994  appendStringInfoString(&argbuf, ", ");
1995  if (i >= numposargs)
1996  {
1997  appendStringInfo(&argbuf, "%s => ", (char *) lfirst(lc));
1998  lc = lnext(argnames, lc);
1999  }
2000  appendStringInfoString(&argbuf, format_type_be(argtypes[i]));
2001  }
2002 
2003  appendStringInfoChar(&argbuf, ')');
2004 
2005  return argbuf.data; /* return palloc'd string buffer */
2006 }
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:321
char * format_type_be(Oid type_oid)
Definition: format_type.c:326
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
#define lfirst(lc)
Definition: pg_list.h:190
static int list_length(const List *l)
Definition: pg_list.h:169
int i

◆ FuncNameAsType()

static Oid FuncNameAsType ( List funcname)
static

Definition at line 1866 of file parse_func.c.

References GETSTRUCT, InvalidOid, LookupTypeNameExtended(), makeTypeNameFromNameList(), OidIsValid, ReleaseSysCache(), typeTypeId(), and typeTypeRelid().

Referenced by func_get_detail().

1867 {
1868  Oid result;
1869  Type typtup;
1870 
1871  /*
1872  * temp_ok=false protects the <refsect1 id="sql-createfunction-security">
1873  * contract for writing SECURITY DEFINER functions safely.
1874  */
1875  typtup = LookupTypeNameExtended(NULL, makeTypeNameFromNameList(funcname),
1876  NULL, false, false);
1877  if (typtup == NULL)
1878  return InvalidOid;
1879 
1880  if (((Form_pg_type) GETSTRUCT(typtup))->typisdefined &&
1881  !OidIsValid(typeTypeRelid(typtup)))
1882  result = typeTypeId(typtup);
1883  else
1884  result = InvalidOid;
1885 
1886  ReleaseSysCache(typtup);
1887  return result;
1888 }
Type LookupTypeNameExtended(ParseState *pstate, const TypeName *typeName, int32 *typmod_p, bool temp_ok, bool missing_ok)
Definition: parse_type.c:73
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:645
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define InvalidOid
Definition: postgres_ext.h:36
FormData_pg_type * Form_pg_type
Definition: pg_type.h:250
Oid typeTypeRelid(Type typ)
Definition: parse_type.c:628
TypeName * makeTypeNameFromNameList(List *names)
Definition: makefuncs.c:454
Oid typeTypeId(Type tp)
Definition: parse_type.c:588

◆ LookupFuncName()

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

Definition at line 2101 of file parse_func.c.

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

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

2102 {
2103  Oid funcoid;
2104  FuncLookupError lookupError;
2105 
2106  funcoid = LookupFuncNameInternal(funcname, nargs, argtypes, missing_ok,
2107  &lookupError);
2108 
2109  if (OidIsValid(funcoid))
2110  return funcoid;
2111 
2112  switch (lookupError)
2113  {
2114  case FUNCLOOKUP_NOSUCHFUNC:
2115  /* Let the caller deal with it when missing_ok is true */
2116  if (missing_ok)
2117  return InvalidOid;
2118 
2119  if (nargs < 0)
2120  ereport(ERROR,
2121  (errcode(ERRCODE_UNDEFINED_FUNCTION),
2122  errmsg("could not find a function named \"%s\"",
2123  NameListToString(funcname))));
2124  else
2125  ereport(ERROR,
2126  (errcode(ERRCODE_UNDEFINED_FUNCTION),
2127  errmsg("function %s does not exist",
2128  func_signature_string(funcname, nargs,
2129  NIL, argtypes))));
2130  break;
2131 
2132  case FUNCLOOKUP_AMBIGUOUS:
2133  /* Raise an error regardless of missing_ok */
2134  ereport(ERROR,
2135  (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
2136  errmsg("function name \"%s\" is not unique",
2137  NameListToString(funcname)),
2138  errhint("Specify the argument list to select the function unambiguously.")));
2139  break;
2140  }
2141 
2142  return InvalidOid; /* Keep compiler quiet */
2143 }
#define NIL
Definition: pg_list.h:65
int errhint(const char *fmt,...)
Definition: elog.c:1069
int errcode(int sqlerrcode)
Definition: elog.c:608
FuncLookupError
Definition: parse_func.c:39
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:645
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:141
const char * func_signature_string(List *funcname, int nargs, List *argnames, const Oid *argtypes)
Definition: parse_func.c:2013
char * NameListToString(List *names)
Definition: namespace.c:3094
#define InvalidOid
Definition: postgres_ext.h:36
int errmsg(const char *fmt,...)
Definition: elog.c:822
static Oid LookupFuncNameInternal(List *funcname, int nargs, const Oid *argtypes, bool missing_ok, FuncLookupError *lookupError)
Definition: parse_func.c:2032

◆ LookupFuncNameInternal()

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

Definition at line 2032 of file parse_func.c.

References _FuncCandidateList::args, Assert, FUNCLOOKUP_AMBIGUOUS, FUNCLOOKUP_NOSUCHFUNC, FuncnameGetCandidates(), InvalidOid, _FuncCandidateList::next, NIL, and _FuncCandidateList::oid.

Referenced by LookupFuncName(), and LookupFuncWithArgs().

2034 {
2035  FuncCandidateList clist;
2036 
2037  /* NULL argtypes allowed for nullary functions only */
2038  Assert(argtypes != NULL || nargs == 0);
2039 
2040  /* Always set *lookupError, to forestall uninitialized-variable warnings */
2041  *lookupError = FUNCLOOKUP_NOSUCHFUNC;
2042 
2043  clist = FuncnameGetCandidates(funcname, nargs, NIL, false, false,
2044  missing_ok);
2045 
2046  /*
2047  * If no arguments were specified, the name must yield a unique candidate.
2048  */
2049  if (nargs < 0)
2050  {
2051  if (clist)
2052  {
2053  /* If there is a second match then it's ambiguous */
2054  if (clist->next)
2055  {
2056  *lookupError = FUNCLOOKUP_AMBIGUOUS;
2057  return InvalidOid;
2058  }
2059  /* Otherwise return the match */
2060  return clist->oid;
2061  }
2062  else
2063  return InvalidOid;
2064  }
2065 
2066  /*
2067  * Otherwise, look for a match to the arg types. FuncnameGetCandidates
2068  * has ensured that there's at most one match in the returned list.
2069  */
2070  while (clist)
2071  {
2072  /* if nargs==0, argtypes can be null; don't pass that to memcmp */
2073  if (nargs == 0 ||
2074  memcmp(argtypes, clist->args, nargs * sizeof(Oid)) == 0)
2075  return clist->oid;
2076  clist = clist->next;
2077  }
2078 
2079  return InvalidOid;
2080 }
#define NIL
Definition: pg_list.h:65
unsigned int Oid
Definition: postgres_ext.h:31
Oid args[FLEXIBLE_ARRAY_MEMBER]
Definition: namespace.h:37
FuncCandidateList FuncnameGetCandidates(List *names, int nargs, List *argnames, bool expand_variadic, bool expand_defaults, bool missing_ok)
Definition: namespace.c:934
struct _FuncCandidateList * next
Definition: namespace.h:30
#define InvalidOid
Definition: postgres_ext.h:36
#define Assert(condition)
Definition: c.h:739

◆ LookupFuncWithArgs()

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

Definition at line 2161 of file parse_func.c.

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

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

2162 {
2163  Oid argoids[FUNC_MAX_ARGS];
2164  int argcount;
2165  int nargs;
2166  int i;
2167  ListCell *args_item;
2168  Oid oid;
2169  FuncLookupError lookupError;
2170 
2171  Assert(objtype == OBJECT_AGGREGATE ||
2172  objtype == OBJECT_FUNCTION ||
2173  objtype == OBJECT_PROCEDURE ||
2174  objtype == OBJECT_ROUTINE);
2175 
2176  argcount = list_length(func->objargs);
2177  if (argcount > FUNC_MAX_ARGS)
2178  {
2179  if (objtype == OBJECT_PROCEDURE)
2180  ereport(ERROR,
2181  (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
2182  errmsg_plural("procedures cannot have more than %d argument",
2183  "procedures cannot have more than %d arguments",
2184  FUNC_MAX_ARGS,
2185  FUNC_MAX_ARGS)));
2186  else
2187  ereport(ERROR,
2188  (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
2189  errmsg_plural("functions cannot have more than %d argument",
2190  "functions cannot have more than %d arguments",
2191  FUNC_MAX_ARGS,
2192  FUNC_MAX_ARGS)));
2193  }
2194 
2195  i = 0;
2196  foreach(args_item, func->objargs)
2197  {
2198  TypeName *t = (TypeName *) lfirst(args_item);
2199 
2200  argoids[i] = LookupTypeNameOid(NULL, t, missing_ok);
2201  if (!OidIsValid(argoids[i]))
2202  return InvalidOid; /* missing_ok must be true */
2203  i++;
2204  }
2205 
2206  /*
2207  * Set nargs for LookupFuncNameInternal. It expects -1 to mean no args
2208  * were specified.
2209  */
2210  nargs = func->args_unspecified ? -1 : argcount;
2211 
2212  oid = LookupFuncNameInternal(func->objname, nargs, argoids, missing_ok,
2213  &lookupError);
2214 
2215  if (OidIsValid(oid))
2216  {
2217  /*
2218  * Even if we found the function, perform validation that the objtype
2219  * matches the prokind of the found function. For historical reasons
2220  * we allow the objtype of FUNCTION to include aggregates and window
2221  * functions; but we draw the line if the object is a procedure. That
2222  * is a new enough feature that this historical rule does not apply.
2223  */
2224  switch (objtype)
2225  {
2226  case OBJECT_FUNCTION:
2227  /* Only complain if it's a procedure. */
2228  if (get_func_prokind(oid) == PROKIND_PROCEDURE)
2229  ereport(ERROR,
2230  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2231  errmsg("%s is not a function",
2232  func_signature_string(func->objname, argcount,
2233  NIL, argoids))));
2234  break;
2235 
2236  case OBJECT_PROCEDURE:
2237  /* Reject if found object is not a procedure. */
2238  if (get_func_prokind(oid) != PROKIND_PROCEDURE)
2239  ereport(ERROR,
2240  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2241  errmsg("%s is not a procedure",
2242  func_signature_string(func->objname, argcount,
2243  NIL, argoids))));
2244  break;
2245 
2246  case OBJECT_AGGREGATE:
2247  /* Reject if found object is not an aggregate. */
2248  if (get_func_prokind(oid) != PROKIND_AGGREGATE)
2249  ereport(ERROR,
2250  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2251  errmsg("function %s is not an aggregate",
2252  func_signature_string(func->objname, argcount,
2253  NIL, argoids))));
2254  break;
2255 
2256  default:
2257  /* OBJECT_ROUTINE accepts anything. */
2258  break;
2259  }
2260 
2261  return oid; /* All good */
2262  }
2263  else
2264  {
2265  /* Deal with cases where the lookup failed */
2266  switch (lookupError)
2267  {
2268  case FUNCLOOKUP_NOSUCHFUNC:
2269  /* Suppress no-such-func errors when missing_ok is true */
2270  if (missing_ok)
2271  break;
2272 
2273  switch (objtype)
2274  {
2275  case OBJECT_PROCEDURE:
2276  if (func->args_unspecified)
2277  ereport(ERROR,
2278  (errcode(ERRCODE_UNDEFINED_FUNCTION),
2279  errmsg("could not find a procedure named \"%s\"",
2280  NameListToString(func->objname))));
2281  else
2282  ereport(ERROR,
2283  (errcode(ERRCODE_UNDEFINED_FUNCTION),
2284  errmsg("procedure %s does not exist",
2285  func_signature_string(func->objname, argcount,
2286  NIL, argoids))));
2287  break;
2288 
2289  case OBJECT_AGGREGATE:
2290  if (func->args_unspecified)
2291  ereport(ERROR,
2292  (errcode(ERRCODE_UNDEFINED_FUNCTION),
2293  errmsg("could not find an aggregate named \"%s\"",
2294  NameListToString(func->objname))));
2295  else if (argcount == 0)
2296  ereport(ERROR,
2297  (errcode(ERRCODE_UNDEFINED_FUNCTION),
2298  errmsg("aggregate %s(*) does not exist",
2299  NameListToString(func->objname))));
2300  else
2301  ereport(ERROR,
2302  (errcode(ERRCODE_UNDEFINED_FUNCTION),
2303  errmsg("aggregate %s does not exist",
2304  func_signature_string(func->objname, argcount,
2305  NIL, argoids))));
2306  break;
2307 
2308  default:
2309  /* FUNCTION and ROUTINE */
2310  if (func->args_unspecified)
2311  ereport(ERROR,
2312  (errcode(ERRCODE_UNDEFINED_FUNCTION),
2313  errmsg("could not find a function named \"%s\"",
2314  NameListToString(func->objname))));
2315  else
2316  ereport(ERROR,
2317  (errcode(ERRCODE_UNDEFINED_FUNCTION),
2318  errmsg("function %s does not exist",
2319  func_signature_string(func->objname, argcount,
2320  NIL, argoids))));
2321  break;
2322  }
2323  break;
2324 
2325  case FUNCLOOKUP_AMBIGUOUS:
2326  switch (objtype)
2327  {
2328  case OBJECT_FUNCTION:
2329  ereport(ERROR,
2330  (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
2331  errmsg("function name \"%s\" is not unique",
2332  NameListToString(func->objname)),
2333  errhint("Specify the argument list to select the function unambiguously.")));
2334  break;
2335  case OBJECT_PROCEDURE:
2336  ereport(ERROR,
2337  (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
2338  errmsg("procedure name \"%s\" is not unique",
2339  NameListToString(func->objname)),
2340  errhint("Specify the argument list to select the procedure unambiguously.")));
2341  break;
2342  case OBJECT_AGGREGATE:
2343  ereport(ERROR,
2344  (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
2345  errmsg("aggregate name \"%s\" is not unique",
2346  NameListToString(func->objname)),
2347  errhint("Specify the argument list to select the aggregate unambiguously.")));
2348  break;
2349  case OBJECT_ROUTINE:
2350  ereport(ERROR,
2351  (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
2352  errmsg("routine name \"%s\" is not unique",
2353  NameListToString(func->objname)),
2354  errhint("Specify the argument list to select the routine unambiguously.")));
2355  break;
2356 
2357  default:
2358  Assert(false); /* Disallowed by Assert above */
2359  break;
2360  }
2361  break;
2362  }
2363 
2364  return InvalidOid;
2365  }
2366 }
#define NIL
Definition: pg_list.h:65
int errhint(const char *fmt,...)
Definition: elog.c:1069
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:932
int errcode(int sqlerrcode)
Definition: elog.c:608
FuncLookupError
Definition: parse_func.c:39
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:645
#define FUNC_MAX_ARGS
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:141
bool args_unspecified
Definition: parsenodes.h:1926
const char * func_signature_string(List *funcname, int nargs, List *argnames, const Oid *argtypes)
Definition: parse_func.c:2013
char * NameListToString(List *names)
Definition: namespace.c:3094
char get_func_prokind(Oid funcid)
Definition: lsyscache.c:1620
#define InvalidOid
Definition: postgres_ext.h:36
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
static int list_length(const List *l)
Definition: pg_list.h:169
int errmsg(const char *fmt,...)
Definition: elog.c:822
int i
static Oid LookupFuncNameInternal(List *funcname, int nargs, const Oid *argtypes, bool missing_ok, FuncLookupError *lookupError)
Definition: parse_func.c:2032
Oid LookupTypeNameOid(ParseState *pstate, const TypeName *typeName, bool missing_ok)
Definition: parse_type.c:232

◆ make_fn_arguments()

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

Definition at line 1810 of file parse_func.c.

References NamedArgExpr::arg, COERCE_IMPLICIT_CAST, coerce_type(), COERCION_IMPLICIT, i, IsA, and lfirst.

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

1814 {
1815  ListCell *current_fargs;
1816  int i = 0;
1817 
1818  foreach(current_fargs, fargs)
1819  {
1820  /* types don't match? then force coercion using a function call... */
1821  if (actual_arg_types[i] != declared_arg_types[i])
1822  {
1823  Node *node = (Node *) lfirst(current_fargs);
1824 
1825  /*
1826  * If arg is a NamedArgExpr, coerce its input expr instead --- we
1827  * want the NamedArgExpr to stay at the top level of the list.
1828  */
1829  if (IsA(node, NamedArgExpr))
1830  {
1831  NamedArgExpr *na = (NamedArgExpr *) node;
1832 
1833  node = coerce_type(pstate,
1834  (Node *) na->arg,
1835  actual_arg_types[i],
1836  declared_arg_types[i], -1,
1839  -1);
1840  na->arg = (Expr *) node;
1841  }
1842  else
1843  {
1844  node = coerce_type(pstate,
1845  node,
1846  actual_arg_types[i],
1847  declared_arg_types[i], -1,
1850  -1);
1851  lfirst(current_fargs) = node;
1852  }
1853  }
1854  i++;
1855  }
1856 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
Node * coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:156
Definition: nodes.h:525
Expr * arg
Definition: primnodes.h:484
#define lfirst(lc)
Definition: pg_list.h:190
int i

◆ ParseComplexProjection()

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

Definition at line 1897 of file parse_func.c.

References FieldSelect::arg, expandRecordVariable(), FieldSelect::fieldnum, get_expr_result_tupdesc(), GetRTEByRangeTablePosn(), i, InvalidAttrNumber, IsA, makeNode, NameStr, TupleDescData::natts, FieldSelect::resultcollid, FieldSelect::resulttype, FieldSelect::resulttypmod, scanRTEForColumn(), and TupleDescAttr.

Referenced by ParseFuncOrColumn().

1899 {
1900  TupleDesc tupdesc;
1901  int i;
1902 
1903  /*
1904  * Special case for whole-row Vars so that we can resolve (foo.*).bar even
1905  * when foo is a reference to a subselect, join, or RECORD function. A
1906  * bonus is that we avoid generating an unnecessary FieldSelect; our
1907  * result can omit the whole-row Var and just be a Var for the selected
1908  * field.
1909  *
1910  * This case could be handled by expandRecordVariable, but it's more
1911  * efficient to do it this way when possible.
1912  */
1913  if (IsA(first_arg, Var) &&
1914  ((Var *) first_arg)->varattno == InvalidAttrNumber)
1915  {
1916  RangeTblEntry *rte;
1917 
1918  rte = GetRTEByRangeTablePosn(pstate,
1919  ((Var *) first_arg)->varno,
1920  ((Var *) first_arg)->varlevelsup);
1921  /* Return a Var if funcname matches a column, else NULL */
1922  return scanRTEForColumn(pstate, rte, funcname, location, 0, NULL);
1923  }
1924 
1925  /*
1926  * Else do it the hard way with get_expr_result_tupdesc().
1927  *
1928  * If it's a Var of type RECORD, we have to work even harder: we have to
1929  * find what the Var refers to, and pass that to get_expr_result_tupdesc.
1930  * That task is handled by expandRecordVariable().
1931  */
1932  if (IsA(first_arg, Var) &&
1933  ((Var *) first_arg)->vartype == RECORDOID)
1934  tupdesc = expandRecordVariable(pstate, (Var *) first_arg, 0);
1935  else
1936  tupdesc = get_expr_result_tupdesc(first_arg, true);
1937  if (!tupdesc)
1938  return NULL; /* unresolvable RECORD type */
1939 
1940  for (i = 0; i < tupdesc->natts; i++)
1941  {
1942  Form_pg_attribute att = TupleDescAttr(tupdesc, i);
1943 
1944  if (strcmp(funcname, NameStr(att->attname)) == 0 &&
1945  !att->attisdropped)
1946  {
1947  /* Success, so generate a FieldSelect expression */
1948  FieldSelect *fselect = makeNode(FieldSelect);
1949 
1950  fselect->arg = (Expr *) first_arg;
1951  fselect->fieldnum = i + 1;
1952  fselect->resulttype = att->atttypid;
1953  fselect->resulttypmod = att->atttypmod;
1954  /* save attribute's collation for parse_collate.c */
1955  fselect->resultcollid = att->attcollation;
1956  return (Node *) fselect;
1957  }
1958  }
1959 
1960  return NULL; /* funcname does not match any column */
1961 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
Oid resulttype
Definition: primnodes.h:750
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
Definition: nodes.h:525
Expr * arg
Definition: primnodes.h:748
Definition: primnodes.h:167
Node * scanRTEForColumn(ParseState *pstate, RangeTblEntry *rte, const char *colname, int location, int fuzzy_rte_penalty, FuzzyAttrMatchState *fuzzystate)
TupleDesc get_expr_result_tupdesc(Node *expr, bool noError)
Definition: funcapi.c:429
Oid resultcollid
Definition: primnodes.h:753
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
TupleDesc expandRecordVariable(ParseState *pstate, Var *var, int levelsup)
RangeTblEntry * GetRTEByRangeTablePosn(ParseState *pstate, int varno, int sublevels_up)
#define makeNode(_type_)
Definition: nodes.h:573
#define InvalidAttrNumber
Definition: attnum.h:23
int i
#define NameStr(name)
Definition: c.h:616
int32 resulttypmod
Definition: primnodes.h:752
AttrNumber fieldnum
Definition: primnodes.h:749

◆ ParseFuncOrColumn()

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

Definition at line 88 of file parse_func.c.

References FuncCall::agg_distinct, FuncCall::agg_filter, FuncCall::agg_order, FuncCall::agg_star, FuncCall::agg_within_group, Aggref::aggfilter, WindowFunc::aggfilter, AGGFNOID, Aggref::aggfnoid, Aggref::aggkind, Aggref::aggsplit, AGGSPLIT_SIMPLE, Aggref::aggstar, Aggref::aggtranstype, Aggref::aggtype, Aggref::aggvariadic, arg, WindowFunc::args, FuncExpr::args, ArrayExpr::array_typeid, Assert, cancel_parser_errposition_callback(), check_srf_call_placement(), COERCE_EXPLICIT_CALL, coerce_type(), COERCION_EXPLICIT, ArrayExpr::element_typeid, ArrayExpr::elements, elog, enforce_generic_type_consistency(), ereport, errcode(), errhint(), errmsg(), errmsg_plural(), ERROR, EXPR_KIND_FILTER, exprLocation(), exprType(), foreach_delete_current, format_type_be(), func_get_detail(), FUNC_MAX_ARGS, func_signature_string(), FuncCall::func_variadic, FUNCDETAIL_AGGREGATE, FUNCDETAIL_COERCION, FUNCDETAIL_MULTIPLE, FUNCDETAIL_NORMAL, FUNCDETAIL_PROCEDURE, FUNCDETAIL_WINDOWFUNC, FuncExpr::funcformat, FuncExpr::funcid, FuncExpr::funcresulttype, FuncExpr::funcretset, FuncExpr::funcvariadic, get_array_type(), get_base_element_type(), GETSTRUCT, HeapTupleIsValid, InvalidOid, IsA, ISCOMPLEX, lappend(), lfirst, linitial, list_copy_tail(), list_length(), list_truncate(), llast, Aggref::location, WindowFunc::location, FuncExpr::location, NamedArgExpr::location, ArrayExpr::location, make_fn_arguments(), makeNode, ArrayExpr::multidims, NamedArgExpr::name, NameListToString(), NIL, ObjectIdGetDatum, OidIsValid, FuncCall::over, ParseState::p_last_srf, ParseComplexProjection(), parser_errposition(), pronargs, ReleaseSysCache(), SearchSysCache1(), setup_parser_errposition_callback(), strVal, transformAggregateCall(), transformWhereClause(), transformWindowFuncCall(), unify_hypothetical_args(), WindowFunc::winagg, WindowFunc::winfnoid, WindowFunc::winstar, and WindowFunc::wintype.

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

90 {
91  bool is_column = (fn == NULL);
92  List *agg_order = (fn ? fn->agg_order : NIL);
93  Expr *agg_filter = NULL;
94  bool agg_within_group = (fn ? fn->agg_within_group : false);
95  bool agg_star = (fn ? fn->agg_star : false);
96  bool agg_distinct = (fn ? fn->agg_distinct : false);
97  bool func_variadic = (fn ? fn->func_variadic : false);
98  WindowDef *over = (fn ? fn->over : NULL);
99  bool could_be_projection;
100  Oid rettype;
101  Oid funcid;
102  ListCell *l;
103  Node *first_arg = NULL;
104  int nargs;
105  int nargsplusdefs;
106  Oid actual_arg_types[FUNC_MAX_ARGS];
107  Oid *declared_arg_types;
108  List *argnames;
109  List *argdefaults;
110  Node *retval;
111  bool retset;
112  int nvargs;
113  Oid vatype;
114  FuncDetailCode fdresult;
115  char aggkind = 0;
116  ParseCallbackState pcbstate;
117 
118  /*
119  * If there's an aggregate filter, transform it using transformWhereClause
120  */
121  if (fn && fn->agg_filter != NULL)
122  agg_filter = (Expr *) transformWhereClause(pstate, fn->agg_filter,
124  "FILTER");
125 
126  /*
127  * Most of the rest of the parser just assumes that functions do not have
128  * more than FUNC_MAX_ARGS parameters. We have to test here to protect
129  * against array overruns, etc. Of course, this may not be a function,
130  * but the test doesn't hurt.
131  */
132  if (list_length(fargs) > FUNC_MAX_ARGS)
133  ereport(ERROR,
134  (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
135  errmsg_plural("cannot pass more than %d argument to a function",
136  "cannot pass more than %d arguments to a function",
138  FUNC_MAX_ARGS),
139  parser_errposition(pstate, location)));
140 
141  /*
142  * Extract arg type info in preparation for function lookup.
143  *
144  * If any arguments are Param markers of type VOID, we discard them from
145  * the parameter list. This is a hack to allow the JDBC driver to not have
146  * to distinguish "input" and "output" parameter symbols while parsing
147  * function-call constructs. Don't do this if dealing with column syntax,
148  * nor if we had WITHIN GROUP (because in that case it's critical to keep
149  * the argument count unchanged).
150  */
151  nargs = 0;
152  foreach(l, fargs)
153  {
154  Node *arg = lfirst(l);
155  Oid argtype = exprType(arg);
156 
157  if (argtype == VOIDOID && IsA(arg, Param) &&
158  !is_column && !agg_within_group)
159  {
160  fargs = foreach_delete_current(fargs, l);
161  continue;
162  }
163 
164  actual_arg_types[nargs++] = argtype;
165  }
166 
167  /*
168  * Check for named arguments; if there are any, build a list of names.
169  *
170  * We allow mixed notation (some named and some not), but only with all
171  * the named parameters after all the unnamed ones. So the name list
172  * corresponds to the last N actual parameters and we don't need any extra
173  * bookkeeping to match things up.
174  */
175  argnames = NIL;
176  foreach(l, fargs)
177  {
178  Node *arg = lfirst(l);
179 
180  if (IsA(arg, NamedArgExpr))
181  {
182  NamedArgExpr *na = (NamedArgExpr *) arg;
183  ListCell *lc;
184 
185  /* Reject duplicate arg names */
186  foreach(lc, argnames)
187  {
188  if (strcmp(na->name, (char *) lfirst(lc)) == 0)
189  ereport(ERROR,
190  (errcode(ERRCODE_SYNTAX_ERROR),
191  errmsg("argument name \"%s\" used more than once",
192  na->name),
193  parser_errposition(pstate, na->location)));
194  }
195  argnames = lappend(argnames, na->name);
196  }
197  else
198  {
199  if (argnames != NIL)
200  ereport(ERROR,
201  (errcode(ERRCODE_SYNTAX_ERROR),
202  errmsg("positional argument cannot follow named argument"),
203  parser_errposition(pstate, exprLocation(arg))));
204  }
205  }
206 
207  if (fargs)
208  {
209  first_arg = linitial(fargs);
210  Assert(first_arg != NULL);
211  }
212 
213  /*
214  * Decide whether it's legitimate to consider the construct to be a column
215  * projection. For that, there has to be a single argument of complex
216  * type, the function name must not be qualified, and there cannot be any
217  * syntactic decoration that'd require it to be a function (such as
218  * aggregate or variadic decoration, or named arguments).
219  */
220  could_be_projection = (nargs == 1 && !proc_call &&
221  agg_order == NIL && agg_filter == NULL &&
222  !agg_star && !agg_distinct && over == NULL &&
223  !func_variadic && argnames == NIL &&
224  list_length(funcname) == 1 &&
225  (actual_arg_types[0] == RECORDOID ||
226  ISCOMPLEX(actual_arg_types[0])));
227 
228  /*
229  * If it's column syntax, check for column projection case first.
230  */
231  if (could_be_projection && is_column)
232  {
233  retval = ParseComplexProjection(pstate,
234  strVal(linitial(funcname)),
235  first_arg,
236  location);
237  if (retval)
238  return retval;
239 
240  /*
241  * If ParseComplexProjection doesn't recognize it as a projection,
242  * just press on.
243  */
244  }
245 
246  /*
247  * func_get_detail looks up the function in the catalogs, does
248  * disambiguation for polymorphic functions, handles inheritance, and
249  * returns the funcid and type and set or singleton status of the
250  * function's return value. It also returns the true argument types to
251  * the function.
252  *
253  * Note: for a named-notation or variadic function call, the reported
254  * "true" types aren't really what is in pg_proc: the types are reordered
255  * to match the given argument order of named arguments, and a variadic
256  * argument is replaced by a suitable number of copies of its element
257  * type. We'll fix up the variadic case below. We may also have to deal
258  * with default arguments.
259  */
260 
261  setup_parser_errposition_callback(&pcbstate, pstate, location);
262 
263  fdresult = func_get_detail(funcname, fargs, argnames, nargs,
264  actual_arg_types,
265  !func_variadic, true,
266  &funcid, &rettype, &retset,
267  &nvargs, &vatype,
268  &declared_arg_types, &argdefaults);
269 
271 
272  /*
273  * Check for various wrong-kind-of-routine cases.
274  */
275 
276  /* If this is a CALL, reject things that aren't procedures */
277  if (proc_call &&
278  (fdresult == FUNCDETAIL_NORMAL ||
279  fdresult == FUNCDETAIL_AGGREGATE ||
280  fdresult == FUNCDETAIL_WINDOWFUNC ||
281  fdresult == FUNCDETAIL_COERCION))
282  ereport(ERROR,
283  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
284  errmsg("%s is not a procedure",
285  func_signature_string(funcname, nargs,
286  argnames,
287  actual_arg_types)),
288  errhint("To call a function, use SELECT."),
289  parser_errposition(pstate, location)));
290  /* Conversely, if not a CALL, reject procedures */
291  if (fdresult == FUNCDETAIL_PROCEDURE && !proc_call)
292  ereport(ERROR,
293  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
294  errmsg("%s is a procedure",
295  func_signature_string(funcname, nargs,
296  argnames,
297  actual_arg_types)),
298  errhint("To call a procedure, use CALL."),
299  parser_errposition(pstate, location)));
300 
301  if (fdresult == FUNCDETAIL_NORMAL ||
302  fdresult == FUNCDETAIL_PROCEDURE ||
303  fdresult == FUNCDETAIL_COERCION)
304  {
305  /*
306  * In these cases, complain if there was anything indicating it must
307  * be an aggregate or window function.
308  */
309  if (agg_star)
310  ereport(ERROR,
311  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
312  errmsg("%s(*) specified, but %s is not an aggregate function",
313  NameListToString(funcname),
314  NameListToString(funcname)),
315  parser_errposition(pstate, location)));
316  if (agg_distinct)
317  ereport(ERROR,
318  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
319  errmsg("DISTINCT specified, but %s is not an aggregate function",
320  NameListToString(funcname)),
321  parser_errposition(pstate, location)));
322  if (agg_within_group)
323  ereport(ERROR,
324  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
325  errmsg("WITHIN GROUP specified, but %s is not an aggregate function",
326  NameListToString(funcname)),
327  parser_errposition(pstate, location)));
328  if (agg_order != NIL)
329  ereport(ERROR,
330  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
331  errmsg("ORDER BY specified, but %s is not an aggregate function",
332  NameListToString(funcname)),
333  parser_errposition(pstate, location)));
334  if (agg_filter)
335  ereport(ERROR,
336  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
337  errmsg("FILTER specified, but %s is not an aggregate function",
338  NameListToString(funcname)),
339  parser_errposition(pstate, location)));
340  if (over)
341  ereport(ERROR,
342  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
343  errmsg("OVER specified, but %s is not a window function nor an aggregate function",
344  NameListToString(funcname)),
345  parser_errposition(pstate, location)));
346  }
347 
348  /*
349  * So far so good, so do some fdresult-type-specific processing.
350  */
351  if (fdresult == FUNCDETAIL_NORMAL || fdresult == FUNCDETAIL_PROCEDURE)
352  {
353  /* Nothing special to do for these cases. */
354  }
355  else if (fdresult == FUNCDETAIL_AGGREGATE)
356  {
357  /*
358  * It's an aggregate; fetch needed info from the pg_aggregate entry.
359  */
360  HeapTuple tup;
361  Form_pg_aggregate classForm;
362  int catDirectArgs;
363 
364  tup = SearchSysCache1(AGGFNOID, ObjectIdGetDatum(funcid));
365  if (!HeapTupleIsValid(tup)) /* should not happen */
366  elog(ERROR, "cache lookup failed for aggregate %u", funcid);
367  classForm = (Form_pg_aggregate) GETSTRUCT(tup);
368  aggkind = classForm->aggkind;
369  catDirectArgs = classForm->aggnumdirectargs;
370  ReleaseSysCache(tup);
371 
372  /* Now check various disallowed cases. */
373  if (AGGKIND_IS_ORDERED_SET(aggkind))
374  {
375  int numAggregatedArgs;
376  int numDirectArgs;
377 
378  if (!agg_within_group)
379  ereport(ERROR,
380  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
381  errmsg("WITHIN GROUP is required for ordered-set aggregate %s",
382  NameListToString(funcname)),
383  parser_errposition(pstate, location)));
384  if (over)
385  ereport(ERROR,
386  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
387  errmsg("OVER is not supported for ordered-set aggregate %s",
388  NameListToString(funcname)),
389  parser_errposition(pstate, location)));
390  /* gram.y rejects DISTINCT + WITHIN GROUP */
391  Assert(!agg_distinct);
392  /* gram.y rejects VARIADIC + WITHIN GROUP */
393  Assert(!func_variadic);
394 
395  /*
396  * Since func_get_detail was working with an undifferentiated list
397  * of arguments, it might have selected an aggregate that doesn't
398  * really match because it requires a different division of direct
399  * and aggregated arguments. Check that the number of direct
400  * arguments is actually OK; if not, throw an "undefined function"
401  * error, similarly to the case where a misplaced ORDER BY is used
402  * in a regular aggregate call.
403  */
404  numAggregatedArgs = list_length(agg_order);
405  numDirectArgs = nargs - numAggregatedArgs;
406  Assert(numDirectArgs >= 0);
407 
408  if (!OidIsValid(vatype))
409  {
410  /* Test is simple if aggregate isn't variadic */
411  if (numDirectArgs != catDirectArgs)
412  ereport(ERROR,
413  (errcode(ERRCODE_UNDEFINED_FUNCTION),
414  errmsg("function %s does not exist",
415  func_signature_string(funcname, nargs,
416  argnames,
417  actual_arg_types)),
418  errhint("There is an ordered-set aggregate %s, but it requires %d direct arguments, not %d.",
419  NameListToString(funcname),
420  catDirectArgs, numDirectArgs),
421  parser_errposition(pstate, location)));
422  }
423  else
424  {
425  /*
426  * If it's variadic, we have two cases depending on whether
427  * the agg was "... ORDER BY VARIADIC" or "..., VARIADIC ORDER
428  * BY VARIADIC". It's the latter if catDirectArgs equals
429  * pronargs; to save a catalog lookup, we reverse-engineer
430  * pronargs from the info we got from func_get_detail.
431  */
432  int pronargs;
433 
434  pronargs = nargs;
435  if (nvargs > 1)
436  pronargs -= nvargs - 1;
437  if (catDirectArgs < pronargs)
438  {
439  /* VARIADIC isn't part of direct args, so still easy */
440  if (numDirectArgs != catDirectArgs)
441  ereport(ERROR,
442  (errcode(ERRCODE_UNDEFINED_FUNCTION),
443  errmsg("function %s does not exist",
444  func_signature_string(funcname, nargs,
445  argnames,
446  actual_arg_types)),
447  errhint("There is an ordered-set aggregate %s, but it requires %d direct arguments, not %d.",
448  NameListToString(funcname),
449  catDirectArgs, numDirectArgs),
450  parser_errposition(pstate, location)));
451  }
452  else
453  {
454  /*
455  * Both direct and aggregated args were declared variadic.
456  * For a standard ordered-set aggregate, it's okay as long
457  * as there aren't too few direct args. For a
458  * hypothetical-set aggregate, we assume that the
459  * hypothetical arguments are those that matched the
460  * variadic parameter; there must be just as many of them
461  * as there are aggregated arguments.
462  */
463  if (aggkind == AGGKIND_HYPOTHETICAL)
464  {
465  if (nvargs != 2 * numAggregatedArgs)
466  ereport(ERROR,
467  (errcode(ERRCODE_UNDEFINED_FUNCTION),
468  errmsg("function %s does not exist",
469  func_signature_string(funcname, nargs,
470  argnames,
471  actual_arg_types)),
472  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).",
473  NameListToString(funcname),
474  nvargs - numAggregatedArgs, numAggregatedArgs),
475  parser_errposition(pstate, location)));
476  }
477  else
478  {
479  if (nvargs <= numAggregatedArgs)
480  ereport(ERROR,
481  (errcode(ERRCODE_UNDEFINED_FUNCTION),
482  errmsg("function %s does not exist",
483  func_signature_string(funcname, nargs,
484  argnames,
485  actual_arg_types)),
486  errhint("There is an ordered-set aggregate %s, but it requires at least %d direct arguments.",
487  NameListToString(funcname),
488  catDirectArgs),
489  parser_errposition(pstate, location)));
490  }
491  }
492  }
493 
494  /* Check type matching of hypothetical arguments */
495  if (aggkind == AGGKIND_HYPOTHETICAL)
496  unify_hypothetical_args(pstate, fargs, numAggregatedArgs,
497  actual_arg_types, declared_arg_types);
498  }
499  else
500  {
501  /* Normal aggregate, so it can't have WITHIN GROUP */
502  if (agg_within_group)
503  ereport(ERROR,
504  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
505  errmsg("%s is not an ordered-set aggregate, so it cannot have WITHIN GROUP",
506  NameListToString(funcname)),
507  parser_errposition(pstate, location)));
508  }
509  }
510  else if (fdresult == FUNCDETAIL_WINDOWFUNC)
511  {
512  /*
513  * True window functions must be called with a window definition.
514  */
515  if (!over)
516  ereport(ERROR,
517  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
518  errmsg("window function %s requires an OVER clause",
519  NameListToString(funcname)),
520  parser_errposition(pstate, location)));
521  /* And, per spec, WITHIN GROUP isn't allowed */
522  if (agg_within_group)
523  ereport(ERROR,
524  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
525  errmsg("window function %s cannot have WITHIN GROUP",
526  NameListToString(funcname)),
527  parser_errposition(pstate, location)));
528  }
529  else if (fdresult == FUNCDETAIL_COERCION)
530  {
531  /*
532  * We interpreted it as a type coercion. coerce_type can handle these
533  * cases, so why duplicate code...
534  */
535  return coerce_type(pstate, linitial(fargs),
536  actual_arg_types[0], rettype, -1,
538  }
539  else if (fdresult == FUNCDETAIL_MULTIPLE)
540  {
541  /*
542  * We found multiple possible functional matches. If we are dealing
543  * with attribute notation, return failure, letting the caller report
544  * "no such column" (we already determined there wasn't one). If
545  * dealing with function notation, report "ambiguous function",
546  * regardless of whether there's also a column by this name.
547  */
548  if (is_column)
549  return NULL;
550 
551  if (proc_call)
552  ereport(ERROR,
553  (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
554  errmsg("procedure %s is not unique",
555  func_signature_string(funcname, nargs, argnames,
556  actual_arg_types)),
557  errhint("Could not choose a best candidate procedure. "
558  "You might need to add explicit type casts."),
559  parser_errposition(pstate, location)));
560  else
561  ereport(ERROR,
562  (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
563  errmsg("function %s is not unique",
564  func_signature_string(funcname, nargs, argnames,
565  actual_arg_types)),
566  errhint("Could not choose a best candidate function. "
567  "You might need to add explicit type casts."),
568  parser_errposition(pstate, location)));
569  }
570  else
571  {
572  /*
573  * Not found as a function. If we are dealing with attribute
574  * notation, return failure, letting the caller report "no such
575  * column" (we already determined there wasn't one).
576  */
577  if (is_column)
578  return NULL;
579 
580  /*
581  * Check for column projection interpretation, since we didn't before.
582  */
583  if (could_be_projection)
584  {
585  retval = ParseComplexProjection(pstate,
586  strVal(linitial(funcname)),
587  first_arg,
588  location);
589  if (retval)
590  return retval;
591  }
592 
593  /*
594  * No function, and no column either. Since we're dealing with
595  * function notation, report "function does not exist".
596  */
597  if (list_length(agg_order) > 1 && !agg_within_group)
598  {
599  /* It's agg(x, ORDER BY y,z) ... perhaps misplaced ORDER BY */
600  ereport(ERROR,
601  (errcode(ERRCODE_UNDEFINED_FUNCTION),
602  errmsg("function %s does not exist",
603  func_signature_string(funcname, nargs, argnames,
604  actual_arg_types)),
605  errhint("No aggregate function matches the given name and argument types. "
606  "Perhaps you misplaced ORDER BY; ORDER BY must appear "
607  "after all regular arguments of the aggregate."),
608  parser_errposition(pstate, location)));
609  }
610  else if (proc_call)
611  ereport(ERROR,
612  (errcode(ERRCODE_UNDEFINED_FUNCTION),
613  errmsg("procedure %s does not exist",
614  func_signature_string(funcname, nargs, argnames,
615  actual_arg_types)),
616  errhint("No procedure matches the given name and argument types. "
617  "You might need to add explicit type casts."),
618  parser_errposition(pstate, location)));
619  else
620  ereport(ERROR,
621  (errcode(ERRCODE_UNDEFINED_FUNCTION),
622  errmsg("function %s does not exist",
623  func_signature_string(funcname, nargs, argnames,
624  actual_arg_types)),
625  errhint("No function matches the given name and argument types. "
626  "You might need to add explicit type casts."),
627  parser_errposition(pstate, location)));
628  }
629 
630  /*
631  * If there are default arguments, we have to include their types in
632  * actual_arg_types for the purpose of checking generic type consistency.
633  * However, we do NOT put them into the generated parse node, because
634  * their actual values might change before the query gets run. The
635  * planner has to insert the up-to-date values at plan time.
636  */
637  nargsplusdefs = nargs;
638  foreach(l, argdefaults)
639  {
640  Node *expr = (Node *) lfirst(l);
641 
642  /* probably shouldn't happen ... */
643  if (nargsplusdefs >= FUNC_MAX_ARGS)
644  ereport(ERROR,
645  (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
646  errmsg_plural("cannot pass more than %d argument to a function",
647  "cannot pass more than %d arguments to a function",
649  FUNC_MAX_ARGS),
650  parser_errposition(pstate, location)));
651 
652  actual_arg_types[nargsplusdefs++] = exprType(expr);
653  }
654 
655  /*
656  * enforce consistency with polymorphic argument and return types,
657  * possibly adjusting return type or declared_arg_types (which will be
658  * used as the cast destination by make_fn_arguments)
659  */
660  rettype = enforce_generic_type_consistency(actual_arg_types,
661  declared_arg_types,
662  nargsplusdefs,
663  rettype,
664  false);
665 
666  /* perform the necessary typecasting of arguments */
667  make_fn_arguments(pstate, fargs, actual_arg_types, declared_arg_types);
668 
669  /*
670  * If the function isn't actually variadic, forget any VARIADIC decoration
671  * on the call. (Perhaps we should throw an error instead, but
672  * historically we've allowed people to write that.)
673  */
674  if (!OidIsValid(vatype))
675  {
676  Assert(nvargs == 0);
677  func_variadic = false;
678  }
679 
680  /*
681  * If it's a variadic function call, transform the last nvargs arguments
682  * into an array --- unless it's an "any" variadic.
683  */
684  if (nvargs > 0 && vatype != ANYOID)
685  {
686  ArrayExpr *newa = makeNode(ArrayExpr);
687  int non_var_args = nargs - nvargs;
688  List *vargs;
689 
690  Assert(non_var_args >= 0);
691  vargs = list_copy_tail(fargs, non_var_args);
692  fargs = list_truncate(fargs, non_var_args);
693 
694  newa->elements = vargs;
695  /* assume all the variadic arguments were coerced to the same type */
696  newa->element_typeid = exprType((Node *) linitial(vargs));
698  if (!OidIsValid(newa->array_typeid))
699  ereport(ERROR,
700  (errcode(ERRCODE_UNDEFINED_OBJECT),
701  errmsg("could not find array type for data type %s",
703  parser_errposition(pstate, exprLocation((Node *) vargs))));
704  /* array_collid will be set by parse_collate.c */
705  newa->multidims = false;
706  newa->location = exprLocation((Node *) vargs);
707 
708  fargs = lappend(fargs, newa);
709 
710  /* We could not have had VARIADIC marking before ... */
711  Assert(!func_variadic);
712  /* ... but now, it's a VARIADIC call */
713  func_variadic = true;
714  }
715 
716  /*
717  * If an "any" variadic is called with explicit VARIADIC marking, insist
718  * that the variadic parameter be of some array type.
719  */
720  if (nargs > 0 && vatype == ANYOID && func_variadic)
721  {
722  Oid va_arr_typid = actual_arg_types[nargs - 1];
723 
724  if (!OidIsValid(get_base_element_type(va_arr_typid)))
725  ereport(ERROR,
726  (errcode(ERRCODE_DATATYPE_MISMATCH),
727  errmsg("VARIADIC argument must be an array"),
728  parser_errposition(pstate,
729  exprLocation((Node *) llast(fargs)))));
730  }
731 
732  /* if it returns a set, check that's OK */
733  if (retset)
734  check_srf_call_placement(pstate, last_srf, location);
735 
736  /* build the appropriate output structure */
737  if (fdresult == FUNCDETAIL_NORMAL || fdresult == FUNCDETAIL_PROCEDURE)
738  {
739  FuncExpr *funcexpr = makeNode(FuncExpr);
740 
741  funcexpr->funcid = funcid;
742  funcexpr->funcresulttype = rettype;
743  funcexpr->funcretset = retset;
744  funcexpr->funcvariadic = func_variadic;
745  funcexpr->funcformat = COERCE_EXPLICIT_CALL;
746  /* funccollid and inputcollid will be set by parse_collate.c */
747  funcexpr->args = fargs;
748  funcexpr->location = location;
749 
750  retval = (Node *) funcexpr;
751  }
752  else if (fdresult == FUNCDETAIL_AGGREGATE && !over)
753  {
754  /* aggregate function */
755  Aggref *aggref = makeNode(Aggref);
756 
757  aggref->aggfnoid = funcid;
758  aggref->aggtype = rettype;
759  /* aggcollid and inputcollid will be set by parse_collate.c */
760  aggref->aggtranstype = InvalidOid; /* will be set by planner */
761  /* aggargtypes will be set by transformAggregateCall */
762  /* aggdirectargs and args will be set by transformAggregateCall */
763  /* aggorder and aggdistinct will be set by transformAggregateCall */
764  aggref->aggfilter = agg_filter;
765  aggref->aggstar = agg_star;
766  aggref->aggvariadic = func_variadic;
767  aggref->aggkind = aggkind;
768  /* agglevelsup will be set by transformAggregateCall */
769  aggref->aggsplit = AGGSPLIT_SIMPLE; /* planner might change this */
770  aggref->location = location;
771 
772  /*
773  * Reject attempt to call a parameterless aggregate without (*)
774  * syntax. This is mere pedantry but some folks insisted ...
775  */
776  if (fargs == NIL && !agg_star && !agg_within_group)
777  ereport(ERROR,
778  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
779  errmsg("%s(*) must be used to call a parameterless aggregate function",
780  NameListToString(funcname)),
781  parser_errposition(pstate, location)));
782 
783  if (retset)
784  ereport(ERROR,
785  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
786  errmsg("aggregates cannot return sets"),
787  parser_errposition(pstate, location)));
788 
789  /*
790  * We might want to support named arguments later, but disallow it for
791  * now. We'd need to figure out the parsed representation (should the
792  * NamedArgExprs go above or below the TargetEntry nodes?) and then
793  * teach the planner to reorder the list properly. Or maybe we could
794  * make transformAggregateCall do that? However, if you'd also like
795  * to allow default arguments for aggregates, we'd need to do it in
796  * planning to avoid semantic problems.
797  */
798  if (argnames != NIL)
799  ereport(ERROR,
800  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
801  errmsg("aggregates cannot use named arguments"),
802  parser_errposition(pstate, location)));
803 
804  /* parse_agg.c does additional aggregate-specific processing */
805  transformAggregateCall(pstate, aggref, fargs, agg_order, agg_distinct);
806 
807  retval = (Node *) aggref;
808  }
809  else
810  {
811  /* window function */
812  WindowFunc *wfunc = makeNode(WindowFunc);
813 
814  Assert(over); /* lack of this was checked above */
815  Assert(!agg_within_group); /* also checked above */
816 
817  wfunc->winfnoid = funcid;
818  wfunc->wintype = rettype;
819  /* wincollid and inputcollid will be set by parse_collate.c */
820  wfunc->args = fargs;
821  /* winref will be set by transformWindowFuncCall */
822  wfunc->winstar = agg_star;
823  wfunc->winagg = (fdresult == FUNCDETAIL_AGGREGATE);
824  wfunc->aggfilter = agg_filter;
825  wfunc->location = location;
826 
827  /*
828  * agg_star is allowed for aggregate functions but distinct isn't
829  */
830  if (agg_distinct)
831  ereport(ERROR,
832  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
833  errmsg("DISTINCT is not implemented for window functions"),
834  parser_errposition(pstate, location)));
835 
836  /*
837  * Reject attempt to call a parameterless aggregate without (*)
838  * syntax. This is mere pedantry but some folks insisted ...
839  */
840  if (wfunc->winagg && fargs == NIL && !agg_star)
841  ereport(ERROR,
842  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
843  errmsg("%s(*) must be used to call a parameterless aggregate function",
844  NameListToString(funcname)),
845  parser_errposition(pstate, location)));
846 
847  /*
848  * ordered aggs not allowed in windows yet
849  */
850  if (agg_order != NIL)
851  ereport(ERROR,
852  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
853  errmsg("aggregate ORDER BY is not implemented for window functions"),
854  parser_errposition(pstate, location)));
855 
856  /*
857  * FILTER is not yet supported with true window functions
858  */
859  if (!wfunc->winagg && agg_filter)
860  ereport(ERROR,
861  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
862  errmsg("FILTER is not implemented for non-aggregate window functions"),
863  parser_errposition(pstate, location)));
864 
865  /*
866  * Window functions can't either take or return sets
867  */
868  if (pstate->p_last_srf != last_srf)
869  ereport(ERROR,
870  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
871  errmsg("window function calls cannot contain set-returning function calls"),
872  errhint("You might be able to move the set-returning function into a LATERAL FROM item."),
873  parser_errposition(pstate,
874  exprLocation(pstate->p_last_srf))));
875 
876  if (retset)
877  ereport(ERROR,
878  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
879  errmsg("window functions cannot return sets"),
880  parser_errposition(pstate, location)));
881 
882  /* parse_agg.c does additional window-func-specific processing */
883  transformWindowFuncCall(pstate, wfunc, over);
884 
885  retval = (Node *) wfunc;
886  }
887 
888  /* if it returns a set, remember it for error checks at higher levels */
889  if (retset)
890  pstate->p_last_srf = retval;
891 
892  return retval;
893 }
Oid funcresulttype
Definition: primnodes.h:456
static void unify_hypothetical_args(ParseState *pstate, List *fargs, int numAggregatedArgs, Oid *actual_arg_types, Oid *declared_arg_types)
Definition: parse_func.c:1730
bool multidims
Definition: primnodes.h:978
#define NIL
Definition: pg_list.h:65
bool aggvariadic
Definition: primnodes.h:310
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
Oid enforce_generic_type_consistency(const Oid *actual_arg_types, Oid *declared_arg_types, int nargs, Oid rettype, bool allow_poly)
int errhint(const char *fmt,...)
Definition: elog.c:1069
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
static Node * ParseComplexProjection(ParseState *pstate, const char *funcname, Node *first_arg, int location)
Definition: parse_func.c:1897
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1191
List * args
Definition: primnodes.h:363
List * args
Definition: primnodes.h:463
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:932
Oid get_array_type(Oid typid)
Definition: lsyscache.c:2554
Node * agg_filter
Definition: parsenodes.h:353
#define llast(l)
Definition: pg_list.h:215
List * list_truncate(List *list, int new_size)
Definition: list.c:586
Node * coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:156
Definition: nodes.h:525
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:608
Oid array_typeid
Definition: primnodes.h:974
char * format_type_be(Oid type_oid)
Definition: format_type.c:326
bool funcretset
Definition: primnodes.h:457
void make_fn_arguments(ParseState *pstate, List *fargs, Oid *actual_arg_types, Oid *declared_arg_types)
Definition: parse_func.c:1810
List * list_copy_tail(const List *oldlist, int nskip)
Definition: list.c:1423
int16 pronargs
Definition: pg_proc.h:81
bool aggstar
Definition: primnodes.h:309
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:645
List * agg_order
Definition: parsenodes.h:352
#define foreach_delete_current(lst, cell)
Definition: pg_list.h:368
#define FUNC_MAX_ARGS
CoercionForm funcformat
Definition: primnodes.h:460
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:160
#define linitial(l)
Definition: pg_list.h:195
Oid funcid
Definition: primnodes.h:455
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
struct WindowDef * over
Definition: parsenodes.h:358
int location
Definition: primnodes.h:315
FuncDetailCode
Definition: parse_func.h:22
char * name
Definition: primnodes.h:485
Oid winfnoid
Definition: primnodes.h:359
List * elements
Definition: primnodes.h:977
#define ereport(elevel, rest)
Definition: elog.h:141
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:144
const char * func_signature_string(List *funcname, int nargs, List *argnames, const Oid *argtypes)
Definition: parse_func.c:2013
List * lappend(List *list, void *datum)
Definition: list.c:322
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void transformWindowFuncCall(ParseState *pstate, WindowFunc *wfunc, WindowDef *windef)
Definition: parse_agg.c:798
bool func_variadic
Definition: parsenodes.h:357
char * NameListToString(List *names)
Definition: namespace.c:3094
int location
Definition: primnodes.h:979
Node * p_last_srf
Definition: parse_node.h:209
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define InvalidOid
Definition: postgres_ext.h:36
Oid aggfnoid
Definition: primnodes.h:298
#define makeNode(_type_)
Definition: nodes.h:573
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
int location
Definition: primnodes.h:368
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
Expr * aggfilter
Definition: primnodes.h:364
FormData_pg_aggregate * Form_pg_aggregate
Definition: pg_aggregate.h:109
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
AggSplit aggsplit
Definition: primnodes.h:314
#define ISCOMPLEX(typeid)
Definition: parse_type.h:58
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
static int list_length(const List *l)
Definition: pg_list.h:169
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
Expr * aggfilter
Definition: primnodes.h:308
FuncDetailCode func_get_detail(List *funcname, List *fargs, List *fargnames, int nargs, Oid *argtypes, bool expand_variadic, bool expand_defaults, Oid *funcid, Oid *rettype, bool *retset, int *nvargs, Oid *vatype, Oid **true_typeids, List **argdefaults)
Definition: parse_func.c:1382
Oid element_typeid
Definition: primnodes.h:976
Oid wintype
Definition: primnodes.h:360
Oid get_base_element_type(Oid typid)
Definition: lsyscache.c:2599
int errmsg(const char *fmt,...)
Definition: elog.c:822
bool winagg
Definition: primnodes.h:367
#define elog(elevel,...)
Definition: elog.h:228
Oid aggtranstype
Definition: primnodes.h:302
void * arg
Oid aggtype
Definition: primnodes.h:299
void check_srf_call_placement(ParseState *pstate, Node *last_srf, int location)
Definition: parse_func.c:2380
char aggkind
Definition: primnodes.h:312
int location
Definition: primnodes.h:464
bool agg_within_group
Definition: parsenodes.h:354
bool agg_distinct
Definition: parsenodes.h:356
bool agg_star
Definition: parsenodes.h:355
Definition: pg_list.h:50
bool funcvariadic
Definition: primnodes.h:458
void transformAggregateCall(ParseState *pstate, Aggref *agg, List *args, List *aggorder, bool agg_distinct)
Definition: parse_agg.c:102
bool winstar
Definition: primnodes.h:366

◆ 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 1730 of file parse_func.c.

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

Referenced by ParseFuncOrColumn().

1735 {
1736  int numDirectArgs,
1737  numNonHypotheticalArgs;
1738  int hargpos;
1739 
1740  numDirectArgs = list_length(fargs) - numAggregatedArgs;
1741  numNonHypotheticalArgs = numDirectArgs - numAggregatedArgs;
1742  /* safety check (should only trigger with a misdeclared agg) */
1743  if (numNonHypotheticalArgs < 0)
1744  elog(ERROR, "incorrect number of arguments to hypothetical-set aggregate");
1745 
1746  /* Check each hypothetical arg and corresponding aggregated arg */
1747  for (hargpos = numNonHypotheticalArgs; hargpos < numDirectArgs; hargpos++)
1748  {
1749  int aargpos = numDirectArgs + (hargpos - numNonHypotheticalArgs);
1750  ListCell *harg = list_nth_cell(fargs, hargpos);
1751  ListCell *aarg = list_nth_cell(fargs, aargpos);
1752  Oid commontype;
1753 
1754  /* A mismatch means AggregateCreate didn't check properly ... */
1755  if (declared_arg_types[hargpos] != declared_arg_types[aargpos])
1756  elog(ERROR, "hypothetical-set aggregate has inconsistent declared argument types");
1757 
1758  /* No need to unify if make_fn_arguments will coerce */
1759  if (declared_arg_types[hargpos] != ANYOID)
1760  continue;
1761 
1762  /*
1763  * Select common type, giving preference to the aggregated argument's
1764  * type (we'd rather coerce the direct argument once than coerce all
1765  * the aggregated values).
1766  */
1767  commontype = select_common_type(pstate,
1768  list_make2(lfirst(aarg), lfirst(harg)),
1769  "WITHIN GROUP",
1770  NULL);
1771 
1772  /*
1773  * Perform the coercions. We don't need to worry about NamedArgExprs
1774  * here because they aren't supported with aggregates.
1775  */
1776  lfirst(harg) = coerce_type(pstate,
1777  (Node *) lfirst(harg),
1778  actual_arg_types[hargpos],
1779  commontype, -1,
1782  -1);
1783  actual_arg_types[hargpos] = commontype;
1784  lfirst(aarg) = coerce_type(pstate,
1785  (Node *) lfirst(aarg),
1786  actual_arg_types[aargpos],
1787  commontype, -1,
1790  -1);
1791  actual_arg_types[aargpos] = commontype;
1792  }
1793 }
#define list_make2(x1, x2)
Definition: pg_list.h:229
static ListCell * list_nth_cell(const List *list, int n)
Definition: pg_list.h:265
Node * coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:156
Definition: nodes.h:525
unsigned int Oid
Definition: postgres_ext.h:31
#define ERROR
Definition: elog.h:43
#define lfirst(lc)
Definition: pg_list.h:190
static int list_length(const List *l)
Definition: pg_list.h:169
#define elog(elevel,...)
Definition: elog.h:228
Oid select_common_type(ParseState *pstate, List *exprs, const char *context, Node **which_expr)