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 (ObjectType objtype, List *funcname, int nargs, const Oid *argtypes, bool include_out_arguments, bool missing_ok, FuncLookupError *lookupError)
 
NodeParseFuncOrColumn (ParseState *pstate, List *funcname, List *fargs, Node *last_srf, FuncCall *fn, bool proc_call, int location)
 
int func_match_argtypes (int nargs, Oid *input_typeids, FuncCandidateList raw_candidates, FuncCandidateList *candidates)
 
FuncCandidateList func_select_candidate (int nargs, Oid *input_typeids, FuncCandidateList candidates)
 
FuncDetailCode func_get_detail (List *funcname, List *fargs, List *fargnames, int nargs, Oid *argtypes, bool expand_variadic, bool expand_defaults, bool include_out_arguments, 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 2512 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_CYCLE_MARK, 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_STATS_EXPRESSION, EXPR_KIND_TRIGGER_WHEN, EXPR_KIND_UPDATE_SOURCE, EXPR_KIND_UPDATE_TARGET, EXPR_KIND_VALUES, EXPR_KIND_VALUES_SINGLE, EXPR_KIND_WHERE, EXPR_KIND_WINDOW_FRAME_GROUPS, EXPR_KIND_WINDOW_FRAME_RANGE, EXPR_KIND_WINDOW_FRAME_ROWS, EXPR_KIND_WINDOW_ORDER, EXPR_KIND_WINDOW_PARTITION, exprLocation(), ParseState::p_expr_kind, ParseState::p_hasTargetSRFs, ParseState::p_last_srf, ParseExprKindName(), and parser_errposition().

Referenced by make_op(), and ParseFuncOrColumn().

2513 {
2514  const char *err;
2515  bool errkind;
2516 
2517  /*
2518  * Check to see if the set-returning function is in an invalid place
2519  * within the query. Basically, we don't allow SRFs anywhere except in
2520  * the targetlist (which includes GROUP BY/ORDER BY expressions), VALUES,
2521  * and functions in FROM.
2522  *
2523  * For brevity we support two schemes for reporting an error here: set
2524  * "err" to a custom message, or set "errkind" true if the error context
2525  * is sufficiently identified by what ParseExprKindName will return, *and*
2526  * what it will return is just a SQL keyword. (Otherwise, use a custom
2527  * message to avoid creating translation problems.)
2528  */
2529  err = NULL;
2530  errkind = false;
2531  switch (pstate->p_expr_kind)
2532  {
2533  case EXPR_KIND_NONE:
2534  Assert(false); /* can't happen */
2535  break;
2536  case EXPR_KIND_OTHER:
2537  /* Accept SRF here; caller must throw error if wanted */
2538  break;
2539  case EXPR_KIND_JOIN_ON:
2540  case EXPR_KIND_JOIN_USING:
2541  err = _("set-returning functions are not allowed in JOIN conditions");
2542  break;
2544  /* can't get here, but just in case, throw an error */
2545  errkind = true;
2546  break;
2548  /* okay, but we don't allow nested SRFs here */
2549  /* errmsg is chosen to match transformRangeFunction() */
2550  /* errposition should point to the inner SRF */
2551  if (pstate->p_last_srf != last_srf)
2552  ereport(ERROR,
2553  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2554  errmsg("set-returning functions must appear at top level of FROM"),
2555  parser_errposition(pstate,
2556  exprLocation(pstate->p_last_srf))));
2557  break;
2558  case EXPR_KIND_WHERE:
2559  errkind = true;
2560  break;
2561  case EXPR_KIND_POLICY:
2562  err = _("set-returning functions are not allowed in policy expressions");
2563  break;
2564  case EXPR_KIND_HAVING:
2565  errkind = true;
2566  break;
2567  case EXPR_KIND_FILTER:
2568  errkind = true;
2569  break;
2572  /* okay, these are effectively GROUP BY/ORDER BY */
2573  pstate->p_hasTargetSRFs = true;
2574  break;
2578  err = _("set-returning functions are not allowed in window definitions");
2579  break;
2582  /* okay */
2583  pstate->p_hasTargetSRFs = true;
2584  break;
2587  /* disallowed because it would be ambiguous what to do */
2588  errkind = true;
2589  break;
2590  case EXPR_KIND_GROUP_BY:
2591  case EXPR_KIND_ORDER_BY:
2592  /* okay */
2593  pstate->p_hasTargetSRFs = true;
2594  break;
2595  case EXPR_KIND_DISTINCT_ON:
2596  /* okay */
2597  pstate->p_hasTargetSRFs = true;
2598  break;
2599  case EXPR_KIND_LIMIT:
2600  case EXPR_KIND_OFFSET:
2601  errkind = true;
2602  break;
2603  case EXPR_KIND_RETURNING:
2604  errkind = true;
2605  break;
2606  case EXPR_KIND_VALUES:
2607  /* SRFs are presently not supported by nodeValuesscan.c */
2608  errkind = true;
2609  break;
2611  /* okay, since we process this like a SELECT tlist */
2612  pstate->p_hasTargetSRFs = true;
2613  break;
2616  err = _("set-returning functions are not allowed in check constraints");
2617  break;
2620  err = _("set-returning functions are not allowed in DEFAULT expressions");
2621  break;
2623  err = _("set-returning functions are not allowed in index expressions");
2624  break;
2626  err = _("set-returning functions are not allowed in index predicates");
2627  break;
2629  err = _("set-returning functions are not allowed in statistics expressions");
2630  break;
2632  err = _("set-returning functions are not allowed in transform expressions");
2633  break;
2635  err = _("set-returning functions are not allowed in EXECUTE parameters");
2636  break;
2638  err = _("set-returning functions are not allowed in trigger WHEN conditions");
2639  break;
2641  err = _("set-returning functions are not allowed in partition bound");
2642  break;
2644  err = _("set-returning functions are not allowed in partition key expressions");
2645  break;
2647  err = _("set-returning functions are not allowed in CALL arguments");
2648  break;
2649  case EXPR_KIND_COPY_WHERE:
2650  err = _("set-returning functions are not allowed in COPY FROM WHERE conditions");
2651  break;
2653  err = _("set-returning functions are not allowed in column generation expressions");
2654  break;
2655  case EXPR_KIND_CYCLE_MARK:
2656  errkind = true;
2657  break;
2658 
2659  /*
2660  * There is intentionally no default: case here, so that the
2661  * compiler will warn if we add a new ParseExprKind without
2662  * extending this switch. If we do see an unrecognized value at
2663  * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
2664  * which is sane anyway.
2665  */
2666  }
2667  if (err)
2668  ereport(ERROR,
2669  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2670  errmsg_internal("%s", err),
2671  parser_errposition(pstate, location)));
2672  if (errkind)
2673  ereport(ERROR,
2674  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2675  /* translator: %s is name of a SQL construct, eg GROUP BY */
2676  errmsg("set-returning functions are not allowed in %s",
2677  ParseExprKindName(pstate->p_expr_kind)),
2678  parser_errposition(pstate, location)));
2679 }
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1250
bool p_hasTargetSRFs
Definition: parse_node.h:210
int errcode(int sqlerrcode)
Definition: elog.c:698
const char * ParseExprKindName(ParseExprKind exprKind)
Definition: parse_expr.c:3001
#define ERROR
Definition: elog.h:46
Node * p_last_srf
Definition: parse_node.h:214
ParseExprKind p_expr_kind
Definition: parse_node.h:196
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
#define Assert(condition)
Definition: c.h:804
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define _(x)
Definition: elog.c:89

◆ func_get_detail()

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

Definition at line 1393 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::nominalnargs, _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().

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

925 {
926  FuncCandidateList current_candidate;
927  FuncCandidateList next_candidate;
928  int ncandidates = 0;
929 
930  *candidates = NULL;
931 
932  for (current_candidate = raw_candidates;
933  current_candidate != NULL;
934  current_candidate = next_candidate)
935  {
936  next_candidate = current_candidate->next;
937  if (can_coerce_type(nargs, input_typeids, current_candidate->args,
939  {
940  current_candidate->next = *candidates;
941  *candidates = current_candidate;
942  ncandidates++;
943  }
944  }
945 
946  return ncandidates;
947 } /* func_match_argtypes() */
bool can_coerce_type(int nargs, const Oid *input_typeids, const Oid *target_typeids, CoercionContext ccontext)
Definition: parse_coerce.c:556
Oid args[FLEXIBLE_ARRAY_MEMBER]
Definition: namespace.h:38
struct _FuncCandidateList * next
Definition: namespace.h:30

◆ func_select_candidate()

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

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

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

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

1996 {
1997  StringInfoData argbuf;
1998  int numposargs;
1999  ListCell *lc;
2000  int i;
2001 
2002  initStringInfo(&argbuf);
2003 
2004  appendStringInfo(&argbuf, "%s(", funcname);
2005 
2006  numposargs = nargs - list_length(argnames);
2007  lc = list_head(argnames);
2008 
2009  for (i = 0; i < nargs; i++)
2010  {
2011  if (i)
2012  appendStringInfoString(&argbuf, ", ");
2013  if (i >= numposargs)
2014  {
2015  appendStringInfo(&argbuf, "%s => ", (char *) lfirst(lc));
2016  lc = lnext(argnames, lc);
2017  }
2018  appendStringInfoString(&argbuf, format_type_be(argtypes[i]));
2019  }
2020 
2021  appendStringInfoChar(&argbuf, ')');
2022 
2023  return argbuf.data; /* return palloc'd string buffer */
2024 }
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:322
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 1882 of file parse_func.c.

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

Referenced by func_get_detail().

1883 {
1884  Oid result;
1885  Type typtup;
1886 
1887  /*
1888  * temp_ok=false protects the <refsect1 id="sql-createfunction-security">
1889  * contract for writing SECURITY DEFINER functions safely.
1890  */
1891  typtup = LookupTypeNameExtended(NULL, makeTypeNameFromNameList(funcname),
1892  NULL, false, false);
1893  if (typtup == NULL)
1894  return InvalidOid;
1895 
1896  if (((Form_pg_type) GETSTRUCT(typtup))->typisdefined &&
1897  !OidIsValid(typeTypeRelid(typtup)))
1898  result = typeTypeId(typtup);
1899  else
1900  result = InvalidOid;
1901 
1902  ReleaseSysCache(typtup);
1903  return result;
1904 }
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:654
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
#define InvalidOid
Definition: postgres_ext.h:36
FormData_pg_type * Form_pg_type
Definition: pg_type.h:261
Oid typeTypeRelid(Type typ)
Definition: parse_type.c:632
TypeName * makeTypeNameFromNameList(List *names)
Definition: makefuncs.c:456
Oid typeTypeId(Type tp)
Definition: parse_type.c:592

◆ LookupFuncName()

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

Definition at line 2145 of file parse_func.c.

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

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

2146 {
2147  Oid funcoid;
2148  FuncLookupError lookupError;
2149 
2151  funcname, nargs, argtypes,
2152  false, missing_ok,
2153  &lookupError);
2154 
2155  if (OidIsValid(funcoid))
2156  return funcoid;
2157 
2158  switch (lookupError)
2159  {
2160  case FUNCLOOKUP_NOSUCHFUNC:
2161  /* Let the caller deal with it when missing_ok is true */
2162  if (missing_ok)
2163  return InvalidOid;
2164 
2165  if (nargs < 0)
2166  ereport(ERROR,
2167  (errcode(ERRCODE_UNDEFINED_FUNCTION),
2168  errmsg("could not find a function named \"%s\"",
2169  NameListToString(funcname))));
2170  else
2171  ereport(ERROR,
2172  (errcode(ERRCODE_UNDEFINED_FUNCTION),
2173  errmsg("function %s does not exist",
2174  func_signature_string(funcname, nargs,
2175  NIL, argtypes))));
2176  break;
2177 
2178  case FUNCLOOKUP_AMBIGUOUS:
2179  /* Raise an error regardless of missing_ok */
2180  ereport(ERROR,
2181  (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
2182  errmsg("function name \"%s\" is not unique",
2183  NameListToString(funcname)),
2184  errhint("Specify the argument list to select the function unambiguously.")));
2185  break;
2186  }
2187 
2188  return InvalidOid; /* Keep compiler quiet */
2189 }
#define NIL
Definition: pg_list.h:65
int errhint(const char *fmt,...)
Definition: elog.c:1156
int errcode(int sqlerrcode)
Definition: elog.c:698
FuncLookupError
Definition: parse_func.c:39
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
#define ERROR
Definition: elog.h:46
const char * func_signature_string(List *funcname, int nargs, List *argnames, const Oid *argtypes)
Definition: parse_func.c:2031
char * NameListToString(List *names)
Definition: namespace.c:3147
static Oid LookupFuncNameInternal(ObjectType objtype, List *funcname, int nargs, const Oid *argtypes, bool include_out_arguments, bool missing_ok, FuncLookupError *lookupError)
Definition: parse_func.c:2050
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ LookupFuncNameInternal()

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

Definition at line 2050 of file parse_func.c.

References _FuncCandidateList::args, Assert, FUNCLOOKUP_AMBIGUOUS, FUNCLOOKUP_NOSUCHFUNC, FuncnameGetCandidates(), get_func_prokind(), InvalidOid, _FuncCandidateList::next, NIL, OBJECT_AGGREGATE, OBJECT_FUNCTION, OBJECT_PROCEDURE, OBJECT_ROUTINE, _FuncCandidateList::oid, and OidIsValid.

Referenced by LookupFuncName(), and LookupFuncWithArgs().

2054 {
2055  Oid result = InvalidOid;
2056  FuncCandidateList clist;
2057 
2058  /* NULL argtypes allowed for nullary functions only */
2059  Assert(argtypes != NULL || nargs == 0);
2060 
2061  /* Always set *lookupError, to forestall uninitialized-variable warnings */
2062  *lookupError = FUNCLOOKUP_NOSUCHFUNC;
2063 
2064  /* Get list of candidate objects */
2065  clist = FuncnameGetCandidates(funcname, nargs, NIL, false, false,
2066  include_out_arguments, missing_ok);
2067 
2068  /* Scan list for a match to the arg types (if specified) and the objtype */
2069  for (; clist != NULL; clist = clist->next)
2070  {
2071  /* Check arg type match, if specified */
2072  if (nargs >= 0)
2073  {
2074  /* if nargs==0, argtypes can be null; don't pass that to memcmp */
2075  if (nargs > 0 &&
2076  memcmp(argtypes, clist->args, nargs * sizeof(Oid)) != 0)
2077  continue;
2078  }
2079 
2080  /* Check for duplicates reported by FuncnameGetCandidates */
2081  if (!OidIsValid(clist->oid))
2082  {
2083  *lookupError = FUNCLOOKUP_AMBIGUOUS;
2084  return InvalidOid;
2085  }
2086 
2087  /* Check objtype match, if specified */
2088  switch (objtype)
2089  {
2090  case OBJECT_FUNCTION:
2091  case OBJECT_AGGREGATE:
2092  /* Ignore procedures */
2093  if (get_func_prokind(clist->oid) == PROKIND_PROCEDURE)
2094  continue;
2095  break;
2096  case OBJECT_PROCEDURE:
2097  /* Ignore non-procedures */
2098  if (get_func_prokind(clist->oid) != PROKIND_PROCEDURE)
2099  continue;
2100  break;
2101  case OBJECT_ROUTINE:
2102  /* no restriction */
2103  break;
2104  default:
2105  Assert(false);
2106  }
2107 
2108  /* Check for multiple matches */
2109  if (OidIsValid(result))
2110  {
2111  *lookupError = FUNCLOOKUP_AMBIGUOUS;
2112  return InvalidOid;
2113  }
2114 
2115  /* OK, we have a candidate */
2116  result = clist->oid;
2117  }
2118 
2119  return result;
2120 }
#define NIL
Definition: pg_list.h:65
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
Oid args[FLEXIBLE_ARRAY_MEMBER]
Definition: namespace.h:38
struct _FuncCandidateList * next
Definition: namespace.h:30
FuncCandidateList FuncnameGetCandidates(List *names, int nargs, List *argnames, bool expand_variadic, bool expand_defaults, bool include_out_arguments, bool missing_ok)
Definition: namespace.c:950
char get_func_prokind(Oid funcid)
Definition: lsyscache.c:1789
#define InvalidOid
Definition: postgres_ext.h:36
#define Assert(condition)
Definition: c.h:804

◆ LookupFuncWithArgs()

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

Definition at line 2207 of file parse_func.c.

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

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

2208 {
2209  Oid argoids[FUNC_MAX_ARGS];
2210  int argcount;
2211  int nargs;
2212  int i;
2213  ListCell *args_item;
2214  Oid oid;
2215  FuncLookupError lookupError;
2216 
2217  Assert(objtype == OBJECT_AGGREGATE ||
2218  objtype == OBJECT_FUNCTION ||
2219  objtype == OBJECT_PROCEDURE ||
2220  objtype == OBJECT_ROUTINE);
2221 
2222  argcount = list_length(func->objargs);
2223  if (argcount > FUNC_MAX_ARGS)
2224  {
2225  if (objtype == OBJECT_PROCEDURE)
2226  ereport(ERROR,
2227  (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
2228  errmsg_plural("procedures cannot have more than %d argument",
2229  "procedures cannot have more than %d arguments",
2230  FUNC_MAX_ARGS,
2231  FUNC_MAX_ARGS)));
2232  else
2233  ereport(ERROR,
2234  (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
2235  errmsg_plural("functions cannot have more than %d argument",
2236  "functions cannot have more than %d arguments",
2237  FUNC_MAX_ARGS,
2238  FUNC_MAX_ARGS)));
2239  }
2240 
2241  /*
2242  * First, perform a lookup considering only input arguments (traditional
2243  * Postgres rules).
2244  */
2245  i = 0;
2246  foreach(args_item, func->objargs)
2247  {
2248  TypeName *t = lfirst_node(TypeName, args_item);
2249 
2250  argoids[i] = LookupTypeNameOid(NULL, t, missing_ok);
2251  if (!OidIsValid(argoids[i]))
2252  return InvalidOid; /* missing_ok must be true */
2253  i++;
2254  }
2255 
2256  /*
2257  * Set nargs for LookupFuncNameInternal. It expects -1 to mean no args
2258  * were specified.
2259  */
2260  nargs = func->args_unspecified ? -1 : argcount;
2261 
2262  /*
2263  * In args_unspecified mode, also tell LookupFuncNameInternal to consider
2264  * the object type, since there seems no reason not to. However, if we
2265  * have an argument list, disable the objtype check, because we'd rather
2266  * complain about "object is of wrong type" than "object doesn't exist".
2267  * (Note that with args, FuncnameGetCandidates will have ensured there's
2268  * only one argtype match, so we're not risking an ambiguity failure via
2269  * this choice.)
2270  */
2271  oid = LookupFuncNameInternal(func->args_unspecified ? objtype : OBJECT_ROUTINE,
2272  func->objname, nargs, argoids,
2273  false, missing_ok,
2274  &lookupError);
2275 
2276  /*
2277  * If PROCEDURE or ROUTINE was specified, and we have an argument list
2278  * that contains no parameter mode markers, and we didn't already discover
2279  * that there's ambiguity, perform a lookup considering all arguments.
2280  * (Note: for a zero-argument procedure, or in args_unspecified mode, the
2281  * normal lookup is sufficient; so it's OK to require non-NIL objfuncargs
2282  * to perform this lookup.)
2283  */
2284  if ((objtype == OBJECT_PROCEDURE || objtype == OBJECT_ROUTINE) &&
2285  func->objfuncargs != NIL &&
2286  lookupError != FUNCLOOKUP_AMBIGUOUS)
2287  {
2288  bool have_param_mode = false;
2289 
2290  /*
2291  * Check for non-default parameter mode markers. If there are any,
2292  * then the command does not conform to SQL-spec syntax, so we may
2293  * assume that the traditional Postgres lookup method of considering
2294  * only input parameters is sufficient. (Note that because the spec
2295  * doesn't have OUT arguments for functions, we also don't need this
2296  * hack in FUNCTION or AGGREGATE mode.)
2297  */
2298  foreach(args_item, func->objfuncargs)
2299  {
2301 
2302  if (fp->mode != FUNC_PARAM_DEFAULT)
2303  {
2304  have_param_mode = true;
2305  break;
2306  }
2307  }
2308 
2309  if (!have_param_mode)
2310  {
2311  Oid poid;
2312 
2313  /* Without mode marks, objargs surely includes all params */
2314  Assert(list_length(func->objfuncargs) == argcount);
2315 
2316  /* For objtype == OBJECT_PROCEDURE, we can ignore non-procedures */
2317  poid = LookupFuncNameInternal(objtype, func->objname,
2318  argcount, argoids,
2319  true, missing_ok,
2320  &lookupError);
2321 
2322  /* Combine results, handling ambiguity */
2323  if (OidIsValid(poid))
2324  {
2325  if (OidIsValid(oid) && oid != poid)
2326  {
2327  /* oops, we got hits both ways, on different objects */
2328  oid = InvalidOid;
2329  lookupError = FUNCLOOKUP_AMBIGUOUS;
2330  }
2331  else
2332  oid = poid;
2333  }
2334  else if (lookupError == FUNCLOOKUP_AMBIGUOUS)
2335  oid = InvalidOid;
2336  }
2337  }
2338 
2339  if (OidIsValid(oid))
2340  {
2341  /*
2342  * Even if we found the function, perform validation that the objtype
2343  * matches the prokind of the found function. For historical reasons
2344  * we allow the objtype of FUNCTION to include aggregates and window
2345  * functions; but we draw the line if the object is a procedure. That
2346  * is a new enough feature that this historical rule does not apply.
2347  *
2348  * (This check is partially redundant with the objtype check in
2349  * LookupFuncNameInternal; but not entirely, since we often don't tell
2350  * LookupFuncNameInternal to apply that check at all.)
2351  */
2352  switch (objtype)
2353  {
2354  case OBJECT_FUNCTION:
2355  /* Only complain if it's a procedure. */
2356  if (get_func_prokind(oid) == PROKIND_PROCEDURE)
2357  ereport(ERROR,
2358  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2359  errmsg("%s is not a function",
2360  func_signature_string(func->objname, argcount,
2361  NIL, argoids))));
2362  break;
2363 
2364  case OBJECT_PROCEDURE:
2365  /* Reject if found object is not a procedure. */
2366  if (get_func_prokind(oid) != PROKIND_PROCEDURE)
2367  ereport(ERROR,
2368  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2369  errmsg("%s is not a procedure",
2370  func_signature_string(func->objname, argcount,
2371  NIL, argoids))));
2372  break;
2373 
2374  case OBJECT_AGGREGATE:
2375  /* Reject if found object is not an aggregate. */
2376  if (get_func_prokind(oid) != PROKIND_AGGREGATE)
2377  ereport(ERROR,
2378  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2379  errmsg("function %s is not an aggregate",
2380  func_signature_string(func->objname, argcount,
2381  NIL, argoids))));
2382  break;
2383 
2384  default:
2385  /* OBJECT_ROUTINE accepts anything. */
2386  break;
2387  }
2388 
2389  return oid; /* All good */
2390  }
2391  else
2392  {
2393  /* Deal with cases where the lookup failed */
2394  switch (lookupError)
2395  {
2396  case FUNCLOOKUP_NOSUCHFUNC:
2397  /* Suppress no-such-func errors when missing_ok is true */
2398  if (missing_ok)
2399  break;
2400 
2401  switch (objtype)
2402  {
2403  case OBJECT_PROCEDURE:
2404  if (func->args_unspecified)
2405  ereport(ERROR,
2406  (errcode(ERRCODE_UNDEFINED_FUNCTION),
2407  errmsg("could not find a procedure named \"%s\"",
2408  NameListToString(func->objname))));
2409  else
2410  ereport(ERROR,
2411  (errcode(ERRCODE_UNDEFINED_FUNCTION),
2412  errmsg("procedure %s does not exist",
2413  func_signature_string(func->objname, argcount,
2414  NIL, argoids))));
2415  break;
2416 
2417  case OBJECT_AGGREGATE:
2418  if (func->args_unspecified)
2419  ereport(ERROR,
2420  (errcode(ERRCODE_UNDEFINED_FUNCTION),
2421  errmsg("could not find an aggregate named \"%s\"",
2422  NameListToString(func->objname))));
2423  else if (argcount == 0)
2424  ereport(ERROR,
2425  (errcode(ERRCODE_UNDEFINED_FUNCTION),
2426  errmsg("aggregate %s(*) does not exist",
2427  NameListToString(func->objname))));
2428  else
2429  ereport(ERROR,
2430  (errcode(ERRCODE_UNDEFINED_FUNCTION),
2431  errmsg("aggregate %s does not exist",
2432  func_signature_string(func->objname, argcount,
2433  NIL, argoids))));
2434  break;
2435 
2436  default:
2437  /* FUNCTION and ROUTINE */
2438  if (func->args_unspecified)
2439  ereport(ERROR,
2440  (errcode(ERRCODE_UNDEFINED_FUNCTION),
2441  errmsg("could not find a function named \"%s\"",
2442  NameListToString(func->objname))));
2443  else
2444  ereport(ERROR,
2445  (errcode(ERRCODE_UNDEFINED_FUNCTION),
2446  errmsg("function %s does not exist",
2447  func_signature_string(func->objname, argcount,
2448  NIL, argoids))));
2449  break;
2450  }
2451  break;
2452 
2453  case FUNCLOOKUP_AMBIGUOUS:
2454  switch (objtype)
2455  {
2456  case OBJECT_FUNCTION:
2457  ereport(ERROR,
2458  (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
2459  errmsg("function name \"%s\" is not unique",
2460  NameListToString(func->objname)),
2461  func->args_unspecified ?
2462  errhint("Specify the argument list to select the function unambiguously.") : 0));
2463  break;
2464  case OBJECT_PROCEDURE:
2465  ereport(ERROR,
2466  (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
2467  errmsg("procedure name \"%s\" is not unique",
2468  NameListToString(func->objname)),
2469  func->args_unspecified ?
2470  errhint("Specify the argument list to select the procedure unambiguously.") : 0));
2471  break;
2472  case OBJECT_AGGREGATE:
2473  ereport(ERROR,
2474  (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
2475  errmsg("aggregate name \"%s\" is not unique",
2476  NameListToString(func->objname)),
2477  func->args_unspecified ?
2478  errhint("Specify the argument list to select the aggregate unambiguously.") : 0));
2479  break;
2480  case OBJECT_ROUTINE:
2481  ereport(ERROR,
2482  (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
2483  errmsg("routine name \"%s\" is not unique",
2484  NameListToString(func->objname)),
2485  func->args_unspecified ?
2486  errhint("Specify the argument list to select the routine unambiguously.") : 0));
2487  break;
2488 
2489  default:
2490  Assert(false); /* Disallowed by Assert above */
2491  break;
2492  }
2493  break;
2494  }
2495 
2496  return InvalidOid;
2497  }
2498 }
#define NIL
Definition: pg_list.h:65
int errhint(const char *fmt,...)
Definition: elog.c:1156
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1019
int errcode(int sqlerrcode)
Definition: elog.c:698
FuncLookupError
Definition: parse_func.c:39
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
#define FUNC_MAX_ARGS
#define ERROR
Definition: elog.h:46
#define lfirst_node(type, lc)
Definition: pg_list.h:172
bool args_unspecified
Definition: parsenodes.h:2062
const char * func_signature_string(List *funcname, int nargs, List *argnames, const Oid *argtypes)
Definition: parse_func.c:2031
char * NameListToString(List *names)
Definition: namespace.c:3147
char get_func_prokind(Oid funcid)
Definition: lsyscache.c:1789
static Oid LookupFuncNameInternal(ObjectType objtype, List *funcname, int nargs, const Oid *argtypes, bool include_out_arguments, bool missing_ok, FuncLookupError *lookupError)
Definition: parse_func.c:2050
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
#define Assert(condition)
Definition: c.h:804
static int list_length(const List *l)
Definition: pg_list.h:149
int errmsg(const char *fmt,...)
Definition: elog.c:909
int i
FunctionParameterMode mode
Definition: parsenodes.h:2992
List * objfuncargs
Definition: parsenodes.h:2061
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 1826 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().

1830 {
1831  ListCell *current_fargs;
1832  int i = 0;
1833 
1834  foreach(current_fargs, fargs)
1835  {
1836  /* types don't match? then force coercion using a function call... */
1837  if (actual_arg_types[i] != declared_arg_types[i])
1838  {
1839  Node *node = (Node *) lfirst(current_fargs);
1840 
1841  /*
1842  * If arg is a NamedArgExpr, coerce its input expr instead --- we
1843  * want the NamedArgExpr to stay at the top level of the list.
1844  */
1845  if (IsA(node, NamedArgExpr))
1846  {
1847  NamedArgExpr *na = (NamedArgExpr *) node;
1848 
1849  node = coerce_type(pstate,
1850  (Node *) na->arg,
1851  actual_arg_types[i],
1852  declared_arg_types[i], -1,
1855  -1);
1856  na->arg = (Expr *) node;
1857  }
1858  else
1859  {
1860  node = coerce_type(pstate,
1861  node,
1862  actual_arg_types[i],
1863  declared_arg_types[i], -1,
1866  -1);
1867  lfirst(current_fargs) = node;
1868  }
1869  }
1870  i++;
1871  }
1872 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:587
Node * coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:157
Definition: nodes.h:536
Expr * arg
Definition: primnodes.h:524
#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 1913 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().

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

◆ ParseFuncOrColumn()

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

Definition at line 90 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(), errhint_plural(), 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().

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

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

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