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

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

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

918 {
919  FuncCandidateList current_candidate;
920  FuncCandidateList next_candidate;
921  int ncandidates = 0;
922 
923  *candidates = NULL;
924 
925  for (current_candidate = raw_candidates;
926  current_candidate != NULL;
927  current_candidate = next_candidate)
928  {
929  next_candidate = current_candidate->next;
930  if (can_coerce_type(nargs, input_typeids, current_candidate->args,
932  {
933  current_candidate->next = *candidates;
934  *candidates = current_candidate;
935  ncandidates++;
936  }
937  }
938 
939  return ncandidates;
940 } /* 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 999 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().

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

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

1988 {
1989  StringInfoData argbuf;
1990  int numposargs;
1991  ListCell *lc;
1992  int i;
1993 
1994  initStringInfo(&argbuf);
1995 
1996  appendStringInfo(&argbuf, "%s(", funcname);
1997 
1998  numposargs = nargs - list_length(argnames);
1999  lc = list_head(argnames);
2000 
2001  for (i = 0; i < nargs; i++)
2002  {
2003  if (i)
2004  appendStringInfoString(&argbuf, ", ");
2005  if (i >= numposargs)
2006  {
2007  appendStringInfo(&argbuf, "%s => ", (char *) lfirst(lc));
2008  lc = lnext(argnames, lc);
2009  }
2010  appendStringInfoString(&argbuf, format_type_be(argtypes[i]));
2011  }
2012 
2013  appendStringInfoChar(&argbuf, ')');
2014 
2015  return argbuf.data; /* return palloc'd string buffer */
2016 }
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

◆ FuncNameAsType()

static Oid FuncNameAsType ( List funcname)
static

Definition at line 1874 of file parse_func.c.

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

Referenced by func_get_detail().

1875 {
1876  Oid result;
1877  Type typtup;
1878 
1879  /*
1880  * temp_ok=false protects the <refsect1 id="sql-createfunction-security">
1881  * contract for writing SECURITY DEFINER functions safely.
1882  */
1883  typtup = LookupTypeNameExtended(NULL, makeTypeNameFromNameList(funcname),
1884  NULL, false, false);
1885  if (typtup == NULL)
1886  return InvalidOid;
1887 
1888  if (((Form_pg_type) GETSTRUCT(typtup))->typisdefined &&
1889  !OidIsValid(typeTypeRelid(typtup)))
1890  result = typeTypeId(typtup);
1891  else
1892  result = InvalidOid;
1893 
1894  ReleaseSysCache(typtup);
1895  return result;
1896 }
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:706
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1163
#define InvalidOid
Definition: postgres_ext.h:36
FormData_pg_type * Form_pg_type
Definition: pg_type.h:255
Oid typeTypeRelid(Type typ)
Definition: parse_type.c:628
TypeName * makeTypeNameFromNameList(List *names)
Definition: makefuncs.c:456
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 2111 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().

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

◆ LookupFuncNameInternal()

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

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

2044 {
2045  FuncCandidateList clist;
2046 
2047  /* NULL argtypes allowed for nullary functions only */
2048  Assert(argtypes != NULL || nargs == 0);
2049 
2050  /* Always set *lookupError, to forestall uninitialized-variable warnings */
2051  *lookupError = FUNCLOOKUP_NOSUCHFUNC;
2052 
2053  clist = FuncnameGetCandidates(funcname, nargs, NIL, false, false,
2054  missing_ok);
2055 
2056  /*
2057  * If no arguments were specified, the name must yield a unique candidate.
2058  */
2059  if (nargs < 0)
2060  {
2061  if (clist)
2062  {
2063  /* If there is a second match then it's ambiguous */
2064  if (clist->next)
2065  {
2066  *lookupError = FUNCLOOKUP_AMBIGUOUS;
2067  return InvalidOid;
2068  }
2069  /* Otherwise return the match */
2070  return clist->oid;
2071  }
2072  else
2073  return InvalidOid;
2074  }
2075 
2076  /*
2077  * Otherwise, look for a match to the arg types. FuncnameGetCandidates
2078  * has ensured that there's at most one match in the returned list.
2079  */
2080  while (clist)
2081  {
2082  /* if nargs==0, argtypes can be null; don't pass that to memcmp */
2083  if (nargs == 0 ||
2084  memcmp(argtypes, clist->args, nargs * sizeof(Oid)) == 0)
2085  return clist->oid;
2086  clist = clist->next;
2087  }
2088 
2089  return InvalidOid;
2090 }
#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:942
struct _FuncCandidateList * next
Definition: namespace.h:30
#define InvalidOid
Definition: postgres_ext.h:36
#define Assert(condition)
Definition: c.h:800

◆ LookupFuncWithArgs()

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

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

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

1822 {
1823  ListCell *current_fargs;
1824  int i = 0;
1825 
1826  foreach(current_fargs, fargs)
1827  {
1828  /* types don't match? then force coercion using a function call... */
1829  if (actual_arg_types[i] != declared_arg_types[i])
1830  {
1831  Node *node = (Node *) lfirst(current_fargs);
1832 
1833  /*
1834  * If arg is a NamedArgExpr, coerce its input expr instead --- we
1835  * want the NamedArgExpr to stay at the top level of the list.
1836  */
1837  if (IsA(node, NamedArgExpr))
1838  {
1839  NamedArgExpr *na = (NamedArgExpr *) node;
1840 
1841  node = coerce_type(pstate,
1842  (Node *) na->arg,
1843  actual_arg_types[i],
1844  declared_arg_types[i], -1,
1847  -1);
1848  na->arg = (Expr *) node;
1849  }
1850  else
1851  {
1852  node = coerce_type(pstate,
1853  node,
1854  actual_arg_types[i],
1855  declared_arg_types[i], -1,
1858  -1);
1859  lfirst(current_fargs) = node;
1860  }
1861  }
1862  i++;
1863  }
1864 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:578
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:527
Expr * arg
Definition: primnodes.h:510
#define lfirst(lc)
Definition: pg_list.h:169
int i

◆ ParseComplexProjection()

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

Definition at line 1905 of file parse_func.c.

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

Referenced by ParseFuncOrColumn().

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

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

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

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

Referenced by ParseFuncOrColumn().

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