PostgreSQL Source Code  git master
parse_coerce.c File Reference
#include "postgres.h"
#include "access/htup_details.h"
#include "catalog/pg_cast.h"
#include "catalog/pg_class.h"
#include "catalog/pg_inherits.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "parser/parse_coerce.h"
#include "parser/parse_relation.h"
#include "parser/parse_type.h"
#include "utils/builtins.h"
#include "utils/datum.h"
#include "utils/lsyscache.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
Include dependency graph for parse_coerce.c:

Go to the source code of this file.

Functions

static Nodecoerce_type_typmod (Node *node, Oid targetTypeId, int32 targetTypMod, CoercionContext ccontext, CoercionForm cformat, int location, bool hideInputCoercion)
 
static void hide_coercion_node (Node *node)
 
static Nodebuild_coercion_expression (Node *node, CoercionPathType pathtype, Oid funcId, Oid targetTypeId, int32 targetTypMod, CoercionContext ccontext, CoercionForm cformat, int location)
 
static Nodecoerce_record_to_complex (ParseState *pstate, Node *node, Oid targetTypeId, CoercionContext ccontext, CoercionForm cformat, int location)
 
static bool is_complex_array (Oid typid)
 
static bool typeIsOfTypedTable (Oid reltypeId, Oid reloftypeId)
 
Nodecoerce_to_target_type (ParseState *pstate, Node *expr, Oid exprtype, Oid targettype, int32 targettypmod, CoercionContext ccontext, CoercionForm cformat, int location)
 
Nodecoerce_type (ParseState *pstate, Node *node, Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod, CoercionContext ccontext, CoercionForm cformat, int location)
 
bool can_coerce_type (int nargs, const Oid *input_typeids, const Oid *target_typeids, CoercionContext ccontext)
 
Nodecoerce_to_domain (Node *arg, Oid baseTypeId, int32 baseTypeMod, Oid typeId, CoercionContext ccontext, CoercionForm cformat, int location, bool hideInputCoercion)
 
Nodecoerce_to_boolean (ParseState *pstate, Node *node, const char *constructName)
 
Nodecoerce_to_specific_type_typmod (ParseState *pstate, Node *node, Oid targetTypeId, int32 targetTypmod, const char *constructName)
 
Nodecoerce_to_specific_type (ParseState *pstate, Node *node, Oid targetTypeId, const char *constructName)
 
int parser_coercion_errposition (ParseState *pstate, int coerce_location, Node *input_expr)
 
Oid select_common_type (ParseState *pstate, List *exprs, const char *context, Node **which_expr)
 
Nodecoerce_to_common_type (ParseState *pstate, Node *node, Oid targetTypeId, const char *context)
 
bool check_generic_type_consistency (const Oid *actual_arg_types, const Oid *declared_arg_types, int nargs)
 
Oid enforce_generic_type_consistency (const Oid *actual_arg_types, Oid *declared_arg_types, int nargs, Oid rettype, bool allow_poly)
 
Oid resolve_generic_type (Oid declared_type, Oid context_actual_type, Oid context_declared_type)
 
TYPCATEGORY TypeCategory (Oid type)
 
bool IsPreferredType (TYPCATEGORY category, Oid type)
 
bool IsBinaryCoercible (Oid srctype, Oid targettype)
 
CoercionPathType find_coercion_pathway (Oid targetTypeId, Oid sourceTypeId, CoercionContext ccontext, Oid *funcid)
 
CoercionPathType find_typmod_coercion_function (Oid typeId, Oid *funcid)
 

Function Documentation

◆ build_coercion_expression()

static Node * build_coercion_expression ( Node node,
CoercionPathType  pathtype,
Oid  funcId,
Oid  targetTypeId,
int32  targetTypMod,
CoercionContext  ccontext,
CoercionForm  cformat,
int  location 
)
static

Definition at line 810 of file parse_coerce.c.

References CoerceViaIO::arg, ArrayCoerceExpr::arg, generate_unaccent_rules::args, Assert, BoolGetDatum, coerce_to_target_type(), CoerceViaIO::coerceformat, ArrayCoerceExpr::coerceformat, COERCION_EXPLICIT, COERCION_PATH_ARRAYCOERCE, COERCION_PATH_COERCEVIAIO, COERCION_PATH_FUNC, CaseTestExpr::collation, ArrayCoerceExpr::elemexpr, elog, ERROR, exprType(), exprTypmod(), get_element_type(), getBaseTypeAndTypmod(), GETSTRUCT, HeapTupleIsValid, Int32GetDatum, InvalidOid, lappend(), list_make1, FuncExpr::location, CoerceViaIO::location, ArrayCoerceExpr::location, makeConst(), makeFuncExpr(), makeNode, ObjectIdGetDatum, OidIsValid, PROCOID, ReleaseSysCache(), CoerceViaIO::resulttype, ArrayCoerceExpr::resulttype, ArrayCoerceExpr::resulttypmod, SearchSysCache1(), CaseTestExpr::typeId, and CaseTestExpr::typeMod.

Referenced by coerce_type(), and coerce_type_typmod().

816 {
817  int nargs = 0;
818 
819  if (OidIsValid(funcId))
820  {
821  HeapTuple tp;
822  Form_pg_proc procstruct;
823 
825  if (!HeapTupleIsValid(tp))
826  elog(ERROR, "cache lookup failed for function %u", funcId);
827  procstruct = (Form_pg_proc) GETSTRUCT(tp);
828 
829  /*
830  * These Asserts essentially check that function is a legal coercion
831  * function. We can't make the seemingly obvious tests on prorettype
832  * and proargtypes[0], even in the COERCION_PATH_FUNC case, because of
833  * various binary-compatibility cases.
834  */
835  /* Assert(targetTypeId == procstruct->prorettype); */
836  Assert(!procstruct->proretset);
837  Assert(procstruct->prokind == PROKIND_FUNCTION);
838  nargs = procstruct->pronargs;
839  Assert(nargs >= 1 && nargs <= 3);
840  /* Assert(procstruct->proargtypes.values[0] == exprType(node)); */
841  Assert(nargs < 2 || procstruct->proargtypes.values[1] == INT4OID);
842  Assert(nargs < 3 || procstruct->proargtypes.values[2] == BOOLOID);
843 
844  ReleaseSysCache(tp);
845  }
846 
847  if (pathtype == COERCION_PATH_FUNC)
848  {
849  /* We build an ordinary FuncExpr with special arguments */
850  FuncExpr *fexpr;
851  List *args;
852  Const *cons;
853 
854  Assert(OidIsValid(funcId));
855 
856  args = list_make1(node);
857 
858  if (nargs >= 2)
859  {
860  /* Pass target typmod as an int4 constant */
861  cons = makeConst(INT4OID,
862  -1,
863  InvalidOid,
864  sizeof(int32),
865  Int32GetDatum(targetTypMod),
866  false,
867  true);
868 
869  args = lappend(args, cons);
870  }
871 
872  if (nargs == 3)
873  {
874  /* Pass it a boolean isExplicit parameter, too */
875  cons = makeConst(BOOLOID,
876  -1,
877  InvalidOid,
878  sizeof(bool),
879  BoolGetDatum(ccontext == COERCION_EXPLICIT),
880  false,
881  true);
882 
883  args = lappend(args, cons);
884  }
885 
886  fexpr = makeFuncExpr(funcId, targetTypeId, args,
887  InvalidOid, InvalidOid, cformat);
888  fexpr->location = location;
889  return (Node *) fexpr;
890  }
891  else if (pathtype == COERCION_PATH_ARRAYCOERCE)
892  {
893  /* We need to build an ArrayCoerceExpr */
896  Oid sourceBaseTypeId;
897  int32 sourceBaseTypeMod;
898  Oid targetElementType;
899  Node *elemexpr;
900 
901  /*
902  * Look through any domain over the source array type. Note we don't
903  * expect that the target type is a domain; it must be a plain array.
904  * (To get to a domain target type, we'll do coerce_to_domain later.)
905  */
906  sourceBaseTypeMod = exprTypmod(node);
907  sourceBaseTypeId = getBaseTypeAndTypmod(exprType(node),
908  &sourceBaseTypeMod);
909 
910  /*
911  * Set up a CaseTestExpr representing one element of the source array.
912  * This is an abuse of CaseTestExpr, but it's OK as long as there
913  * can't be any CaseExpr or ArrayCoerceExpr within the completed
914  * elemexpr.
915  */
916  ctest->typeId = get_element_type(sourceBaseTypeId);
917  Assert(OidIsValid(ctest->typeId));
918  ctest->typeMod = sourceBaseTypeMod;
919  ctest->collation = InvalidOid; /* Assume coercions don't care */
920 
921  /* And coerce it to the target element type */
922  targetElementType = get_element_type(targetTypeId);
923  Assert(OidIsValid(targetElementType));
924 
925  elemexpr = coerce_to_target_type(NULL,
926  (Node *) ctest,
927  ctest->typeId,
928  targetElementType,
929  targetTypMod,
930  ccontext,
931  cformat,
932  location);
933  if (elemexpr == NULL) /* shouldn't happen */
934  elog(ERROR, "failed to coerce array element type as expected");
935 
936  acoerce->arg = (Expr *) node;
937  acoerce->elemexpr = (Expr *) elemexpr;
938  acoerce->resulttype = targetTypeId;
939 
940  /*
941  * Label the output as having a particular element typmod only if we
942  * ended up with a per-element expression that is labeled that way.
943  */
944  acoerce->resulttypmod = exprTypmod(elemexpr);
945  /* resultcollid will be set by parse_collate.c */
946  acoerce->coerceformat = cformat;
947  acoerce->location = location;
948 
949  return (Node *) acoerce;
950  }
951  else if (pathtype == COERCION_PATH_COERCEVIAIO)
952  {
953  /* We need to build a CoerceViaIO node */
954  CoerceViaIO *iocoerce = makeNode(CoerceViaIO);
955 
956  Assert(!OidIsValid(funcId));
957 
958  iocoerce->arg = (Expr *) node;
959  iocoerce->resulttype = targetTypeId;
960  /* resultcollid will be set by parse_collate.c */
961  iocoerce->coerceformat = cformat;
962  iocoerce->location = location;
963 
964  return (Node *) iocoerce;
965  }
966  else
967  {
968  elog(ERROR, "unsupported pathtype %d in build_coercion_expression",
969  (int) pathtype);
970  return NULL; /* keep compiler quiet */
971  }
972 }
Oid getBaseTypeAndTypmod(Oid typid, int32 *typmod)
Definition: lsyscache.c:2316
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:275
Oid get_element_type(Oid typid)
Definition: lsyscache.c:2526
Oid resulttype
Definition: primnodes.h:835
Definition: nodes.h:525
unsigned int Oid
Definition: postgres_ext.h:31
Const * makeConst(Oid consttype, int32 consttypmod, Oid constcollid, int constlen, Datum constvalue, bool constisnull, bool constbyval)
Definition: makefuncs.c:297
#define OidIsValid(objectId)
Definition: c.h:645
int32 typeMod
Definition: primnodes.h:973
signed int int32
Definition: c.h:347
#define list_make1(x1)
Definition: pg_list.h:227
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
Node * coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype, Oid targettype, int32 targettypmod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:78
Expr * arg
Definition: primnodes.h:834
Expr * elemexpr
Definition: primnodes.h:859
List * lappend(List *list, void *datum)
Definition: list.c:322
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
CoercionForm coerceformat
Definition: primnodes.h:863
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:133
#define BoolGetDatum(X)
Definition: postgres.h:402
#define InvalidOid
Definition: postgres_ext.h:36
#define makeNode(_type_)
Definition: nodes.h:573
int location
Definition: primnodes.h:839
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:739
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
CoercionForm coerceformat
Definition: primnodes.h:838
#define Int32GetDatum(X)
Definition: postgres.h:479
#define elog(elevel,...)
Definition: elog.h:228
int location
Definition: primnodes.h:478
int32 resulttypmod
Definition: primnodes.h:861
Definition: pg_list.h:50
FuncExpr * makeFuncExpr(Oid funcid, Oid rettype, List *args, Oid funccollid, Oid inputcollid, CoercionForm fformat)
Definition: makefuncs.c:517

◆ can_coerce_type()

bool can_coerce_type ( int  nargs,
const Oid input_typeids,
const Oid target_typeids,
CoercionContext  ccontext 
)

Definition at line 543 of file parse_coerce.c.

References check_generic_type_consistency(), COERCION_PATH_NONE, find_coercion_pathway(), i, is_complex_array(), ISCOMPLEX, typeInheritsFrom(), and typeIsOfTypedTable().

Referenced by ATAddForeignKeyConstraint(), coerce_to_common_type(), coerce_to_target_type(), func_match_argtypes(), func_select_candidate(), select_common_type(), and transformFrameOffset().

545 {
546  bool have_generics = false;
547  int i;
548 
549  /* run through argument list... */
550  for (i = 0; i < nargs; i++)
551  {
552  Oid inputTypeId = input_typeids[i];
553  Oid targetTypeId = target_typeids[i];
554  CoercionPathType pathtype;
555  Oid funcId;
556 
557  /* no problem if same type */
558  if (inputTypeId == targetTypeId)
559  continue;
560 
561  /* accept if target is ANY */
562  if (targetTypeId == ANYOID)
563  continue;
564 
565  /* accept if target is polymorphic, for now */
566  if (IsPolymorphicType(targetTypeId))
567  {
568  have_generics = true; /* do more checking later */
569  continue;
570  }
571 
572  /*
573  * If input is an untyped string constant, assume we can convert it to
574  * anything.
575  */
576  if (inputTypeId == UNKNOWNOID)
577  continue;
578 
579  /*
580  * If pg_cast shows that we can coerce, accept. This test now covers
581  * both binary-compatible and coercion-function cases.
582  */
583  pathtype = find_coercion_pathway(targetTypeId, inputTypeId, ccontext,
584  &funcId);
585  if (pathtype != COERCION_PATH_NONE)
586  continue;
587 
588  /*
589  * If input is RECORD and target is a composite type, assume we can
590  * coerce (may need tighter checking here)
591  */
592  if (inputTypeId == RECORDOID &&
593  ISCOMPLEX(targetTypeId))
594  continue;
595 
596  /*
597  * If input is a composite type and target is RECORD, accept
598  */
599  if (targetTypeId == RECORDOID &&
600  ISCOMPLEX(inputTypeId))
601  continue;
602 
603 #ifdef NOT_USED /* not implemented yet */
604 
605  /*
606  * If input is record[] and target is a composite array type, assume
607  * we can coerce (may need tighter checking here)
608  */
609  if (inputTypeId == RECORDARRAYOID &&
610  is_complex_array(targetTypeId))
611  continue;
612 #endif
613 
614  /*
615  * If input is a composite array type and target is record[], accept
616  */
617  if (targetTypeId == RECORDARRAYOID &&
618  is_complex_array(inputTypeId))
619  continue;
620 
621  /*
622  * If input is a class type that inherits from target, accept
623  */
624  if (typeInheritsFrom(inputTypeId, targetTypeId)
625  || typeIsOfTypedTable(inputTypeId, targetTypeId))
626  continue;
627 
628  /*
629  * Else, cannot coerce at this argument position
630  */
631  return false;
632  }
633 
634  /* If we found any generic argument types, cross-check them */
635  if (have_generics)
636  {
637  if (!check_generic_type_consistency(input_typeids, target_typeids,
638  nargs))
639  return false;
640  }
641 
642  return true;
643 }
bool check_generic_type_consistency(const Oid *actual_arg_types, const Oid *declared_arg_types, int nargs)
unsigned int Oid
Definition: postgres_ext.h:31
CoercionPathType
Definition: parse_coerce.h:24
bool typeInheritsFrom(Oid subclassTypeId, Oid superclassTypeId)
Definition: pg_inherits.c:315
#define ISCOMPLEX(typeid)
Definition: parse_type.h:58
static bool typeIsOfTypedTable(Oid reltypeId, Oid reloftypeId)
CoercionPathType find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId, CoercionContext ccontext, Oid *funcid)
int i
static bool is_complex_array(Oid typid)

◆ check_generic_type_consistency()

bool check_generic_type_consistency ( const Oid actual_arg_types,
const Oid declared_arg_types,
int  nargs 
)

Definition at line 1474 of file parse_coerce.c.

References get_element_type(), get_range_subtype(), getBaseType(), InvalidOid, OidIsValid, type_is_array_domain, and type_is_enum().

Referenced by can_coerce_type().

1477 {
1478  int j;
1479  Oid elem_typeid = InvalidOid;
1480  Oid array_typeid = InvalidOid;
1481  Oid array_typelem;
1482  Oid range_typeid = InvalidOid;
1483  Oid range_typelem;
1484  bool have_anyelement = false;
1485  bool have_anynonarray = false;
1486  bool have_anyenum = false;
1487 
1488  /*
1489  * Loop through the arguments to see if we have any that are polymorphic.
1490  * If so, require the actual types to be consistent.
1491  */
1492  for (j = 0; j < nargs; j++)
1493  {
1494  Oid decl_type = declared_arg_types[j];
1495  Oid actual_type = actual_arg_types[j];
1496 
1497  if (decl_type == ANYELEMENTOID ||
1498  decl_type == ANYNONARRAYOID ||
1499  decl_type == ANYENUMOID)
1500  {
1501  have_anyelement = true;
1502  if (decl_type == ANYNONARRAYOID)
1503  have_anynonarray = true;
1504  else if (decl_type == ANYENUMOID)
1505  have_anyenum = true;
1506  if (actual_type == UNKNOWNOID)
1507  continue;
1508  if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
1509  return false;
1510  elem_typeid = actual_type;
1511  }
1512  else if (decl_type == ANYARRAYOID)
1513  {
1514  if (actual_type == UNKNOWNOID)
1515  continue;
1516  actual_type = getBaseType(actual_type); /* flatten domains */
1517  if (OidIsValid(array_typeid) && actual_type != array_typeid)
1518  return false;
1519  array_typeid = actual_type;
1520  }
1521  else if (decl_type == ANYRANGEOID)
1522  {
1523  if (actual_type == UNKNOWNOID)
1524  continue;
1525  actual_type = getBaseType(actual_type); /* flatten domains */
1526  if (OidIsValid(range_typeid) && actual_type != range_typeid)
1527  return false;
1528  range_typeid = actual_type;
1529  }
1530  }
1531 
1532  /* Get the element type based on the array type, if we have one */
1533  if (OidIsValid(array_typeid))
1534  {
1535  if (array_typeid == ANYARRAYOID)
1536  {
1537  /* Special case for ANYARRAY input: okay iff no ANYELEMENT */
1538  if (have_anyelement)
1539  return false;
1540  return true;
1541  }
1542 
1543  array_typelem = get_element_type(array_typeid);
1544  if (!OidIsValid(array_typelem))
1545  return false; /* should be an array, but isn't */
1546 
1547  if (!OidIsValid(elem_typeid))
1548  {
1549  /*
1550  * if we don't have an element type yet, use the one we just got
1551  */
1552  elem_typeid = array_typelem;
1553  }
1554  else if (array_typelem != elem_typeid)
1555  {
1556  /* otherwise, they better match */
1557  return false;
1558  }
1559  }
1560 
1561  /* Get the element type based on the range type, if we have one */
1562  if (OidIsValid(range_typeid))
1563  {
1564  range_typelem = get_range_subtype(range_typeid);
1565  if (!OidIsValid(range_typelem))
1566  return false; /* should be a range, but isn't */
1567 
1568  if (!OidIsValid(elem_typeid))
1569  {
1570  /*
1571  * if we don't have an element type yet, use the one we just got
1572  */
1573  elem_typeid = range_typelem;
1574  }
1575  else if (range_typelem != elem_typeid)
1576  {
1577  /* otherwise, they better match */
1578  return false;
1579  }
1580  }
1581 
1582  if (have_anynonarray)
1583  {
1584  /* require the element type to not be an array or domain over array */
1585  if (type_is_array_domain(elem_typeid))
1586  return false;
1587  }
1588 
1589  if (have_anyenum)
1590  {
1591  /* require the element type to be an enum */
1592  if (!type_is_enum(elem_typeid))
1593  return false;
1594  }
1595 
1596  /* Looks valid */
1597  return true;
1598 }
#define type_is_array_domain(typid)
Definition: lsyscache.h:186
Oid get_element_type(Oid typid)
Definition: lsyscache.c:2526
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:645
#define InvalidOid
Definition: postgres_ext.h:36
bool type_is_enum(Oid typid)
Definition: lsyscache.c:2456
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2299
Oid get_range_subtype(Oid rangeOid)
Definition: lsyscache.c:3135

◆ coerce_record_to_complex()

static Node * coerce_record_to_complex ( ParseState pstate,
Node node,
Oid  targetTypeId,
CoercionContext  ccontext,
CoercionForm  cformat,
int  location 
)
static

Definition at line 983 of file parse_coerce.c.

References arg, generate_unaccent_rules::args, RowExpr::args, COERCE_IMPLICIT_CAST, coerce_to_domain(), coerce_to_target_type(), RowExpr::colnames, ereport, errcode(), errdetail(), errmsg(), ERROR, expandNSItemVars(), exprType(), format_type_be(), getBaseTypeAndTypmod(), GetNSItemByRangeTablePosn(), i, InvalidAttrNumber, InvalidOid, IsA, lappend(), lfirst, list_head(), lnext(), RowExpr::location, lookup_rowtype_tupdesc(), makeNode, makeNullConst(), TupleDescData::natts, NIL, parser_coercion_errposition(), ReleaseTupleDesc, RowExpr::row_format, RowExpr::row_typeid, and TupleDescAttr.

Referenced by coerce_type().

988 {
989  RowExpr *rowexpr;
990  Oid baseTypeId;
991  int32 baseTypeMod = -1;
992  TupleDesc tupdesc;
993  List *args = NIL;
994  List *newargs;
995  int i;
996  int ucolno;
997  ListCell *arg;
998 
999  if (node && IsA(node, RowExpr))
1000  {
1001  /*
1002  * Since the RowExpr must be of type RECORD, we needn't worry about it
1003  * containing any dropped columns.
1004  */
1005  args = ((RowExpr *) node)->args;
1006  }
1007  else if (node && IsA(node, Var) &&
1008  ((Var *) node)->varattno == InvalidAttrNumber)
1009  {
1010  int rtindex = ((Var *) node)->varno;
1011  int sublevels_up = ((Var *) node)->varlevelsup;
1012  int vlocation = ((Var *) node)->location;
1013  ParseNamespaceItem *nsitem;
1014 
1015  nsitem = GetNSItemByRangeTablePosn(pstate, rtindex, sublevels_up);
1016  args = expandNSItemVars(nsitem, sublevels_up, vlocation, NULL);
1017  }
1018  else
1019  ereport(ERROR,
1020  (errcode(ERRCODE_CANNOT_COERCE),
1021  errmsg("cannot cast type %s to %s",
1022  format_type_be(RECORDOID),
1023  format_type_be(targetTypeId)),
1024  parser_coercion_errposition(pstate, location, node)));
1025 
1026  /*
1027  * Look up the composite type, accounting for possibility that what we are
1028  * given is a domain over composite.
1029  */
1030  baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
1031  tupdesc = lookup_rowtype_tupdesc(baseTypeId, baseTypeMod);
1032 
1033  /* Process the fields */
1034  newargs = NIL;
1035  ucolno = 1;
1036  arg = list_head(args);
1037  for (i = 0; i < tupdesc->natts; i++)
1038  {
1039  Node *expr;
1040  Node *cexpr;
1041  Oid exprtype;
1042  Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
1043 
1044  /* Fill in NULLs for dropped columns in rowtype */
1045  if (attr->attisdropped)
1046  {
1047  /*
1048  * can't use atttypid here, but it doesn't really matter what type
1049  * the Const claims to be.
1050  */
1051  newargs = lappend(newargs,
1052  makeNullConst(INT4OID, -1, InvalidOid));
1053  continue;
1054  }
1055 
1056  if (arg == NULL)
1057  ereport(ERROR,
1058  (errcode(ERRCODE_CANNOT_COERCE),
1059  errmsg("cannot cast type %s to %s",
1060  format_type_be(RECORDOID),
1061  format_type_be(targetTypeId)),
1062  errdetail("Input has too few columns."),
1063  parser_coercion_errposition(pstate, location, node)));
1064  expr = (Node *) lfirst(arg);
1065  exprtype = exprType(expr);
1066 
1067  cexpr = coerce_to_target_type(pstate,
1068  expr, exprtype,
1069  attr->atttypid,
1070  attr->atttypmod,
1071  ccontext,
1073  -1);
1074  if (cexpr == NULL)
1075  ereport(ERROR,
1076  (errcode(ERRCODE_CANNOT_COERCE),
1077  errmsg("cannot cast type %s to %s",
1078  format_type_be(RECORDOID),
1079  format_type_be(targetTypeId)),
1080  errdetail("Cannot cast type %s to %s in column %d.",
1081  format_type_be(exprtype),
1082  format_type_be(attr->atttypid),
1083  ucolno),
1084  parser_coercion_errposition(pstate, location, expr)));
1085  newargs = lappend(newargs, cexpr);
1086  ucolno++;
1087  arg = lnext(args, arg);
1088  }
1089  if (arg != NULL)
1090  ereport(ERROR,
1091  (errcode(ERRCODE_CANNOT_COERCE),
1092  errmsg("cannot cast type %s to %s",
1093  format_type_be(RECORDOID),
1094  format_type_be(targetTypeId)),
1095  errdetail("Input has too many columns."),
1096  parser_coercion_errposition(pstate, location, node)));
1097 
1098  ReleaseTupleDesc(tupdesc);
1099 
1100  rowexpr = makeNode(RowExpr);
1101  rowexpr->args = newargs;
1102  rowexpr->row_typeid = baseTypeId;
1103  rowexpr->row_format = cformat;
1104  rowexpr->colnames = NIL; /* not needed for named target type */
1105  rowexpr->location = location;
1106 
1107  /* If target is a domain, apply constraints */
1108  if (baseTypeId != targetTypeId)
1109  {
1110  rowexpr->row_format = COERCE_IMPLICIT_CAST;
1111  return coerce_to_domain((Node *) rowexpr,
1112  baseTypeId, baseTypeMod,
1113  targetTypeId,
1114  ccontext, cformat, location,
1115  false);
1116  }
1117 
1118  return (Node *) rowexpr;
1119 }
#define NIL
Definition: pg_list.h:65
Oid getBaseTypeAndTypmod(Oid typid, int32 *typmod)
Definition: lsyscache.c:2316
List * args
Definition: primnodes.h:1022
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
Definition: typcache.c:1652
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:321
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:608
char * format_type_be(Oid type_oid)
Definition: format_type.c:326
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:181
signed int int32
Definition: c.h:347
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:335
#define ERROR
Definition: elog.h:43
List * colnames
Definition: primnodes.h:1038
Node * coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype, Oid targettype, int32 targettypmod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:78
Node * coerce_to_domain(Node *arg, Oid baseTypeId, int32 baseTypeMod, Oid typeId, CoercionContext ccontext, CoercionForm cformat, int location, bool hideInputCoercion)
Definition: parse_coerce.c:663
int location
Definition: primnodes.h:1039
int errdetail(const char *fmt,...)
Definition: elog.c:955
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
#define ereport(elevel, rest)
Definition: elog.h:141
List * lappend(List *list, void *datum)
Definition: list.c:322
#define InvalidOid
Definition: postgres_ext.h:36
#define makeNode(_type_)
Definition: nodes.h:573
#define lfirst(lc)
Definition: pg_list.h:190
List * expandNSItemVars(ParseNamespaceItem *nsitem, int sublevels_up, int location, List **colnames)
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
Oid row_typeid
Definition: primnodes.h:1023
#define InvalidAttrNumber
Definition: attnum.h:23
ParseNamespaceItem * GetNSItemByRangeTablePosn(ParseState *pstate, int varno, int sublevels_up)
int errmsg(const char *fmt,...)
Definition: elog.c:822
int parser_coercion_errposition(ParseState *pstate, int coerce_location, Node *input_expr)
int i
void * arg
#define ReleaseTupleDesc(tupdesc)
Definition: tupdesc.h:122
CoercionForm row_format
Definition: primnodes.h:1037
Definition: pg_list.h:50

◆ coerce_to_boolean()

Node* coerce_to_boolean ( ParseState pstate,
Node node,
const char *  constructName 
)

Definition at line 1132 of file parse_coerce.c.

References COERCE_IMPLICIT_CAST, coerce_to_target_type(), COERCION_ASSIGNMENT, ereport, errcode(), errmsg(), ERROR, expression_returns_set(), exprLocation(), exprType(), format_type_be(), and parser_errposition().

Referenced by cookConstraint(), DoCopy(), domainAddConstraint(), transformAExprIn(), transformBooleanTest(), transformBoolExpr(), transformCaseExpr(), transformJoinUsingClause(), transformWhereClause(), and transformXmlExpr().

1134 {
1135  Oid inputTypeId = exprType(node);
1136 
1137  if (inputTypeId != BOOLOID)
1138  {
1139  Node *newnode;
1140 
1141  newnode = coerce_to_target_type(pstate, node, inputTypeId,
1142  BOOLOID, -1,
1145  -1);
1146  if (newnode == NULL)
1147  ereport(ERROR,
1148  (errcode(ERRCODE_DATATYPE_MISMATCH),
1149  /* translator: first %s is name of a SQL construct, eg WHERE */
1150  errmsg("argument of %s must be type %s, not type %s",
1151  constructName, "boolean",
1152  format_type_be(inputTypeId)),
1153  parser_errposition(pstate, exprLocation(node))));
1154  node = newnode;
1155  }
1156 
1157  if (expression_returns_set(node))
1158  ereport(ERROR,
1159  (errcode(ERRCODE_DATATYPE_MISMATCH),
1160  /* translator: %s is name of a SQL construct, eg WHERE */
1161  errmsg("argument of %s must not return a set",
1162  constructName),
1163  parser_errposition(pstate, exprLocation(node))));
1164 
1165  return node;
1166 }
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1191
bool expression_returns_set(Node *clause)
Definition: nodeFuncs.c:669
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:608
char * format_type_be(Oid type_oid)
Definition: format_type.c:326
unsigned int Oid
Definition: postgres_ext.h:31
#define ERROR
Definition: elog.h:43
Node * coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype, Oid targettype, int32 targettypmod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:78
#define ereport(elevel, rest)
Definition: elog.h:141
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
int errmsg(const char *fmt,...)
Definition: elog.c:822

◆ coerce_to_common_type()

Node* coerce_to_common_type ( ParseState pstate,
Node node,
Oid  targetTypeId,
const char *  context 
)

Definition at line 1403 of file parse_coerce.c.

References can_coerce_type(), COERCE_IMPLICIT_CAST, coerce_type(), COERCION_IMPLICIT, ereport, errcode(), errmsg(), ERROR, exprLocation(), exprType(), format_type_be(), and parser_errposition().

Referenced by generate_setop_tlist(), transformAExprIn(), transformArrayExpr(), transformCaseExpr(), transformCoalesceExpr(), transformMinMaxExpr(), transformSetOperationTree(), and transformValuesClause().

1405 {
1406  Oid inputTypeId = exprType(node);
1407 
1408  if (inputTypeId == targetTypeId)
1409  return node; /* no work */
1410  if (can_coerce_type(1, &inputTypeId, &targetTypeId, COERCION_IMPLICIT))
1411  node = coerce_type(pstate, node, inputTypeId, targetTypeId, -1,
1413  else
1414  ereport(ERROR,
1415  (errcode(ERRCODE_CANNOT_COERCE),
1416  /* translator: first %s is name of a SQL construct, eg CASE */
1417  errmsg("%s could not convert type %s to %s",
1418  context,
1419  format_type_be(inputTypeId),
1420  format_type_be(targetTypeId)),
1421  parser_errposition(pstate, exprLocation(node))));
1422  return node;
1423 }
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1191
bool can_coerce_type(int nargs, const Oid *input_typeids, const Oid *target_typeids, CoercionContext ccontext)
Definition: parse_coerce.c:543
Node * coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:156
int errcode(int sqlerrcode)
Definition: elog.c:608
char * format_type_be(Oid type_oid)
Definition: format_type.c:326
unsigned int Oid
Definition: postgres_ext.h:31
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:141
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
int errmsg(const char *fmt,...)
Definition: elog.c:822

◆ coerce_to_domain()

Node* coerce_to_domain ( Node arg,
Oid  baseTypeId,
int32  baseTypeMod,
Oid  typeId,
CoercionContext  ccontext,
CoercionForm  cformat,
int  location,
bool  hideInputCoercion 
)

Definition at line 663 of file parse_coerce.c.

References arg, CoerceToDomain::arg, COERCE_IMPLICIT_CAST, coerce_type_typmod(), CoerceToDomain::coercionformat, getBaseTypeAndTypmod(), hide_coercion_node(), InvalidOid, CoerceToDomain::location, makeNode, CoerceToDomain::resulttype, and CoerceToDomain::resulttypmod.

Referenced by coerce_record_to_complex(), coerce_type(), expand_targetlist(), ReplaceVarsFromTargetList_callback(), rewriteTargetListIU(), rewriteValuesRTE(), and transformAssignmentIndirection().

666 {
667  CoerceToDomain *result;
668 
669  /* Get the base type if it hasn't been supplied */
670  if (baseTypeId == InvalidOid)
671  baseTypeId = getBaseTypeAndTypmod(typeId, &baseTypeMod);
672 
673  /* If it isn't a domain, return the node as it was passed in */
674  if (baseTypeId == typeId)
675  return arg;
676 
677  /* Suppress display of nested coercion steps */
678  if (hideInputCoercion)
679  hide_coercion_node(arg);
680 
681  /*
682  * If the domain applies a typmod to its base type, build the appropriate
683  * coercion step. Mark it implicit for display purposes, because we don't
684  * want it shown separately by ruleutils.c; but the isExplicit flag passed
685  * to the conversion function depends on the manner in which the domain
686  * coercion is invoked, so that the semantics of implicit and explicit
687  * coercion differ. (Is that really the behavior we want?)
688  *
689  * NOTE: because we apply this as part of the fixed expression structure,
690  * ALTER DOMAIN cannot alter the typtypmod. But it's unclear that that
691  * would be safe to do anyway, without lots of knowledge about what the
692  * base type thinks the typmod means.
693  */
694  arg = coerce_type_typmod(arg, baseTypeId, baseTypeMod,
695  ccontext, COERCE_IMPLICIT_CAST, location,
696  false);
697 
698  /*
699  * Now build the domain coercion node. This represents run-time checking
700  * of any constraints currently attached to the domain. This also ensures
701  * that the expression is properly labeled as to result type.
702  */
703  result = makeNode(CoerceToDomain);
704  result->arg = (Expr *) arg;
705  result->resulttype = typeId;
706  result->resulttypmod = -1; /* currently, always -1 for domains */
707  /* resultcollid will be set by parse_collate.c */
708  result->coercionformat = cformat;
709  result->location = location;
710 
711  return (Node *) result;
712 }
Oid getBaseTypeAndTypmod(Oid typid, int32 *typmod)
Definition: lsyscache.c:2316
int32 resulttypmod
Definition: primnodes.h:1261
Definition: nodes.h:525
CoercionForm coercionformat
Definition: primnodes.h:1263
static void hide_coercion_node(Node *node)
Definition: parse_coerce.c:782
static Node * coerce_type_typmod(Node *node, Oid targetTypeId, int32 targetTypMod, CoercionContext ccontext, CoercionForm cformat, int location, bool hideInputCoercion)
Definition: parse_coerce.c:740
#define InvalidOid
Definition: postgres_ext.h:36
#define makeNode(_type_)
Definition: nodes.h:573
void * arg

◆ coerce_to_specific_type()

Node* coerce_to_specific_type ( ParseState pstate,
Node node,
Oid  targetTypeId,
const char *  constructName 
)

Definition at line 1228 of file parse_coerce.c.

References coerce_to_specific_type_typmod().

Referenced by interpret_function_parameter_list(), transformFrameOffset(), transformLimitClause(), transformRangeTableFunc(), transformRangeTableSample(), transformXmlExpr(), and transformXmlSerialize().

1231 {
1232  return coerce_to_specific_type_typmod(pstate, node,
1233  targetTypeId, -1,
1234  constructName);
1235 }
Node * coerce_to_specific_type_typmod(ParseState *pstate, Node *node, Oid targetTypeId, int32 targetTypmod, const char *constructName)

◆ coerce_to_specific_type_typmod()

Node* coerce_to_specific_type_typmod ( ParseState pstate,
Node node,
Oid  targetTypeId,
int32  targetTypmod,
const char *  constructName 
)

Definition at line 1179 of file parse_coerce.c.

References COERCE_IMPLICIT_CAST, coerce_to_target_type(), COERCION_ASSIGNMENT, ereport, errcode(), errmsg(), ERROR, expression_returns_set(), exprLocation(), exprType(), format_type_be(), and parser_errposition().

Referenced by coerce_to_specific_type(), and transformRangeTableFunc().

1182 {
1183  Oid inputTypeId = exprType(node);
1184 
1185  if (inputTypeId != targetTypeId)
1186  {
1187  Node *newnode;
1188 
1189  newnode = coerce_to_target_type(pstate, node, inputTypeId,
1190  targetTypeId, targetTypmod,
1193  -1);
1194  if (newnode == NULL)
1195  ereport(ERROR,
1196  (errcode(ERRCODE_DATATYPE_MISMATCH),
1197  /* translator: first %s is name of a SQL construct, eg LIMIT */
1198  errmsg("argument of %s must be type %s, not type %s",
1199  constructName,
1200  format_type_be(targetTypeId),
1201  format_type_be(inputTypeId)),
1202  parser_errposition(pstate, exprLocation(node))));
1203  node = newnode;
1204  }
1205 
1206  if (expression_returns_set(node))
1207  ereport(ERROR,
1208  (errcode(ERRCODE_DATATYPE_MISMATCH),
1209  /* translator: %s is name of a SQL construct, eg LIMIT */
1210  errmsg("argument of %s must not return a set",
1211  constructName),
1212  parser_errposition(pstate, exprLocation(node))));
1213 
1214  return node;
1215 }
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1191
bool expression_returns_set(Node *clause)
Definition: nodeFuncs.c:669
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:608
char * format_type_be(Oid type_oid)
Definition: format_type.c:326
unsigned int Oid
Definition: postgres_ext.h:31
#define ERROR
Definition: elog.h:43
Node * coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype, Oid targettype, int32 targettypmod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:78
#define ereport(elevel, rest)
Definition: elog.h:141
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
int errmsg(const char *fmt,...)
Definition: elog.c:822

◆ coerce_to_target_type()

Node* coerce_to_target_type ( ParseState pstate,
Node expr,
Oid  exprtype,
Oid  targettype,
int32  targettypmod,
CoercionContext  ccontext,
CoercionForm  cformat,
int  location 
)

Definition at line 78 of file parse_coerce.c.

References arg, CollateExpr::arg, can_coerce_type(), coerce_type(), coerce_type_typmod(), CollateExpr::collOid, IsA, CollateExpr::location, and makeNode.

Referenced by ATExecAddColumn(), ATExecAlterColumnType(), ATPrepAlterColumnType(), build_coercion_expression(), build_column_default(), coerce_fn_result_column(), coerce_record_to_complex(), coerce_to_boolean(), coerce_to_specific_type_typmod(), cookDefault(), EvaluateParams(), get_cast_hashentry(), transformArrayExpr(), transformAssignedExpr(), transformAssignmentIndirection(), transformAssignmentSubscripts(), transformContainerSubscripts(), transformPartitionBoundValue(), transformTypeCast(), and transformXmlSerialize().

83 {
84  Node *result;
85  Node *origexpr;
86 
87  if (!can_coerce_type(1, &exprtype, &targettype, ccontext))
88  return NULL;
89 
90  /*
91  * If the input has a CollateExpr at the top, strip it off, perform the
92  * coercion, and put a new one back on. This is annoying since it
93  * duplicates logic in coerce_type, but if we don't do this then it's too
94  * hard to tell whether coerce_type actually changed anything, and we
95  * *must* know that to avoid possibly calling hide_coercion_node on
96  * something that wasn't generated by coerce_type. Note that if there are
97  * multiple stacked CollateExprs, we just discard all but the topmost.
98  */
99  origexpr = expr;
100  while (expr && IsA(expr, CollateExpr))
101  expr = (Node *) ((CollateExpr *) expr)->arg;
102 
103  result = coerce_type(pstate, expr, exprtype,
104  targettype, targettypmod,
105  ccontext, cformat, location);
106 
107  /*
108  * If the target is a fixed-length type, it may need a length coercion as
109  * well as a type coercion. If we find ourselves adding both, force the
110  * inner coercion node to implicit display form.
111  */
112  result = coerce_type_typmod(result,
113  targettype, targettypmod,
114  ccontext, cformat, location,
115  (result != expr && !IsA(result, Const)));
116 
117  if (expr != origexpr)
118  {
119  /* Reinstall top CollateExpr */
120  CollateExpr *coll = (CollateExpr *) origexpr;
121  CollateExpr *newcoll = makeNode(CollateExpr);
122 
123  newcoll->arg = (Expr *) result;
124  newcoll->collOid = coll->collOid;
125  newcoll->location = coll->location;
126  result = (Node *) newcoll;
127  }
128 
129  return result;
130 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
bool can_coerce_type(int nargs, const Oid *input_typeids, const Oid *target_typeids, CoercionContext ccontext)
Definition: parse_coerce.c:543
Node * coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:156
Definition: nodes.h:525
static Node * coerce_type_typmod(Node *node, Oid targetTypeId, int32 targetTypMod, CoercionContext ccontext, CoercionForm cformat, int location, bool hideInputCoercion)
Definition: parse_coerce.c:740
#define makeNode(_type_)
Definition: nodes.h:573
Expr * arg
Definition: primnodes.h:900
void * arg
int location
Definition: primnodes.h:902

◆ coerce_type()

Node* coerce_type ( ParseState pstate,
Node node,
Oid  inputTypeId,
Oid  targetTypeId,
int32  targetTypeMod,
CoercionContext  ccontext,
CoercionForm  cformat,
int  location 
)

Definition at line 156 of file parse_coerce.c.

References ConvertRowtypeExpr::arg, CollateExpr::arg, build_coercion_expression(), cancel_parser_errposition_callback(), COERCE_IMPLICIT_CAST, coerce_record_to_complex(), coerce_to_domain(), coerce_type(), COERCION_PATH_NONE, COERCION_PATH_RELABELTYPE, CollateExpr::collOid, Const::constbyval, Const::constcollid, Const::constisnull, Const::constlen, Const::consttype, Const::consttypmod, Const::constvalue, ConvertRowtypeExpr::convertformat, DatumGetCString, datumIsEqual(), elog, ERROR, find_coercion_pathway(), format_type_be(), getBaseType(), getBaseTypeAndTypmod(), InvalidOid, is_complex_array(), IsA, ISCOMPLEX, Const::location, RelabelType::location, ConvertRowtypeExpr::location, CollateExpr::location, makeNode, makeRelabelType(), ParseState::p_coerce_param_hook, PG_DETOAST_DATUM, PointerGetDatum, ReleaseSysCache(), ConvertRowtypeExpr::resulttype, setup_parser_errposition_callback(), stringTypeDatum(), typeByVal(), typeidType(), typeInheritsFrom(), typeIsOfTypedTable(), typeLen(), typeTypeCollation(), typeTypeName(), and WARNING.

Referenced by addTargetToGroupList(), addTargetToSortList(), buildMergedJoinVar(), coerce_to_common_type(), coerce_to_target_type(), coerce_type(), make_fn_arguments(), ParseFuncOrColumn(), resolveTargetListUnknowns(), transformArrayExpr(), and unify_hypothetical_args().

159 {
160  Node *result;
161  CoercionPathType pathtype;
162  Oid funcId;
163 
164  if (targetTypeId == inputTypeId ||
165  node == NULL)
166  {
167  /* no conversion needed */
168  return node;
169  }
170  if (targetTypeId == ANYOID ||
171  targetTypeId == ANYELEMENTOID ||
172  targetTypeId == ANYNONARRAYOID)
173  {
174  /*
175  * Assume can_coerce_type verified that implicit coercion is okay.
176  *
177  * Note: by returning the unmodified node here, we are saying that
178  * it's OK to treat an UNKNOWN constant as a valid input for a
179  * function accepting ANY, ANYELEMENT, or ANYNONARRAY. This should be
180  * all right, since an UNKNOWN value is still a perfectly valid Datum.
181  *
182  * NB: we do NOT want a RelabelType here: the exposed type of the
183  * function argument must be its actual type, not the polymorphic
184  * pseudotype.
185  */
186  return node;
187  }
188  if (targetTypeId == ANYARRAYOID ||
189  targetTypeId == ANYENUMOID ||
190  targetTypeId == ANYRANGEOID)
191  {
192  /*
193  * Assume can_coerce_type verified that implicit coercion is okay.
194  *
195  * These cases are unlike the ones above because the exposed type of
196  * the argument must be an actual array, enum, or range type. In
197  * particular the argument must *not* be an UNKNOWN constant. If it
198  * is, we just fall through; below, we'll call anyarray_in,
199  * anyenum_in, or anyrange_in, which will produce an error. Also, if
200  * what we have is a domain over array, enum, or range, we have to
201  * relabel it to its base type.
202  *
203  * Note: currently, we can't actually see a domain-over-enum here,
204  * since the other functions in this file will not match such a
205  * parameter to ANYENUM. But that should get changed eventually.
206  */
207  if (inputTypeId != UNKNOWNOID)
208  {
209  Oid baseTypeId = getBaseType(inputTypeId);
210 
211  if (baseTypeId != inputTypeId)
212  {
213  RelabelType *r = makeRelabelType((Expr *) node,
214  baseTypeId, -1,
215  InvalidOid,
216  cformat);
217 
218  r->location = location;
219  return (Node *) r;
220  }
221  /* Not a domain type, so return it as-is */
222  return node;
223  }
224  }
225  if (inputTypeId == UNKNOWNOID && IsA(node, Const))
226  {
227  /*
228  * Input is a string constant with previously undetermined type. Apply
229  * the target type's typinput function to it to produce a constant of
230  * the target type.
231  *
232  * NOTE: this case cannot be folded together with the other
233  * constant-input case, since the typinput function does not
234  * necessarily behave the same as a type conversion function. For
235  * example, int4's typinput function will reject "1.2", whereas
236  * float-to-int type conversion will round to integer.
237  *
238  * XXX if the typinput function is not immutable, we really ought to
239  * postpone evaluation of the function call until runtime. But there
240  * is no way to represent a typinput function call as an expression
241  * tree, because C-string values are not Datums. (XXX This *is*
242  * possible as of 7.3, do we want to do it?)
243  */
244  Const *con = (Const *) node;
245  Const *newcon = makeNode(Const);
246  Oid baseTypeId;
247  int32 baseTypeMod;
248  int32 inputTypeMod;
249  Type baseType;
250  ParseCallbackState pcbstate;
251 
252  /*
253  * If the target type is a domain, we want to call its base type's
254  * input routine, not domain_in(). This is to avoid premature failure
255  * when the domain applies a typmod: existing input routines follow
256  * implicit-coercion semantics for length checks, which is not always
257  * what we want here. The needed check will be applied properly
258  * inside coerce_to_domain().
259  */
260  baseTypeMod = targetTypeMod;
261  baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
262 
263  /*
264  * For most types we pass typmod -1 to the input routine, because
265  * existing input routines follow implicit-coercion semantics for
266  * length checks, which is not always what we want here. Any length
267  * constraint will be applied later by our caller. An exception
268  * however is the INTERVAL type, for which we *must* pass the typmod
269  * or it won't be able to obey the bizarre SQL-spec input rules. (Ugly
270  * as sin, but so is this part of the spec...)
271  */
272  if (baseTypeId == INTERVALOID)
273  inputTypeMod = baseTypeMod;
274  else
275  inputTypeMod = -1;
276 
277  baseType = typeidType(baseTypeId);
278 
279  newcon->consttype = baseTypeId;
280  newcon->consttypmod = inputTypeMod;
281  newcon->constcollid = typeTypeCollation(baseType);
282  newcon->constlen = typeLen(baseType);
283  newcon->constbyval = typeByVal(baseType);
284  newcon->constisnull = con->constisnull;
285 
286  /*
287  * We use the original literal's location regardless of the position
288  * of the coercion. This is a change from pre-9.2 behavior, meant to
289  * simplify life for pg_stat_statements.
290  */
291  newcon->location = con->location;
292 
293  /*
294  * Set up to point at the constant's text if the input routine throws
295  * an error.
296  */
297  setup_parser_errposition_callback(&pcbstate, pstate, con->location);
298 
299  /*
300  * We assume here that UNKNOWN's internal representation is the same
301  * as CSTRING.
302  */
303  if (!con->constisnull)
304  newcon->constvalue = stringTypeDatum(baseType,
306  inputTypeMod);
307  else
308  newcon->constvalue = stringTypeDatum(baseType,
309  NULL,
310  inputTypeMod);
311 
312  /*
313  * If it's a varlena value, force it to be in non-expanded
314  * (non-toasted) format; this avoids any possible dependency on
315  * external values and improves consistency of representation.
316  */
317  if (!con->constisnull && newcon->constlen == -1)
318  newcon->constvalue =
320 
321 #ifdef RANDOMIZE_ALLOCATED_MEMORY
322 
323  /*
324  * For pass-by-reference data types, repeat the conversion to see if
325  * the input function leaves any uninitialized bytes in the result. We
326  * can only detect that reliably if RANDOMIZE_ALLOCATED_MEMORY is
327  * enabled, so we don't bother testing otherwise. The reason we don't
328  * want any instability in the input function is that comparison of
329  * Const nodes relies on bytewise comparison of the datums, so if the
330  * input function leaves garbage then subexpressions that should be
331  * identical may not get recognized as such. See pgsql-hackers
332  * discussion of 2008-04-04.
333  */
334  if (!con->constisnull && !newcon->constbyval)
335  {
336  Datum val2;
337 
338  val2 = stringTypeDatum(baseType,
340  inputTypeMod);
341  if (newcon->constlen == -1)
342  val2 = PointerGetDatum(PG_DETOAST_DATUM(val2));
343  if (!datumIsEqual(newcon->constvalue, val2, false, newcon->constlen))
344  elog(WARNING, "type %s has unstable input conversion for \"%s\"",
345  typeTypeName(baseType), DatumGetCString(con->constvalue));
346  }
347 #endif
348 
350 
351  result = (Node *) newcon;
352 
353  /* If target is a domain, apply constraints. */
354  if (baseTypeId != targetTypeId)
355  result = coerce_to_domain(result,
356  baseTypeId, baseTypeMod,
357  targetTypeId,
358  ccontext, cformat, location,
359  false);
360 
361  ReleaseSysCache(baseType);
362 
363  return result;
364  }
365  if (IsA(node, Param) &&
366  pstate != NULL && pstate->p_coerce_param_hook != NULL)
367  {
368  /*
369  * Allow the CoerceParamHook to decide what happens. It can return a
370  * transformed node (very possibly the same Param node), or return
371  * NULL to indicate we should proceed with normal coercion.
372  */
373  result = pstate->p_coerce_param_hook(pstate,
374  (Param *) node,
375  targetTypeId,
376  targetTypeMod,
377  location);
378  if (result)
379  return result;
380  }
381  if (IsA(node, CollateExpr))
382  {
383  /*
384  * If we have a COLLATE clause, we have to push the coercion
385  * underneath the COLLATE. This is really ugly, but there is little
386  * choice because the above hacks on Consts and Params wouldn't happen
387  * otherwise. This kluge has consequences in coerce_to_target_type.
388  */
389  CollateExpr *coll = (CollateExpr *) node;
390  CollateExpr *newcoll = makeNode(CollateExpr);
391 
392  newcoll->arg = (Expr *)
393  coerce_type(pstate, (Node *) coll->arg,
394  inputTypeId, targetTypeId, targetTypeMod,
395  ccontext, cformat, location);
396  newcoll->collOid = coll->collOid;
397  newcoll->location = coll->location;
398  return (Node *) newcoll;
399  }
400  pathtype = find_coercion_pathway(targetTypeId, inputTypeId, ccontext,
401  &funcId);
402  if (pathtype != COERCION_PATH_NONE)
403  {
404  if (pathtype != COERCION_PATH_RELABELTYPE)
405  {
406  /*
407  * Generate an expression tree representing run-time application
408  * of the conversion function. If we are dealing with a domain
409  * target type, the conversion function will yield the base type,
410  * and we need to extract the correct typmod to use from the
411  * domain's typtypmod.
412  */
413  Oid baseTypeId;
414  int32 baseTypeMod;
415 
416  baseTypeMod = targetTypeMod;
417  baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
418 
419  result = build_coercion_expression(node, pathtype, funcId,
420  baseTypeId, baseTypeMod,
421  ccontext, cformat, location);
422 
423  /*
424  * If domain, coerce to the domain type and relabel with domain
425  * type ID, hiding the previous coercion node.
426  */
427  if (targetTypeId != baseTypeId)
428  result = coerce_to_domain(result, baseTypeId, baseTypeMod,
429  targetTypeId,
430  ccontext, cformat, location,
431  true);
432  }
433  else
434  {
435  /*
436  * We don't need to do a physical conversion, but we do need to
437  * attach a RelabelType node so that the expression will be seen
438  * to have the intended type when inspected by higher-level code.
439  *
440  * Also, domains may have value restrictions beyond the base type
441  * that must be accounted for. If the destination is a domain
442  * then we won't need a RelabelType node.
443  */
444  result = coerce_to_domain(node, InvalidOid, -1, targetTypeId,
445  ccontext, cformat, location,
446  false);
447  if (result == node)
448  {
449  /*
450  * XXX could we label result with exprTypmod(node) instead of
451  * default -1 typmod, to save a possible length-coercion
452  * later? Would work if both types have same interpretation of
453  * typmod, which is likely but not certain.
454  */
455  RelabelType *r = makeRelabelType((Expr *) result,
456  targetTypeId, -1,
457  InvalidOid,
458  cformat);
459 
460  r->location = location;
461  result = (Node *) r;
462  }
463  }
464  return result;
465  }
466  if (inputTypeId == RECORDOID &&
467  ISCOMPLEX(targetTypeId))
468  {
469  /* Coerce a RECORD to a specific complex type */
470  return coerce_record_to_complex(pstate, node, targetTypeId,
471  ccontext, cformat, location);
472  }
473  if (targetTypeId == RECORDOID &&
474  ISCOMPLEX(inputTypeId))
475  {
476  /* Coerce a specific complex type to RECORD */
477  /* NB: we do NOT want a RelabelType here */
478  return node;
479  }
480 #ifdef NOT_USED
481  if (inputTypeId == RECORDARRAYOID &&
482  is_complex_array(targetTypeId))
483  {
484  /* Coerce record[] to a specific complex array type */
485  /* not implemented yet ... */
486  }
487 #endif
488  if (targetTypeId == RECORDARRAYOID &&
489  is_complex_array(inputTypeId))
490  {
491  /* Coerce a specific complex array type to record[] */
492  /* NB: we do NOT want a RelabelType here */
493  return node;
494  }
495  if (typeInheritsFrom(inputTypeId, targetTypeId)
496  || typeIsOfTypedTable(inputTypeId, targetTypeId))
497  {
498  /*
499  * Input class type is a subclass of target, so generate an
500  * appropriate runtime conversion (removing unneeded columns and
501  * possibly rearranging the ones that are wanted).
502  *
503  * We will also get here when the input is a domain over a subclass of
504  * the target type. To keep life simple for the executor, we define
505  * ConvertRowtypeExpr as only working between regular composite types;
506  * therefore, in such cases insert a RelabelType to smash the input
507  * expression down to its base type.
508  */
509  Oid baseTypeId = getBaseType(inputTypeId);
511 
512  if (baseTypeId != inputTypeId)
513  {
514  RelabelType *rt = makeRelabelType((Expr *) node,
515  baseTypeId, -1,
516  InvalidOid,
518 
519  rt->location = location;
520  node = (Node *) rt;
521  }
522  r->arg = (Expr *) node;
523  r->resulttype = targetTypeId;
524  r->convertformat = cformat;
525  r->location = location;
526  return (Node *) r;
527  }
528  /* If we get here, caller blew it */
529  elog(ERROR, "failed to find conversion function from %s to %s",
530  format_type_be(inputTypeId), format_type_be(targetTypeId));
531  return NULL; /* keep compiler quiet */
532 }
Datum constvalue
Definition: primnodes.h:214
Oid getBaseTypeAndTypmod(Oid typid, int32 *typmod)
Definition: lsyscache.c:2316
Oid typeTypeCollation(Type typ)
Definition: parse_type.c:638
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
bool constbyval
Definition: primnodes.h:217
int16 typeLen(Type t)
Definition: parse_type.c:597
#define PointerGetDatum(X)
Definition: postgres.h:556
bool datumIsEqual(Datum value1, Datum value2, bool typByVal, int typLen)
Definition: datum.c:221
CoerceParamHook p_coerce_param_hook
Definition: parse_node.h:221
Node * coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:156
Definition: nodes.h:525
char * format_type_be(Oid type_oid)
Definition: format_type.c:326
unsigned int Oid
Definition: postgres_ext.h:31
CoercionPathType
Definition: parse_coerce.h:24
signed int int32
Definition: c.h:347
int constlen
Definition: primnodes.h:213
Oid consttype
Definition: primnodes.h:210
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:160
bool typeByVal(Type t)
Definition: parse_type.c:607
#define ERROR
Definition: elog.h:43
#define DatumGetCString(X)
Definition: postgres.h:566
char * typeTypeName(Type t)
Definition: parse_type.c:617
Datum stringTypeDatum(Type tp, char *string, int32 atttypmod)
Definition: parse_type.c:652
Node * coerce_to_domain(Node *arg, Oid baseTypeId, int32 baseTypeMod, Oid typeId, CoercionContext ccontext, CoercionForm cformat, int location, bool hideInputCoercion)
Definition: parse_coerce.c:663
Oid constcollid
Definition: primnodes.h:212
RelabelType * makeRelabelType(Expr *arg, Oid rtype, int32 rtypmod, Oid rcollid, CoercionForm rformat)
Definition: makefuncs.c:400
static Node * build_coercion_expression(Node *node, CoercionPathType pathtype, Oid funcId, Oid targetTypeId, int32 targetTypMod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:810
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:144
#define WARNING
Definition: elog.h:40
int location
Definition: primnodes.h:221
uintptr_t Datum
Definition: postgres.h:367
CoercionForm convertformat
Definition: primnodes.h:886
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define InvalidOid
Definition: postgres_ext.h:36
#define makeNode(_type_)
Definition: nodes.h:573
bool typeInheritsFrom(Oid subclassTypeId, Oid superclassTypeId)
Definition: pg_inherits.c:315
#define ISCOMPLEX(typeid)
Definition: parse_type.h:58
static bool typeIsOfTypedTable(Oid reltypeId, Oid reloftypeId)
Expr * arg
Definition: primnodes.h:900
static Node * coerce_record_to_complex(ParseState *pstate, Node *node, Oid targetTypeId, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:983
int32 consttypmod
Definition: primnodes.h:211
CoercionPathType find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId, CoercionContext ccontext, Oid *funcid)
#define elog(elevel,...)
Definition: elog.h:228
#define PG_DETOAST_DATUM(datum)
Definition: fmgr.h:235
static bool is_complex_array(Oid typid)
Type typeidType(Oid id)
Definition: parse_type.c:576
int location
Definition: primnodes.h:902
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2299
int location
Definition: primnodes.h:819
bool constisnull
Definition: primnodes.h:215

◆ coerce_type_typmod()

static Node * coerce_type_typmod ( Node node,
Oid  targetTypeId,
int32  targetTypMod,
CoercionContext  ccontext,
CoercionForm  cformat,
int  location,
bool  hideInputCoercion 
)
static

Definition at line 740 of file parse_coerce.c.

References build_coercion_expression(), COERCION_PATH_NONE, exprTypmod(), find_typmod_coercion_function(), and hide_coercion_node().

Referenced by coerce_to_domain(), and coerce_to_target_type().

744 {
745  CoercionPathType pathtype;
746  Oid funcId;
747 
748  /*
749  * A negative typmod is assumed to mean that no coercion is wanted. Also,
750  * skip coercion if already done.
751  */
752  if (targetTypMod < 0 || targetTypMod == exprTypmod(node))
753  return node;
754 
755  pathtype = find_typmod_coercion_function(targetTypeId, &funcId);
756 
757  if (pathtype != COERCION_PATH_NONE)
758  {
759  /* Suppress display of nested coercion steps */
760  if (hideInputCoercion)
761  hide_coercion_node(node);
762 
763  node = build_coercion_expression(node, pathtype, funcId,
764  targetTypeId, targetTypMod,
765  ccontext, cformat, location);
766  }
767 
768  return node;
769 }
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:275
unsigned int Oid
Definition: postgres_ext.h:31
CoercionPathType
Definition: parse_coerce.h:24
static void hide_coercion_node(Node *node)
Definition: parse_coerce.c:782
static Node * build_coercion_expression(Node *node, CoercionPathType pathtype, Oid funcId, Oid targetTypeId, int32 targetTypMod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:810
CoercionPathType find_typmod_coercion_function(Oid typeId, Oid *funcid)

◆ enforce_generic_type_consistency()

Oid enforce_generic_type_consistency ( const Oid actual_arg_types,
Oid declared_arg_types,
int  nargs,
Oid  rettype,
bool  allow_poly 
)

Definition at line 1671 of file parse_coerce.c.

References ereport, errcode(), errdetail(), errmsg(), ERROR, format_type_be(), get_array_type(), get_element_type(), get_range_subtype(), getBaseType(), InvalidOid, OidIsValid, type_is_array_domain, and type_is_enum().

Referenced by lookup_agg_function(), make_op(), make_scalar_array_op(), ParseFuncOrColumn(), recheck_cast_function_args(), and resolve_aggregate_transtype().

1676 {
1677  int j;
1678  bool have_generics = false;
1679  bool have_unknowns = false;
1680  Oid elem_typeid = InvalidOid;
1681  Oid array_typeid = InvalidOid;
1682  Oid range_typeid = InvalidOid;
1683  Oid array_typelem;
1684  Oid range_typelem;
1685  bool have_anyelement = (rettype == ANYELEMENTOID ||
1686  rettype == ANYNONARRAYOID ||
1687  rettype == ANYENUMOID);
1688  bool have_anynonarray = (rettype == ANYNONARRAYOID);
1689  bool have_anyenum = (rettype == ANYENUMOID);
1690 
1691  /*
1692  * Loop through the arguments to see if we have any that are polymorphic.
1693  * If so, require the actual types to be consistent.
1694  */
1695  for (j = 0; j < nargs; j++)
1696  {
1697  Oid decl_type = declared_arg_types[j];
1698  Oid actual_type = actual_arg_types[j];
1699 
1700  if (decl_type == ANYELEMENTOID ||
1701  decl_type == ANYNONARRAYOID ||
1702  decl_type == ANYENUMOID)
1703  {
1704  have_generics = have_anyelement = true;
1705  if (decl_type == ANYNONARRAYOID)
1706  have_anynonarray = true;
1707  else if (decl_type == ANYENUMOID)
1708  have_anyenum = true;
1709  if (actual_type == UNKNOWNOID)
1710  {
1711  have_unknowns = true;
1712  continue;
1713  }
1714  if (allow_poly && decl_type == actual_type)
1715  continue; /* no new information here */
1716  if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
1717  ereport(ERROR,
1718  (errcode(ERRCODE_DATATYPE_MISMATCH),
1719  errmsg("arguments declared \"anyelement\" are not all alike"),
1720  errdetail("%s versus %s",
1721  format_type_be(elem_typeid),
1722  format_type_be(actual_type))));
1723  elem_typeid = actual_type;
1724  }
1725  else if (decl_type == ANYARRAYOID)
1726  {
1727  have_generics = true;
1728  if (actual_type == UNKNOWNOID)
1729  {
1730  have_unknowns = true;
1731  continue;
1732  }
1733  if (allow_poly && decl_type == actual_type)
1734  continue; /* no new information here */
1735  actual_type = getBaseType(actual_type); /* flatten domains */
1736  if (OidIsValid(array_typeid) && actual_type != array_typeid)
1737  ereport(ERROR,
1738  (errcode(ERRCODE_DATATYPE_MISMATCH),
1739  errmsg("arguments declared \"anyarray\" are not all alike"),
1740  errdetail("%s versus %s",
1741  format_type_be(array_typeid),
1742  format_type_be(actual_type))));
1743  array_typeid = actual_type;
1744  }
1745  else if (decl_type == ANYRANGEOID)
1746  {
1747  have_generics = true;
1748  if (actual_type == UNKNOWNOID)
1749  {
1750  have_unknowns = true;
1751  continue;
1752  }
1753  if (allow_poly && decl_type == actual_type)
1754  continue; /* no new information here */
1755  actual_type = getBaseType(actual_type); /* flatten domains */
1756  if (OidIsValid(range_typeid) && actual_type != range_typeid)
1757  ereport(ERROR,
1758  (errcode(ERRCODE_DATATYPE_MISMATCH),
1759  errmsg("arguments declared \"anyrange\" are not all alike"),
1760  errdetail("%s versus %s",
1761  format_type_be(range_typeid),
1762  format_type_be(actual_type))));
1763  range_typeid = actual_type;
1764  }
1765  }
1766 
1767  /*
1768  * Fast Track: if none of the arguments are polymorphic, return the
1769  * unmodified rettype. We assume it can't be polymorphic either.
1770  */
1771  if (!have_generics)
1772  return rettype;
1773 
1774  /* Get the element type based on the array type, if we have one */
1775  if (OidIsValid(array_typeid))
1776  {
1777  if (array_typeid == ANYARRAYOID && !have_anyelement)
1778  {
1779  /* Special case for ANYARRAY input: okay iff no ANYELEMENT */
1780  array_typelem = ANYELEMENTOID;
1781  }
1782  else
1783  {
1784  array_typelem = get_element_type(array_typeid);
1785  if (!OidIsValid(array_typelem))
1786  ereport(ERROR,
1787  (errcode(ERRCODE_DATATYPE_MISMATCH),
1788  errmsg("argument declared %s is not an array but type %s",
1789  "anyarray", format_type_be(array_typeid))));
1790  }
1791 
1792  if (!OidIsValid(elem_typeid))
1793  {
1794  /*
1795  * if we don't have an element type yet, use the one we just got
1796  */
1797  elem_typeid = array_typelem;
1798  }
1799  else if (array_typelem != elem_typeid)
1800  {
1801  /* otherwise, they better match */
1802  ereport(ERROR,
1803  (errcode(ERRCODE_DATATYPE_MISMATCH),
1804  errmsg("argument declared %s is not consistent with argument declared %s",
1805  "anyarray", "anyelement"),
1806  errdetail("%s versus %s",
1807  format_type_be(array_typeid),
1808  format_type_be(elem_typeid))));
1809  }
1810  }
1811 
1812  /* Get the element type based on the range type, if we have one */
1813  if (OidIsValid(range_typeid))
1814  {
1815  if (range_typeid == ANYRANGEOID && !have_anyelement)
1816  {
1817  /* Special case for ANYRANGE input: okay iff no ANYELEMENT */
1818  range_typelem = ANYELEMENTOID;
1819  }
1820  else
1821  {
1822  range_typelem = get_range_subtype(range_typeid);
1823  if (!OidIsValid(range_typelem))
1824  ereport(ERROR,
1825  (errcode(ERRCODE_DATATYPE_MISMATCH),
1826  errmsg("argument declared %s is not a range type but type %s",
1827  "anyrange",
1828  format_type_be(range_typeid))));
1829  }
1830 
1831  if (!OidIsValid(elem_typeid))
1832  {
1833  /*
1834  * if we don't have an element type yet, use the one we just got
1835  */
1836  elem_typeid = range_typelem;
1837  }
1838  else if (range_typelem != elem_typeid)
1839  {
1840  /* otherwise, they better match */
1841  ereport(ERROR,
1842  (errcode(ERRCODE_DATATYPE_MISMATCH),
1843  errmsg("argument declared %s is not consistent with argument declared %s",
1844  "anyrange", "anyelement"),
1845  errdetail("%s versus %s",
1846  format_type_be(range_typeid),
1847  format_type_be(elem_typeid))));
1848  }
1849  }
1850 
1851  if (!OidIsValid(elem_typeid))
1852  {
1853  if (allow_poly)
1854  {
1855  elem_typeid = ANYELEMENTOID;
1856  array_typeid = ANYARRAYOID;
1857  range_typeid = ANYRANGEOID;
1858  }
1859  else
1860  {
1861  /* Only way to get here is if all the generic args are UNKNOWN */
1862  ereport(ERROR,
1863  (errcode(ERRCODE_DATATYPE_MISMATCH),
1864  errmsg("could not determine polymorphic type because input has type %s",
1865  "unknown")));
1866  }
1867  }
1868 
1869  if (have_anynonarray && elem_typeid != ANYELEMENTOID)
1870  {
1871  /* require the element type to not be an array or domain over array */
1872  if (type_is_array_domain(elem_typeid))
1873  ereport(ERROR,
1874  (errcode(ERRCODE_DATATYPE_MISMATCH),
1875  errmsg("type matched to anynonarray is an array type: %s",
1876  format_type_be(elem_typeid))));
1877  }
1878 
1879  if (have_anyenum && elem_typeid != ANYELEMENTOID)
1880  {
1881  /* require the element type to be an enum */
1882  if (!type_is_enum(elem_typeid))
1883  ereport(ERROR,
1884  (errcode(ERRCODE_DATATYPE_MISMATCH),
1885  errmsg("type matched to anyenum is not an enum type: %s",
1886  format_type_be(elem_typeid))));
1887  }
1888 
1889  /*
1890  * If we had any unknown inputs, re-scan to assign correct types
1891  */
1892  if (have_unknowns)
1893  {
1894  for (j = 0; j < nargs; j++)
1895  {
1896  Oid decl_type = declared_arg_types[j];
1897  Oid actual_type = actual_arg_types[j];
1898 
1899  if (actual_type != UNKNOWNOID)
1900  continue;
1901 
1902  if (decl_type == ANYELEMENTOID ||
1903  decl_type == ANYNONARRAYOID ||
1904  decl_type == ANYENUMOID)
1905  declared_arg_types[j] = elem_typeid;
1906  else if (decl_type == ANYARRAYOID)
1907  {
1908  if (!OidIsValid(array_typeid))
1909  {
1910  array_typeid = get_array_type(elem_typeid);
1911  if (!OidIsValid(array_typeid))
1912  ereport(ERROR,
1913  (errcode(ERRCODE_UNDEFINED_OBJECT),
1914  errmsg("could not find array type for data type %s",
1915  format_type_be(elem_typeid))));
1916  }
1917  declared_arg_types[j] = array_typeid;
1918  }
1919  else if (decl_type == ANYRANGEOID)
1920  {
1921  if (!OidIsValid(range_typeid))
1922  {
1923  ereport(ERROR,
1924  (errcode(ERRCODE_UNDEFINED_OBJECT),
1925  errmsg("could not find range type for data type %s",
1926  format_type_be(elem_typeid))));
1927  }
1928  declared_arg_types[j] = range_typeid;
1929  }
1930  }
1931  }
1932 
1933  /* if we return ANYARRAY use the appropriate argument type */
1934  if (rettype == ANYARRAYOID)
1935  {
1936  if (!OidIsValid(array_typeid))
1937  {
1938  array_typeid = get_array_type(elem_typeid);
1939  if (!OidIsValid(array_typeid))
1940  ereport(ERROR,
1941  (errcode(ERRCODE_UNDEFINED_OBJECT),
1942  errmsg("could not find array type for data type %s",
1943  format_type_be(elem_typeid))));
1944  }
1945  return array_typeid;
1946  }
1947 
1948  /* if we return ANYRANGE use the appropriate argument type */
1949  if (rettype == ANYRANGEOID)
1950  {
1951  if (!OidIsValid(range_typeid))
1952  {
1953  ereport(ERROR,
1954  (errcode(ERRCODE_UNDEFINED_OBJECT),
1955  errmsg("could not find range type for data type %s",
1956  format_type_be(elem_typeid))));
1957  }
1958  return range_typeid;
1959  }
1960 
1961  /* if we return ANYELEMENT use the appropriate argument type */
1962  if (rettype == ANYELEMENTOID ||
1963  rettype == ANYNONARRAYOID ||
1964  rettype == ANYENUMOID)
1965  return elem_typeid;
1966 
1967  /* we don't return a generic type; send back the original return type */
1968  return rettype;
1969 }
#define type_is_array_domain(typid)
Definition: lsyscache.h:186
Oid get_element_type(Oid typid)
Definition: lsyscache.c:2526
Oid get_array_type(Oid typid)
Definition: lsyscache.c:2554
int errcode(int sqlerrcode)
Definition: elog.c:608
char * format_type_be(Oid type_oid)
Definition: format_type.c:326
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:645
#define ERROR
Definition: elog.h:43
int errdetail(const char *fmt,...)
Definition: elog.c:955
#define ereport(elevel, rest)
Definition: elog.h:141
#define InvalidOid
Definition: postgres_ext.h:36
bool type_is_enum(Oid typid)
Definition: lsyscache.c:2456
int errmsg(const char *fmt,...)
Definition: elog.c:822
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2299
Oid get_range_subtype(Oid rangeOid)
Definition: lsyscache.c:3135

◆ find_coercion_pathway()

CoercionPathType find_coercion_pathway ( Oid  targetTypeId,
Oid  sourceTypeId,
CoercionContext  ccontext,
Oid funcid 
)

Definition at line 2230 of file parse_coerce.c.

References CASTSOURCETARGET, COERCION_ASSIGNMENT, COERCION_EXPLICIT, COERCION_IMPLICIT, COERCION_PATH_ARRAYCOERCE, COERCION_PATH_COERCEVIAIO, COERCION_PATH_FUNC, COERCION_PATH_NONE, COERCION_PATH_RELABELTYPE, elog, ERROR, find_coercion_pathway(), get_element_type(), getBaseType(), GETSTRUCT, HeapTupleIsValid, InvalidOid, ObjectIdGetDatum, OidIsValid, ReleaseSysCache(), SearchSysCache2(), and TypeCategory().

Referenced by can_coerce_type(), coerce_type(), find_coercion_pathway(), findFkeyCast(), func_get_detail(), json_categorize_type(), jsonb_categorize_type(), and ri_HashCompareOp().

2233 {
2235  HeapTuple tuple;
2236 
2237  *funcid = InvalidOid;
2238 
2239  /* Perhaps the types are domains; if so, look at their base types */
2240  if (OidIsValid(sourceTypeId))
2241  sourceTypeId = getBaseType(sourceTypeId);
2242  if (OidIsValid(targetTypeId))
2243  targetTypeId = getBaseType(targetTypeId);
2244 
2245  /* Domains are always coercible to and from their base type */
2246  if (sourceTypeId == targetTypeId)
2248 
2249  /* Look in pg_cast */
2251  ObjectIdGetDatum(sourceTypeId),
2252  ObjectIdGetDatum(targetTypeId));
2253 
2254  if (HeapTupleIsValid(tuple))
2255  {
2256  Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
2257  CoercionContext castcontext;
2258 
2259  /* convert char value for castcontext to CoercionContext enum */
2260  switch (castForm->castcontext)
2261  {
2262  case COERCION_CODE_IMPLICIT:
2263  castcontext = COERCION_IMPLICIT;
2264  break;
2265  case COERCION_CODE_ASSIGNMENT:
2266  castcontext = COERCION_ASSIGNMENT;
2267  break;
2268  case COERCION_CODE_EXPLICIT:
2269  castcontext = COERCION_EXPLICIT;
2270  break;
2271  default:
2272  elog(ERROR, "unrecognized castcontext: %d",
2273  (int) castForm->castcontext);
2274  castcontext = 0; /* keep compiler quiet */
2275  break;
2276  }
2277 
2278  /* Rely on ordering of enum for correct behavior here */
2279  if (ccontext >= castcontext)
2280  {
2281  switch (castForm->castmethod)
2282  {
2283  case COERCION_METHOD_FUNCTION:
2284  result = COERCION_PATH_FUNC;
2285  *funcid = castForm->castfunc;
2286  break;
2287  case COERCION_METHOD_INOUT:
2288  result = COERCION_PATH_COERCEVIAIO;
2289  break;
2290  case COERCION_METHOD_BINARY:
2291  result = COERCION_PATH_RELABELTYPE;
2292  break;
2293  default:
2294  elog(ERROR, "unrecognized castmethod: %d",
2295  (int) castForm->castmethod);
2296  break;
2297  }
2298  }
2299 
2300  ReleaseSysCache(tuple);
2301  }
2302  else
2303  {
2304  /*
2305  * If there's no pg_cast entry, perhaps we are dealing with a pair of
2306  * array types. If so, and if their element types have a conversion
2307  * pathway, report that we can coerce with an ArrayCoerceExpr.
2308  *
2309  * Hack: disallow coercions to oidvector and int2vector, which
2310  * otherwise tend to capture coercions that should go to "real" array
2311  * types. We want those types to be considered "real" arrays for many
2312  * purposes, but not this one. (Also, ArrayCoerceExpr isn't
2313  * guaranteed to produce an output that meets the restrictions of
2314  * these datatypes, such as being 1-dimensional.)
2315  */
2316  if (targetTypeId != OIDVECTOROID && targetTypeId != INT2VECTOROID)
2317  {
2318  Oid targetElem;
2319  Oid sourceElem;
2320 
2321  if ((targetElem = get_element_type(targetTypeId)) != InvalidOid &&
2322  (sourceElem = get_element_type(sourceTypeId)) != InvalidOid)
2323  {
2324  CoercionPathType elempathtype;
2325  Oid elemfuncid;
2326 
2327  elempathtype = find_coercion_pathway(targetElem,
2328  sourceElem,
2329  ccontext,
2330  &elemfuncid);
2331  if (elempathtype != COERCION_PATH_NONE)
2332  {
2333  result = COERCION_PATH_ARRAYCOERCE;
2334  }
2335  }
2336  }
2337 
2338  /*
2339  * If we still haven't found a possibility, consider automatic casting
2340  * using I/O functions. We allow assignment casts to string types and
2341  * explicit casts from string types to be handled this way. (The
2342  * CoerceViaIO mechanism is a lot more general than that, but this is
2343  * all we want to allow in the absence of a pg_cast entry.) It would
2344  * probably be better to insist on explicit casts in both directions,
2345  * but this is a compromise to preserve something of the pre-8.3
2346  * behavior that many types had implicit (yipes!) casts to text.
2347  */
2348  if (result == COERCION_PATH_NONE)
2349  {
2350  if (ccontext >= COERCION_ASSIGNMENT &&
2351  TypeCategory(targetTypeId) == TYPCATEGORY_STRING)
2352  result = COERCION_PATH_COERCEVIAIO;
2353  else if (ccontext >= COERCION_EXPLICIT &&
2354  TypeCategory(sourceTypeId) == TYPCATEGORY_STRING)
2355  result = COERCION_PATH_COERCEVIAIO;
2356  }
2357  }
2358 
2359  return result;
2360 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Oid get_element_type(Oid typid)
Definition: lsyscache.c:2526
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:645
CoercionContext
Definition: primnodes.h:440
CoercionPathType
Definition: parse_coerce.h:24
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
FormData_pg_cast * Form_pg_cast
Definition: pg_cast.h:56
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define InvalidOid
Definition: postgres_ext.h:36
TYPCATEGORY TypeCategory(Oid type)
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition: syscache.c:1127
CoercionPathType find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId, CoercionContext ccontext, Oid *funcid)
#define elog(elevel,...)
Definition: elog.h:228
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2299

◆ find_typmod_coercion_function()

CoercionPathType find_typmod_coercion_function ( Oid  typeId,
Oid funcid 
)

Definition at line 2385 of file parse_coerce.c.

References CASTSOURCETARGET, COERCION_PATH_ARRAYCOERCE, COERCION_PATH_FUNC, COERCION_PATH_NONE, GETSTRUCT, HeapTupleIsValid, InvalidOid, ObjectIdGetDatum, OidIsValid, ReleaseSysCache(), SearchSysCache2(), and typeidType().

Referenced by coerce_type_typmod().

2387 {
2388  CoercionPathType result;
2389  Type targetType;
2390  Form_pg_type typeForm;
2391  HeapTuple tuple;
2392 
2393  *funcid = InvalidOid;
2394  result = COERCION_PATH_FUNC;
2395 
2396  targetType = typeidType(typeId);
2397  typeForm = (Form_pg_type) GETSTRUCT(targetType);
2398 
2399  /* Check for a varlena array type */
2400  if (typeForm->typelem != InvalidOid && typeForm->typlen == -1)
2401  {
2402  /* Yes, switch our attention to the element type */
2403  typeId = typeForm->typelem;
2404  result = COERCION_PATH_ARRAYCOERCE;
2405  }
2406  ReleaseSysCache(targetType);
2407 
2408  /* Look in pg_cast */
2410  ObjectIdGetDatum(typeId),
2411  ObjectIdGetDatum(typeId));
2412 
2413  if (HeapTupleIsValid(tuple))
2414  {
2415  Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
2416 
2417  *funcid = castForm->castfunc;
2418  ReleaseSysCache(tuple);
2419  }
2420 
2421  if (!OidIsValid(*funcid))
2422  result = COERCION_PATH_NONE;
2423 
2424  return result;
2425 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define OidIsValid(objectId)
Definition: c.h:645
CoercionPathType
Definition: parse_coerce.h:24
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
FormData_pg_cast * Form_pg_cast
Definition: pg_cast.h:56
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
FormData_pg_type * Form_pg_type
Definition: pg_type.h:250
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition: syscache.c:1127
Type typeidType(Oid id)
Definition: parse_type.c:576

◆ hide_coercion_node()

static void hide_coercion_node ( Node node)
static

Definition at line 782 of file parse_coerce.c.

References COERCE_IMPLICIT_CAST, elog, ERROR, IsA, and nodeTag.

Referenced by coerce_to_domain(), and coerce_type_typmod().

783 {
784  if (IsA(node, FuncExpr))
785  ((FuncExpr *) node)->funcformat = COERCE_IMPLICIT_CAST;
786  else if (IsA(node, RelabelType))
787  ((RelabelType *) node)->relabelformat = COERCE_IMPLICIT_CAST;
788  else if (IsA(node, CoerceViaIO))
789  ((CoerceViaIO *) node)->coerceformat = COERCE_IMPLICIT_CAST;
790  else if (IsA(node, ArrayCoerceExpr))
791  ((ArrayCoerceExpr *) node)->coerceformat = COERCE_IMPLICIT_CAST;
792  else if (IsA(node, ConvertRowtypeExpr))
793  ((ConvertRowtypeExpr *) node)->convertformat = COERCE_IMPLICIT_CAST;
794  else if (IsA(node, RowExpr))
795  ((RowExpr *) node)->row_format = COERCE_IMPLICIT_CAST;
796  else if (IsA(node, CoerceToDomain))
797  ((CoerceToDomain *) node)->coercionformat = COERCE_IMPLICIT_CAST;
798  else
799  elog(ERROR, "unsupported node type: %d", (int) nodeTag(node));
800 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
#define ERROR
Definition: elog.h:43
#define nodeTag(nodeptr)
Definition: nodes.h:530
#define elog(elevel,...)
Definition: elog.h:228

◆ is_complex_array()

static bool is_complex_array ( Oid  typid)
static

Definition at line 2435 of file parse_coerce.c.

References get_element_type(), ISCOMPLEX, and OidIsValid.

Referenced by can_coerce_type(), coerce_type(), and IsBinaryCoercible().

2436 {
2437  Oid elemtype = get_element_type(typid);
2438 
2439  return (OidIsValid(elemtype) && ISCOMPLEX(elemtype));
2440 }
Oid get_element_type(Oid typid)
Definition: lsyscache.c:2526
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:645
#define ISCOMPLEX(typeid)
Definition: parse_type.h:58

◆ IsBinaryCoercible()

bool IsBinaryCoercible ( Oid  srctype,
Oid  targettype 
)

Definition at line 2134 of file parse_coerce.c.

References CASTSOURCETARGET, getBaseType(), GETSTRUCT, HeapTupleIsValid, is_complex_array(), ISCOMPLEX, ObjectIdGetDatum, OidIsValid, ReleaseSysCache(), SearchSysCache2(), type_is_array, type_is_enum(), and type_is_range().

Referenced by AggregateCreate(), build_pertrans_for_aggref(), check_amproc_signature(), check_hash_func_signature(), compatible_oper(), CreateCast(), findRangeSubOpclass(), GetDefaultOpClass(), initialize_peragg(), lookup_agg_function(), ResolveOpClass(), ri_HashCompareOp(), satisfies_hash_partition(), ts_stat_sql(), tsvector_update_trigger(), and tupledesc_match().

2135 {
2136  HeapTuple tuple;
2137  Form_pg_cast castForm;
2138  bool result;
2139 
2140  /* Fast path if same type */
2141  if (srctype == targettype)
2142  return true;
2143 
2144  /* Anything is coercible to ANY or ANYELEMENT */
2145  if (targettype == ANYOID || targettype == ANYELEMENTOID)
2146  return true;
2147 
2148  /* If srctype is a domain, reduce to its base type */
2149  if (OidIsValid(srctype))
2150  srctype = getBaseType(srctype);
2151 
2152  /* Somewhat-fast path for domain -> base type case */
2153  if (srctype == targettype)
2154  return true;
2155 
2156  /* Also accept any array type as coercible to ANYARRAY */
2157  if (targettype == ANYARRAYOID)
2158  if (type_is_array(srctype))
2159  return true;
2160 
2161  /* Also accept any non-array type as coercible to ANYNONARRAY */
2162  if (targettype == ANYNONARRAYOID)
2163  if (!type_is_array(srctype))
2164  return true;
2165 
2166  /* Also accept any enum type as coercible to ANYENUM */
2167  if (targettype == ANYENUMOID)
2168  if (type_is_enum(srctype))
2169  return true;
2170 
2171  /* Also accept any range type as coercible to ANYRANGE */
2172  if (targettype == ANYRANGEOID)
2173  if (type_is_range(srctype))
2174  return true;
2175 
2176  /* Also accept any composite type as coercible to RECORD */
2177  if (targettype == RECORDOID)
2178  if (ISCOMPLEX(srctype))
2179  return true;
2180 
2181  /* Also accept any composite array type as coercible to RECORD[] */
2182  if (targettype == RECORDARRAYOID)
2183  if (is_complex_array(srctype))
2184  return true;
2185 
2186  /* Else look in pg_cast */
2188  ObjectIdGetDatum(srctype),
2189  ObjectIdGetDatum(targettype));
2190  if (!HeapTupleIsValid(tuple))
2191  return false; /* no cast */
2192  castForm = (Form_pg_cast) GETSTRUCT(tuple);
2193 
2194  result = (castForm->castmethod == COERCION_METHOD_BINARY &&
2195  castForm->castcontext == COERCION_CODE_IMPLICIT);
2196 
2197  ReleaseSysCache(tuple);
2198 
2199  return result;
2200 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
bool type_is_range(Oid typid)
Definition: lsyscache.c:2466
#define OidIsValid(objectId)
Definition: c.h:645
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
FormData_pg_cast * Form_pg_cast
Definition: pg_cast.h:56
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define ISCOMPLEX(typeid)
Definition: parse_type.h:58
bool type_is_enum(Oid typid)
Definition: lsyscache.c:2456
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition: syscache.c:1127
#define type_is_array(typid)
Definition: lsyscache.h:184
static bool is_complex_array(Oid typid)
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2299

◆ IsPreferredType()

bool IsPreferredType ( TYPCATEGORY  category,
Oid  type 
)

Definition at line 2099 of file parse_coerce.c.

References get_type_category_preferred().

Referenced by func_select_candidate(), and GetDefaultOpClass().

2100 {
2101  char typcategory;
2102  bool typispreferred;
2103 
2104  get_type_category_preferred(type, &typcategory, &typispreferred);
2105  if (category == typcategory || category == TYPCATEGORY_INVALID)
2106  return typispreferred;
2107  else
2108  return false;
2109 }
void get_type_category_preferred(Oid typid, char *typcategory, bool *typispreferred)
Definition: lsyscache.c:2478

◆ parser_coercion_errposition()

int parser_coercion_errposition ( ParseState pstate,
int  coerce_location,
Node input_expr 
)

Definition at line 1248 of file parse_coerce.c.

References exprLocation(), and parser_errposition().

Referenced by coerce_record_to_complex(), and transformTypeCast().

1251 {
1252  if (coerce_location >= 0)
1253  return parser_errposition(pstate, coerce_location);
1254  else
1255  return parser_errposition(pstate, exprLocation(input_expr));
1256 }
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1191
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110

◆ resolve_generic_type()

Oid resolve_generic_type ( Oid  declared_type,
Oid  context_actual_type,
Oid  context_declared_type 
)

Definition at line 1985 of file parse_coerce.c.

References elog, ereport, errcode(), errmsg(), ERROR, format_type_be(), get_array_type(), get_element_type(), get_range_subtype(), getBaseType(), InvalidOid, and OidIsValid.

Referenced by resolve_polymorphic_argtypes(), and resolve_polymorphic_tupdesc().

1988 {
1989  if (declared_type == ANYARRAYOID)
1990  {
1991  if (context_declared_type == ANYARRAYOID)
1992  {
1993  /*
1994  * Use actual type, but it must be an array; or if it's a domain
1995  * over array, use the base array type.
1996  */
1997  Oid context_base_type = getBaseType(context_actual_type);
1998  Oid array_typelem = get_element_type(context_base_type);
1999 
2000  if (!OidIsValid(array_typelem))
2001  ereport(ERROR,
2002  (errcode(ERRCODE_DATATYPE_MISMATCH),
2003  errmsg("argument declared %s is not an array but type %s",
2004  "anyarray", format_type_be(context_base_type))));
2005  return context_base_type;
2006  }
2007  else if (context_declared_type == ANYELEMENTOID ||
2008  context_declared_type == ANYNONARRAYOID ||
2009  context_declared_type == ANYENUMOID ||
2010  context_declared_type == ANYRANGEOID)
2011  {
2012  /* Use the array type corresponding to actual type */
2013  Oid array_typeid = get_array_type(context_actual_type);
2014 
2015  if (!OidIsValid(array_typeid))
2016  ereport(ERROR,
2017  (errcode(ERRCODE_UNDEFINED_OBJECT),
2018  errmsg("could not find array type for data type %s",
2019  format_type_be(context_actual_type))));
2020  return array_typeid;
2021  }
2022  }
2023  else if (declared_type == ANYELEMENTOID ||
2024  declared_type == ANYNONARRAYOID ||
2025  declared_type == ANYENUMOID ||
2026  declared_type == ANYRANGEOID)
2027  {
2028  if (context_declared_type == ANYARRAYOID)
2029  {
2030  /* Use the element type corresponding to actual type */
2031  Oid context_base_type = getBaseType(context_actual_type);
2032  Oid array_typelem = get_element_type(context_base_type);
2033 
2034  if (!OidIsValid(array_typelem))
2035  ereport(ERROR,
2036  (errcode(ERRCODE_DATATYPE_MISMATCH),
2037  errmsg("argument declared %s is not an array but type %s",
2038  "anyarray", format_type_be(context_base_type))));
2039  return array_typelem;
2040  }
2041  else if (context_declared_type == ANYRANGEOID)
2042  {
2043  /* Use the element type corresponding to actual type */
2044  Oid context_base_type = getBaseType(context_actual_type);
2045  Oid range_typelem = get_range_subtype(context_base_type);
2046 
2047  if (!OidIsValid(range_typelem))
2048  ereport(ERROR,
2049  (errcode(ERRCODE_DATATYPE_MISMATCH),
2050  errmsg("argument declared %s is not a range type but type %s",
2051  "anyrange", format_type_be(context_base_type))));
2052  return range_typelem;
2053  }
2054  else if (context_declared_type == ANYELEMENTOID ||
2055  context_declared_type == ANYNONARRAYOID ||
2056  context_declared_type == ANYENUMOID)
2057  {
2058  /* Use the actual type; it doesn't matter if array or not */
2059  return context_actual_type;
2060  }
2061  }
2062  else
2063  {
2064  /* declared_type isn't polymorphic, so return it as-is */
2065  return declared_type;
2066  }
2067  /* If we get here, declared_type is polymorphic and context isn't */
2068  /* NB: this is a calling-code logic error, not a user error */
2069  elog(ERROR, "could not determine polymorphic type because context isn't polymorphic");
2070  return InvalidOid; /* keep compiler quiet */
2071 }
Oid get_element_type(Oid typid)
Definition: lsyscache.c:2526
Oid get_array_type(Oid typid)
Definition: lsyscache.c:2554
int errcode(int sqlerrcode)
Definition: elog.c:608
char * format_type_be(Oid type_oid)
Definition: format_type.c:326
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:645
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:141
#define InvalidOid
Definition: postgres_ext.h:36
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define elog(elevel,...)
Definition: elog.h:228
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2299
Oid get_range_subtype(Oid rangeOid)
Definition: lsyscache.c:3135

◆ select_common_type()

Oid select_common_type ( ParseState pstate,
List exprs,
const char *  context,
Node **  which_expr 
)

Definition at line 1274 of file parse_coerce.c.

References Assert, can_coerce_type(), COERCION_IMPLICIT, ereport, errcode(), errmsg(), ERROR, exprLocation(), exprType(), for_each_cell, format_type_be(), get_type_category_preferred(), getBaseType(), InvalidOid, lfirst, linitial, list_second_cell(), NIL, and parser_errposition().

Referenced by buildMergedJoinVar(), transformAExprIn(), transformArrayExpr(), transformCaseExpr(), transformCoalesceExpr(), transformMinMaxExpr(), transformSetOperationTree(), transformValuesClause(), and unify_hypothetical_args().

1276 {
1277  Node *pexpr;
1278  Oid ptype;
1279  TYPCATEGORY pcategory;
1280  bool pispreferred;
1281  ListCell *lc;
1282 
1283  Assert(exprs != NIL);
1284  pexpr = (Node *) linitial(exprs);
1285  lc = list_second_cell(exprs);
1286  ptype = exprType(pexpr);
1287 
1288  /*
1289  * If all input types are valid and exactly the same, just pick that type.
1290  * This is the only way that we will resolve the result as being a domain
1291  * type; otherwise domains are smashed to their base types for comparison.
1292  */
1293  if (ptype != UNKNOWNOID)
1294  {
1295  for_each_cell(lc, exprs, lc)
1296  {
1297  Node *nexpr = (Node *) lfirst(lc);
1298  Oid ntype = exprType(nexpr);
1299 
1300  if (ntype != ptype)
1301  break;
1302  }
1303  if (lc == NULL) /* got to the end of the list? */
1304  {
1305  if (which_expr)
1306  *which_expr = pexpr;
1307  return ptype;
1308  }
1309  }
1310 
1311  /*
1312  * Nope, so set up for the full algorithm. Note that at this point, lc
1313  * points to the first list item with type different from pexpr's; we need
1314  * not re-examine any items the previous loop advanced over.
1315  */
1316  ptype = getBaseType(ptype);
1317  get_type_category_preferred(ptype, &pcategory, &pispreferred);
1318 
1319  for_each_cell(lc, exprs, lc)
1320  {
1321  Node *nexpr = (Node *) lfirst(lc);
1322  Oid ntype = getBaseType(exprType(nexpr));
1323 
1324  /* move on to next one if no new information... */
1325  if (ntype != UNKNOWNOID && ntype != ptype)
1326  {
1327  TYPCATEGORY ncategory;
1328  bool nispreferred;
1329 
1330  get_type_category_preferred(ntype, &ncategory, &nispreferred);
1331  if (ptype == UNKNOWNOID)
1332  {
1333  /* so far, only unknowns so take anything... */
1334  pexpr = nexpr;
1335  ptype = ntype;
1336  pcategory = ncategory;
1337  pispreferred = nispreferred;
1338  }
1339  else if (ncategory != pcategory)
1340  {
1341  /*
1342  * both types in different categories? then not much hope...
1343  */
1344  if (context == NULL)
1345  return InvalidOid;
1346  ereport(ERROR,
1347  (errcode(ERRCODE_DATATYPE_MISMATCH),
1348  /*------
1349  translator: first %s is name of a SQL construct, eg CASE */
1350  errmsg("%s types %s and %s cannot be matched",
1351  context,
1352  format_type_be(ptype),
1353  format_type_be(ntype)),
1354  parser_errposition(pstate, exprLocation(nexpr))));
1355  }
1356  else if (!pispreferred &&
1357  can_coerce_type(1, &ptype, &ntype, COERCION_IMPLICIT) &&
1358  !can_coerce_type(1, &ntype, &ptype, COERCION_IMPLICIT))
1359  {
1360  /*
1361  * take new type if can coerce to it implicitly but not the
1362  * other way; but if we have a preferred type, stay on it.
1363  */
1364  pexpr = nexpr;
1365  ptype = ntype;
1366  pcategory = ncategory;
1367  pispreferred = nispreferred;
1368  }
1369  }
1370  }
1371 
1372  /*
1373  * If all the inputs were UNKNOWN type --- ie, unknown-type literals ---
1374  * then resolve as type TEXT. This situation comes up with constructs
1375  * like SELECT (CASE WHEN foo THEN 'bar' ELSE 'baz' END); SELECT 'foo'
1376  * UNION SELECT 'bar'; It might seem desirable to leave the construct's
1377  * output type as UNKNOWN, but that really doesn't work, because we'd
1378  * probably end up needing a runtime coercion from UNKNOWN to something
1379  * else, and we usually won't have it. We need to coerce the unknown
1380  * literals while they are still literals, so a decision has to be made
1381  * now.
1382  */
1383  if (ptype == UNKNOWNOID)
1384  ptype = TEXTOID;
1385 
1386  if (which_expr)
1387  *which_expr = pexpr;
1388  return ptype;
1389 }
#define NIL
Definition: pg_list.h:65
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1191
#define for_each_cell(cell, lst, initcell)
Definition: pg_list.h:390
bool can_coerce_type(int nargs, const Oid *input_typeids, const Oid *target_typeids, CoercionContext ccontext)
Definition: parse_coerce.c:543
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:608
char * format_type_be(Oid type_oid)
Definition: format_type.c:326
unsigned int Oid
Definition: postgres_ext.h:31
char TYPCATEGORY
Definition: parse_coerce.h:21
#define linitial(l)
Definition: pg_list.h:195
#define ERROR
Definition: elog.h:43
static ListCell * list_second_cell(const List *l)
Definition: pg_list.h:139
#define ereport(elevel, rest)
Definition: elog.h:141
#define InvalidOid
Definition: postgres_ext.h:36
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
int errmsg(const char *fmt,...)
Definition: elog.c:822
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2299
void get_type_category_preferred(Oid typid, char *typcategory, bool *typispreferred)
Definition: lsyscache.c:2478

◆ TypeCategory()

TYPCATEGORY TypeCategory ( Oid  type)

Definition at line 2080 of file parse_coerce.c.

References Assert, and get_type_category_preferred().

Referenced by find_coercion_pathway(), func_get_detail(), func_select_candidate(), and GetDefaultOpClass().

2081 {
2082  char typcategory;
2083  bool typispreferred;
2084 
2085  get_type_category_preferred(type, &typcategory, &typispreferred);
2086  Assert(typcategory != TYPCATEGORY_INVALID);
2087  return (TYPCATEGORY) typcategory;
2088 }
char TYPCATEGORY
Definition: parse_coerce.h:21
#define Assert(condition)
Definition: c.h:739
void get_type_category_preferred(Oid typid, char *typcategory, bool *typispreferred)
Definition: lsyscache.c:2478

◆ typeIsOfTypedTable()

static bool typeIsOfTypedTable ( Oid  reltypeId,
Oid  reloftypeId 
)
static

Definition at line 2449 of file parse_coerce.c.

References elog, ERROR, GETSTRUCT, HeapTupleIsValid, ObjectIdGetDatum, ReleaseSysCache(), RELOID, SearchSysCache1(), and typeOrDomainTypeRelid().

Referenced by can_coerce_type(), and coerce_type().

2450 {
2451  Oid relid = typeOrDomainTypeRelid(reltypeId);
2452  bool result = false;
2453 
2454  if (relid)
2455  {
2456  HeapTuple tp;
2457  Form_pg_class reltup;
2458 
2459  tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
2460  if (!HeapTupleIsValid(tp))
2461  elog(ERROR, "cache lookup failed for relation %u", relid);
2462 
2463  reltup = (Form_pg_class) GETSTRUCT(tp);
2464  if (reltup->reloftype == reloftypeId)
2465  result = true;
2466 
2467  ReleaseSysCache(tp);
2468  }
2469 
2470  return result;
2471 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Oid typeOrDomainTypeRelid(Oid type_id)
Definition: parse_type.c:687
unsigned int Oid
Definition: postgres_ext.h:31
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
FormData_pg_class * Form_pg_class
Definition: pg_class.h:150
#define elog(elevel,...)
Definition: elog.h:228