use super::{CharLength, IntervalTypmod, NumericTypmod};
use core::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TypeCollation {
Default,
C,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct BitLength(u32);
impl BitLength {
#[must_use]
pub const fn new(length: u32) -> Option<Self> {
if length >= 1 && length <= 83_886_080 {
Some(Self(length))
} else {
None
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct TimePrecision(u8);
impl TimePrecision {
#[must_use]
pub const fn new(precision: u8) -> Self {
Self(if precision > 6 { 6 } else { precision })
}
#[must_use]
pub const fn get(self) -> u8 {
self.0
}
}
impl fmt::Display for TimePrecision {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(formatter)
}
}
macro_rules! builtin_types {
(
plain { $( $plain:ident = $plain_oid:literal, $plain_name:literal, $plain_spelling:literal, $plain_diagnostic:literal; )* }
modified { $( $modified:ident = $modified_oid:literal, $modified_name:literal, $modified_spelling:literal, $modified_diagnostic:literal, $modifier:ty, $default:expr; )* }
) => {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BuiltinType {
$( #[doc = concat!("`", $plain_name, "`.")] $plain, )*
$( #[doc = concat!("`", $modified_name, "` with its modifier.")] $modified($modifier), )*
}
impl BuiltinType {
pub const ALL: &'static [Self] = &[$(Self::$plain,)* $(Self::$modified($default),)*];
#[must_use]
pub const fn oid(self) -> u32 {
match self { $(Self::$plain => $plain_oid,)* $(Self::$modified(_) => $modified_oid,)* }
}
#[must_use]
pub const fn from_oid(oid: u32) -> Option<Self> {
match oid { $($plain_oid => Some(Self::$plain),)* $($modified_oid => Some(Self::$modified($default)),)* _ => None }
}
#[must_use]
pub const fn catalog_name(self) -> &'static str {
match self { $(Self::$plain => $plain_name,)* $(Self::$modified(_) => $modified_name,)* }
}
#[must_use]
pub fn from_catalog_name(name: &str) -> Option<Self> {
match name { $($plain_name => Some(Self::$plain),)* $($modified_name => Some(Self::$modified($default)),)* _ => None }
}
#[must_use]
pub const fn diagnostic_name(self) -> &'static str {
match self { $(Self::$plain => $plain_diagnostic,)* $(Self::$modified(_) => $modified_diagnostic,)* }
}
const fn unmodified_name(self) -> &'static str {
match self { $(Self::$plain => $plain_spelling,)* $(Self::$modified(_) => $modified_spelling,)* }
}
#[must_use]
pub const fn pg_type(self) -> Self {
match self { $(Self::$modified(_) => Self::$modified($default),)* other => other }
}
}
}
}
builtin_types! {
plain {
Boolean = 16, "bool", "boolean", "boolean";
Bytea = 17, "bytea", "bytea", "bytea";
InternalChar = 18, "char", "\"char\"", "\"char\"";
Name = 19, "name", "name", "name";
Bigint = 20, "int8", "bigint", "bigint";
Smallint = 21, "int2", "smallint", "smallint";
Int2Vector = 22, "int2vector", "int2vector", "int2vector";
Integer = 23, "int4", "integer", "integer";
Regproc = 24, "regproc", "regproc", "regproc";
Text = 25, "text", "text", "text";
Oid = 26, "oid", "oid", "oid";
Tid = 27, "tid", "tid", "tid";
Xid = 28, "xid", "xid", "xid";
Cid = 29, "cid", "cid", "cid";
Oidvector = 30, "oidvector", "oidvector", "oidvector";
PgDdlCommand = 32, "pg_ddl_command", "pg_ddl_command", "pg_ddl_command";
PgType = 71, "pg_type", "pg_type", "pg_type";
PgAttribute = 75, "pg_attribute", "pg_attribute", "pg_attribute";
PgProc = 81, "pg_proc", "pg_proc", "pg_proc";
PgClass = 83, "pg_class", "pg_class", "pg_class";
Json = 114, "json", "json", "json";
Xml = 142, "xml", "xml", "xml";
XmlArray = 143, "_xml", "xml[]", "xml[]";
PgNodeTree = 194, "pg_node_tree", "pg_node_tree", "pg_node_tree";
JsonArray = 199, "_json", "json[]", "json[]";
PgTypeArray = 210, "_pg_type", "pg_type[]", "pg_type[]";
TableAmHandler = 269, "table_am_handler", "table_am_handler", "table_am_handler";
PgAttributeArray = 270, "_pg_attribute", "pg_attribute[]", "pg_attribute[]";
Xid8Array = 271, "_xid8", "xid8[]", "xid8[]";
PgProcArray = 272, "_pg_proc", "pg_proc[]", "pg_proc[]";
PgClassArray = 273, "_pg_class", "pg_class[]", "pg_class[]";
IndexAmHandler = 325, "index_am_handler", "index_am_handler", "index_am_handler";
Point = 600, "point", "point", "point";
Lseg = 601, "lseg", "lseg", "lseg";
Path = 602, "path", "path", "path";
Box = 603, "box", "box", "box";
Polygon = 604, "polygon", "polygon", "polygon";
Line = 628, "line", "line", "line";
LineArray = 629, "_line", "line[]", "line[]";
Cidr = 650, "cidr", "cidr", "cidr";
CidrArray = 651, "_cidr", "cidr[]", "cidr[]";
Real = 700, "float4", "real", "real";
DoublePrecision = 701, "float8", "double precision", "double precision";
Unknown = 705, "unknown", "unknown", "unknown";
Circle = 718, "circle", "circle", "circle";
CircleArray = 719, "_circle", "circle[]", "circle[]";
Macaddr8 = 774, "macaddr8", "macaddr8", "macaddr8";
Macaddr8Array = 775, "_macaddr8", "macaddr8[]", "macaddr8[]";
Money = 790, "money", "money", "money";
MoneyArray = 791, "_money", "money[]", "money[]";
Macaddr = 829, "macaddr", "macaddr", "macaddr";
Inet = 869, "inet", "inet", "inet";
BooleanArray = 1000, "_bool", "boolean[]", "boolean[]";
ByteaArray = 1001, "_bytea", "bytea[]", "bytea[]";
InternalCharArray = 1002, "_char", "\"char\"[]", "\"char\"[]";
NameArray = 1003, "_name", "name[]", "name[]";
SmallintArray = 1005, "_int2", "smallint[]", "smallint[]";
Int2VectorArray = 1006, "_int2vector", "int2vector[]", "int2vector[]";
IntegerArray = 1007, "_int4", "integer[]", "integer[]";
RegprocArray = 1008, "_regproc", "regproc[]", "regproc[]";
TextArray = 1009, "_text", "text[]", "text[]";
TidArray = 1010, "_tid", "tid[]", "tid[]";
XidArray = 1011, "_xid", "xid[]", "xid[]";
CidArray = 1012, "_cid", "cid[]", "cid[]";
OidvectorArray = 1013, "_oidvector", "oidvector[]", "oidvector[]";
BigintArray = 1016, "_int8", "bigint[]", "bigint[]";
PointArray = 1017, "_point", "point[]", "point[]";
LsegArray = 1018, "_lseg", "lseg[]", "lseg[]";
PathArray = 1019, "_path", "path[]", "path[]";
BoxArray = 1020, "_box", "box[]", "box[]";
RealArray = 1021, "_float4", "real[]", "real[]";
DoublePrecisionArray = 1022, "_float8", "double precision[]", "double precision[]";
PolygonArray = 1027, "_polygon", "polygon[]", "polygon[]";
OidArray = 1028, "_oid", "oid[]", "oid[]";
Aclitem = 1033, "aclitem", "aclitem", "aclitem";
AclitemArray = 1034, "_aclitem", "aclitem[]", "aclitem[]";
MacaddrArray = 1040, "_macaddr", "macaddr[]", "macaddr[]";
InetArray = 1041, "_inet", "inet[]", "inet[]";
Date = 1082, "date", "date", "date";
DateArray = 1182, "_date", "date[]", "date[]";
PgDatabase = 1248, "pg_database", "pg_database", "pg_database";
CstringArray = 1263, "_cstring", "cstring[]", "cstring[]";
Refcursor = 1790, "refcursor", "refcursor", "refcursor";
RefcursorArray = 2201, "_refcursor", "refcursor[]", "refcursor[]";
Regprocedure = 2202, "regprocedure", "regprocedure", "regprocedure";
Regoper = 2203, "regoper", "regoper", "regoper";
Regoperator = 2204, "regoperator", "regoperator", "regoperator";
Regclass = 2205, "regclass", "regclass", "regclass";
Regtype = 2206, "regtype", "regtype", "regtype";
RegprocedureArray = 2207, "_regprocedure", "regprocedure[]", "regprocedure[]";
RegoperArray = 2208, "_regoper", "regoper[]", "regoper[]";
RegoperatorArray = 2209, "_regoperator", "regoperator[]", "regoperator[]";
RegclassArray = 2210, "_regclass", "regclass[]", "regclass[]";
RegtypeArray = 2211, "_regtype", "regtype[]", "regtype[]";
Record = 2249, "record", "record", "record";
Cstring = 2275, "cstring", "cstring", "cstring";
Any = 2276, "any", "\"any\"", "\"any\"";
Anyarray = 2277, "anyarray", "anyarray", "anyarray";
Void = 2278, "void", "void", "void";
Trigger = 2279, "trigger", "trigger", "trigger";
LanguageHandler = 2280, "language_handler", "language_handler", "language_handler";
Internal = 2281, "internal", "internal", "internal";
Anyelement = 2283, "anyelement", "anyelement", "anyelement";
RecordArray = 2287, "_record", "record[]", "record[]";
Anynonarray = 2776, "anynonarray", "anynonarray", "anynonarray";
PgAuthid = 2842, "pg_authid", "pg_authid", "pg_authid";
PgAuthMembers = 2843, "pg_auth_members", "pg_auth_members", "pg_auth_members";
TxidSnapshotArray = 2949, "_txid_snapshot", "txid_snapshot[]", "txid_snapshot[]";
Uuid = 2950, "uuid", "uuid", "uuid";
UuidArray = 2951, "_uuid", "uuid[]", "uuid[]";
TxidSnapshot = 2970, "txid_snapshot", "txid_snapshot", "txid_snapshot";
FdwHandler = 3115, "fdw_handler", "fdw_handler", "fdw_handler";
PgLsn = 3220, "pg_lsn", "pg_lsn", "pg_lsn";
PgLsnArray = 3221, "_pg_lsn", "pg_lsn[]", "pg_lsn[]";
TsmHandler = 3310, "tsm_handler", "tsm_handler", "tsm_handler";
PgNdistinct = 3361, "pg_ndistinct", "pg_ndistinct", "pg_ndistinct";
PgDependencies = 3402, "pg_dependencies", "pg_dependencies", "pg_dependencies";
Anyenum = 3500, "anyenum", "anyenum", "anyenum";
Tsvector = 3614, "tsvector", "tsvector", "tsvector";
Tsquery = 3615, "tsquery", "tsquery", "tsquery";
Gtsvector = 3642, "gtsvector", "gtsvector", "gtsvector";
TsvectorArray = 3643, "_tsvector", "tsvector[]", "tsvector[]";
GtsvectorArray = 3644, "_gtsvector", "gtsvector[]", "gtsvector[]";
TsqueryArray = 3645, "_tsquery", "tsquery[]", "tsquery[]";
Regconfig = 3734, "regconfig", "regconfig", "regconfig";
RegconfigArray = 3735, "_regconfig", "regconfig[]", "regconfig[]";
Regdictionary = 3769, "regdictionary", "regdictionary", "regdictionary";
RegdictionaryArray = 3770, "_regdictionary", "regdictionary[]", "regdictionary[]";
Jsonb = 3802, "jsonb", "jsonb", "jsonb";
JsonbArray = 3807, "_jsonb", "jsonb[]", "jsonb[]";
Anyrange = 3831, "anyrange", "anyrange", "anyrange";
EventTrigger = 3838, "event_trigger", "event_trigger", "event_trigger";
Int4Range = 3904, "int4range", "int4range", "int4range";
Int4RangeArray = 3905, "_int4range", "int4range[]", "int4range[]";
Numrange = 3906, "numrange", "numrange", "numrange";
NumrangeArray = 3907, "_numrange", "numrange[]", "numrange[]";
Tsrange = 3908, "tsrange", "tsrange", "tsrange";
TsrangeArray = 3909, "_tsrange", "tsrange[]", "tsrange[]";
Tstzrange = 3910, "tstzrange", "tstzrange", "tstzrange";
TstzrangeArray = 3911, "_tstzrange", "tstzrange[]", "tstzrange[]";
Daterange = 3912, "daterange", "daterange", "daterange";
DaterangeArray = 3913, "_daterange", "daterange[]", "daterange[]";
Int8Range = 3926, "int8range", "int8range", "int8range";
Int8RangeArray = 3927, "_int8range", "int8range[]", "int8range[]";
PgShseclabel = 4066, "pg_shseclabel", "pg_shseclabel", "pg_shseclabel";
Jsonpath = 4072, "jsonpath", "jsonpath", "jsonpath";
JsonpathArray = 4073, "_jsonpath", "jsonpath[]", "jsonpath[]";
Regnamespace = 4089, "regnamespace", "regnamespace", "regnamespace";
RegnamespaceArray = 4090, "_regnamespace", "regnamespace[]", "regnamespace[]";
Regrole = 4096, "regrole", "regrole", "regrole";
RegroleArray = 4097, "_regrole", "regrole[]", "regrole[]";
Regcollation = 4191, "regcollation", "regcollation", "regcollation";
RegcollationArray = 4192, "_regcollation", "regcollation[]", "regcollation[]";
Int4Multirange = 4451, "int4multirange", "int4multirange", "int4multirange";
Nummultirange = 4532, "nummultirange", "nummultirange", "nummultirange";
Tsmultirange = 4533, "tsmultirange", "tsmultirange", "tsmultirange";
Tstzmultirange = 4534, "tstzmultirange", "tstzmultirange", "tstzmultirange";
Datemultirange = 4535, "datemultirange", "datemultirange", "datemultirange";
Int8Multirange = 4536, "int8multirange", "int8multirange", "int8multirange";
Anymultirange = 4537, "anymultirange", "anymultirange", "anymultirange";
Anycompatiblemultirange = 4538, "anycompatiblemultirange", "anycompatiblemultirange", "anycompatiblemultirange";
PgBrinBloomSummary = 4600, "pg_brin_bloom_summary", "pg_brin_bloom_summary", "pg_brin_bloom_summary";
PgBrinMinmaxMultiSummary = 4601, "pg_brin_minmax_multi_summary", "pg_brin_minmax_multi_summary", "pg_brin_minmax_multi_summary";
PgMcvList = 5017, "pg_mcv_list", "pg_mcv_list", "pg_mcv_list";
PgSnapshot = 5038, "pg_snapshot", "pg_snapshot", "pg_snapshot";
PgSnapshotArray = 5039, "_pg_snapshot", "pg_snapshot[]", "pg_snapshot[]";
Xid8 = 5069, "xid8", "xid8", "xid8";
Anycompatible = 5077, "anycompatible", "anycompatible", "anycompatible";
Anycompatiblearray = 5078, "anycompatiblearray", "anycompatiblearray", "anycompatiblearray";
Anycompatiblenonarray = 5079, "anycompatiblenonarray", "anycompatiblenonarray", "anycompatiblenonarray";
Anycompatiblerange = 5080, "anycompatiblerange", "anycompatiblerange", "anycompatiblerange";
PgSubscription = 6101, "pg_subscription", "pg_subscription", "pg_subscription";
Int4MultirangeArray = 6150, "_int4multirange", "int4multirange[]", "int4multirange[]";
NummultirangeArray = 6151, "_nummultirange", "nummultirange[]", "nummultirange[]";
TsmultirangeArray = 6152, "_tsmultirange", "tsmultirange[]", "tsmultirange[]";
TstzmultirangeArray = 6153, "_tstzmultirange", "tstzmultirange[]", "tstzmultirange[]";
DatemultirangeArray = 6155, "_datemultirange", "datemultirange[]", "datemultirange[]";
Int8MultirangeArray = 6157, "_int8multirange", "int8multirange[]", "int8multirange[]";
}
modified {
BpcharArray = 1014, "_bpchar", "bpchar[]", "character[]", Option<CharLength>, None;
VarcharArray = 1015, "_varchar", "character varying[]", "character varying[]", Option<CharLength>, None;
Bpchar = 1042, "bpchar", "bpchar", "character", Option<CharLength>, None;
Varchar = 1043, "varchar", "character varying", "character varying", Option<CharLength>, None;
Time = 1083, "time", "time without time zone", "time without time zone", Option<TimePrecision>, None;
Timestamp = 1114, "timestamp", "timestamp without time zone", "timestamp without time zone", Option<TimePrecision>, None;
TimestampArray = 1115, "_timestamp", "timestamp without time zone[]", "timestamp without time zone[]", Option<TimePrecision>, None;
TimeArray = 1183, "_time", "time without time zone[]", "time without time zone[]", Option<TimePrecision>, None;
TimestampTz = 1184, "timestamptz", "timestamp with time zone", "timestamp with time zone", Option<TimePrecision>, None;
TimestampTzArray = 1185, "_timestamptz", "timestamp with time zone[]", "timestamp with time zone[]", Option<TimePrecision>, None;
Interval = 1186, "interval", "interval", "interval", IntervalTypmod, IntervalTypmod::UNMODIFIED;
IntervalArray = 1187, "_interval", "interval[]", "interval[]", IntervalTypmod, IntervalTypmod::UNMODIFIED;
NumericArray = 1231, "_numeric", "numeric[]", "numeric[]", Option<NumericTypmod>, None;
TimeTz = 1266, "timetz", "time with time zone", "time with time zone", Option<TimePrecision>, None;
TimeTzArray = 1270, "_timetz", "time with time zone[]", "time with time zone[]", Option<TimePrecision>, None;
Bit = 1560, "bit", "\"bit\"", "bit", Option<BitLength>, None;
BitArray = 1561, "_bit", "\"bit\"[]", "bit[]", Option<BitLength>, None;
Varbit = 1562, "varbit", "bit varying", "bit varying", Option<BitLength>, None;
VarbitArray = 1563, "_varbit", "bit varying[]", "bit varying[]", Option<BitLength>, None;
Numeric = 1700, "numeric", "numeric", "numeric", Option<NumericTypmod>, None;
}
}
impl BuiltinType {
#[must_use]
pub const fn collation(self) -> Option<TypeCollation> {
match self {
Self::Name | Self::NameArray => Some(TypeCollation::C),
Self::Text
| Self::TextArray
| Self::PgNodeTree
| Self::Bpchar(_)
| Self::BpcharArray(_)
| Self::Varchar(_)
| Self::VarcharArray(_)
| Self::PgNdistinct
| Self::PgDependencies
| Self::PgBrinBloomSummary
| Self::PgBrinMinmaxMultiSummary
| Self::PgMcvList => Some(TypeCollation::Default),
_ => None,
}
}
pub(crate) const fn input_name(self) -> &'static str {
match self {
Self::Timestamp(_) => "timestamp",
Self::Time(_) => "time",
other => other.diagnostic_name(),
}
}
pub(crate) const fn supports_cast(self) -> bool {
matches!(
self,
Self::Boolean
| Self::Smallint
| Self::Integer
| Self::Bigint
| Self::Numeric(_)
| Self::Text
| Self::Varchar(_)
| Self::Bpchar(_)
| Self::Date
| Self::Timestamp(_)
| Self::TimestampTz(_)
| Self::Time(_)
| Self::TimeTz(_)
| Self::Jsonb
| Self::Uuid
| Self::Interval(_)
)
}
}
impl fmt::Display for BuiltinType {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Self::Numeric(Some(modifier)) | Self::NumericArray(Some(modifier)) => {
write!(
formatter,
"numeric({},{})",
modifier.precision(),
modifier.scale()
)?;
}
Self::Varchar(Some(length)) | Self::VarcharArray(Some(length)) => {
write!(formatter, "character varying({})", length.get())?;
}
Self::Bpchar(Some(length)) | Self::BpcharArray(Some(length)) => {
write!(formatter, "character({})", length.get())?;
}
Self::Bit(Some(length)) | Self::BitArray(Some(length)) => {
write!(formatter, "bit({})", length.0)?;
}
Self::Varbit(Some(length)) | Self::VarbitArray(Some(length)) => {
write!(formatter, "bit varying({})", length.0)?;
}
Self::Time(Some(precision)) | Self::TimeArray(Some(precision)) => {
write!(formatter, "time({}) without time zone", precision.get())?;
}
Self::TimeTz(Some(precision)) | Self::TimeTzArray(Some(precision)) => {
write!(formatter, "time({}) with time zone", precision.get())?;
}
Self::Timestamp(Some(precision)) | Self::TimestampArray(Some(precision)) => {
write!(
formatter,
"timestamp({}) without time zone",
precision.get()
)?;
}
Self::TimestampTz(Some(precision)) | Self::TimestampTzArray(Some(precision)) => {
write!(formatter, "timestamp({}) with time zone", precision.get())?;
}
Self::Interval(modifier) | Self::IntervalArray(modifier) => {
write!(formatter, "interval{modifier}")?;
}
_ => return formatter.write_str(self.unmodified_name()),
}
if self.catalog_name().starts_with('_') {
formatter.write_str("[]")?;
}
Ok(())
}
}
impl BuiltinType {
#[must_use]
pub fn typmod(self) -> i32 {
match self {
Self::Numeric(Some(modifier)) | Self::NumericArray(Some(modifier)) => {
(i32::from(modifier.precision()) << 16) + (i32::from(modifier.scale()) & 0x7ff) + 4
}
Self::Varchar(Some(length))
| Self::VarcharArray(Some(length))
| Self::Bpchar(Some(length))
| Self::BpcharArray(Some(length)) => {
debug_assert!(length.get() <= 10_485_760);
length.get() as i32 + 4
}
Self::Bit(Some(length))
| Self::BitArray(Some(length))
| Self::Varbit(Some(length))
| Self::VarbitArray(Some(length)) => {
debug_assert!(length.0 <= 83_886_080);
length.0 as i32
}
Self::Time(Some(precision))
| Self::TimeArray(Some(precision))
| Self::TimeTz(Some(precision))
| Self::TimeTzArray(Some(precision))
| Self::Timestamp(Some(precision))
| Self::TimestampArray(Some(precision))
| Self::TimestampTz(Some(precision))
| Self::TimestampTzArray(Some(precision)) => i32::from(precision.get()),
Self::Interval(modifier) | Self::IntervalArray(modifier) => modifier.catalog_typmod(),
_ => -1,
}
}
#[must_use]
pub fn with_typmod(self, typmod: i32) -> Option<Self> {
if typmod == -1 {
return Some(self.pg_type());
}
let modified = match self {
Self::Numeric(_) | Self::NumericArray(_) => {
let packed = typmod.checked_sub(4)?;
let precision = u16::try_from(packed >> 16).ok()?;
let scale = i16::try_from(((packed & 0x7ff) ^ 0x400) - 0x400).ok()?;
let modifier = Some(NumericTypmod::new(precision, scale)?);
match self {
Self::Numeric(_) => Self::Numeric(modifier),
_ => Self::NumericArray(modifier),
}
}
Self::Varchar(_) | Self::VarcharArray(_) | Self::Bpchar(_) | Self::BpcharArray(_) => {
let length = Some(CharLength::new(
usize::try_from(typmod.checked_sub(4)?).ok()?,
)?);
match self {
Self::Varchar(_) => Self::Varchar(length),
Self::VarcharArray(_) => Self::VarcharArray(length),
Self::Bpchar(_) => Self::Bpchar(length),
_ => Self::BpcharArray(length),
}
}
Self::Bit(_) | Self::BitArray(_) | Self::Varbit(_) | Self::VarbitArray(_) => {
let length = Some(BitLength::new(u32::try_from(typmod).ok()?)?);
match self {
Self::Bit(_) => Self::Bit(length),
Self::BitArray(_) => Self::BitArray(length),
Self::Varbit(_) => Self::Varbit(length),
_ => Self::VarbitArray(length),
}
}
Self::Time(_) => Self::Time(Some(TimePrecision::new(u8::try_from(typmod).ok()?))),
Self::TimeArray(_) => {
Self::TimeArray(Some(TimePrecision::new(u8::try_from(typmod).ok()?)))
}
Self::TimeTz(_) => Self::TimeTz(Some(TimePrecision::new(u8::try_from(typmod).ok()?))),
Self::TimeTzArray(_) => {
Self::TimeTzArray(Some(TimePrecision::new(u8::try_from(typmod).ok()?)))
}
Self::Timestamp(_) => {
Self::Timestamp(Some(TimePrecision::new(u8::try_from(typmod).ok()?)))
}
Self::TimestampArray(_) => {
Self::TimestampArray(Some(TimePrecision::new(u8::try_from(typmod).ok()?)))
}
Self::TimestampTz(_) => {
Self::TimestampTz(Some(TimePrecision::new(u8::try_from(typmod).ok()?)))
}
Self::TimestampTzArray(_) => {
Self::TimestampTzArray(Some(TimePrecision::new(u8::try_from(typmod).ok()?)))
}
Self::Interval(_) => Self::Interval(IntervalTypmod::from_catalog_typmod(typmod)?),
Self::IntervalArray(_) => {
Self::IntervalArray(IntervalTypmod::from_catalog_typmod(typmod)?)
}
_ => return None,
};
(modified.typmod() == typmod).then_some(modified)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::postgres::IntervalFields;
use alloc::string::ToString;
#[test]
fn time_precision_canonicalizes_type_identity() {
use core::hash::{Hash, Hasher};
extern crate std;
use std::collections::hash_map::DefaultHasher;
for constructor in [
BuiltinType::Time,
BuiltinType::TimeArray,
BuiltinType::TimeTz,
BuiltinType::TimeTzArray,
BuiltinType::Timestamp,
BuiltinType::TimestampArray,
BuiltinType::TimestampTz,
BuiltinType::TimestampTzArray,
] {
let maximum = constructor(Some(TimePrecision::new(6)));
for precision in [7, u8::MAX] {
let identity = constructor(Some(TimePrecision::new(precision)));
assert_eq!(identity, maximum);
let mut identity_hash = DefaultHasher::new();
let mut maximum_hash = DefaultHasher::new();
identity.hash(&mut identity_hash);
maximum.hash(&mut maximum_hash);
assert_eq!(identity_hash.finish(), maximum_hash.finish());
assert_eq!(identity.typmod(), 6);
assert_eq!(
constructor(None).with_typmod(identity.typmod()),
Some(identity)
);
assert_eq!(identity.with_typmod(i32::from(precision)), None);
}
for precision in 0..=6 {
let identity = constructor(Some(TimePrecision::new(precision)));
assert_eq!(TimePrecision::new(precision).get(), precision);
assert_eq!(identity.typmod(), i32::from(precision));
assert_eq!(
constructor(None).with_typmod(identity.typmod()),
Some(identity)
);
}
assert_eq!(maximum.with_typmod(-1), Some(constructor(None)));
assert_eq!(maximum.with_typmod(-2), None);
assert_eq!(maximum.with_typmod(256), None);
}
}
struct LimitedWriter(usize);
impl fmt::Write for LimitedWriter {
fn write_str(&mut self, text: &str) -> fmt::Result {
self.0 = self.0.checked_sub(text.len()).ok_or(fmt::Error)?;
Ok(())
}
}
#[test]
fn modifier_display_propagates_writer_errors() {
use core::fmt::Write;
for (identity, expected) in [
(
BuiltinType::NumericArray(NumericTypmod::new(4, 2)),
"numeric(4,2)[]",
),
(
BuiltinType::TimestampArray(Some(TimePrecision::new(3))),
"timestamp(3) without time zone[]",
),
(
BuiltinType::IntervalArray(
IntervalTypmod::new(Some(IntervalFields::DayToSecond), Some(3)).unwrap(),
),
"interval day to second(3)[]",
),
] {
assert_eq!(identity.to_string(), expected);
for (capacity, _) in expected.bytes().enumerate() {
assert_eq!(
write!(LimitedWriter(capacity), "{identity}"),
Err(fmt::Error),
"{identity:?} {capacity}",
);
}
assert_eq!(write!(LimitedWriter(expected.len()), "{identity}"), Ok(()));
}
}
#[test]
fn catalog_collations() {
let collated = [
(BuiltinType::Name, TypeCollation::C),
(BuiltinType::NameArray, TypeCollation::C),
(BuiltinType::Text, TypeCollation::Default),
(BuiltinType::PgNodeTree, TypeCollation::Default),
(BuiltinType::TextArray, TypeCollation::Default),
(BuiltinType::BpcharArray(None), TypeCollation::Default),
(BuiltinType::VarcharArray(None), TypeCollation::Default),
(BuiltinType::Bpchar(None), TypeCollation::Default),
(BuiltinType::Varchar(None), TypeCollation::Default),
(BuiltinType::PgNdistinct, TypeCollation::Default),
(BuiltinType::PgDependencies, TypeCollation::Default),
(BuiltinType::PgBrinBloomSummary, TypeCollation::Default),
(
BuiltinType::PgBrinMinmaxMultiSummary,
TypeCollation::Default,
),
(BuiltinType::PgMcvList, TypeCollation::Default),
];
for &identity in BuiltinType::ALL {
let expected = collated
.iter()
.find_map(|&(collated, collation)| (identity == collated).then_some(collation));
assert_eq!(identity.collation(), expected, "{identity:?}");
}
for constructor in [
BuiltinType::Bpchar,
BuiltinType::BpcharArray,
BuiltinType::Varchar,
BuiltinType::VarcharArray,
] {
for length in [1, 10_485_760] {
assert_eq!(
constructor(CharLength::new(length)).collation(),
Some(TypeCollation::Default),
);
}
}
}
#[test]
fn typmod_round_trips() {
for &identity in BuiltinType::ALL {
assert_eq!(identity.with_typmod(-1), Some(identity));
assert_eq!(identity.typmod(), -1);
}
for constructor in [BuiltinType::Numeric, BuiltinType::NumericArray] {
for precision in [1, 1000] {
for scale in [-1000, -1, 0, 1, 1000] {
let value = constructor(NumericTypmod::new(precision, scale));
assert_eq!(value.with_typmod(value.typmod()), Some(value));
assert_eq!(value.with_typmod(-1), Some(value.pg_type()));
}
}
}
for constructor in [
BuiltinType::Bpchar,
BuiltinType::BpcharArray,
BuiltinType::Varchar,
BuiltinType::VarcharArray,
] {
for length in [1, 10_485_760] {
let value = constructor(CharLength::new(length));
assert_eq!(value.with_typmod(value.typmod()), Some(value));
assert_eq!(value.with_typmod(-1), Some(value.pg_type()));
}
}
for constructor in [
BuiltinType::Bit,
BuiltinType::BitArray,
BuiltinType::Varbit,
BuiltinType::VarbitArray,
] {
for length in [1, 83_886_080] {
let value = constructor(BitLength::new(length));
assert_eq!(value.with_typmod(value.typmod()), Some(value));
assert_eq!(value.with_typmod(-1), Some(value.pg_type()));
}
}
for constructor in [
BuiltinType::Time,
BuiltinType::TimeArray,
BuiltinType::TimeTz,
BuiltinType::TimeTzArray,
BuiltinType::Timestamp,
BuiltinType::TimestampArray,
BuiltinType::TimestampTz,
BuiltinType::TimestampTzArray,
] {
for precision in 0..=6 {
let value = constructor(Some(TimePrecision::new(precision)));
assert_eq!(value.with_typmod(value.typmod()), Some(value));
assert_eq!(value.with_typmod(-1), Some(value.pg_type()));
}
}
for constructor in [BuiltinType::Interval, BuiltinType::IntervalArray] {
for fields in [
None,
Some(IntervalFields::Year),
Some(IntervalFields::Month),
Some(IntervalFields::Day),
Some(IntervalFields::Hour),
Some(IntervalFields::Minute),
Some(IntervalFields::Second),
Some(IntervalFields::YearToMonth),
Some(IntervalFields::DayToHour),
Some(IntervalFields::DayToMinute),
Some(IntervalFields::DayToSecond),
Some(IntervalFields::HourToMinute),
Some(IntervalFields::HourToSecond),
Some(IntervalFields::MinuteToSecond),
] {
for precision in [None, Some(0), Some(6)] {
let value = constructor(IntervalTypmod::new(fields, precision).unwrap());
assert_eq!(value.with_typmod(value.typmod()), Some(value));
assert_eq!(value.with_typmod(-1), Some(value.pg_type()));
}
}
}
}
#[test]
fn typmod_rejects_invalid_catalog_values() {
for &identity in BuiltinType::ALL {
for typmod in [i32::MIN, -2, i32::MAX] {
assert_eq!(identity.with_typmod(typmod), None);
}
let invalid = match identity {
BuiltinType::Numeric(_) | BuiltinType::NumericArray(_) => &[
4,
(1001 << 16) + 4,
(1 << 16) + 1001 + 4,
(1 << 16) + 1047 + 4,
(1 << 16) + 0x800 + 4,
][..],
BuiltinType::Varchar(_)
| BuiltinType::VarcharArray(_)
| BuiltinType::Bpchar(_)
| BuiltinType::BpcharArray(_) => &[0, 4, 10_485_765],
BuiltinType::Bit(_)
| BuiltinType::BitArray(_)
| BuiltinType::Varbit(_)
| BuiltinType::VarbitArray(_) => &[0, 83_886_081],
BuiltinType::Time(_)
| BuiltinType::TimeArray(_)
| BuiltinType::TimeTz(_)
| BuiltinType::TimeTzArray(_)
| BuiltinType::Timestamp(_)
| BuiltinType::TimestampArray(_)
| BuiltinType::TimestampTz(_)
| BuiltinType::TimestampTzArray(_) => &[7, 255],
BuiltinType::Interval(_) | BuiltinType::IntervalArray(_) => {
&[0, 0x7fff_0007, 0x0001_ffff, 0x7fff_ffff]
}
_ => &[0, 1],
};
for &typmod in invalid {
assert_eq!(identity.with_typmod(typmod), None, "{identity:?} {typmod}");
}
}
}
}