PostgreSQL Source Code  git master
parse_func.c File Reference
#include "postgres.h"
#include "access/htup_details.h"
#include "catalog/pg_aggregate.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "funcapi.h"
#include "lib/stringinfo.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "parser/parse_agg.h"
#include "parser/parse_clause.h"
#include "parser/parse_coerce.h"
#include "parser/parse_expr.h"
#include "parser/parse_func.h"
#include "parser/parse_relation.h"
#include "parser/parse_target.h"
#include "parser/parse_type.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/syscache.h"
Include dependency graph for parse_func.c:

Go to the source code of this file.

Enumerations

enum  FuncLookupError { FUNCLOOKUP_NOSUCHFUNC , FUNCLOOKUP_AMBIGUOUS }
 

Functions

static void unify_hypothetical_args (ParseState *pstate, List *fargs, int numAggregatedArgs, Oid *actual_arg_types, Oid *declared_arg_types)
 
static Oid FuncNameAsType (List *funcname)
 
static NodeParseComplexProjection (ParseState *pstate, const char *funcname, Node *first_arg, int location)
 
static Oid LookupFuncNameInternal (ObjectType objtype, List *funcname, int nargs, const Oid *argtypes, bool include_out_arguments, bool missing_ok, FuncLookupError *lookupError)
 
NodeParseFuncOrColumn (ParseState *pstate, List *funcname, List *fargs, Node *last_srf, FuncCall *fn, bool proc_call, int location)
 
int func_match_argtypes (int nargs, Oid *input_typeids, FuncCandidateList raw_candidates, FuncCandidateList *candidates)
 
FuncCandidateList func_select_candidate (int nargs, Oid *input_typeids, FuncCandidateList candidates)
 
FuncDetailCode func_get_detail (List *funcname, List *fargs, List *fargnames, int nargs, Oid *argtypes, bool expand_variadic, bool expand_defaults, bool include_out_arguments, Oid *funcid, Oid *rettype, bool *retset, int *nvargs, Oid *vatype, Oid **true_typeids, List **argdefaults)
 
void make_fn_arguments (ParseState *pstate, List *fargs, Oid *actual_arg_types, Oid *declared_arg_types)
 
const char * funcname_signature_string (const char *funcname, int nargs, List *argnames, const Oid *argtypes)
 
const char * func_signature_string (List *funcname, int nargs, List *argnames, const Oid *argtypes)
 
Oid LookupFuncName (List *funcname, int nargs, const Oid *argtypes, bool missing_ok)
 
Oid LookupFuncWithArgs (ObjectType objtype, ObjectWithArgs *func, bool missing_ok)
 
void check_srf_call_placement (ParseState *pstate, Node *last_srf, int location)
 

Enumeration Type Documentation

◆ FuncLookupError

Enumerator
FUNCLOOKUP_NOSUCHFUNC 
FUNCLOOKUP_AMBIGUOUS 

Definition at line 39 of file parse_func.c.

40 {
FuncLookupError
Definition: parse_func.c:40
@ FUNCLOOKUP_NOSUCHFUNC
Definition: parse_func.c:41
@ FUNCLOOKUP_AMBIGUOUS
Definition: parse_func.c:42

Function Documentation

◆ check_srf_call_placement()

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

Definition at line 2513 of file parse_func.c.

2514 {
2515  const char *err;
2516  bool errkind;
2517 
2518  /*
2519  * Check to see if the set-returning function is in an invalid place
2520  * within the query. Basically, we don't allow SRFs anywhere except in
2521  * the targetlist (which includes GROUP BY/ORDER BY expressions), VALUES,
2522  * and functions in FROM.
2523  *
2524  * For brevity we support two schemes for reporting an error here: set
2525  * "err" to a custom message, or set "errkind" true if the error context
2526  * is sufficiently identified by what ParseExprKindName will return, *and*
2527  * what it will return is just a SQL keyword. (Otherwise, use a custom
2528  * message to avoid creating translation problems.)
2529  */
2530  err = NULL;
2531  errkind = false;
2532  switch (pstate->p_expr_kind)
2533  {
2534  case EXPR_KIND_NONE:
2535  Assert(false); /* can't happen */
2536  break;
2537  case EXPR_KIND_OTHER:
2538  /* Accept SRF here; caller must throw error if wanted */
2539  break;
2540  case EXPR_KIND_JOIN_ON:
2541  case EXPR_KIND_JOIN_USING:
2542  err = _("set-returning functions are not allowed in JOIN conditions");
2543  break;
2545  /* can't get here, but just in case, throw an error */
2546  errkind = true;
2547  break;
2549  /* okay, but we don't allow nested SRFs here */
2550  /* errmsg is chosen to match transformRangeFunction() */
2551  /* errposition should point to the inner SRF */
2552  if (pstate->p_last_srf != last_srf)
2553  ereport(ERROR,
2554  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2555  errmsg("set-returning functions must appear at top level of FROM"),
2556  parser_errposition(pstate,
2557  exprLocation(pstate->p_last_srf))));
2558  break;
2559  case EXPR_KIND_WHERE:
2560  errkind = true;
2561  break;
2562  case EXPR_KIND_POLICY:
2563  err = _("set-returning functions are not allowed in policy expressions");
2564  break;
2565  case EXPR_KIND_HAVING:
2566  errkind = true;
2567  break;
2568  case EXPR_KIND_FILTER:
2569  errkind = true;
2570  break;
2573  /* okay, these are effectively GROUP BY/ORDER BY */
2574  pstate->p_hasTargetSRFs = true;
2575  break;
2579  err = _("set-returning functions are not allowed in window definitions");
2580  break;
2583  /* okay */
2584  pstate->p_hasTargetSRFs = true;
2585  break;
2588  /* disallowed because it would be ambiguous what to do */
2589  errkind = true;
2590  break;
2591  case EXPR_KIND_GROUP_BY:
2592  case EXPR_KIND_ORDER_BY:
2593  /* okay */
2594  pstate->p_hasTargetSRFs = true;
2595  break;
2596  case EXPR_KIND_DISTINCT_ON:
2597  /* okay */
2598  pstate->p_hasTargetSRFs = true;
2599  break;
2600  case EXPR_KIND_LIMIT:
2601  case EXPR_KIND_OFFSET:
2602  errkind = true;
2603  break;
2604  case EXPR_KIND_RETURNING:
2605  errkind = true;
2606  break;
2607  case EXPR_KIND_VALUES:
2608  /* SRFs are presently not supported by nodeValuesscan.c */
2609  errkind = true;
2610  break;
2612  /* okay, since we process this like a SELECT tlist */
2613  pstate->p_hasTargetSRFs = true;
2614  break;
2615  case EXPR_KIND_MERGE_WHEN:
2616  err = _("set-returning functions are not allowed in MERGE WHEN conditions");
2617  break;
2620  err = _("set-returning functions are not allowed in check constraints");
2621  break;
2624  err = _("set-returning functions are not allowed in DEFAULT expressions");
2625  break;
2627  err = _("set-returning functions are not allowed in index expressions");
2628  break;
2630  err = _("set-returning functions are not allowed in index predicates");
2631  break;
2633  err = _("set-returning functions are not allowed in statistics expressions");
2634  break;
2636  err = _("set-returning functions are not allowed in transform expressions");
2637  break;
2639  err = _("set-returning functions are not allowed in EXECUTE parameters");
2640  break;
2642  err = _("set-returning functions are not allowed in trigger WHEN conditions");
2643  break;
2645  err = _("set-returning functions are not allowed in partition bound");
2646  break;
2648  err = _("set-returning functions are not allowed in partition key expressions");
2649  break;
2651  err = _("set-returning functions are not allowed in CALL arguments");
2652  break;
2653  case EXPR_KIND_COPY_WHERE:
2654  err = _("set-returning functions are not allowed in COPY FROM WHERE conditions");
2655  break;
2657  err = _("set-returning functions are not allowed in column generation expressions");
2658  break;
2659  case EXPR_KIND_CYCLE_MARK:
2660  errkind = true;
2661  break;
2662 
2663  /*
2664  * There is intentionally no default: case here, so that the
2665  * compiler will warn if we add a new ParseExprKind without
2666  * extending this switch. If we do see an unrecognized value at
2667  * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
2668  * which is sane anyway.
2669  */
2670  }
2671  if (err)
2672  ereport(ERROR,
2673  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2674  errmsg_internal("%s", err),
2675  parser_errposition(pstate, location)));
2676  if (errkind)
2677  ereport(ERROR,
2678  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2679  /* translator: %s is name of a SQL construct, eg GROUP BY */
2680  errmsg("set-returning functions are not allowed in %s",
2681  ParseExprKindName(pstate->p_expr_kind)),
2682  parser_errposition(pstate, location)));
2683 }
int errmsg_internal(const char *fmt,...)
Definition: elog.c:993
int errcode(int sqlerrcode)
Definition: elog.c:695
int errmsg(const char *fmt,...)
Definition: elog.c:906
#define _(x)
Definition: elog.c:90
#define ERROR
Definition: elog.h:35
#define ereport(elevel,...)
Definition: elog.h:145
Assert(fmt[strlen(fmt) - 1] !='\n')
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1243
const char * ParseExprKindName(ParseExprKind exprKind)
Definition: parse_expr.c:2946
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
@ EXPR_KIND_EXECUTE_PARAMETER
Definition: parse_node.h:75
@ EXPR_KIND_DOMAIN_CHECK
Definition: parse_node.h:68
@ EXPR_KIND_COPY_WHERE
Definition: parse_node.h:81
@ EXPR_KIND_COLUMN_DEFAULT
Definition: parse_node.h:69
@ EXPR_KIND_DISTINCT_ON
Definition: parse_node.h:61
@ EXPR_KIND_MERGE_WHEN
Definition: parse_node.h:58
@ EXPR_KIND_STATS_EXPRESSION
Definition: parse_node.h:73
@ EXPR_KIND_INDEX_EXPRESSION
Definition: parse_node.h:71
@ EXPR_KIND_PARTITION_BOUND
Definition: parse_node.h:78
@ EXPR_KIND_FUNCTION_DEFAULT
Definition: parse_node.h:70
@ EXPR_KIND_WINDOW_FRAME_RANGE
Definition: parse_node.h:51
@ EXPR_KIND_VALUES
Definition: parse_node.h:65
@ EXPR_KIND_FROM_SUBSELECT
Definition: parse_node.h:44
@ EXPR_KIND_POLICY
Definition: parse_node.h:77
@ EXPR_KIND_WINDOW_FRAME_GROUPS
Definition: parse_node.h:53
@ EXPR_KIND_PARTITION_EXPRESSION
Definition: parse_node.h:79
@ EXPR_KIND_JOIN_USING
Definition: parse_node.h:43
@ EXPR_KIND_INDEX_PREDICATE
Definition: parse_node.h:72
@ EXPR_KIND_ORDER_BY
Definition: parse_node.h:60
@ EXPR_KIND_OFFSET
Definition: parse_node.h:63
@ EXPR_KIND_JOIN_ON
Definition: parse_node.h:42
@ EXPR_KIND_HAVING
Definition: parse_node.h:47
@ EXPR_KIND_INSERT_TARGET
Definition: parse_node.h:55
@ EXPR_KIND_ALTER_COL_TRANSFORM
Definition: parse_node.h:74
@ EXPR_KIND_LIMIT
Definition: parse_node.h:62
@ EXPR_KIND_WHERE
Definition: parse_node.h:46
@ EXPR_KIND_UPDATE_TARGET
Definition: parse_node.h:57
@ EXPR_KIND_SELECT_TARGET
Definition: parse_node.h:54
@ EXPR_KIND_RETURNING
Definition: parse_node.h:64
@ EXPR_KIND_GENERATED_COLUMN
Definition: parse_node.h:82
@ EXPR_KIND_NONE
Definition: parse_node.h:40
@ EXPR_KIND_CALL_ARGUMENT
Definition: parse_node.h:80
@ EXPR_KIND_GROUP_BY
Definition: parse_node.h:59
@ EXPR_KIND_OTHER
Definition: parse_node.h:41
@ EXPR_KIND_FROM_FUNCTION
Definition: parse_node.h:45
@ EXPR_KIND_TRIGGER_WHEN
Definition: parse_node.h:76
@ EXPR_KIND_FILTER
Definition: parse_node.h:48
@ EXPR_KIND_UPDATE_SOURCE
Definition: parse_node.h:56
@ EXPR_KIND_CHECK_CONSTRAINT
Definition: parse_node.h:67
@ EXPR_KIND_WINDOW_PARTITION
Definition: parse_node.h:49
@ EXPR_KIND_CYCLE_MARK
Definition: parse_node.h:83
@ EXPR_KIND_WINDOW_FRAME_ROWS
Definition: parse_node.h:52
@ EXPR_KIND_WINDOW_ORDER
Definition: parse_node.h:50
@ EXPR_KIND_VALUES_SINGLE
Definition: parse_node.h:66
bool p_hasTargetSRFs
Definition: parse_node.h:211
ParseExprKind p_expr_kind
Definition: parse_node.h:197
Node * p_last_srf
Definition: parse_node.h:215

References _, Assert(), ereport, errcode(), errmsg(), errmsg_internal(), ERROR, EXPR_KIND_ALTER_COL_TRANSFORM, EXPR_KIND_CALL_ARGUMENT, EXPR_KIND_CHECK_CONSTRAINT, EXPR_KIND_COLUMN_DEFAULT, EXPR_KIND_COPY_WHERE, EXPR_KIND_CYCLE_MARK, EXPR_KIND_DISTINCT_ON, EXPR_KIND_DOMAIN_CHECK, EXPR_KIND_EXECUTE_PARAMETER, EXPR_KIND_FILTER, EXPR_KIND_FROM_FUNCTION, EXPR_KIND_FROM_SUBSELECT, EXPR_KIND_FUNCTION_DEFAULT, EXPR_KIND_GENERATED_COLUMN, EXPR_KIND_GROUP_BY, EXPR_KIND_HAVING, EXPR_KIND_INDEX_EXPRESSION, EXPR_KIND_INDEX_PREDICATE, EXPR_KIND_INSERT_TARGET, EXPR_KIND_JOIN_ON, EXPR_KIND_JOIN_USING, EXPR_KIND_LIMIT, EXPR_KIND_MERGE_WHEN, EXPR_KIND_NONE, EXPR_KIND_OFFSET, EXPR_KIND_ORDER_BY, EXPR_KIND_OTHER, EXPR_KIND_PARTITION_BOUND, EXPR_KIND_PARTITION_EXPRESSION, EXPR_KIND_POLICY, EXPR_KIND_RETURNING, EXPR_KIND_SELECT_TARGET, EXPR_KIND_STATS_EXPRESSION, EXPR_KIND_TRIGGER_WHEN, EXPR_KIND_UPDATE_SOURCE, EXPR_KIND_UPDATE_TARGET, EXPR_KIND_VALUES, EXPR_KIND_VALUES_SINGLE, EXPR_KIND_WHERE, EXPR_KIND_WINDOW_FRAME_GROUPS, EXPR_KIND_WINDOW_FRAME_RANGE, EXPR_KIND_WINDOW_FRAME_ROWS, EXPR_KIND_WINDOW_ORDER, EXPR_KIND_WINDOW_PARTITION, exprLocation(), ParseState::p_expr_kind, ParseState::p_hasTargetSRFs, ParseState::p_last_srf, ParseExprKindName(), and parser_errposition().

Referenced by make_op(), and ParseFuncOrColumn().

◆ func_get_detail()

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

Definition at line 1394 of file parse_func.c.

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

References NamedArgExpr::argnumber, _FuncCandidateList::argnumbers, _FuncCandidateList::args, Assert(), bms_add_member(), bms_free(), bms_is_member(), castNode, COERCION_EXPLICIT, COERCION_PATH_COERCEVIAIO, COERCION_PATH_RELABELTYPE, elog(), ERROR, find_coercion_pathway(), func_match_argtypes(), func_select_candidate(), FUNCDETAIL_AGGREGATE, FUNCDETAIL_COERCION, FUNCDETAIL_MULTIPLE, FUNCDETAIL_NORMAL, FUNCDETAIL_NOTFOUND, FUNCDETAIL_PROCEDURE, FUNCDETAIL_WINDOWFUNC, FuncNameAsType(), FuncnameGetCandidates(), GETSTRUCT, HeapTupleIsValid, i, InvalidOid, IsA, ISCOMPLEX, lappend(), lfirst, linitial, list_delete_first_n(), list_length(), _FuncCandidateList::nargs, _FuncCandidateList::ndargs, _FuncCandidateList::next, NIL, _FuncCandidateList::nominalnargs, _FuncCandidateList::nvargs, ObjectIdGetDatum(), _FuncCandidateList::oid, OidIsValid, pfree(), PROCOID, ReleaseSysCache(), SearchSysCache1(), generate_unaccent_rules::str, stringToNode(), SysCacheGetAttr(), TextDatumGetCString, and TypeCategory().

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

◆ func_match_argtypes()

int func_match_argtypes ( int  nargs,
Oid input_typeids,
FuncCandidateList  raw_candidates,
FuncCandidateList candidates 
)

Definition at line 922 of file parse_func.c.

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

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

Referenced by func_get_detail(), and oper_select_candidate().

◆ func_select_candidate()

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

Definition at line 1007 of file parse_func.c.

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

References _FuncCandidateList::args, can_coerce_type(), COERCION_IMPLICIT, ereport, errcode(), errmsg_plural(), ERROR, FUNC_MAX_ARGS, get_type_category_preferred(), getBaseType(), i, IsPreferredType(), _FuncCandidateList::next, and TypeCategory().

Referenced by func_get_detail(), and oper_select_candidate().

◆ func_signature_string()

const char* func_signature_string ( List funcname,
int  nargs,
List argnames,
const Oid argtypes 
)

◆ funcname_signature_string()

const char* funcname_signature_string ( const char *  funcname,
int  nargs,
List argnames,
const Oid argtypes 
)

Definition at line 1995 of file parse_func.c.

1997 {
1998  StringInfoData argbuf;
1999  int numposargs;
2000  ListCell *lc;
2001  int i;
2002 
2003  initStringInfo(&argbuf);
2004 
2005  appendStringInfo(&argbuf, "%s(", funcname);
2006 
2007  numposargs = nargs - list_length(argnames);
2008  lc = list_head(argnames);
2009 
2010  for (i = 0; i < nargs; i++)
2011  {
2012  if (i)
2013  appendStringInfoString(&argbuf, ", ");
2014  if (i >= numposargs)
2015  {
2016  appendStringInfo(&argbuf, "%s => ", (char *) lfirst(lc));
2017  lc = lnext(argnames, lc);
2018  }
2019  appendStringInfoString(&argbuf, format_type_be(argtypes[i]));
2020  }
2021 
2022  appendStringInfoChar(&argbuf, ')');
2023 
2024  return argbuf.data; /* return palloc'd string buffer */
2025 }
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
static ListCell * list_head(const List *l)
Definition: pg_list.h:126
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:341
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59

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

◆ FuncNameAsType()

static Oid FuncNameAsType ( List funcname)
static

Definition at line 1883 of file parse_func.c.

1884 {
1885  Oid result;
1886  Type typtup;
1887 
1888  /*
1889  * temp_ok=false protects the <refsect1 id="sql-createfunction-security">
1890  * contract for writing SECURITY DEFINER functions safely.
1891  */
1892  typtup = LookupTypeNameExtended(NULL, makeTypeNameFromNameList(funcname),
1893  NULL, false, false);
1894  if (typtup == NULL)
1895  return InvalidOid;
1896 
1897  if (((Form_pg_type) GETSTRUCT(typtup))->typisdefined &&
1898  !OidIsValid(typeTypeRelid(typtup)))
1899  result = typeTypeId(typtup);
1900  else
1901  result = InvalidOid;
1902 
1903  ReleaseSysCache(typtup);
1904  return result;
1905 }
TypeName * makeTypeNameFromNameList(List *names)
Definition: makefuncs.c:456
Oid typeTypeRelid(Type typ)
Definition: parse_type.c:630
Type LookupTypeNameExtended(ParseState *pstate, const TypeName *typeName, int32 *typmod_p, bool temp_ok, bool missing_ok)
Definition: parse_type.c:73
Oid typeTypeId(Type tp)
Definition: parse_type.c:590
FormData_pg_type * Form_pg_type
Definition: pg_type.h:261

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

Referenced by func_get_detail().

◆ LookupFuncName()

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

Definition at line 2146 of file parse_func.c.

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

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

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

◆ LookupFuncNameInternal()

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

Definition at line 2051 of file parse_func.c.

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

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

Referenced by LookupFuncName(), and LookupFuncWithArgs().

◆ LookupFuncWithArgs()

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

Definition at line 2208 of file parse_func.c.

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

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

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

◆ make_fn_arguments()

void make_fn_arguments ( ParseState pstate,
List fargs,
Oid actual_arg_types,
Oid declared_arg_types 
)

Definition at line 1827 of file parse_func.c.

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

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

◆ ParseComplexProjection()

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

Definition at line 1914 of file parse_func.c.

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

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

Referenced by ParseFuncOrColumn().

◆ ParseFuncOrColumn()

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

Definition at line 90 of file parse_func.c.

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

References Aggref::aggfilter, WindowFunc::aggfilter, Aggref::aggfnoid, AGGFNOID, Aggref::aggkind, Aggref::aggno, Aggref::aggsplit, AGGSPLIT_SIMPLE, Aggref::aggstar, Aggref::aggtransno, Aggref::aggtype, Aggref::aggvariadic, arg, WindowFunc::args, FuncExpr::args, ArrayExpr::array_typeid, Assert(), cancel_parser_errposition_callback(), check_srf_call_placement(), COERCE_EXPLICIT_CALL, coerce_type(), COERCION_EXPLICIT, ArrayExpr::element_typeid, ArrayExpr::elements, elog(), enforce_generic_type_consistency(), ereport, errcode(), errhint(), errhint_plural(), errmsg(), errmsg_plural(), ERROR, EXPR_KIND_FILTER, exprLocation(), exprType(), fn(), foreach_delete_current, format_type_be(), func_get_detail(), FUNC_MAX_ARGS, func_signature_string(), FUNCDETAIL_AGGREGATE, FUNCDETAIL_COERCION, FUNCDETAIL_MULTIPLE, FUNCDETAIL_NORMAL, FUNCDETAIL_PROCEDURE, FUNCDETAIL_WINDOWFUNC, FuncExpr::funcformat, FuncExpr::funcid, FuncExpr::funcresulttype, FuncExpr::funcretset, FuncExpr::funcvariadic, get_array_type(), get_base_element_type(), GETSTRUCT, HeapTupleIsValid, InvalidOid, IsA, ISCOMPLEX, lappend(), lfirst, linitial, list_copy_tail(), list_length(), list_truncate(), llast, Aggref::location, WindowFunc::location, FuncExpr::location, NamedArgExpr::location, ArrayExpr::location, make_fn_arguments(), makeNode, ArrayExpr::multidims, NamedArgExpr::name, NameListToString(), NIL, ObjectIdGetDatum(), OidIsValid, ParseState::p_last_srf, ParseComplexProjection(), parser_errposition(), pronargs, ReleaseSysCache(), SearchSysCache1(), setup_parser_errposition_callback(), strVal, transformAggregateCall(), transformWhereClause(), transformWindowFuncCall(), unify_hypothetical_args(), WindowFunc::winagg, WindowFunc::winfnoid, WindowFunc::winstar, and WindowFunc::wintype.

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

◆ unify_hypothetical_args()

static void unify_hypothetical_args ( ParseState pstate,
List fargs,
int  numAggregatedArgs,
Oid actual_arg_types,
Oid declared_arg_types 
)
static

Definition at line 1743 of file parse_func.c.

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

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

Referenced by ParseFuncOrColumn().