PostgreSQL Source Code  git master
parse_func.h File Reference
Include dependency graph for parse_func.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Enumerations

enum  FuncDetailCode {
  FUNCDETAIL_NOTFOUND, FUNCDETAIL_MULTIPLE, FUNCDETAIL_NORMAL, FUNCDETAIL_PROCEDURE,
  FUNCDETAIL_AGGREGATE, FUNCDETAIL_WINDOWFUNC, FUNCDETAIL_COERCION
}
 

Functions

NodeParseFuncOrColumn (ParseState *pstate, List *funcname, List *fargs, Node *last_srf, FuncCall *fn, bool proc_call, int location)
 
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)
 
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)
 
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

◆ FuncDetailCode

Enumerator
FUNCDETAIL_NOTFOUND 
FUNCDETAIL_MULTIPLE 
FUNCDETAIL_NORMAL 
FUNCDETAIL_PROCEDURE 
FUNCDETAIL_AGGREGATE 
FUNCDETAIL_WINDOWFUNC 
FUNCDETAIL_COERCION 

Definition at line 22 of file parse_func.h.

23 {
24  FUNCDETAIL_NOTFOUND, /* no matching function */
25  FUNCDETAIL_MULTIPLE, /* too many matching functions */
26  FUNCDETAIL_NORMAL, /* found a matching regular function */
27  FUNCDETAIL_PROCEDURE, /* found a matching procedure */
28  FUNCDETAIL_AGGREGATE, /* found a matching aggregate function */
29  FUNCDETAIL_WINDOWFUNC, /* found a matching window function */
30  FUNCDETAIL_COERCION /* it's a type coercion request */
FuncDetailCode
Definition: parse_func.h:22

Function Documentation

◆ check_srf_call_placement()

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

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

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

◆ 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:579
#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:597
static Oid FuncNameAsType(List *funcname)
Definition: parse_func.c:1870
Definition: nodes.h:528
void * stringToNode(const char *str)
Definition: read.c:89
List * list_copy_tail(const List *oldlist, int nskip)
Definition: list.c:1422
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:652
CoercionPathType
Definition: parse_coerce.h:24
Oid args[FLEXIBLE_ARRAY_MEMBER]
Definition: namespace.h:37
void pfree(void *pointer)
Definition: mcxt.c:1057
#define linitial(l)
Definition: pg_list.h:174
#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:942
FuncDetailCode
Definition: parse_func.h:22
struct _FuncCandidateList * next
Definition: namespace.h:30
List * lappend(List *list, void *datum)
Definition: list.c:321
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
#define TextDatumGetCString(d)
Definition: builtins.h:87
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:746
#define lfirst(lc)
Definition: pg_list.h:169
#define ISCOMPLEX(typeid)
Definition: parse_type.h:58
static int list_length(const List *l)
Definition: pg_list.h:149
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:214
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:546
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:931
bool can_coerce_type(int nargs, const Oid *input_typeids, const Oid *target_typeids, CoercionContext ccontext)
Definition: parse_coerce.c:546
int errcode(int sqlerrcode)
Definition: elog.c:610
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
TYPCATEGORY TypeCategory(Oid type)
#define ereport(elevel,...)
Definition: elog.h:144
int i
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2409
void get_type_category_preferred(Oid typid, char *typcategory, bool *typispreferred)
Definition: lsyscache.c:2588

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

1984 {
1985  StringInfoData argbuf;
1986  int numposargs;
1987  ListCell *lc;
1988  int i;
1989 
1990  initStringInfo(&argbuf);
1991 
1992  appendStringInfo(&argbuf, "%s(", funcname);
1993 
1994  numposargs = nargs - list_length(argnames);
1995  lc = list_head(argnames);
1996 
1997  for (i = 0; i < nargs; i++)
1998  {
1999  if (i)
2000  appendStringInfoString(&argbuf, ", ");
2001  if (i >= numposargs)
2002  {
2003  appendStringInfo(&argbuf, "%s => ", (char *) lfirst(lc));
2004  lc = lnext(argnames, lc);
2005  }
2006  appendStringInfoString(&argbuf, format_type_be(argtypes[i]));
2007  }
2008 
2009  appendStringInfoChar(&argbuf, ')');
2010 
2011  return argbuf.data; /* return palloc'd string buffer */
2012 }
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:310
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
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:169
static int list_length(const List *l)
Definition: pg_list.h:149
int i

◆ LookupFuncName()

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

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

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

◆ LookupFuncWithArgs()

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

Definition at line 2167 of file parse_func.c.

References ObjectWithArgs::args_unspecified, Assert, ereport, errcode(), ERRCODE_WRONG_OBJECT_TYPE, 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().

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

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

◆ 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(), ERRCODE_WRONG_OBJECT_TYPE, 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,
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,
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,
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,
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,
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,
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,
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,
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,
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,
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,
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,
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,
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,
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:470
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:995
#define NIL
Definition: pg_list.h:65
bool aggvariadic
Definition: primnodes.h:324
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
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:1068
#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:1901
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1240
List * args
Definition: primnodes.h:377
List * args
Definition: primnodes.h:477
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:931
Oid get_array_type(Oid typid)
Definition: lsyscache.c:2664
Node * agg_filter
Definition: parsenodes.h:355
#define llast(l)
Definition: pg_list.h:194
List * list_truncate(List *list, int new_size)
Definition: list.c:585
Node * coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:155
Definition: nodes.h:528
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:610
Oid array_typeid
Definition: primnodes.h:991
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
bool funcretset
Definition: primnodes.h:471
void make_fn_arguments(ParseState *pstate, List *fargs, Oid *actual_arg_types, Oid *declared_arg_types)
Definition: parse_func.c:1814
List * list_copy_tail(const List *oldlist, int nskip)
Definition: list.c:1422
int16 pronargs
Definition: pg_proc.h:81
bool aggstar
Definition: primnodes.h:323
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:652
List * agg_order
Definition: parsenodes.h:354
#define foreach_delete_current(lst, cell)
Definition: pg_list.h:357
#define FUNC_MAX_ARGS
CoercionForm funcformat
Definition: primnodes.h:474
#define ERRCODE_WRONG_OBJECT_TYPE
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:160
#define linitial(l)
Definition: pg_list.h:174
Oid funcid
Definition: primnodes.h:469
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
struct WindowDef * over
Definition: parsenodes.h:360
int location
Definition: primnodes.h:329
FuncDetailCode
Definition: parse_func.h:22
char * name
Definition: primnodes.h:499
Oid winfnoid
Definition: primnodes.h:373
List * elements
Definition: primnodes.h:994
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:2019
List * lappend(List *list, void *datum)
Definition: list.c:321
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:359
char * NameListToString(List *names)
Definition: namespace.c:3101
int location
Definition: primnodes.h:996
Node * p_last_srf
Definition: parse_node.h:212
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define InvalidOid
Definition: postgres_ext.h:36
Oid aggfnoid
Definition: primnodes.h:312
#define ereport(elevel,...)
Definition: elog.h:144
#define makeNode(_type_)
Definition: nodes.h:576
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
int location
Definition: primnodes.h:382
#define Assert(condition)
Definition: c.h:746
#define lfirst(lc)
Definition: pg_list.h:169
Expr * aggfilter
Definition: primnodes.h:378
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:328
#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:149
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
Expr * aggfilter
Definition: primnodes.h:322
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:993
Oid wintype
Definition: primnodes.h:374
Oid get_base_element_type(Oid typid)
Definition: lsyscache.c:2709
int errmsg(const char *fmt,...)
Definition: elog.c:821
bool winagg
Definition: primnodes.h:381
#define elog(elevel,...)
Definition: elog.h:214
Oid aggtranstype
Definition: primnodes.h:316
void * arg
Oid aggtype
Definition: primnodes.h:313
void check_srf_call_placement(ParseState *pstate, Node *last_srf, int location)
Definition: parse_func.c:2386
char aggkind
Definition: primnodes.h:326
int location
Definition: primnodes.h:478
bool agg_within_group
Definition: parsenodes.h:356
bool agg_distinct
Definition: parsenodes.h:358
bool agg_star
Definition: parsenodes.h:357
Definition: pg_list.h:50
bool funcvariadic
Definition: primnodes.h:472
void transformAggregateCall(ParseState *pstate, Aggref *agg, List *args, List *aggorder, bool agg_distinct)
Definition: parse_agg.c:102
bool winstar
Definition: primnodes.h:380