PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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.

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

Function Documentation

void check_srf_call_placement ( ParseState pstate,
int  location 
)

Definition at line 2088 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, NULL, ParseState::p_expr_kind, ParseState::p_hasTargetSRFs, ParseExprKindName(), and parser_errposition().

Referenced by make_op(), and ParseFuncOrColumn().

2089 {
2090  const char *err;
2091  bool errkind;
2092 
2093  /*
2094  * Check to see if the set-returning function is in an invalid place
2095  * within the query. Basically, we don't allow SRFs anywhere except in
2096  * the targetlist (which includes GROUP BY/ORDER BY expressions), VALUES,
2097  * and functions in FROM.
2098  *
2099  * For brevity we support two schemes for reporting an error here: set
2100  * "err" to a custom message, or set "errkind" true if the error context
2101  * is sufficiently identified by what ParseExprKindName will return, *and*
2102  * what it will return is just a SQL keyword. (Otherwise, use a custom
2103  * message to avoid creating translation problems.)
2104  */
2105  err = NULL;
2106  errkind = false;
2107  switch (pstate->p_expr_kind)
2108  {
2109  case EXPR_KIND_NONE:
2110  Assert(false); /* can't happen */
2111  break;
2112  case EXPR_KIND_OTHER:
2113  /* Accept SRF here; caller must throw error if wanted */
2114  break;
2115  case EXPR_KIND_JOIN_ON:
2116  case EXPR_KIND_JOIN_USING:
2117  err = _("set-returning functions are not allowed in JOIN conditions");
2118  break;
2120  /* can't get here, but just in case, throw an error */
2121  errkind = true;
2122  break;
2124  /* okay ... but we can't check nesting here */
2125  break;
2126  case EXPR_KIND_WHERE:
2127  errkind = true;
2128  break;
2129  case EXPR_KIND_POLICY:
2130  err = _("set-returning functions are not allowed in policy expressions");
2131  break;
2132  case EXPR_KIND_HAVING:
2133  errkind = true;
2134  break;
2135  case EXPR_KIND_FILTER:
2136  errkind = true;
2137  break;
2140  /* okay, these are effectively GROUP BY/ORDER BY */
2141  pstate->p_hasTargetSRFs = true;
2142  break;
2145  err = _("set-returning functions are not allowed in window definitions");
2146  break;
2149  /* okay */
2150  pstate->p_hasTargetSRFs = true;
2151  break;
2154  /* disallowed because it would be ambiguous what to do */
2155  errkind = true;
2156  break;
2157  case EXPR_KIND_GROUP_BY:
2158  case EXPR_KIND_ORDER_BY:
2159  /* okay */
2160  pstate->p_hasTargetSRFs = true;
2161  break;
2162  case EXPR_KIND_DISTINCT_ON:
2163  /* okay */
2164  pstate->p_hasTargetSRFs = true;
2165  break;
2166  case EXPR_KIND_LIMIT:
2167  case EXPR_KIND_OFFSET:
2168  errkind = true;
2169  break;
2170  case EXPR_KIND_RETURNING:
2171  errkind = true;
2172  break;
2173  case EXPR_KIND_VALUES:
2174  /* SRFs are presently not supported by nodeValuesscan.c */
2175  errkind = true;
2176  break;
2178  /* okay, since we process this like a SELECT tlist */
2179  pstate->p_hasTargetSRFs = true;
2180  break;
2183  err = _("set-returning functions are not allowed in check constraints");
2184  break;
2187  err = _("set-returning functions are not allowed in DEFAULT expressions");
2188  break;
2190  err = _("set-returning functions are not allowed in index expressions");
2191  break;
2193  err = _("set-returning functions are not allowed in index predicates");
2194  break;
2196  err = _("set-returning functions are not allowed in transform expressions");
2197  break;
2199  err = _("set-returning functions are not allowed in EXECUTE parameters");
2200  break;
2202  err = _("set-returning functions are not allowed in trigger WHEN conditions");
2203  break;
2205  err = _("set-returning functions are not allowed in partition key expression");
2206  break;
2207 
2208  /*
2209  * There is intentionally no default: case here, so that the
2210  * compiler will warn if we add a new ParseExprKind without
2211  * extending this switch. If we do see an unrecognized value at
2212  * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
2213  * which is sane anyway.
2214  */
2215  }
2216  if (err)
2217  ereport(ERROR,
2218  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2219  errmsg_internal("%s", err),
2220  parser_errposition(pstate, location)));
2221  if (errkind)
2222  ereport(ERROR,
2223  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2224  /* translator: %s is name of a SQL construct, eg GROUP BY */
2225  errmsg("set-returning functions are not allowed in %s",
2226  ParseExprKindName(pstate->p_expr_kind)),
2227  parser_errposition(pstate, location)));
2228 }
bool p_hasTargetSRFs
Definition: parse_node.h:197
int errcode(int sqlerrcode)
Definition: elog.c:575
const char * ParseExprKindName(ParseExprKind exprKind)
Definition: parse_expr.c:3352
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
ParseExprKind p_expr_kind
Definition: parse_node.h:183
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
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 1264 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, NULL, _FuncCandidateList::nvargs, ObjectIdGetDatum, _FuncCandidateList::oid, OidIsValid, pfree(), PROCOID, RECORDOID, ReleaseSysCache(), result, SearchSysCache1, stringToNode(), SysCacheGetAttr(), TextDatumGetCString, TYPCATEGORY_STRING, TypeCategory(), and UNKNOWNOID.

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

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

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

Referenced by func_get_detail(), and oper_select_candidate().

796 {
797  FuncCandidateList current_candidate;
798  FuncCandidateList next_candidate;
799  int ncandidates = 0;
800 
801  *candidates = NULL;
802 
803  for (current_candidate = raw_candidates;
804  current_candidate != NULL;
805  current_candidate = next_candidate)
806  {
807  next_candidate = current_candidate->next;
808  if (can_coerce_type(nargs, input_typeids, current_candidate->args,
810  {
811  current_candidate->next = *candidates;
812  *candidates = current_candidate;
813  ncandidates++;
814  }
815  }
816 
817  return ncandidates;
818 } /* func_match_argtypes() */
Oid args[FLEXIBLE_ARRAY_MEMBER]
Definition: namespace.h:37
struct _FuncCandidateList * next
Definition: namespace.h:30
#define NULL
Definition: c.h:229
bool can_coerce_type(int nargs, Oid *input_typeids, Oid *target_typeids, CoercionContext ccontext)
Definition: parse_coerce.c:527
FuncCandidateList func_select_candidate ( int  nargs,
Oid input_typeids,
FuncCandidateList  candidates 
)

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

Referenced by func_get_detail(), and oper_select_candidate().

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

1854 {
1855  StringInfoData argbuf;
1856  int numposargs;
1857  ListCell *lc;
1858  int i;
1859 
1860  initStringInfo(&argbuf);
1861 
1862  appendStringInfo(&argbuf, "%s(", funcname);
1863 
1864  numposargs = nargs - list_length(argnames);
1865  lc = list_head(argnames);
1866 
1867  for (i = 0; i < nargs; i++)
1868  {
1869  if (i)
1870  appendStringInfoString(&argbuf, ", ");
1871  if (i >= numposargs)
1872  {
1873  appendStringInfo(&argbuf, "%s => ", (char *) lfirst(lc));
1874  lc = lnext(lc);
1875  }
1876  appendStringInfoString(&argbuf, format_type_be(argtypes[i]));
1877  }
1878 
1879  appendStringInfoChar(&argbuf, ')');
1880 
1881  return argbuf.data; /* return palloc'd string buffer */
1882 }
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:110
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:189
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:201
void initStringInfo(StringInfo str)
Definition: stringinfo.c:65
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
int i
static Oid FuncNameAsType ( List funcname)
static

Definition at line 1748 of file parse_func.c.

References GETSTRUCT, InvalidOid, LookupTypeName(), makeTypeNameFromNameList(), NULL, OidIsValid, ReleaseSysCache(), result, typeTypeId(), and typeTypeRelid().

Referenced by func_get_detail().

1749 {
1750  Oid result;
1751  Type typtup;
1752 
1753  typtup = LookupTypeName(NULL, makeTypeNameFromNameList(funcname), NULL, false);
1754  if (typtup == NULL)
1755  return InvalidOid;
1756 
1757  if (((Form_pg_type) GETSTRUCT(typtup))->typisdefined &&
1758  !OidIsValid(typeTypeRelid(typtup)))
1759  result = typeTypeId(typtup);
1760  else
1761  result = InvalidOid;
1762 
1763  ReleaseSysCache(typtup);
1764  return result;
1765 }
Type LookupTypeName(ParseState *pstate, const TypeName *typeName, int32 *typmod_p, bool missing_ok)
Definition: parse_type.c:57
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
return result
Definition: formatting.c:1618
FormData_pg_type * Form_pg_type
Definition: pg_type.h:233
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:538
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1116
#define InvalidOid
Definition: postgres_ext.h:36
#define NULL
Definition: c.h:229
Oid typeTypeRelid(Type typ)
Definition: parse_type.c:611
TypeName * makeTypeNameFromNameList(List *names)
Definition: makefuncs.c:453
Oid typeTypeId(Type tp)
Definition: parse_type.c:571
Oid LookupAggWithArgs ( ObjectWithArgs agg,
bool  noError 
)

Definition at line 2008 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, NULL, ObjectWithArgs::objargs, ObjectIdGetDatum, ObjectWithArgs::objname, OidIsValid, PROCOID, ReleaseSysCache(), and SearchSysCache1.

Referenced by get_object_address().

2009 {
2010  Oid argoids[FUNC_MAX_ARGS];
2011  int argcount;
2012  int i;
2013  ListCell *lc;
2014  Oid oid;
2015  HeapTuple ftup;
2016  Form_pg_proc pform;
2017 
2018  argcount = list_length(agg->objargs);
2019  if (argcount > FUNC_MAX_ARGS)
2020  ereport(ERROR,
2021  (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
2022  errmsg_plural("functions cannot have more than %d argument",
2023  "functions cannot have more than %d arguments",
2024  FUNC_MAX_ARGS,
2025  FUNC_MAX_ARGS)));
2026 
2027  i = 0;
2028  foreach(lc, agg->objargs)
2029  {
2030  TypeName *t = (TypeName *) lfirst(lc);
2031 
2032  argoids[i] = LookupTypeNameOid(NULL, t, noError);
2033  i++;
2034  }
2035 
2036  oid = LookupFuncName(agg->objname, argcount, argoids, true);
2037 
2038  if (!OidIsValid(oid))
2039  {
2040  if (noError)
2041  return InvalidOid;
2042  if (argcount == 0)
2043  ereport(ERROR,
2044  (errcode(ERRCODE_UNDEFINED_FUNCTION),
2045  errmsg("aggregate %s(*) does not exist",
2046  NameListToString(agg->objname))));
2047  else
2048  ereport(ERROR,
2049  (errcode(ERRCODE_UNDEFINED_FUNCTION),
2050  errmsg("aggregate %s does not exist",
2051  func_signature_string(agg->objname, argcount,
2052  NIL, argoids))));
2053  }
2054 
2055  /* Make sure it's an aggregate */
2057  if (!HeapTupleIsValid(ftup)) /* should not happen */
2058  elog(ERROR, "cache lookup failed for function %u", oid);
2059  pform = (Form_pg_proc) GETSTRUCT(ftup);
2060 
2061  if (!pform->proisagg)
2062  {
2063  ReleaseSysCache(ftup);
2064  if (noError)
2065  return InvalidOid;
2066  /* we do not use the (*) notation for functions... */
2067  ereport(ERROR,
2068  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2069  errmsg("function %s is not an aggregate",
2070  func_signature_string(agg->objname, argcount,
2071  NIL, argoids))));
2072  }
2073 
2074  ReleaseSysCache(ftup);
2075 
2076  return oid;
2077 }
#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:538
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:152
#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:1889
char * NameListToString(List *names)
Definition: namespace.c:2953
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1116
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 NULL
Definition: c.h:229
#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:1910
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 1910 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().

1911 {
1912  FuncCandidateList clist;
1913 
1914  /* Passing NULL for argtypes is no longer allowed */
1915  Assert(argtypes);
1916 
1917  clist = FuncnameGetCandidates(funcname, nargs, NIL, false, false, noError);
1918 
1919  /*
1920  * If no arguments were specified, the name must yield a unique candidate.
1921  */
1922  if (nargs == -1)
1923  {
1924  if (clist)
1925  {
1926  if (clist->next)
1927  {
1928  if (!noError)
1929  ereport(ERROR,
1930  (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
1931  errmsg("function name \"%s\" is not unique",
1932  NameListToString(funcname)),
1933  errhint("Specify the argument list to select the function unambiguously.")));
1934  }
1935  else
1936  return clist->oid;
1937  }
1938  else
1939  {
1940  if (!noError)
1941  ereport(ERROR,
1942  (errcode(ERRCODE_UNDEFINED_FUNCTION),
1943  errmsg("could not find a function named \"%s\"",
1944  NameListToString(funcname))));
1945  }
1946  }
1947 
1948  while (clist)
1949  {
1950  if (memcmp(argtypes, clist->args, nargs * sizeof(Oid)) == 0)
1951  return clist->oid;
1952  clist = clist->next;
1953  }
1954 
1955  if (!noError)
1956  ereport(ERROR,
1957  (errcode(ERRCODE_UNDEFINED_FUNCTION),
1958  errmsg("function %s does not exist",
1959  func_signature_string(funcname, nargs,
1960  NIL, argtypes))));
1961 
1962  return InvalidOid;
1963 }
#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:902
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:1889
char * NameListToString(List *names)
Definition: namespace.c:2953
#define InvalidOid
Definition: postgres_ext.h:36
#define Assert(condition)
Definition: c.h:675
int errmsg(const char *fmt,...)
Definition: elog.c:797
Oid LookupFuncWithArgs ( ObjectWithArgs func,
bool  noError 
)

Definition at line 1971 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(), NULL, ObjectWithArgs::objargs, and ObjectWithArgs::objname.

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

1972 {
1973  Oid argoids[FUNC_MAX_ARGS];
1974  int argcount;
1975  int i;
1976  ListCell *args_item;
1977 
1978  argcount = list_length(func->objargs);
1979  if (argcount > FUNC_MAX_ARGS)
1980  ereport(ERROR,
1981  (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
1982  errmsg_plural("functions cannot have more than %d argument",
1983  "functions cannot have more than %d arguments",
1984  FUNC_MAX_ARGS,
1985  FUNC_MAX_ARGS)));
1986 
1987  args_item = list_head(func->objargs);
1988  for (i = 0; i < argcount; i++)
1989  {
1990  TypeName *t = (TypeName *) lfirst(args_item);
1991 
1992  argoids[i] = LookupTypeNameOid(NULL, t, noError);
1993  args_item = lnext(args_item);
1994  }
1995 
1996  return LookupFuncName(func->objname, func->args_unspecified ? -1 : argcount, argoids, noError);
1997 }
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:1846
#define NULL
Definition: c.h:229
#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:1910
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 1692 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().

1696 {
1697  ListCell *current_fargs;
1698  int i = 0;
1699 
1700  foreach(current_fargs, fargs)
1701  {
1702  /* types don't match? then force coercion using a function call... */
1703  if (actual_arg_types[i] != declared_arg_types[i])
1704  {
1705  Node *node = (Node *) lfirst(current_fargs);
1706 
1707  /*
1708  * If arg is a NamedArgExpr, coerce its input expr instead --- we
1709  * want the NamedArgExpr to stay at the top level of the list.
1710  */
1711  if (IsA(node, NamedArgExpr))
1712  {
1713  NamedArgExpr *na = (NamedArgExpr *) node;
1714 
1715  node = coerce_type(pstate,
1716  (Node *) na->arg,
1717  actual_arg_types[i],
1718  declared_arg_types[i], -1,
1721  -1);
1722  na->arg = (Expr *) node;
1723  }
1724  else
1725  {
1726  node = coerce_type(pstate,
1727  node,
1728  actual_arg_types[i],
1729  declared_arg_types[i], -1,
1732  -1);
1733  lfirst(current_fargs) = node;
1734  }
1735  }
1736  i++;
1737  }
1738 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
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:509
Expr * arg
Definition: primnodes.h:477
#define lfirst(lc)
Definition: pg_list.h:106
int i
static Node * ParseComplexProjection ( ParseState pstate,
char *  funcname,
Node first_arg,
int  location 
)
static

Definition at line 1774 of file parse_func.c.

References FieldSelect::arg, Assert, tupleDesc::attrs, expandRecordVariable(), FieldSelect::fieldnum, get_expr_result_type(), GetRTEByRangeTablePosn(), i, InvalidAttrNumber, IsA, makeNode, NameStr, tupleDesc::natts, NULL, RECORDOID, FieldSelect::resultcollid, FieldSelect::resulttype, FieldSelect::resulttypmod, scanRTEForColumn(), and TYPEFUNC_COMPOSITE.

Referenced by ParseFuncOrColumn().

1776 {
1777  TupleDesc tupdesc;
1778  int i;
1779 
1780  /*
1781  * Special case for whole-row Vars so that we can resolve (foo.*).bar even
1782  * when foo is a reference to a subselect, join, or RECORD function. A
1783  * bonus is that we avoid generating an unnecessary FieldSelect; our
1784  * result can omit the whole-row Var and just be a Var for the selected
1785  * field.
1786  *
1787  * This case could be handled by expandRecordVariable, but it's more
1788  * efficient to do it this way when possible.
1789  */
1790  if (IsA(first_arg, Var) &&
1791  ((Var *) first_arg)->varattno == InvalidAttrNumber)
1792  {
1793  RangeTblEntry *rte;
1794 
1795  rte = GetRTEByRangeTablePosn(pstate,
1796  ((Var *) first_arg)->varno,
1797  ((Var *) first_arg)->varlevelsup);
1798  /* Return a Var if funcname matches a column, else NULL */
1799  return scanRTEForColumn(pstate, rte, funcname, location, 0, NULL);
1800  }
1801 
1802  /*
1803  * Else do it the hard way with get_expr_result_type().
1804  *
1805  * If it's a Var of type RECORD, we have to work even harder: we have to
1806  * find what the Var refers to, and pass that to get_expr_result_type.
1807  * That task is handled by expandRecordVariable().
1808  */
1809  if (IsA(first_arg, Var) &&
1810  ((Var *) first_arg)->vartype == RECORDOID)
1811  tupdesc = expandRecordVariable(pstate, (Var *) first_arg, 0);
1812  else if (get_expr_result_type(first_arg, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
1813  return NULL; /* unresolvable RECORD type */
1814  Assert(tupdesc);
1815 
1816  for (i = 0; i < tupdesc->natts; i++)
1817  {
1818  Form_pg_attribute att = tupdesc->attrs[i];
1819 
1820  if (strcmp(funcname, NameStr(att->attname)) == 0 &&
1821  !att->attisdropped)
1822  {
1823  /* Success, so generate a FieldSelect expression */
1824  FieldSelect *fselect = makeNode(FieldSelect);
1825 
1826  fselect->arg = (Expr *) first_arg;
1827  fselect->fieldnum = i + 1;
1828  fselect->resulttype = att->atttypid;
1829  fselect->resulttypmod = att->atttypmod;
1830  /* save attribute's collation for parse_collate.c */
1831  fselect->resultcollid = att->attcollation;
1832  return (Node *) fselect;
1833  }
1834  }
1835 
1836  return NULL; /* funcname does not match any column */
1837 }
Node * scanRTEForColumn(ParseState *pstate, RangeTblEntry *rte, char *colname, int location, int fuzzy_rte_penalty, FuzzyAttrMatchState *fuzzystate)
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
Oid resulttype
Definition: primnodes.h:743
Form_pg_attribute * attrs
Definition: tupdesc.h:74
Definition: nodes.h:509
Expr * arg
Definition: primnodes.h:741
Definition: primnodes.h:163
TypeFuncClass get_expr_result_type(Node *expr, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:227
int natts
Definition: tupdesc.h:73
Oid resultcollid
Definition: primnodes.h:746
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
#define RECORDOID
Definition: pg_type.h:680
TupleDesc expandRecordVariable(ParseState *pstate, Var *var, int levelsup)
RangeTblEntry * GetRTEByRangeTablePosn(ParseState *pstate, int varno, int sublevels_up)
#define makeNode(_type_)
Definition: nodes.h:557
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define InvalidAttrNumber
Definition: attnum.h:23
int i
#define NameStr(name)
Definition: c.h:499
int32 resulttypmod
Definition: primnodes.h:745
AttrNumber fieldnum
Definition: primnodes.h:742
Node* ParseFuncOrColumn ( ParseState pstate,
List funcname,
List fargs,
FuncCall fn,
int  location 
)

Definition at line 69 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, NULL, ObjectIdGetDatum, OidIsValid, FuncCall::over, 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().

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

Definition at line 1598 of file parse_func.c.

References ANYOID, generate_unaccent_rules::args, COERCE_IMPLICIT_CAST, coerce_type(), COERCION_IMPLICIT, elog, ERROR, FUNC_MAX_ARGS, i, lfirst, list_length(), list_make2, NULL, and select_common_type().

Referenced by ParseFuncOrColumn().

1603 {
1605  int numDirectArgs,
1606  numNonHypotheticalArgs;
1607  int i;
1608  ListCell *lc;
1609 
1610  numDirectArgs = list_length(fargs) - numAggregatedArgs;
1611  numNonHypotheticalArgs = numDirectArgs - numAggregatedArgs;
1612  /* safety check (should only trigger with a misdeclared agg) */
1613  if (numNonHypotheticalArgs < 0)
1614  elog(ERROR, "incorrect number of arguments to hypothetical-set aggregate");
1615 
1616  /* Deconstruct fargs into an array for ease of subscripting */
1617  i = 0;
1618  foreach(lc, fargs)
1619  {
1620  args[i++] = (Node *) lfirst(lc);
1621  }
1622 
1623  /* Check each hypothetical arg and corresponding aggregated arg */
1624  for (i = numNonHypotheticalArgs; i < numDirectArgs; i++)
1625  {
1626  int aargpos = numDirectArgs + (i - numNonHypotheticalArgs);
1627  Oid commontype;
1628 
1629  /* A mismatch means AggregateCreate didn't check properly ... */
1630  if (declared_arg_types[i] != declared_arg_types[aargpos])
1631  elog(ERROR, "hypothetical-set aggregate has inconsistent declared argument types");
1632 
1633  /* No need to unify if make_fn_arguments will coerce */
1634  if (declared_arg_types[i] != ANYOID)
1635  continue;
1636 
1637  /*
1638  * Select common type, giving preference to the aggregated argument's
1639  * type (we'd rather coerce the direct argument once than coerce all
1640  * the aggregated values).
1641  */
1642  commontype = select_common_type(pstate,
1643  list_make2(args[aargpos], args[i]),
1644  "WITHIN GROUP",
1645  NULL);
1646 
1647  /*
1648  * Perform the coercions. We don't need to worry about NamedArgExprs
1649  * here because they aren't supported with aggregates.
1650  */
1651  args[i] = coerce_type(pstate,
1652  args[i],
1653  actual_arg_types[i],
1654  commontype, -1,
1657  -1);
1658  actual_arg_types[i] = commontype;
1659  args[aargpos] = coerce_type(pstate,
1660  args[aargpos],
1661  actual_arg_types[aargpos],
1662  commontype, -1,
1665  -1);
1666  actual_arg_types[aargpos] = commontype;
1667  }
1668 
1669  /* Reconstruct fargs from array */
1670  i = 0;
1671  foreach(lc, fargs)
1672  {
1673  lfirst(lc) = args[i++];
1674  }
1675 }
#define list_make2(x1, x2)
Definition: pg_list.h:140
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:509
unsigned int Oid
Definition: postgres_ext.h:31
#define FUNC_MAX_ARGS
#define ERROR
Definition: elog.h:43
#define ANYOID
Definition: pg_type.h:686
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
int i
Oid select_common_type(ParseState *pstate, List *exprs, const char *context, Node **which_expr)
#define elog
Definition: elog.h:219