Skip to main content

sql_values/postgres/
builtin_type.rs

1//! PostgreSQL's fixed built-in type identities and spellings.
2
3use super::{CharLength, IntervalTypmod, NumericTypmod};
4use core::fmt;
5
6/// A collation assigned to a built-in type by `pg_type.typcollation`.
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8pub enum TypeCollation {
9    /// The database default collation, with object identifier `100`.
10    Default,
11    /// The `C` collation, with object identifier `950`.
12    C,
13}
14
15/// A `bit` or `varbit` length accepted by PostgreSQL.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17pub struct BitLength(u32);
18
19impl BitLength {
20    /// The length accepted by `bittypmodin` and `varbittypmodin`.
21    #[must_use]
22    pub const fn new(length: u32) -> Option<Self> {
23        if length >= 1 && length <= 83_886_080 {
24            Some(Self(length))
25        } else {
26            None
27        }
28    }
29}
30
31/// Fractional-second precision for PostgreSQL time, timestamp and interval types.
32#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
33pub struct TimePrecision(u8);
34
35impl TimePrecision {
36    /// Reduces precision above PostgreSQL's maximum to six fractional-second digits.
37    #[must_use]
38    pub const fn new(precision: u8) -> Self {
39        Self(if precision > 6 { 6 } else { precision })
40    }
41
42    /// The number of fractional-second digits.
43    #[must_use]
44    pub const fn get(self) -> u8 {
45        self.0
46    }
47}
48
49impl fmt::Display for TimePrecision {
50    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
51        self.0.fmt(formatter)
52    }
53}
54
55macro_rules! builtin_types {
56    (
57        plain { $( $plain:ident = $plain_oid:literal, $plain_name:literal, $plain_spelling:literal, $plain_diagnostic:literal; )* }
58        modified { $( $modified:ident = $modified_oid:literal, $modified_name:literal, $modified_spelling:literal, $modified_diagnostic:literal, $modifier:ty, $default:expr; )* }
59    ) => {
60        /// A fixed PostgreSQL built-in type identity with its type modifier.
61        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
62        pub enum BuiltinType {
63            $( #[doc = concat!("`", $plain_name, "`.")] $plain, )*
64            $( #[doc = concat!("`", $modified_name, "` with its modifier.")] $modified($modifier), )*
65        }
66
67        impl BuiltinType {
68            /// Excludes identities assigned by `initdb` rather than fixed by PostgreSQL.
69            pub const ALL: &'static [Self] = &[$(Self::$plain,)* $(Self::$modified($default),)*];
70
71            /// The built-in object identifier.
72            #[must_use]
73            pub const fn oid(self) -> u32 {
74                match self { $(Self::$plain => $plain_oid,)* $(Self::$modified(_) => $modified_oid,)* }
75            }
76
77            /// The built-in identity for a fixed object identifier, without a modifier.
78            #[must_use]
79            pub const fn from_oid(oid: u32) -> Option<Self> {
80                match oid { $($plain_oid => Some(Self::$plain),)* $($modified_oid => Some(Self::$modified($default)),)* _ => None }
81            }
82
83            /// The `pg_type.typname` of this identity.
84            #[must_use]
85            pub const fn catalog_name(self) -> &'static str {
86                match self { $(Self::$plain => $plain_name,)* $(Self::$modified(_) => $modified_name,)* }
87            }
88
89            /// The built-in identity whose `pg_type.typname` is `name`, without a modifier.
90            #[must_use]
91            pub fn from_catalog_name(name: &str) -> Option<Self> {
92                match name { $($plain_name => Some(Self::$plain),)* $($modified_name => Some(Self::$modified($default)),)* _ => None }
93            }
94
95            /// The spelling `format_type(oid, NULL)` uses in diagnostics.
96            #[must_use]
97            pub const fn diagnostic_name(self) -> &'static str {
98                match self { $(Self::$plain => $plain_diagnostic,)* $(Self::$modified(_) => $modified_diagnostic,)* }
99            }
100
101            /// The spelling `format_type(oid, -1)` uses without a modifier.
102            const fn unmodified_name(self) -> &'static str {
103                match self { $(Self::$plain => $plain_spelling,)* $(Self::$modified(_) => $modified_spelling,)* }
104            }
105
106            /// This identity without its modifier.
107            #[must_use]
108            pub const fn pg_type(self) -> Self {
109                match self { $(Self::$modified(_) => Self::$modified($default),)* other => other }
110            }
111        }
112    }
113}
114
115builtin_types! {
116    plain {
117        Boolean = 16, "bool", "boolean", "boolean";
118        Bytea = 17, "bytea", "bytea", "bytea";
119        InternalChar = 18, "char", "\"char\"", "\"char\"";
120        Name = 19, "name", "name", "name";
121        Bigint = 20, "int8", "bigint", "bigint";
122        Smallint = 21, "int2", "smallint", "smallint";
123        Int2Vector = 22, "int2vector", "int2vector", "int2vector";
124        Integer = 23, "int4", "integer", "integer";
125        Regproc = 24, "regproc", "regproc", "regproc";
126        Text = 25, "text", "text", "text";
127        Oid = 26, "oid", "oid", "oid";
128        Tid = 27, "tid", "tid", "tid";
129        Xid = 28, "xid", "xid", "xid";
130        Cid = 29, "cid", "cid", "cid";
131        Oidvector = 30, "oidvector", "oidvector", "oidvector";
132        PgDdlCommand = 32, "pg_ddl_command", "pg_ddl_command", "pg_ddl_command";
133        PgType = 71, "pg_type", "pg_type", "pg_type";
134        PgAttribute = 75, "pg_attribute", "pg_attribute", "pg_attribute";
135        PgProc = 81, "pg_proc", "pg_proc", "pg_proc";
136        PgClass = 83, "pg_class", "pg_class", "pg_class";
137        Json = 114, "json", "json", "json";
138        Xml = 142, "xml", "xml", "xml";
139        XmlArray = 143, "_xml", "xml[]", "xml[]";
140        PgNodeTree = 194, "pg_node_tree", "pg_node_tree", "pg_node_tree";
141        JsonArray = 199, "_json", "json[]", "json[]";
142        PgTypeArray = 210, "_pg_type", "pg_type[]", "pg_type[]";
143        TableAmHandler = 269, "table_am_handler", "table_am_handler", "table_am_handler";
144        PgAttributeArray = 270, "_pg_attribute", "pg_attribute[]", "pg_attribute[]";
145        Xid8Array = 271, "_xid8", "xid8[]", "xid8[]";
146        PgProcArray = 272, "_pg_proc", "pg_proc[]", "pg_proc[]";
147        PgClassArray = 273, "_pg_class", "pg_class[]", "pg_class[]";
148        IndexAmHandler = 325, "index_am_handler", "index_am_handler", "index_am_handler";
149        Point = 600, "point", "point", "point";
150        Lseg = 601, "lseg", "lseg", "lseg";
151        Path = 602, "path", "path", "path";
152        Box = 603, "box", "box", "box";
153        Polygon = 604, "polygon", "polygon", "polygon";
154        Line = 628, "line", "line", "line";
155        LineArray = 629, "_line", "line[]", "line[]";
156        Cidr = 650, "cidr", "cidr", "cidr";
157        CidrArray = 651, "_cidr", "cidr[]", "cidr[]";
158        Real = 700, "float4", "real", "real";
159        DoublePrecision = 701, "float8", "double precision", "double precision";
160        Unknown = 705, "unknown", "unknown", "unknown";
161        Circle = 718, "circle", "circle", "circle";
162        CircleArray = 719, "_circle", "circle[]", "circle[]";
163        Macaddr8 = 774, "macaddr8", "macaddr8", "macaddr8";
164        Macaddr8Array = 775, "_macaddr8", "macaddr8[]", "macaddr8[]";
165        Money = 790, "money", "money", "money";
166        MoneyArray = 791, "_money", "money[]", "money[]";
167        Macaddr = 829, "macaddr", "macaddr", "macaddr";
168        Inet = 869, "inet", "inet", "inet";
169        BooleanArray = 1000, "_bool", "boolean[]", "boolean[]";
170        ByteaArray = 1001, "_bytea", "bytea[]", "bytea[]";
171        InternalCharArray = 1002, "_char", "\"char\"[]", "\"char\"[]";
172        NameArray = 1003, "_name", "name[]", "name[]";
173        SmallintArray = 1005, "_int2", "smallint[]", "smallint[]";
174        Int2VectorArray = 1006, "_int2vector", "int2vector[]", "int2vector[]";
175        IntegerArray = 1007, "_int4", "integer[]", "integer[]";
176        RegprocArray = 1008, "_regproc", "regproc[]", "regproc[]";
177        TextArray = 1009, "_text", "text[]", "text[]";
178        TidArray = 1010, "_tid", "tid[]", "tid[]";
179        XidArray = 1011, "_xid", "xid[]", "xid[]";
180        CidArray = 1012, "_cid", "cid[]", "cid[]";
181        OidvectorArray = 1013, "_oidvector", "oidvector[]", "oidvector[]";
182        BigintArray = 1016, "_int8", "bigint[]", "bigint[]";
183        PointArray = 1017, "_point", "point[]", "point[]";
184        LsegArray = 1018, "_lseg", "lseg[]", "lseg[]";
185        PathArray = 1019, "_path", "path[]", "path[]";
186        BoxArray = 1020, "_box", "box[]", "box[]";
187        RealArray = 1021, "_float4", "real[]", "real[]";
188        DoublePrecisionArray = 1022, "_float8", "double precision[]", "double precision[]";
189        PolygonArray = 1027, "_polygon", "polygon[]", "polygon[]";
190        OidArray = 1028, "_oid", "oid[]", "oid[]";
191        Aclitem = 1033, "aclitem", "aclitem", "aclitem";
192        AclitemArray = 1034, "_aclitem", "aclitem[]", "aclitem[]";
193        MacaddrArray = 1040, "_macaddr", "macaddr[]", "macaddr[]";
194        InetArray = 1041, "_inet", "inet[]", "inet[]";
195        Date = 1082, "date", "date", "date";
196        DateArray = 1182, "_date", "date[]", "date[]";
197        PgDatabase = 1248, "pg_database", "pg_database", "pg_database";
198        CstringArray = 1263, "_cstring", "cstring[]", "cstring[]";
199        Refcursor = 1790, "refcursor", "refcursor", "refcursor";
200        RefcursorArray = 2201, "_refcursor", "refcursor[]", "refcursor[]";
201        Regprocedure = 2202, "regprocedure", "regprocedure", "regprocedure";
202        Regoper = 2203, "regoper", "regoper", "regoper";
203        Regoperator = 2204, "regoperator", "regoperator", "regoperator";
204        Regclass = 2205, "regclass", "regclass", "regclass";
205        Regtype = 2206, "regtype", "regtype", "regtype";
206        RegprocedureArray = 2207, "_regprocedure", "regprocedure[]", "regprocedure[]";
207        RegoperArray = 2208, "_regoper", "regoper[]", "regoper[]";
208        RegoperatorArray = 2209, "_regoperator", "regoperator[]", "regoperator[]";
209        RegclassArray = 2210, "_regclass", "regclass[]", "regclass[]";
210        RegtypeArray = 2211, "_regtype", "regtype[]", "regtype[]";
211        Record = 2249, "record", "record", "record";
212        Cstring = 2275, "cstring", "cstring", "cstring";
213        Any = 2276, "any", "\"any\"", "\"any\"";
214        Anyarray = 2277, "anyarray", "anyarray", "anyarray";
215        Void = 2278, "void", "void", "void";
216        Trigger = 2279, "trigger", "trigger", "trigger";
217        LanguageHandler = 2280, "language_handler", "language_handler", "language_handler";
218        Internal = 2281, "internal", "internal", "internal";
219        Anyelement = 2283, "anyelement", "anyelement", "anyelement";
220        RecordArray = 2287, "_record", "record[]", "record[]";
221        Anynonarray = 2776, "anynonarray", "anynonarray", "anynonarray";
222        PgAuthid = 2842, "pg_authid", "pg_authid", "pg_authid";
223        PgAuthMembers = 2843, "pg_auth_members", "pg_auth_members", "pg_auth_members";
224        TxidSnapshotArray = 2949, "_txid_snapshot", "txid_snapshot[]", "txid_snapshot[]";
225        Uuid = 2950, "uuid", "uuid", "uuid";
226        UuidArray = 2951, "_uuid", "uuid[]", "uuid[]";
227        TxidSnapshot = 2970, "txid_snapshot", "txid_snapshot", "txid_snapshot";
228        FdwHandler = 3115, "fdw_handler", "fdw_handler", "fdw_handler";
229        PgLsn = 3220, "pg_lsn", "pg_lsn", "pg_lsn";
230        PgLsnArray = 3221, "_pg_lsn", "pg_lsn[]", "pg_lsn[]";
231        TsmHandler = 3310, "tsm_handler", "tsm_handler", "tsm_handler";
232        PgNdistinct = 3361, "pg_ndistinct", "pg_ndistinct", "pg_ndistinct";
233        PgDependencies = 3402, "pg_dependencies", "pg_dependencies", "pg_dependencies";
234        Anyenum = 3500, "anyenum", "anyenum", "anyenum";
235        Tsvector = 3614, "tsvector", "tsvector", "tsvector";
236        Tsquery = 3615, "tsquery", "tsquery", "tsquery";
237        Gtsvector = 3642, "gtsvector", "gtsvector", "gtsvector";
238        TsvectorArray = 3643, "_tsvector", "tsvector[]", "tsvector[]";
239        GtsvectorArray = 3644, "_gtsvector", "gtsvector[]", "gtsvector[]";
240        TsqueryArray = 3645, "_tsquery", "tsquery[]", "tsquery[]";
241        Regconfig = 3734, "regconfig", "regconfig", "regconfig";
242        RegconfigArray = 3735, "_regconfig", "regconfig[]", "regconfig[]";
243        Regdictionary = 3769, "regdictionary", "regdictionary", "regdictionary";
244        RegdictionaryArray = 3770, "_regdictionary", "regdictionary[]", "regdictionary[]";
245        Jsonb = 3802, "jsonb", "jsonb", "jsonb";
246        JsonbArray = 3807, "_jsonb", "jsonb[]", "jsonb[]";
247        Anyrange = 3831, "anyrange", "anyrange", "anyrange";
248        EventTrigger = 3838, "event_trigger", "event_trigger", "event_trigger";
249        Int4Range = 3904, "int4range", "int4range", "int4range";
250        Int4RangeArray = 3905, "_int4range", "int4range[]", "int4range[]";
251        Numrange = 3906, "numrange", "numrange", "numrange";
252        NumrangeArray = 3907, "_numrange", "numrange[]", "numrange[]";
253        Tsrange = 3908, "tsrange", "tsrange", "tsrange";
254        TsrangeArray = 3909, "_tsrange", "tsrange[]", "tsrange[]";
255        Tstzrange = 3910, "tstzrange", "tstzrange", "tstzrange";
256        TstzrangeArray = 3911, "_tstzrange", "tstzrange[]", "tstzrange[]";
257        Daterange = 3912, "daterange", "daterange", "daterange";
258        DaterangeArray = 3913, "_daterange", "daterange[]", "daterange[]";
259        Int8Range = 3926, "int8range", "int8range", "int8range";
260        Int8RangeArray = 3927, "_int8range", "int8range[]", "int8range[]";
261        PgShseclabel = 4066, "pg_shseclabel", "pg_shseclabel", "pg_shseclabel";
262        Jsonpath = 4072, "jsonpath", "jsonpath", "jsonpath";
263        JsonpathArray = 4073, "_jsonpath", "jsonpath[]", "jsonpath[]";
264        Regnamespace = 4089, "regnamespace", "regnamespace", "regnamespace";
265        RegnamespaceArray = 4090, "_regnamespace", "regnamespace[]", "regnamespace[]";
266        Regrole = 4096, "regrole", "regrole", "regrole";
267        RegroleArray = 4097, "_regrole", "regrole[]", "regrole[]";
268        Regcollation = 4191, "regcollation", "regcollation", "regcollation";
269        RegcollationArray = 4192, "_regcollation", "regcollation[]", "regcollation[]";
270        Int4Multirange = 4451, "int4multirange", "int4multirange", "int4multirange";
271        Nummultirange = 4532, "nummultirange", "nummultirange", "nummultirange";
272        Tsmultirange = 4533, "tsmultirange", "tsmultirange", "tsmultirange";
273        Tstzmultirange = 4534, "tstzmultirange", "tstzmultirange", "tstzmultirange";
274        Datemultirange = 4535, "datemultirange", "datemultirange", "datemultirange";
275        Int8Multirange = 4536, "int8multirange", "int8multirange", "int8multirange";
276        Anymultirange = 4537, "anymultirange", "anymultirange", "anymultirange";
277        Anycompatiblemultirange = 4538, "anycompatiblemultirange", "anycompatiblemultirange", "anycompatiblemultirange";
278        PgBrinBloomSummary = 4600, "pg_brin_bloom_summary", "pg_brin_bloom_summary", "pg_brin_bloom_summary";
279        PgBrinMinmaxMultiSummary = 4601, "pg_brin_minmax_multi_summary", "pg_brin_minmax_multi_summary", "pg_brin_minmax_multi_summary";
280        PgMcvList = 5017, "pg_mcv_list", "pg_mcv_list", "pg_mcv_list";
281        PgSnapshot = 5038, "pg_snapshot", "pg_snapshot", "pg_snapshot";
282        PgSnapshotArray = 5039, "_pg_snapshot", "pg_snapshot[]", "pg_snapshot[]";
283        Xid8 = 5069, "xid8", "xid8", "xid8";
284        Anycompatible = 5077, "anycompatible", "anycompatible", "anycompatible";
285        Anycompatiblearray = 5078, "anycompatiblearray", "anycompatiblearray", "anycompatiblearray";
286        Anycompatiblenonarray = 5079, "anycompatiblenonarray", "anycompatiblenonarray", "anycompatiblenonarray";
287        Anycompatiblerange = 5080, "anycompatiblerange", "anycompatiblerange", "anycompatiblerange";
288        PgSubscription = 6101, "pg_subscription", "pg_subscription", "pg_subscription";
289        Int4MultirangeArray = 6150, "_int4multirange", "int4multirange[]", "int4multirange[]";
290        NummultirangeArray = 6151, "_nummultirange", "nummultirange[]", "nummultirange[]";
291        TsmultirangeArray = 6152, "_tsmultirange", "tsmultirange[]", "tsmultirange[]";
292        TstzmultirangeArray = 6153, "_tstzmultirange", "tstzmultirange[]", "tstzmultirange[]";
293        DatemultirangeArray = 6155, "_datemultirange", "datemultirange[]", "datemultirange[]";
294        Int8MultirangeArray = 6157, "_int8multirange", "int8multirange[]", "int8multirange[]";
295    }
296    modified {
297        BpcharArray = 1014, "_bpchar", "bpchar[]", "character[]", Option<CharLength>, None;
298        VarcharArray = 1015, "_varchar", "character varying[]", "character varying[]", Option<CharLength>, None;
299        Bpchar = 1042, "bpchar", "bpchar", "character", Option<CharLength>, None;
300        Varchar = 1043, "varchar", "character varying", "character varying", Option<CharLength>, None;
301        Time = 1083, "time", "time without time zone", "time without time zone", Option<TimePrecision>, None;
302        Timestamp = 1114, "timestamp", "timestamp without time zone", "timestamp without time zone", Option<TimePrecision>, None;
303        TimestampArray = 1115, "_timestamp", "timestamp without time zone[]", "timestamp without time zone[]", Option<TimePrecision>, None;
304        TimeArray = 1183, "_time", "time without time zone[]", "time without time zone[]", Option<TimePrecision>, None;
305        TimestampTz = 1184, "timestamptz", "timestamp with time zone", "timestamp with time zone", Option<TimePrecision>, None;
306        TimestampTzArray = 1185, "_timestamptz", "timestamp with time zone[]", "timestamp with time zone[]", Option<TimePrecision>, None;
307        Interval = 1186, "interval", "interval", "interval", IntervalTypmod, IntervalTypmod::UNMODIFIED;
308        IntervalArray = 1187, "_interval", "interval[]", "interval[]", IntervalTypmod, IntervalTypmod::UNMODIFIED;
309        NumericArray = 1231, "_numeric", "numeric[]", "numeric[]", Option<NumericTypmod>, None;
310        TimeTz = 1266, "timetz", "time with time zone", "time with time zone", Option<TimePrecision>, None;
311        TimeTzArray = 1270, "_timetz", "time with time zone[]", "time with time zone[]", Option<TimePrecision>, None;
312        Bit = 1560, "bit", "\"bit\"", "bit", Option<BitLength>, None;
313        BitArray = 1561, "_bit", "\"bit\"[]", "bit[]", Option<BitLength>, None;
314        Varbit = 1562, "varbit", "bit varying", "bit varying", Option<BitLength>, None;
315        VarbitArray = 1563, "_varbit", "bit varying[]", "bit varying[]", Option<BitLength>, None;
316        Numeric = 1700, "numeric", "numeric", "numeric", Option<NumericTypmod>, None;
317    }
318}
319
320impl BuiltinType {
321    /// The type's `pg_type.typcollation`, independent of its modifier.
322    ///
323    /// ```
324    /// use sql_values::postgres::{BuiltinType, TypeCollation};
325    ///
326    /// assert_eq!(BuiltinType::Text.collation(), Some(TypeCollation::Default));
327    /// assert_eq!(BuiltinType::Name.collation(), Some(TypeCollation::C));
328    /// assert_eq!(BuiltinType::Integer.collation(), None);
329    /// ```
330    #[must_use]
331    pub const fn collation(self) -> Option<TypeCollation> {
332        match self {
333            Self::Name | Self::NameArray => Some(TypeCollation::C),
334            Self::Text
335            | Self::TextArray
336            | Self::PgNodeTree
337            | Self::Bpchar(_)
338            | Self::BpcharArray(_)
339            | Self::Varchar(_)
340            | Self::VarcharArray(_)
341            | Self::PgNdistinct
342            | Self::PgDependencies
343            | Self::PgBrinBloomSummary
344            | Self::PgBrinMinmaxMultiSummary
345            | Self::PgMcvList => Some(TypeCollation::Default),
346            _ => None,
347        }
348    }
349
350    /// The type name used by its input function.
351    pub(crate) const fn input_name(self) -> &'static str {
352        match self {
353            Self::Timestamp(_) => "timestamp",
354            Self::Time(_) => "time",
355            other => other.diagnostic_name(),
356        }
357    }
358
359    /// Whether value casts to this identity are modelled.
360    pub(crate) const fn supports_cast(self) -> bool {
361        matches!(
362            self,
363            Self::Boolean
364                | Self::Smallint
365                | Self::Integer
366                | Self::Bigint
367                | Self::Numeric(_)
368                | Self::Text
369                | Self::Varchar(_)
370                | Self::Bpchar(_)
371                | Self::Date
372                | Self::Timestamp(_)
373                | Self::TimestampTz(_)
374                | Self::Time(_)
375                | Self::TimeTz(_)
376                | Self::Jsonb
377                | Self::Uuid
378                | Self::Interval(_)
379        )
380    }
381}
382
383impl fmt::Display for BuiltinType {
384    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
385        match *self {
386            Self::Numeric(Some(modifier)) | Self::NumericArray(Some(modifier)) => {
387                write!(
388                    formatter,
389                    "numeric({},{})",
390                    modifier.precision(),
391                    modifier.scale()
392                )?;
393            }
394            Self::Varchar(Some(length)) | Self::VarcharArray(Some(length)) => {
395                write!(formatter, "character varying({})", length.get())?;
396            }
397            Self::Bpchar(Some(length)) | Self::BpcharArray(Some(length)) => {
398                write!(formatter, "character({})", length.get())?;
399            }
400            Self::Bit(Some(length)) | Self::BitArray(Some(length)) => {
401                write!(formatter, "bit({})", length.0)?;
402            }
403            Self::Varbit(Some(length)) | Self::VarbitArray(Some(length)) => {
404                write!(formatter, "bit varying({})", length.0)?;
405            }
406            Self::Time(Some(precision)) | Self::TimeArray(Some(precision)) => {
407                write!(formatter, "time({}) without time zone", precision.get())?;
408            }
409            Self::TimeTz(Some(precision)) | Self::TimeTzArray(Some(precision)) => {
410                write!(formatter, "time({}) with time zone", precision.get())?;
411            }
412            Self::Timestamp(Some(precision)) | Self::TimestampArray(Some(precision)) => {
413                write!(
414                    formatter,
415                    "timestamp({}) without time zone",
416                    precision.get()
417                )?;
418            }
419            Self::TimestampTz(Some(precision)) | Self::TimestampTzArray(Some(precision)) => {
420                write!(formatter, "timestamp({}) with time zone", precision.get())?;
421            }
422            Self::Interval(modifier) | Self::IntervalArray(modifier) => {
423                write!(formatter, "interval{modifier}")?;
424            }
425            _ => return formatter.write_str(self.unmodified_name()),
426        }
427        if self.catalog_name().starts_with('_') {
428            formatter.write_str("[]")?;
429        }
430        Ok(())
431    }
432}
433
434impl BuiltinType {
435    /// The catalog modifier passed to `format_type`, or `-1` when absent.
436    #[must_use]
437    pub fn typmod(self) -> i32 {
438        match self {
439            Self::Numeric(Some(modifier)) | Self::NumericArray(Some(modifier)) => {
440                (i32::from(modifier.precision()) << 16) + (i32::from(modifier.scale()) & 0x7ff) + 4
441            }
442            Self::Varchar(Some(length))
443            | Self::VarcharArray(Some(length))
444            | Self::Bpchar(Some(length))
445            | Self::BpcharArray(Some(length)) => {
446                debug_assert!(length.get() <= 10_485_760);
447                // Character lengths are bounded by `MaxAttrSize`.
448                length.get() as i32 + 4
449            }
450            Self::Bit(Some(length))
451            | Self::BitArray(Some(length))
452            | Self::Varbit(Some(length))
453            | Self::VarbitArray(Some(length)) => {
454                debug_assert!(length.0 <= 83_886_080);
455                // Bit lengths are bounded by `MaxAttrSize * 8`.
456                length.0 as i32
457            }
458            Self::Time(Some(precision))
459            | Self::TimeArray(Some(precision))
460            | Self::TimeTz(Some(precision))
461            | Self::TimeTzArray(Some(precision))
462            | Self::Timestamp(Some(precision))
463            | Self::TimestampArray(Some(precision))
464            | Self::TimestampTz(Some(precision))
465            | Self::TimestampTzArray(Some(precision)) => i32::from(precision.get()),
466            Self::Interval(modifier) | Self::IntervalArray(modifier) => modifier.catalog_typmod(),
467            _ => -1,
468        }
469    }
470
471    /// Replaces the modifier with a valid PostgreSQL catalog `typmod`, clearing it for `-1`.
472    ///
473    /// ```
474    /// use sql_values::postgres::{BuiltinType, CharLength};
475    ///
476    /// let varchar = BuiltinType::Varchar(CharLength::new(10));
477    /// assert_eq!(BuiltinType::Varchar(None).with_typmod(14), Some(varchar));
478    /// assert_eq!(varchar.with_typmod(-1), Some(BuiltinType::Varchar(None)));
479    /// assert_eq!(BuiltinType::Time(None).with_typmod(7), None);
480    /// assert_eq!(BuiltinType::Boolean.with_typmod(0), None);
481    /// ```
482    #[must_use]
483    pub fn with_typmod(self, typmod: i32) -> Option<Self> {
484        if typmod == -1 {
485            return Some(self.pg_type());
486        }
487        let modified = match self {
488            Self::Numeric(_) | Self::NumericArray(_) => {
489                let packed = typmod.checked_sub(4)?;
490                let precision = u16::try_from(packed >> 16).ok()?;
491                let scale = i16::try_from(((packed & 0x7ff) ^ 0x400) - 0x400).ok()?;
492                let modifier = Some(NumericTypmod::new(precision, scale)?);
493                match self {
494                    Self::Numeric(_) => Self::Numeric(modifier),
495                    _ => Self::NumericArray(modifier),
496                }
497            }
498            Self::Varchar(_) | Self::VarcharArray(_) | Self::Bpchar(_) | Self::BpcharArray(_) => {
499                let length = Some(CharLength::new(
500                    usize::try_from(typmod.checked_sub(4)?).ok()?,
501                )?);
502                match self {
503                    Self::Varchar(_) => Self::Varchar(length),
504                    Self::VarcharArray(_) => Self::VarcharArray(length),
505                    Self::Bpchar(_) => Self::Bpchar(length),
506                    _ => Self::BpcharArray(length),
507                }
508            }
509            Self::Bit(_) | Self::BitArray(_) | Self::Varbit(_) | Self::VarbitArray(_) => {
510                let length = Some(BitLength::new(u32::try_from(typmod).ok()?)?);
511                match self {
512                    Self::Bit(_) => Self::Bit(length),
513                    Self::BitArray(_) => Self::BitArray(length),
514                    Self::Varbit(_) => Self::Varbit(length),
515                    _ => Self::VarbitArray(length),
516                }
517            }
518            Self::Time(_) => Self::Time(Some(TimePrecision::new(u8::try_from(typmod).ok()?))),
519            Self::TimeArray(_) => {
520                Self::TimeArray(Some(TimePrecision::new(u8::try_from(typmod).ok()?)))
521            }
522            Self::TimeTz(_) => Self::TimeTz(Some(TimePrecision::new(u8::try_from(typmod).ok()?))),
523            Self::TimeTzArray(_) => {
524                Self::TimeTzArray(Some(TimePrecision::new(u8::try_from(typmod).ok()?)))
525            }
526            Self::Timestamp(_) => {
527                Self::Timestamp(Some(TimePrecision::new(u8::try_from(typmod).ok()?)))
528            }
529            Self::TimestampArray(_) => {
530                Self::TimestampArray(Some(TimePrecision::new(u8::try_from(typmod).ok()?)))
531            }
532            Self::TimestampTz(_) => {
533                Self::TimestampTz(Some(TimePrecision::new(u8::try_from(typmod).ok()?)))
534            }
535            Self::TimestampTzArray(_) => {
536                Self::TimestampTzArray(Some(TimePrecision::new(u8::try_from(typmod).ok()?)))
537            }
538            Self::Interval(_) => Self::Interval(IntervalTypmod::from_catalog_typmod(typmod)?),
539            Self::IntervalArray(_) => {
540                Self::IntervalArray(IntervalTypmod::from_catalog_typmod(typmod)?)
541            }
542            _ => return None,
543        };
544        (modified.typmod() == typmod).then_some(modified)
545    }
546}
547
548#[cfg(test)]
549mod tests {
550    use super::*;
551    use crate::postgres::IntervalFields;
552    use alloc::string::ToString;
553
554    #[test]
555    fn time_precision_canonicalizes_type_identity() {
556        use core::hash::{Hash, Hasher};
557        extern crate std;
558        use std::collections::hash_map::DefaultHasher;
559
560        for constructor in [
561            BuiltinType::Time,
562            BuiltinType::TimeArray,
563            BuiltinType::TimeTz,
564            BuiltinType::TimeTzArray,
565            BuiltinType::Timestamp,
566            BuiltinType::TimestampArray,
567            BuiltinType::TimestampTz,
568            BuiltinType::TimestampTzArray,
569        ] {
570            let maximum = constructor(Some(TimePrecision::new(6)));
571            for precision in [7, u8::MAX] {
572                let identity = constructor(Some(TimePrecision::new(precision)));
573                assert_eq!(identity, maximum);
574                let mut identity_hash = DefaultHasher::new();
575                let mut maximum_hash = DefaultHasher::new();
576                identity.hash(&mut identity_hash);
577                maximum.hash(&mut maximum_hash);
578                assert_eq!(identity_hash.finish(), maximum_hash.finish());
579                assert_eq!(identity.typmod(), 6);
580                assert_eq!(
581                    constructor(None).with_typmod(identity.typmod()),
582                    Some(identity)
583                );
584                assert_eq!(identity.with_typmod(i32::from(precision)), None);
585            }
586            for precision in 0..=6 {
587                let identity = constructor(Some(TimePrecision::new(precision)));
588                assert_eq!(TimePrecision::new(precision).get(), precision);
589                assert_eq!(identity.typmod(), i32::from(precision));
590                assert_eq!(
591                    constructor(None).with_typmod(identity.typmod()),
592                    Some(identity)
593                );
594            }
595            assert_eq!(maximum.with_typmod(-1), Some(constructor(None)));
596            assert_eq!(maximum.with_typmod(-2), None);
597            assert_eq!(maximum.with_typmod(256), None);
598        }
599    }
600
601    struct LimitedWriter(usize);
602
603    impl fmt::Write for LimitedWriter {
604        fn write_str(&mut self, text: &str) -> fmt::Result {
605            self.0 = self.0.checked_sub(text.len()).ok_or(fmt::Error)?;
606            Ok(())
607        }
608    }
609
610    #[test]
611    fn modifier_display_propagates_writer_errors() {
612        use core::fmt::Write;
613
614        for (identity, expected) in [
615            (
616                BuiltinType::NumericArray(NumericTypmod::new(4, 2)),
617                "numeric(4,2)[]",
618            ),
619            (
620                BuiltinType::TimestampArray(Some(TimePrecision::new(3))),
621                "timestamp(3) without time zone[]",
622            ),
623            (
624                BuiltinType::IntervalArray(
625                    IntervalTypmod::new(Some(IntervalFields::DayToSecond), Some(3)).unwrap(),
626                ),
627                "interval day to second(3)[]",
628            ),
629        ] {
630            assert_eq!(identity.to_string(), expected);
631            for (capacity, _) in expected.bytes().enumerate() {
632                assert_eq!(
633                    write!(LimitedWriter(capacity), "{identity}"),
634                    Err(fmt::Error),
635                    "{identity:?} {capacity}",
636                );
637            }
638            assert_eq!(write!(LimitedWriter(expected.len()), "{identity}"), Ok(()));
639        }
640    }
641
642    #[test]
643    fn catalog_collations() {
644        let collated = [
645            (BuiltinType::Name, TypeCollation::C),
646            (BuiltinType::NameArray, TypeCollation::C),
647            (BuiltinType::Text, TypeCollation::Default),
648            (BuiltinType::PgNodeTree, TypeCollation::Default),
649            (BuiltinType::TextArray, TypeCollation::Default),
650            (BuiltinType::BpcharArray(None), TypeCollation::Default),
651            (BuiltinType::VarcharArray(None), TypeCollation::Default),
652            (BuiltinType::Bpchar(None), TypeCollation::Default),
653            (BuiltinType::Varchar(None), TypeCollation::Default),
654            (BuiltinType::PgNdistinct, TypeCollation::Default),
655            (BuiltinType::PgDependencies, TypeCollation::Default),
656            (BuiltinType::PgBrinBloomSummary, TypeCollation::Default),
657            (
658                BuiltinType::PgBrinMinmaxMultiSummary,
659                TypeCollation::Default,
660            ),
661            (BuiltinType::PgMcvList, TypeCollation::Default),
662        ];
663        for &identity in BuiltinType::ALL {
664            let expected = collated
665                .iter()
666                .find_map(|&(collated, collation)| (identity == collated).then_some(collation));
667            assert_eq!(identity.collation(), expected, "{identity:?}");
668        }
669        for constructor in [
670            BuiltinType::Bpchar,
671            BuiltinType::BpcharArray,
672            BuiltinType::Varchar,
673            BuiltinType::VarcharArray,
674        ] {
675            for length in [1, 10_485_760] {
676                assert_eq!(
677                    constructor(CharLength::new(length)).collation(),
678                    Some(TypeCollation::Default),
679                );
680            }
681        }
682    }
683
684    #[test]
685    fn typmod_round_trips() {
686        for &identity in BuiltinType::ALL {
687            assert_eq!(identity.with_typmod(-1), Some(identity));
688            assert_eq!(identity.typmod(), -1);
689        }
690        for constructor in [BuiltinType::Numeric, BuiltinType::NumericArray] {
691            for precision in [1, 1000] {
692                for scale in [-1000, -1, 0, 1, 1000] {
693                    let value = constructor(NumericTypmod::new(precision, scale));
694                    assert_eq!(value.with_typmod(value.typmod()), Some(value));
695                    assert_eq!(value.with_typmod(-1), Some(value.pg_type()));
696                }
697            }
698        }
699        for constructor in [
700            BuiltinType::Bpchar,
701            BuiltinType::BpcharArray,
702            BuiltinType::Varchar,
703            BuiltinType::VarcharArray,
704        ] {
705            for length in [1, 10_485_760] {
706                let value = constructor(CharLength::new(length));
707                assert_eq!(value.with_typmod(value.typmod()), Some(value));
708                assert_eq!(value.with_typmod(-1), Some(value.pg_type()));
709            }
710        }
711        for constructor in [
712            BuiltinType::Bit,
713            BuiltinType::BitArray,
714            BuiltinType::Varbit,
715            BuiltinType::VarbitArray,
716        ] {
717            for length in [1, 83_886_080] {
718                let value = constructor(BitLength::new(length));
719                assert_eq!(value.with_typmod(value.typmod()), Some(value));
720                assert_eq!(value.with_typmod(-1), Some(value.pg_type()));
721            }
722        }
723        for constructor in [
724            BuiltinType::Time,
725            BuiltinType::TimeArray,
726            BuiltinType::TimeTz,
727            BuiltinType::TimeTzArray,
728            BuiltinType::Timestamp,
729            BuiltinType::TimestampArray,
730            BuiltinType::TimestampTz,
731            BuiltinType::TimestampTzArray,
732        ] {
733            for precision in 0..=6 {
734                let value = constructor(Some(TimePrecision::new(precision)));
735                assert_eq!(value.with_typmod(value.typmod()), Some(value));
736                assert_eq!(value.with_typmod(-1), Some(value.pg_type()));
737            }
738        }
739        for constructor in [BuiltinType::Interval, BuiltinType::IntervalArray] {
740            for fields in [
741                None,
742                Some(IntervalFields::Year),
743                Some(IntervalFields::Month),
744                Some(IntervalFields::Day),
745                Some(IntervalFields::Hour),
746                Some(IntervalFields::Minute),
747                Some(IntervalFields::Second),
748                Some(IntervalFields::YearToMonth),
749                Some(IntervalFields::DayToHour),
750                Some(IntervalFields::DayToMinute),
751                Some(IntervalFields::DayToSecond),
752                Some(IntervalFields::HourToMinute),
753                Some(IntervalFields::HourToSecond),
754                Some(IntervalFields::MinuteToSecond),
755            ] {
756                for precision in [None, Some(0), Some(6)] {
757                    let value = constructor(IntervalTypmod::new(fields, precision).unwrap());
758                    assert_eq!(value.with_typmod(value.typmod()), Some(value));
759                    assert_eq!(value.with_typmod(-1), Some(value.pg_type()));
760                }
761            }
762        }
763    }
764
765    #[test]
766    fn typmod_rejects_invalid_catalog_values() {
767        for &identity in BuiltinType::ALL {
768            for typmod in [i32::MIN, -2, i32::MAX] {
769                assert_eq!(identity.with_typmod(typmod), None);
770            }
771            let invalid = match identity {
772                BuiltinType::Numeric(_) | BuiltinType::NumericArray(_) => &[
773                    4,
774                    (1001 << 16) + 4,
775                    (1 << 16) + 1001 + 4,
776                    (1 << 16) + 1047 + 4,
777                    (1 << 16) + 0x800 + 4,
778                ][..],
779                BuiltinType::Varchar(_)
780                | BuiltinType::VarcharArray(_)
781                | BuiltinType::Bpchar(_)
782                | BuiltinType::BpcharArray(_) => &[0, 4, 10_485_765],
783                BuiltinType::Bit(_)
784                | BuiltinType::BitArray(_)
785                | BuiltinType::Varbit(_)
786                | BuiltinType::VarbitArray(_) => &[0, 83_886_081],
787                BuiltinType::Time(_)
788                | BuiltinType::TimeArray(_)
789                | BuiltinType::TimeTz(_)
790                | BuiltinType::TimeTzArray(_)
791                | BuiltinType::Timestamp(_)
792                | BuiltinType::TimestampArray(_)
793                | BuiltinType::TimestampTz(_)
794                | BuiltinType::TimestampTzArray(_) => &[7, 255],
795                BuiltinType::Interval(_) | BuiltinType::IntervalArray(_) => {
796                    &[0, 0x7fff_0007, 0x0001_ffff, 0x7fff_ffff]
797                }
798                _ => &[0, 1],
799            };
800            for &typmod in invalid {
801                assert_eq!(identity.with_typmod(typmod), None, "{identity:?} {typmod}");
802            }
803        }
804    }
805}