PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
parse_func.h File Reference
Include dependency graph for parse_func.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Enumerations

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

Functions

NodeParseFuncOrColumn (ParseState *pstate, List *funcname, List *fargs, Node *last_srf, FuncCall *fn, int location)
 
FuncDetailCode func_get_detail (List *funcname, List *fargs, List *fargnames, int nargs, Oid *argtypes, bool expand_variadic, bool expand_defaults, Oid *funcid, Oid *rettype, bool *retset, int *nvargs, Oid *vatype, Oid **true_typeids, List **argdefaults)
 
int func_match_argtypes (int nargs, Oid *input_typeids, FuncCandidateList raw_candidates, FuncCandidateList *candidates)
 
FuncCandidateList func_select_candidate (int nargs, Oid *input_typeids, FuncCandidateList candidates)
 
void make_fn_arguments (ParseState *pstate, List *fargs, Oid *actual_arg_types, Oid *declared_arg_types)
 
const char * funcname_signature_string (const char *funcname, int nargs, List *argnames, const Oid *argtypes)
 
const char * func_signature_string (List *funcname, int nargs, List *argnames, const Oid *argtypes)
 
Oid LookupFuncName (List *funcname, int nargs, const Oid *argtypes, bool noError)
 
Oid LookupFuncWithArgs (ObjectWithArgs *func, bool noError)
 
Oid LookupAggWithArgs (ObjectWithArgs *agg, bool noError)
 
void check_srf_call_placement (ParseState *pstate, Node *last_srf, int location)
 

Enumeration Type Documentation

Enumerator
FUNCDETAIL_NOTFOUND 
FUNCDETAIL_MULTIPLE 
FUNCDETAIL_NORMAL 
FUNCDETAIL_AGGREGATE 
FUNCDETAIL_WINDOWFUNC 
FUNCDETAIL_COERCION 

Definition at line 22 of file parse_func.h.

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

Function Documentation

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

Definition at line 2111 of file parse_func.c.

References _, Assert, ereport, errcode(), errmsg(), errmsg_internal(), ERROR, EXPR_KIND_ALTER_COL_TRANSFORM, EXPR_KIND_CHECK_CONSTRAINT, EXPR_KIND_COLUMN_DEFAULT, 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_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_EXPRESSION, EXPR_KIND_POLICY, EXPR_KIND_RETURNING, EXPR_KIND_SELECT_TARGET, EXPR_KIND_TRIGGER_WHEN, EXPR_KIND_UPDATE_SOURCE, EXPR_KIND_UPDATE_TARGET, EXPR_KIND_VALUES, EXPR_KIND_VALUES_SINGLE, EXPR_KIND_WHERE, EXPR_KIND_WINDOW_FRAME_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().

2112 {
2113  const char *err;
2114  bool errkind;
2115 
2116  /*
2117  * Check to see if the set-returning function is in an invalid place
2118  * within the query. Basically, we don't allow SRFs anywhere except in
2119  * the targetlist (which includes GROUP BY/ORDER BY expressions), VALUES,
2120  * and functions in FROM.
2121  *
2122  * For brevity we support two schemes for reporting an error here: set
2123  * "err" to a custom message, or set "errkind" true if the error context
2124  * is sufficiently identified by what ParseExprKindName will return, *and*
2125  * what it will return is just a SQL keyword. (Otherwise, use a custom
2126  * message to avoid creating translation problems.)
2127  */
2128  err = NULL;
2129  errkind = false;
2130  switch (pstate->p_expr_kind)
2131  {
2132  case EXPR_KIND_NONE:
2133  Assert(false); /* can't happen */
2134  break;
2135  case EXPR_KIND_OTHER:
2136  /* Accept SRF here; caller must throw error if wanted */
2137  break;
2138  case EXPR_KIND_JOIN_ON:
2139  case EXPR_KIND_JOIN_USING:
2140  err = _("set-returning functions are not allowed in JOIN conditions");
2141  break;
2143  /* can't get here, but just in case, throw an error */
2144  errkind = true;
2145  break;
2147  /* okay, but we don't allow nested SRFs here */
2148  /* errmsg is chosen to match transformRangeFunction() */
2149  /* errposition should point to the inner SRF */
2150  if (pstate->p_last_srf != last_srf)
2151  ereport(ERROR,
2152  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2153  errmsg("set-returning functions must appear at top level of FROM"),
2154  parser_errposition(pstate,
2155  exprLocation(pstate->p_last_srf))));
2156  break;
2157  case EXPR_KIND_WHERE:
2158  errkind = true;
2159  break;
2160  case EXPR_KIND_POLICY:
2161  err = _("set-returning functions are not allowed in policy expressions");
2162  break;
2163  case EXPR_KIND_HAVING:
2164  errkind = true;
2165  break;
2166  case EXPR_KIND_FILTER:
2167  errkind = true;
2168  break;
2171  /* okay, these are effectively GROUP BY/ORDER BY */
2172  pstate->p_hasTargetSRFs = true;
2173  break;
2176  err = _("set-returning functions are not allowed in window definitions");
2177  break;
2180  /* okay */
2181  pstate->p_hasTargetSRFs = true;
2182  break;
2185  /* disallowed because it would be ambiguous what to do */
2186  errkind = true;
2187  break;
2188  case EXPR_KIND_GROUP_BY:
2189  case EXPR_KIND_ORDER_BY:
2190  /* okay */
2191  pstate->p_hasTargetSRFs = true;
2192  break;
2193  case EXPR_KIND_DISTINCT_ON:
2194  /* okay */
2195  pstate->p_hasTargetSRFs = true;
2196  break;
2197  case EXPR_KIND_LIMIT:
2198  case EXPR_KIND_OFFSET:
2199  errkind = true;
2200  break;
2201  case EXPR_KIND_RETURNING:
2202  errkind = true;
2203  break;
2204  case EXPR_KIND_VALUES:
2205  /* SRFs are presently not supported by nodeValuesscan.c */
2206  errkind = true;
2207  break;
2209  /* okay, since we process this like a SELECT tlist */
2210  pstate->p_hasTargetSRFs = true;
2211  break;
2214  err = _("set-returning functions are not allowed in check constraints");
2215  break;
2218  err = _("set-returning functions are not allowed in DEFAULT expressions");
2219  break;
2221  err = _("set-returning functions are not allowed in index expressions");
2222  break;
2224  err = _("set-returning functions are not allowed in index predicates");
2225  break;
2227  err = _("set-returning functions are not allowed in transform expressions");
2228  break;
2230  err = _("set-returning functions are not allowed in EXECUTE parameters");
2231  break;
2233  err = _("set-returning functions are not allowed in trigger WHEN conditions");
2234  break;
2236  err = _("set-returning functions are not allowed in partition key expressions");
2237  break;
2238 
2239  /*
2240  * There is intentionally no default: case here, so that the
2241  * compiler will warn if we add a new ParseExprKind without
2242  * extending this switch. If we do see an unrecognized value at
2243  * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
2244  * which is sane anyway.
2245  */
2246  }
2247  if (err)
2248  ereport(ERROR,
2249  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2250  errmsg_internal("%s", err),
2251  parser_errposition(pstate, location)));
2252  if (errkind)
2253  ereport(ERROR,
2254  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2255  /* translator: %s is name of a SQL construct, eg GROUP BY */
2256  errmsg("set-returning functions are not allowed in %s",
2257  ParseExprKindName(pstate->p_expr_kind)),
2258  parser_errposition(pstate, location)));
2259 }
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1186
bool p_hasTargetSRFs
Definition: parse_node.h:200
int errcode(int sqlerrcode)
Definition: elog.c:575
const char * ParseExprKindName(ParseExprKind exprKind)
Definition: parse_expr.c:3393
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
Node * p_last_srf
Definition: parse_node.h:204
ParseExprKind p_expr_kind
Definition: parse_node.h:186
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
#define Assert(condition)
Definition: c.h:681
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define _(x)
Definition: elog.c:84
FuncDetailCode func_get_detail ( List funcname,
List fargs,
List fargnames,
int  nargs,
Oid argtypes,
bool  expand_variadic,
bool  expand_defaults,
Oid funcid,
Oid rettype,
bool retset,
int *  nvargs,
Oid vatype,
Oid **  true_typeids,
List **  argdefaults 
)

Definition at line 1283 of file parse_func.c.

References Anum_pg_proc_proargdefaults, 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_WINDOWFUNC, FuncNameAsType(), FuncnameGetCandidates(), GETSTRUCT, HeapTupleIsValid, i, InvalidOid, IsA, ISCOMPLEX, lappend(), lfirst, linitial, list_delete_first(), list_length(), _FuncCandidateList::nargs, _FuncCandidateList::ndargs, _FuncCandidateList::next, NIL, _FuncCandidateList::nvargs, ObjectIdGetDatum, _FuncCandidateList::oid, OidIsValid, pfree(), PROCOID, RECORDOID, ReleaseSysCache(), SearchSysCache1(), stringToNode(), SysCacheGetAttr(), TextDatumGetCString, TYPCATEGORY_STRING, TypeCategory(), and UNKNOWNOID.

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

1297 {
1298  FuncCandidateList raw_candidates;
1299  FuncCandidateList best_candidate;
1300 
1301  /* Passing NULL for argtypes is no longer allowed */
1302  Assert(argtypes);
1303 
1304  /* initialize output arguments to silence compiler warnings */
1305  *funcid = InvalidOid;
1306  *rettype = InvalidOid;
1307  *retset = false;
1308  *nvargs = 0;
1309  *vatype = InvalidOid;
1310  *true_typeids = NULL;
1311  if (argdefaults)
1312  *argdefaults = NIL;
1313 
1314  /* Get list of possible candidates from namespace search */
1315  raw_candidates = FuncnameGetCandidates(funcname, nargs, fargnames,
1316  expand_variadic, expand_defaults,
1317  false);
1318 
1319  /*
1320  * Quickly check if there is an exact match to the input datatypes (there
1321  * can be only one)
1322  */
1323  for (best_candidate = raw_candidates;
1324  best_candidate != NULL;
1325  best_candidate = best_candidate->next)
1326  {
1327  if (memcmp(argtypes, best_candidate->args, nargs * sizeof(Oid)) == 0)
1328  break;
1329  }
1330 
1331  if (best_candidate == NULL)
1332  {
1333  /*
1334  * If we didn't find an exact match, next consider the possibility
1335  * that this is really a type-coercion request: a single-argument
1336  * function call where the function name is a type name. If so, and
1337  * if the coercion path is RELABELTYPE or COERCEVIAIO, then go ahead
1338  * and treat the "function call" as a coercion.
1339  *
1340  * This interpretation needs to be given higher priority than
1341  * interpretations involving a type coercion followed by a function
1342  * call, otherwise we can produce surprising results. For example, we
1343  * want "text(varchar)" to be interpreted as a simple coercion, not as
1344  * "text(name(varchar))" which the code below this point is entirely
1345  * capable of selecting.
1346  *
1347  * We also treat a coercion of a previously-unknown-type literal
1348  * constant to a specific type this way.
1349  *
1350  * The reason we reject COERCION_PATH_FUNC here is that we expect the
1351  * cast implementation function to be named after the target type.
1352  * Thus the function will be found by normal lookup if appropriate.
1353  *
1354  * The reason we reject COERCION_PATH_ARRAYCOERCE is mainly that you
1355  * can't write "foo[] (something)" as a function call. In theory
1356  * someone might want to invoke it as "_foo (something)" but we have
1357  * never supported that historically, so we can insist that people
1358  * write it as a normal cast instead.
1359  *
1360  * We also reject the specific case of COERCEVIAIO for a composite
1361  * source type and a string-category target type. This is a case that
1362  * find_coercion_pathway() allows by default, but experience has shown
1363  * that it's too commonly invoked by mistake. So, again, insist that
1364  * people use cast syntax if they want to do that.
1365  *
1366  * NB: it's important that this code does not exceed what coerce_type
1367  * can do, because the caller will try to apply coerce_type if we
1368  * return FUNCDETAIL_COERCION. If we return that result for something
1369  * coerce_type can't handle, we'll cause infinite recursion between
1370  * this module and coerce_type!
1371  */
1372  if (nargs == 1 && fargs != NIL && fargnames == NIL)
1373  {
1374  Oid targetType = FuncNameAsType(funcname);
1375 
1376  if (OidIsValid(targetType))
1377  {
1378  Oid sourceType = argtypes[0];
1379  Node *arg1 = linitial(fargs);
1380  bool iscoercion;
1381 
1382  if (sourceType == UNKNOWNOID && IsA(arg1, Const))
1383  {
1384  /* always treat typename('literal') as coercion */
1385  iscoercion = true;
1386  }
1387  else
1388  {
1389  CoercionPathType cpathtype;
1390  Oid cfuncid;
1391 
1392  cpathtype = find_coercion_pathway(targetType, sourceType,
1394  &cfuncid);
1395  switch (cpathtype)
1396  {
1398  iscoercion = true;
1399  break;
1401  if ((sourceType == RECORDOID ||
1402  ISCOMPLEX(sourceType)) &&
1403  TypeCategory(targetType) == TYPCATEGORY_STRING)
1404  iscoercion = false;
1405  else
1406  iscoercion = true;
1407  break;
1408  default:
1409  iscoercion = false;
1410  break;
1411  }
1412  }
1413 
1414  if (iscoercion)
1415  {
1416  /* Treat it as a type coercion */
1417  *funcid = InvalidOid;
1418  *rettype = targetType;
1419  *retset = false;
1420  *nvargs = 0;
1421  *vatype = InvalidOid;
1422  *true_typeids = argtypes;
1423  return FUNCDETAIL_COERCION;
1424  }
1425  }
1426  }
1427 
1428  /*
1429  * didn't find an exact match, so now try to match up candidates...
1430  */
1431  if (raw_candidates != NULL)
1432  {
1433  FuncCandidateList current_candidates;
1434  int ncandidates;
1435 
1436  ncandidates = func_match_argtypes(nargs,
1437  argtypes,
1438  raw_candidates,
1439  &current_candidates);
1440 
1441  /* one match only? then run with it... */
1442  if (ncandidates == 1)
1443  best_candidate = current_candidates;
1444 
1445  /*
1446  * multiple candidates? then better decide or throw an error...
1447  */
1448  else if (ncandidates > 1)
1449  {
1450  best_candidate = func_select_candidate(nargs,
1451  argtypes,
1452  current_candidates);
1453 
1454  /*
1455  * If we were able to choose a best candidate, we're done.
1456  * Otherwise, ambiguous function call.
1457  */
1458  if (!best_candidate)
1459  return FUNCDETAIL_MULTIPLE;
1460  }
1461  }
1462  }
1463 
1464  if (best_candidate)
1465  {
1466  HeapTuple ftup;
1467  Form_pg_proc pform;
1468  FuncDetailCode result;
1469 
1470  /*
1471  * If processing named args or expanding variadics or defaults, the
1472  * "best candidate" might represent multiple equivalently good
1473  * functions; treat this case as ambiguous.
1474  */
1475  if (!OidIsValid(best_candidate->oid))
1476  return FUNCDETAIL_MULTIPLE;
1477 
1478  /*
1479  * We disallow VARIADIC with named arguments unless the last argument
1480  * (the one with VARIADIC attached) actually matched the variadic
1481  * parameter. This is mere pedantry, really, but some folks insisted.
1482  */
1483  if (fargnames != NIL && !expand_variadic && nargs > 0 &&
1484  best_candidate->argnumbers[nargs - 1] != nargs - 1)
1485  return FUNCDETAIL_NOTFOUND;
1486 
1487  *funcid = best_candidate->oid;
1488  *nvargs = best_candidate->nvargs;
1489  *true_typeids = best_candidate->args;
1490 
1491  /*
1492  * If processing named args, return actual argument positions into
1493  * NamedArgExpr nodes in the fargs list. This is a bit ugly but not
1494  * worth the extra notation needed to do it differently.
1495  */
1496  if (best_candidate->argnumbers != NULL)
1497  {
1498  int i = 0;
1499  ListCell *lc;
1500 
1501  foreach(lc, fargs)
1502  {
1503  NamedArgExpr *na = (NamedArgExpr *) lfirst(lc);
1504 
1505  if (IsA(na, NamedArgExpr))
1506  na->argnumber = best_candidate->argnumbers[i];
1507  i++;
1508  }
1509  }
1510 
1511  ftup = SearchSysCache1(PROCOID,
1512  ObjectIdGetDatum(best_candidate->oid));
1513  if (!HeapTupleIsValid(ftup)) /* should not happen */
1514  elog(ERROR, "cache lookup failed for function %u",
1515  best_candidate->oid);
1516  pform = (Form_pg_proc) GETSTRUCT(ftup);
1517  *rettype = pform->prorettype;
1518  *retset = pform->proretset;
1519  *vatype = pform->provariadic;
1520  /* fetch default args if caller wants 'em */
1521  if (argdefaults && best_candidate->ndargs > 0)
1522  {
1523  Datum proargdefaults;
1524  bool isnull;
1525  char *str;
1526  List *defaults;
1527 
1528  /* shouldn't happen, FuncnameGetCandidates messed up */
1529  if (best_candidate->ndargs > pform->pronargdefaults)
1530  elog(ERROR, "not enough default arguments");
1531 
1532  proargdefaults = SysCacheGetAttr(PROCOID, ftup,
1534  &isnull);
1535  Assert(!isnull);
1536  str = TextDatumGetCString(proargdefaults);
1537  defaults = castNode(List, stringToNode(str));
1538  pfree(str);
1539 
1540  /* Delete any unused defaults from the returned list */
1541  if (best_candidate->argnumbers != NULL)
1542  {
1543  /*
1544  * This is a bit tricky in named notation, since the supplied
1545  * arguments could replace any subset of the defaults. We
1546  * work by making a bitmapset of the argnumbers of defaulted
1547  * arguments, then scanning the defaults list and selecting
1548  * the needed items. (This assumes that defaulted arguments
1549  * should be supplied in their positional order.)
1550  */
1551  Bitmapset *defargnumbers;
1552  int *firstdefarg;
1553  List *newdefaults;
1554  ListCell *lc;
1555  int i;
1556 
1557  defargnumbers = NULL;
1558  firstdefarg = &best_candidate->argnumbers[best_candidate->nargs - best_candidate->ndargs];
1559  for (i = 0; i < best_candidate->ndargs; i++)
1560  defargnumbers = bms_add_member(defargnumbers,
1561  firstdefarg[i]);
1562  newdefaults = NIL;
1563  i = pform->pronargs - pform->pronargdefaults;
1564  foreach(lc, defaults)
1565  {
1566  if (bms_is_member(i, defargnumbers))
1567  newdefaults = lappend(newdefaults, lfirst(lc));
1568  i++;
1569  }
1570  Assert(list_length(newdefaults) == best_candidate->ndargs);
1571  bms_free(defargnumbers);
1572  *argdefaults = newdefaults;
1573  }
1574  else
1575  {
1576  /*
1577  * Defaults for positional notation are lots easier; just
1578  * remove any unwanted ones from the front.
1579  */
1580  int ndelete;
1581 
1582  ndelete = list_length(defaults) - best_candidate->ndargs;
1583  while (ndelete-- > 0)
1584  defaults = list_delete_first(defaults);
1585  *argdefaults = defaults;
1586  }
1587  }
1588  if (pform->proisagg)
1589  result = FUNCDETAIL_AGGREGATE;
1590  else if (pform->proiswindow)
1591  result = FUNCDETAIL_WINDOWFUNC;
1592  else
1593  result = FUNCDETAIL_NORMAL;
1594  ReleaseSysCache(ftup);
1595  return result;
1596  }
1597 
1598  return FUNCDETAIL_NOTFOUND;
1599 }
#define NIL
Definition: pg_list.h:69
void * stringToNode(char *str)
Definition: read.c:38
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
int func_match_argtypes(int nargs, Oid *input_typeids, FuncCandidateList raw_candidates, FuncCandidateList *candidates)
Definition: parse_func.c:811
#define castNode(_type_, nodeptr)
Definition: nodes.h:579
static Oid FuncNameAsType(List *funcname)
Definition: parse_func.c:1767
Definition: nodes.h:510
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:532
CoercionPathType
Definition: parse_coerce.h:24
Oid args[FLEXIBLE_ARRAY_MEMBER]
Definition: namespace.h:37
void pfree(void *pointer)
Definition: mcxt.c:949
#define linitial(l)
Definition: pg_list.h:111
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
FuncCandidateList FuncnameGetCandidates(List *names, int nargs, List *argnames, bool expand_variadic, bool expand_defaults, bool missing_ok)
Definition: namespace.c:903
#define Anum_pg_proc_proargdefaults
Definition: pg_proc.h:113
FuncDetailCode
Definition: parse_func.h:22
#define RECORDOID
Definition: pg_type.h:680
struct _FuncCandidateList * next
Definition: namespace.h:30
List * lappend(List *list, void *datum)
Definition: list.c:128
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
#define TextDatumGetCString(d)
Definition: builtins.h:92
uintptr_t Datum
Definition: postgres.h:372
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1368
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:83
#define InvalidOid
Definition: postgres_ext.h:36
TYPCATEGORY TypeCategory(Oid type)
#define TYPCATEGORY_STRING
Definition: pg_type.h:738
void bms_free(Bitmapset *a)
Definition: bitmapset.c:201
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define Assert(condition)
Definition: c.h:681
#define lfirst(lc)
Definition: pg_list.h:106
#define ISCOMPLEX(typeid)
Definition: parse_type.h:53
static int list_length(const List *l)
Definition: pg_list.h:89
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:698
#define UNKNOWNOID
Definition: pg_type.h:431
FuncCandidateList func_select_candidate(int nargs, Oid *input_typeids, FuncCandidateList candidates)
Definition: parse_func.c:896
CoercionPathType find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId, CoercionContext ccontext, Oid *funcid)
int i
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:420
List * list_delete_first(List *list)
Definition: list.c:666
int func_match_argtypes ( int  nargs,
Oid input_typeids,
FuncCandidateList  raw_candidates,
FuncCandidateList candidates 
)

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

815 {
816  FuncCandidateList current_candidate;
817  FuncCandidateList next_candidate;
818  int ncandidates = 0;
819 
820  *candidates = NULL;
821 
822  for (current_candidate = raw_candidates;
823  current_candidate != NULL;
824  current_candidate = next_candidate)
825  {
826  next_candidate = current_candidate->next;
827  if (can_coerce_type(nargs, input_typeids, current_candidate->args,
829  {
830  current_candidate->next = *candidates;
831  *candidates = current_candidate;
832  ncandidates++;
833  }
834  }
835 
836  return ncandidates;
837 } /* func_match_argtypes() */
Oid args[FLEXIBLE_ARRAY_MEMBER]
Definition: namespace.h:37
struct _FuncCandidateList * next
Definition: namespace.h:30
bool can_coerce_type(int nargs, Oid *input_typeids, Oid *target_typeids, CoercionContext ccontext)
Definition: parse_coerce.c:526
FuncCandidateList func_select_candidate ( int  nargs,
Oid input_typeids,
FuncCandidateList  candidates 
)

Definition at line 896 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, TYPCATEGORY_INVALID, TYPCATEGORY_STRING, TypeCategory(), and UNKNOWNOID.

Referenced by func_get_detail(), and oper_select_candidate().

899 {
900  FuncCandidateList current_candidate,
901  first_candidate,
902  last_candidate;
903  Oid *current_typeids;
904  Oid current_type;
905  int i;
906  int ncandidates;
907  int nbestMatch,
908  nmatch,
909  nunknowns;
910  Oid input_base_typeids[FUNC_MAX_ARGS];
911  TYPCATEGORY slot_category[FUNC_MAX_ARGS],
912  current_category;
913  bool current_is_preferred;
914  bool slot_has_preferred_type[FUNC_MAX_ARGS];
915  bool resolved_unknowns;
916 
917  /* protect local fixed-size arrays */
918  if (nargs > FUNC_MAX_ARGS)
919  ereport(ERROR,
920  (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
921  errmsg_plural("cannot pass more than %d argument to a function",
922  "cannot pass more than %d arguments to a function",
924  FUNC_MAX_ARGS)));
925 
926  /*
927  * If any input types are domains, reduce them to their base types. This
928  * ensures that we will consider functions on the base type to be "exact
929  * matches" in the exact-match heuristic; it also makes it possible to do
930  * something useful with the type-category heuristics. Note that this
931  * makes it difficult, but not impossible, to use functions declared to
932  * take a domain as an input datatype. Such a function will be selected
933  * over the base-type function only if it is an exact match at all
934  * argument positions, and so was already chosen by our caller.
935  *
936  * While we're at it, count the number of unknown-type arguments for use
937  * later.
938  */
939  nunknowns = 0;
940  for (i = 0; i < nargs; i++)
941  {
942  if (input_typeids[i] != UNKNOWNOID)
943  input_base_typeids[i] = getBaseType(input_typeids[i]);
944  else
945  {
946  /* no need to call getBaseType on UNKNOWNOID */
947  input_base_typeids[i] = UNKNOWNOID;
948  nunknowns++;
949  }
950  }
951 
952  /*
953  * Run through all candidates and keep those with the most matches on
954  * exact types. Keep all candidates if none match.
955  */
956  ncandidates = 0;
957  nbestMatch = 0;
958  last_candidate = NULL;
959  for (current_candidate = candidates;
960  current_candidate != NULL;
961  current_candidate = current_candidate->next)
962  {
963  current_typeids = current_candidate->args;
964  nmatch = 0;
965  for (i = 0; i < nargs; i++)
966  {
967  if (input_base_typeids[i] != UNKNOWNOID &&
968  current_typeids[i] == input_base_typeids[i])
969  nmatch++;
970  }
971 
972  /* take this one as the best choice so far? */
973  if ((nmatch > nbestMatch) || (last_candidate == NULL))
974  {
975  nbestMatch = nmatch;
976  candidates = current_candidate;
977  last_candidate = current_candidate;
978  ncandidates = 1;
979  }
980  /* no worse than the last choice, so keep this one too? */
981  else if (nmatch == nbestMatch)
982  {
983  last_candidate->next = current_candidate;
984  last_candidate = current_candidate;
985  ncandidates++;
986  }
987  /* otherwise, don't bother keeping this one... */
988  }
989 
990  if (last_candidate) /* terminate rebuilt list */
991  last_candidate->next = NULL;
992 
993  if (ncandidates == 1)
994  return candidates;
995 
996  /*
997  * Still too many candidates? Now look for candidates which have either
998  * exact matches or preferred types at the args that will require
999  * coercion. (Restriction added in 7.4: preferred type must be of same
1000  * category as input type; give no preference to cross-category
1001  * conversions to preferred types.) Keep all candidates if none match.
1002  */
1003  for (i = 0; i < nargs; i++) /* avoid multiple lookups */
1004  slot_category[i] = TypeCategory(input_base_typeids[i]);
1005  ncandidates = 0;
1006  nbestMatch = 0;
1007  last_candidate = NULL;
1008  for (current_candidate = candidates;
1009  current_candidate != NULL;
1010  current_candidate = current_candidate->next)
1011  {
1012  current_typeids = current_candidate->args;
1013  nmatch = 0;
1014  for (i = 0; i < nargs; i++)
1015  {
1016  if (input_base_typeids[i] != UNKNOWNOID)
1017  {
1018  if (current_typeids[i] == input_base_typeids[i] ||
1019  IsPreferredType(slot_category[i], current_typeids[i]))
1020  nmatch++;
1021  }
1022  }
1023 
1024  if ((nmatch > nbestMatch) || (last_candidate == NULL))
1025  {
1026  nbestMatch = nmatch;
1027  candidates = current_candidate;
1028  last_candidate = current_candidate;
1029  ncandidates = 1;
1030  }
1031  else if (nmatch == nbestMatch)
1032  {
1033  last_candidate->next = current_candidate;
1034  last_candidate = current_candidate;
1035  ncandidates++;
1036  }
1037  }
1038 
1039  if (last_candidate) /* terminate rebuilt list */
1040  last_candidate->next = NULL;
1041 
1042  if (ncandidates == 1)
1043  return candidates;
1044 
1045  /*
1046  * Still too many candidates? Try assigning types for the unknown inputs.
1047  *
1048  * If there are no unknown inputs, we have no more heuristics that apply,
1049  * and must fail.
1050  */
1051  if (nunknowns == 0)
1052  return NULL; /* failed to select a best candidate */
1053 
1054  /*
1055  * The next step examines each unknown argument position to see if we can
1056  * determine a "type category" for it. If any candidate has an input
1057  * datatype of STRING category, use STRING category (this bias towards
1058  * STRING is appropriate since unknown-type literals look like strings).
1059  * Otherwise, if all the candidates agree on the type category of this
1060  * argument position, use that category. Otherwise, fail because we
1061  * cannot determine a category.
1062  *
1063  * If we are able to determine a type category, also notice whether any of
1064  * the candidates takes a preferred datatype within the category.
1065  *
1066  * Having completed this examination, remove candidates that accept the
1067  * wrong category at any unknown position. Also, if at least one
1068  * candidate accepted a preferred type at a position, remove candidates
1069  * that accept non-preferred types. If just one candidate remains, return
1070  * that one. However, if this rule turns out to reject all candidates,
1071  * keep them all instead.
1072  */
1073  resolved_unknowns = false;
1074  for (i = 0; i < nargs; i++)
1075  {
1076  bool have_conflict;
1077 
1078  if (input_base_typeids[i] != UNKNOWNOID)
1079  continue;
1080  resolved_unknowns = true; /* assume we can do it */
1081  slot_category[i] = TYPCATEGORY_INVALID;
1082  slot_has_preferred_type[i] = false;
1083  have_conflict = false;
1084  for (current_candidate = candidates;
1085  current_candidate != NULL;
1086  current_candidate = current_candidate->next)
1087  {
1088  current_typeids = current_candidate->args;
1089  current_type = current_typeids[i];
1090  get_type_category_preferred(current_type,
1091  &current_category,
1092  &current_is_preferred);
1093  if (slot_category[i] == TYPCATEGORY_INVALID)
1094  {
1095  /* first candidate */
1096  slot_category[i] = current_category;
1097  slot_has_preferred_type[i] = current_is_preferred;
1098  }
1099  else if (current_category == slot_category[i])
1100  {
1101  /* more candidates in same category */
1102  slot_has_preferred_type[i] |= current_is_preferred;
1103  }
1104  else
1105  {
1106  /* category conflict! */
1107  if (current_category == TYPCATEGORY_STRING)
1108  {
1109  /* STRING always wins if available */
1110  slot_category[i] = current_category;
1111  slot_has_preferred_type[i] = current_is_preferred;
1112  }
1113  else
1114  {
1115  /*
1116  * Remember conflict, but keep going (might find STRING)
1117  */
1118  have_conflict = true;
1119  }
1120  }
1121  }
1122  if (have_conflict && slot_category[i] != TYPCATEGORY_STRING)
1123  {
1124  /* Failed to resolve category conflict at this position */
1125  resolved_unknowns = false;
1126  break;
1127  }
1128  }
1129 
1130  if (resolved_unknowns)
1131  {
1132  /* Strip non-matching candidates */
1133  ncandidates = 0;
1134  first_candidate = candidates;
1135  last_candidate = NULL;
1136  for (current_candidate = candidates;
1137  current_candidate != NULL;
1138  current_candidate = current_candidate->next)
1139  {
1140  bool keepit = true;
1141 
1142  current_typeids = current_candidate->args;
1143  for (i = 0; i < nargs; i++)
1144  {
1145  if (input_base_typeids[i] != UNKNOWNOID)
1146  continue;
1147  current_type = current_typeids[i];
1148  get_type_category_preferred(current_type,
1149  &current_category,
1150  &current_is_preferred);
1151  if (current_category != slot_category[i])
1152  {
1153  keepit = false;
1154  break;
1155  }
1156  if (slot_has_preferred_type[i] && !current_is_preferred)
1157  {
1158  keepit = false;
1159  break;
1160  }
1161  }
1162  if (keepit)
1163  {
1164  /* keep this candidate */
1165  last_candidate = current_candidate;
1166  ncandidates++;
1167  }
1168  else
1169  {
1170  /* forget this candidate */
1171  if (last_candidate)
1172  last_candidate->next = current_candidate->next;
1173  else
1174  first_candidate = current_candidate->next;
1175  }
1176  }
1177 
1178  /* if we found any matches, restrict our attention to those */
1179  if (last_candidate)
1180  {
1181  candidates = first_candidate;
1182  /* terminate rebuilt list */
1183  last_candidate->next = NULL;
1184  }
1185 
1186  if (ncandidates == 1)
1187  return candidates;
1188  }
1189 
1190  /*
1191  * Last gasp: if there are both known- and unknown-type inputs, and all
1192  * the known types are the same, assume the unknown inputs are also that
1193  * type, and see if that gives us a unique match. If so, use that match.
1194  *
1195  * NOTE: for a binary operator with one unknown and one non-unknown input,
1196  * we already tried this heuristic in binary_oper_exact(). However, that
1197  * code only finds exact matches, whereas here we will handle matches that
1198  * involve coercion, polymorphic type resolution, etc.
1199  */
1200  if (nunknowns < nargs)
1201  {
1202  Oid known_type = UNKNOWNOID;
1203 
1204  for (i = 0; i < nargs; i++)
1205  {
1206  if (input_base_typeids[i] == UNKNOWNOID)
1207  continue;
1208  if (known_type == UNKNOWNOID) /* first known arg? */
1209  known_type = input_base_typeids[i];
1210  else if (known_type != input_base_typeids[i])
1211  {
1212  /* oops, not all match */
1213  known_type = UNKNOWNOID;
1214  break;
1215  }
1216  }
1217 
1218  if (known_type != UNKNOWNOID)
1219  {
1220  /* okay, just one known type, apply the heuristic */
1221  for (i = 0; i < nargs; i++)
1222  input_base_typeids[i] = known_type;
1223  ncandidates = 0;
1224  last_candidate = NULL;
1225  for (current_candidate = candidates;
1226  current_candidate != NULL;
1227  current_candidate = current_candidate->next)
1228  {
1229  current_typeids = current_candidate->args;
1230  if (can_coerce_type(nargs, input_base_typeids, current_typeids,
1232  {
1233  if (++ncandidates > 1)
1234  break; /* not unique, give up */
1235  last_candidate = current_candidate;
1236  }
1237  }
1238  if (ncandidates == 1)
1239  {
1240  /* successfully identified a unique match */
1241  last_candidate->next = NULL;
1242  return last_candidate;
1243  }
1244  }
1245  }
1246 
1247  return NULL; /* failed to select a best candidate */
1248 } /* func_select_candidate() */
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:850
int errcode(int sqlerrcode)
Definition: elog.c:575
unsigned int Oid
Definition: postgres_ext.h:31
bool IsPreferredType(TYPCATEGORY category, Oid type)
#define FUNC_MAX_ARGS
char TYPCATEGORY
Definition: parse_coerce.h:21
Oid args[FLEXIBLE_ARRAY_MEMBER]
Definition: namespace.h:37
#define ERROR
Definition: elog.h:43
#define TYPCATEGORY_INVALID
Definition: pg_type.h:727
struct _FuncCandidateList * next
Definition: namespace.h:30
#define ereport(elevel, rest)
Definition: elog.h:122
TYPCATEGORY TypeCategory(Oid type)
#define TYPCATEGORY_STRING
Definition: pg_type.h:738
#define UNKNOWNOID
Definition: pg_type.h:431
bool can_coerce_type(int nargs, Oid *input_typeids, Oid *target_typeids, CoercionContext ccontext)
Definition: parse_coerce.c:526
int i
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2271
void get_type_category_preferred(Oid typid, char *typcategory, bool *typispreferred)
Definition: lsyscache.c:2436
const char* func_signature_string ( List funcname,
int  nargs,
List argnames,
const Oid argtypes 
)
const char* funcname_signature_string ( const char *  funcname,
int  nargs,
List argnames,
const Oid argtypes 
)

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

1873 {
1874  StringInfoData argbuf;
1875  int numposargs;
1876  ListCell *lc;
1877  int i;
1878 
1879  initStringInfo(&argbuf);
1880 
1881  appendStringInfo(&argbuf, "%s(", funcname);
1882 
1883  numposargs = nargs - list_length(argnames);
1884  lc = list_head(argnames);
1885 
1886  for (i = 0; i < nargs; i++)
1887  {
1888  if (i)
1889  appendStringInfoString(&argbuf, ", ");
1890  if (i >= numposargs)
1891  {
1892  appendStringInfo(&argbuf, "%s => ", (char *) lfirst(lc));
1893  lc = lnext(lc);
1894  }
1895  appendStringInfoString(&argbuf, format_type_be(argtypes[i]));
1896  }
1897 
1898  appendStringInfoChar(&argbuf, ')');
1899 
1900  return argbuf.data; /* return palloc'd string buffer */
1901 }
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
#define lnext(lc)
Definition: pg_list.h:105
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:169
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
int i
Oid LookupAggWithArgs ( ObjectWithArgs agg,
bool  noError 
)

Definition at line 2027 of file parse_func.c.

References elog, ereport, errcode(), errmsg(), errmsg_plural(), ERROR, FUNC_MAX_ARGS, func_signature_string(), GETSTRUCT, HeapTupleIsValid, i, InvalidOid, lfirst, list_length(), LookupFuncName(), LookupTypeNameOid(), NameListToString(), NIL, ObjectWithArgs::objargs, ObjectIdGetDatum, ObjectWithArgs::objname, OidIsValid, PROCOID, ReleaseSysCache(), and SearchSysCache1().

Referenced by get_object_address().

2028 {
2029  Oid argoids[FUNC_MAX_ARGS];
2030  int argcount;
2031  int i;
2032  ListCell *lc;
2033  Oid oid;
2034  HeapTuple ftup;
2035  Form_pg_proc pform;
2036 
2037  argcount = list_length(agg->objargs);
2038  if (argcount > FUNC_MAX_ARGS)
2039  ereport(ERROR,
2040  (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
2041  errmsg_plural("functions cannot have more than %d argument",
2042  "functions cannot have more than %d arguments",
2043  FUNC_MAX_ARGS,
2044  FUNC_MAX_ARGS)));
2045 
2046  i = 0;
2047  foreach(lc, agg->objargs)
2048  {
2049  TypeName *t = (TypeName *) lfirst(lc);
2050 
2051  argoids[i] = LookupTypeNameOid(NULL, t, noError);
2052  i++;
2053  }
2054 
2055  oid = LookupFuncName(agg->objname, argcount, argoids, true);
2056 
2057  if (!OidIsValid(oid))
2058  {
2059  if (noError)
2060  return InvalidOid;
2061  if (argcount == 0)
2062  ereport(ERROR,
2063  (errcode(ERRCODE_UNDEFINED_FUNCTION),
2064  errmsg("aggregate %s(*) does not exist",
2065  NameListToString(agg->objname))));
2066  else
2067  ereport(ERROR,
2068  (errcode(ERRCODE_UNDEFINED_FUNCTION),
2069  errmsg("aggregate %s does not exist",
2070  func_signature_string(agg->objname, argcount,
2071  NIL, argoids))));
2072  }
2073 
2074  /* Make sure it's an aggregate */
2076  if (!HeapTupleIsValid(ftup)) /* should not happen */
2077  elog(ERROR, "cache lookup failed for function %u", oid);
2078  pform = (Form_pg_proc) GETSTRUCT(ftup);
2079 
2080  if (!pform->proisagg)
2081  {
2082  ReleaseSysCache(ftup);
2083  if (noError)
2084  return InvalidOid;
2085  /* we do not use the (*) notation for functions... */
2086  ereport(ERROR,
2087  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2088  errmsg("function %s is not an aggregate",
2089  func_signature_string(agg->objname, argcount,
2090  NIL, argoids))));
2091  }
2092 
2093  ReleaseSysCache(ftup);
2094 
2095  return oid;
2096 }
#define NIL
Definition: pg_list.h:69
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:850
int errcode(int sqlerrcode)
Definition: elog.c:575
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:532
#define FUNC_MAX_ARGS
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
const char * func_signature_string(List *funcname, int nargs, List *argnames, const Oid *argtypes)
Definition: parse_func.c:1908
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
char * NameListToString(List *names)
Definition: namespace.c:3063
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:83
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
Oid LookupFuncName(List *funcname, int nargs, const Oid *argtypes, bool noError)
Definition: parse_func.c:1929
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define elog
Definition: elog.h:219
Oid LookupTypeNameOid(ParseState *pstate, const TypeName *typeName, bool missing_ok)
Definition: parse_type.c:215
Oid LookupFuncName ( List funcname,
int  nargs,
const Oid argtypes,
bool  noError 
)

Definition at line 1929 of file parse_func.c.

References _FuncCandidateList::args, Assert, ereport, errcode(), errhint(), errmsg(), ERROR, func_signature_string(), FuncnameGetCandidates(), InvalidOid, NameListToString(), _FuncCandidateList::next, NIL, and _FuncCandidateList::oid.

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

1930 {
1931  FuncCandidateList clist;
1932 
1933  /* Passing NULL for argtypes is no longer allowed */
1934  Assert(argtypes);
1935 
1936  clist = FuncnameGetCandidates(funcname, nargs, NIL, false, false, noError);
1937 
1938  /*
1939  * If no arguments were specified, the name must yield a unique candidate.
1940  */
1941  if (nargs == -1)
1942  {
1943  if (clist)
1944  {
1945  if (clist->next)
1946  {
1947  if (!noError)
1948  ereport(ERROR,
1949  (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
1950  errmsg("function name \"%s\" is not unique",
1951  NameListToString(funcname)),
1952  errhint("Specify the argument list to select the function unambiguously.")));
1953  }
1954  else
1955  return clist->oid;
1956  }
1957  else
1958  {
1959  if (!noError)
1960  ereport(ERROR,
1961  (errcode(ERRCODE_UNDEFINED_FUNCTION),
1962  errmsg("could not find a function named \"%s\"",
1963  NameListToString(funcname))));
1964  }
1965  }
1966 
1967  while (clist)
1968  {
1969  if (memcmp(argtypes, clist->args, nargs * sizeof(Oid)) == 0)
1970  return clist->oid;
1971  clist = clist->next;
1972  }
1973 
1974  if (!noError)
1975  ereport(ERROR,
1976  (errcode(ERRCODE_UNDEFINED_FUNCTION),
1977  errmsg("function %s does not exist",
1978  func_signature_string(funcname, nargs,
1979  NIL, argtypes))));
1980 
1981  return InvalidOid;
1982 }
#define NIL
Definition: pg_list.h:69
int errhint(const char *fmt,...)
Definition: elog.c:987
int errcode(int sqlerrcode)
Definition: elog.c:575
unsigned int Oid
Definition: postgres_ext.h:31
Oid args[FLEXIBLE_ARRAY_MEMBER]
Definition: namespace.h:37
#define ERROR
Definition: elog.h:43
FuncCandidateList FuncnameGetCandidates(List *names, int nargs, List *argnames, bool expand_variadic, bool expand_defaults, bool missing_ok)
Definition: namespace.c:903
struct _FuncCandidateList * next
Definition: namespace.h:30
#define ereport(elevel, rest)
Definition: elog.h:122
const char * func_signature_string(List *funcname, int nargs, List *argnames, const Oid *argtypes)
Definition: parse_func.c:1908
char * NameListToString(List *names)
Definition: namespace.c:3063
#define InvalidOid
Definition: postgres_ext.h:36
#define Assert(condition)
Definition: c.h:681
int errmsg(const char *fmt,...)
Definition: elog.c:797
Oid LookupFuncWithArgs ( ObjectWithArgs func,
bool  noError 
)

Definition at line 1990 of file parse_func.c.

References ObjectWithArgs::args_unspecified, ereport, errcode(), errmsg_plural(), ERROR, FUNC_MAX_ARGS, i, lfirst, list_head(), list_length(), lnext, LookupFuncName(), LookupTypeNameOid(), ObjectWithArgs::objargs, and ObjectWithArgs::objname.

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

1991 {
1992  Oid argoids[FUNC_MAX_ARGS];
1993  int argcount;
1994  int i;
1995  ListCell *args_item;
1996 
1997  argcount = list_length(func->objargs);
1998  if (argcount > FUNC_MAX_ARGS)
1999  ereport(ERROR,
2000  (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
2001  errmsg_plural("functions cannot have more than %d argument",
2002  "functions cannot have more than %d arguments",
2003  FUNC_MAX_ARGS,
2004  FUNC_MAX_ARGS)));
2005 
2006  args_item = list_head(func->objargs);
2007  for (i = 0; i < argcount; i++)
2008  {
2009  TypeName *t = (TypeName *) lfirst(args_item);
2010 
2011  argoids[i] = LookupTypeNameOid(NULL, t, noError);
2012  args_item = lnext(args_item);
2013  }
2014 
2015  return LookupFuncName(func->objname, func->args_unspecified ? -1 : argcount, argoids, noError);
2016 }
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:850
int errcode(int sqlerrcode)
Definition: elog.c:575
unsigned int Oid
Definition: postgres_ext.h:31
#define FUNC_MAX_ARGS
#define ERROR
Definition: elog.h:43
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
#define lnext(lc)
Definition: pg_list.h:105
#define ereport(elevel, rest)
Definition: elog.h:122
bool args_unspecified
Definition: parsenodes.h:1881
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
Oid LookupFuncName(List *funcname, int nargs, const Oid *argtypes, bool noError)
Definition: parse_func.c:1929
int i
Oid LookupTypeNameOid(ParseState *pstate, const TypeName *typeName, bool missing_ok)
Definition: parse_type.c:215
void make_fn_arguments ( ParseState pstate,
List fargs,
Oid actual_arg_types,
Oid declared_arg_types 
)

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

1715 {
1716  ListCell *current_fargs;
1717  int i = 0;
1718 
1719  foreach(current_fargs, fargs)
1720  {
1721  /* types don't match? then force coercion using a function call... */
1722  if (actual_arg_types[i] != declared_arg_types[i])
1723  {
1724  Node *node = (Node *) lfirst(current_fargs);
1725 
1726  /*
1727  * If arg is a NamedArgExpr, coerce its input expr instead --- we
1728  * want the NamedArgExpr to stay at the top level of the list.
1729  */
1730  if (IsA(node, NamedArgExpr))
1731  {
1732  NamedArgExpr *na = (NamedArgExpr *) node;
1733 
1734  node = coerce_type(pstate,
1735  (Node *) na->arg,
1736  actual_arg_types[i],
1737  declared_arg_types[i], -1,
1740  -1);
1741  na->arg = (Expr *) node;
1742  }
1743  else
1744  {
1745  node = coerce_type(pstate,
1746  node,
1747  actual_arg_types[i],
1748  declared_arg_types[i], -1,
1751  -1);
1752  lfirst(current_fargs) = node;
1753  }
1754  }
1755  i++;
1756  }
1757 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
Node * coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:156
Definition: nodes.h:510
Expr * arg
Definition: primnodes.h:478
#define lfirst(lc)
Definition: pg_list.h:106
int i
Node* ParseFuncOrColumn ( ParseState pstate,
List funcname,
List fargs,
Node last_srf,
FuncCall fn,
int  location 
)

Definition at line 73 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, AGGKIND_HYPOTHETICAL, AGGKIND_IS_ORDERED_SET, Aggref::aggsplit, AGGSPLIT_SIMPLE, Aggref::aggstar, Aggref::aggtranstype, Aggref::aggtype, Aggref::aggvariadic, ANYOID, arg, WindowFunc::args, FuncExpr::args, ArrayExpr::array_typeid, Assert, cancel_parser_errposition_callback(), check_srf_call_placement(), COERCE_EXPLICIT_CALL, coerce_type(), COERCION_EXPLICIT, ArrayExpr::element_typeid, ArrayExpr::elements, elog, enforce_generic_type_consistency(), ereport, errcode(), errhint(), errmsg(), errmsg_plural(), ERROR, EXPR_KIND_FILTER, exprLocation(), exprType(), format_type_be(), func_get_detail(), FUNC_MAX_ARGS, func_signature_string(), FuncCall::func_variadic, FUNCDETAIL_AGGREGATE, FUNCDETAIL_COERCION, FUNCDETAIL_MULTIPLE, FUNCDETAIL_NORMAL, FUNCDETAIL_WINDOWFUNC, FuncExpr::funcformat, FuncExpr::funcid, FuncExpr::funcresulttype, FuncExpr::funcretset, FuncExpr::funcvariadic, get_array_type(), get_base_element_type(), GETSTRUCT, HeapTupleIsValid, InvalidOid, IsA, ISCOMPLEX, lappend(), lfirst, linitial, list_copy_tail(), list_delete_ptr(), list_head(), list_length(), list_truncate(), llast, lnext, 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(), RECORDOID, ReleaseSysCache(), SearchSysCache1(), setup_parser_errposition_callback(), strVal, transformAggregateCall(), transformWhereClause(), transformWindowFuncCall(), unify_hypothetical_args(), VOIDOID, WindowFunc::winagg, WindowFunc::winfnoid, WindowFunc::winstar, and WindowFunc::wintype.

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

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