Skip to main content

uqa_sql/ast/
types.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7use serde::{Deserialize, Serialize};
8
9use super::{IntervalFields, RangeSubtype};
10
11mod catalog_names;
12mod display;
13mod identity;
14mod modifiers;
15mod names;
16mod parsing;
17mod production;
18mod references;
19
20pub use display::TypeDisplayScope;
21pub use identity::{UserTypeIdentity, UserTypeKind};
22
23pub(crate) use modifiers::split_type_modifier_with_control;
24
25#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
26pub enum ColumnType {
27    /// A declaration awaiting catalog type resolution. This variant is never a stored column type.
28    Named(String),
29    SmallInteger,
30    Integer,
31    BigInteger,
32    /// `PostgreSQL` object identifier (`pg_catalog.oid`).
33    Oid,
34    /// `PostgreSQL` transaction identifier (`pg_catalog.xid`).
35    Xid,
36    Boolean,
37    /// `PostgreSQL`'s non-null zero-width `void` pseudo-type.
38    Void,
39    Text,
40    /// `PostgreSQL` cursor portal name (`pg_catalog.refcursor`).
41    RefCursor,
42    Name,
43    Uuid,
44    Varchar(Option<u32>),
45    /// Internal unconstrained `bpchar` type used after common-type selection.
46    Bpchar,
47    /// `PostgreSQL` blank-padded `CHARACTER(n)` / `CHAR(n)` (`bpchar`).
48    /// The length counts Unicode scalar values and defaults to one when the
49    /// declaration omits an explicit modifier.
50    Character(u32),
51    Real,
52    DoublePrecision,
53    /// `NUMERIC(precision, scale)` -- exact decimal storage. When
54    /// `scale` is `Some(s)` the engine rounds `INSERT` values to `s`
55    /// fractional digits. `precision` is captured for round-tripping
56    /// the catalog text but is not currently enforced.
57    Numeric {
58        precision: Option<u32>,
59        scale: Option<i32>,
60    },
61    /// `JSON` / `JSONB` columns store typed JSON values.
62    Json,
63    /// Native SQL/XML value; its textual carrier retains the original admitted input.
64    Xml,
65    /// `JSONB` columns store typed JSON values with `PostgreSQL` JSONB operators.
66    JsonB,
67    /// `BYTEA` columns store opaque bytes.
68    Bytea,
69    /// Fixed-length bit sequence; the unmodified catalog type has no length constraint.
70    Bit(Option<u32>),
71    /// Varying bit sequence with an optional maximum logical length.
72    VarBit(Option<u32>),
73    /// `PostgreSQL`'s internal single-byte `"char"` catalog type.
74    InternalChar,
75    Regproc,
76    /// `PostgreSQL` routine-signature object identifier (`pg_catalog.regprocedure`).
77    Regprocedure,
78    /// `PostgreSQL` relation object identifier (`pg_catalog.regclass`).
79    Regclass,
80    /// `PostgreSQL` namespace object identifier (`pg_catalog.regnamespace`).
81    Regnamespace,
82    /// `PostgreSQL` collation object identifier (`pg_catalog.regcollation`).
83    Regcollation,
84    /// `PostgreSQL` role object identifier (`pg_catalog.regrole`).
85    Regrole,
86    Regtype,
87    PgNodeTree,
88    AclItem,
89    Int2Vector,
90    OidVector,
91    AnyArray,
92    /// `PostgreSQL`'s anonymous composite pseudo-type (OID 2249).
93    Record,
94    /// A `PostgreSQL` array whose elements retain their declared SQL type.
95    /// Nested array bounds are represented recursively.
96    Array(Box<ColumnType>),
97    /// `DATE` columns store days since 1970-01-01.
98    Date,
99    /// `TIME` columns store microseconds since midnight.
100    Time,
101    /// `TIME(p)` with an explicit fractional-second precision.
102    TimePrecision(u32),
103    /// `TIME WITH TIME ZONE` columns store local time plus offset.
104    TimeTz,
105    /// `TIME(p) WITH TIME ZONE` with an explicit fractional-second precision.
106    TimeTzPrecision(u32),
107    /// `TIMESTAMP WITHOUT TIME ZONE` columns store naive microseconds
108    /// since 1970-01-01 00:00:00.
109    Timestamp,
110    /// `TIMESTAMP(p)` with an explicit fractional-second precision.
111    TimestampPrecision(u32),
112    /// `TIMESTAMP WITH TIME ZONE` columns store UTC microseconds since
113    /// 1970-01-01 00:00:00Z.
114    TimestampTz,
115    /// `TIMESTAMP(p) WITH TIME ZONE` with an explicit fractional-second precision.
116    TimestampTzPrecision(u32),
117    Interval,
118    /// An interval retaining its stored-field restriction and fractional-second precision.
119    IntervalWithFields {
120        fields: IntervalFields,
121        precision: Option<u32>,
122    },
123    /// One of `PostgreSQL`'s six built-in range identities. Values use a
124    /// canonical textual carrier so bounds remain durable across every
125    /// storage backend while the declared subtype stays in row metadata.
126    Range(RangeSubtype),
127    /// The `PostgreSQL` multirange paired with one built-in range subtype.
128    Multirange(RangeSubtype),
129    /// A catalog-bound range identity, independent of its endpoint type.
130    DeclaredRange(super::RangeTypeReference),
131    /// A catalog-bound multirange identity with its own name and array type.
132    DeclaredMultirange(super::RangeTypeReference),
133    /// `VECTOR(N)` columns store an `N`-dimensional `f32` embedding.
134    Vector(u32),
135    /// `TENSOR(N)` columns store an array of `N`-dimensional `f32`
136    /// embeddings. The row remains the retrieval identity; vector
137    /// indexes score against the best element in the tensor.
138    Tensor(u32),
139    /// A named `PostgreSQL` domain retaining both its own type identity and the
140    /// base type used for value conversion and operator selection.
141    Domain {
142        schema: String,
143        name: String,
144        oid: u32,
145        /// The OID of the domain's generated array type, allocated with the domain. Domains created before array OIDs were recorded derive it from the domain OID.
146        #[serde(default, skip_serializing_if = "Option::is_none")]
147        array_oid: Option<u32>,
148        /// Immutable default collation selected when the domain was declared. Legacy domains inherit the base type's collation.
149        #[serde(default, skip_serializing_if = "Option::is_none")]
150        collation_oid: Option<u32>,
151        base: Box<ColumnType>,
152    },
153    /// A user-defined enum type bound by catalog identity.
154    Enum(super::EnumTypeReference),
155    /// A composite type bound by catalog identity: a standalone composite type or a relation's row type.
156    Composite(super::CompositeTypeReference),
157}
158
159pub(crate) fn builtin_array_element_name(type_name: &str) -> Option<&'static str> {
160    Some(match type_name {
161        "_bool" => "bool",
162        "_bytea" => "bytea",
163        "_char" => "\"char\"",
164        "_name" => "name",
165        "_int8" => "int8",
166        "_int2" => "int2",
167        "_int2vector" => "int2vector",
168        "_int4" => "int4",
169        "_regproc" => "regproc",
170        "_regprocedure" => "regprocedure",
171        "_regclass" => "regclass",
172        "_regrole" => "regrole",
173        "_text" => "text",
174        "_refcursor" => "refcursor",
175        "_oid" => "oid",
176        "_oidvector" => "oidvector",
177        "_bpchar" => "bpchar",
178        "_varchar" => "varchar",
179        "_bit" => "\"bit\"",
180        "_varbit" => "varbit",
181        "_float4" => "float4",
182        "_float8" => "float8",
183        "_aclitem" => "aclitem",
184        "_date" => "date",
185        "_time" => "time",
186        "_timestamp" => "timestamp",
187        "_timestamptz" => "timestamptz",
188        "_interval" => "interval",
189        "_numeric" => "numeric",
190        "_timetz" => "timetz",
191        "_record" => "record",
192        "_uuid" => "uuid",
193        "_json" => "json",
194        "_xml" => "xml",
195        "_jsonb" => "jsonb",
196        "_regtype" => "regtype",
197        "_xid" => "xid",
198        "_int4range" => "int4range",
199        "_int8range" => "int8range",
200        "_numrange" => "numrange",
201        "_daterange" => "daterange",
202        "_tsrange" => "tsrange",
203        "_tstzrange" => "tstzrange",
204        "_int4multirange" => "int4multirange",
205        "_int8multirange" => "int8multirange",
206        "_nummultirange" => "nummultirange",
207        "_datemultirange" => "datemultirange",
208        "_tsmultirange" => "tsmultirange",
209        "_tstzmultirange" => "tstzmultirange",
210        _ => return None,
211    })
212}
213
214impl ColumnType {
215    /// `PostgreSQL`'s array element identity is independent of its number of dimensions. A domain element remains a domain even when its own base type is an array.
216    #[must_use]
217    pub fn array_element_type(&self) -> Option<&Self> {
218        let Self::Array(element) = self else {
219            return None;
220        };
221        let mut element = element;
222        while let Self::Array(inner) = element.as_ref() {
223            element = inner;
224        }
225        Some(element)
226    }
227
228    /// Whether modifier removal changes this type; a domain retains its declared base.
229    pub(crate) fn has_type_modifiers(&self) -> bool {
230        match self {
231            Self::Varchar(length) | Self::Bit(length) | Self::VarBit(length) => length.is_some(),
232            Self::Numeric { precision, scale } => precision.is_some() || scale.is_some(),
233            Self::Array(element) => element.has_type_modifiers(),
234            Self::Character(_)
235            | Self::TimePrecision(_)
236            | Self::TimeTzPrecision(_)
237            | Self::TimestampPrecision(_)
238            | Self::TimestampTzPrecision(_)
239            | Self::IntervalWithFields { .. } => true,
240            _ => false,
241        }
242    }
243
244    /// Retain the SQL type identity without a declaration's length, scale, or temporal precision.
245    #[must_use]
246    pub fn without_type_modifiers(&self) -> Self {
247        self.without_type_modifiers_with_control(
248            &uqa_core::memory::ProductionControl::uncontrolled(),
249        )
250        .expect("ordinary type modifier removal cannot be limited or cancelled")
251        .into_uncontrolled()
252        .expect("ordinary type modifier removal has no reservation")
253    }
254
255    #[must_use]
256    pub const fn temporal_precision(&self) -> Option<u32> {
257        match self {
258            Self::IntervalWithFields { precision, .. } => *precision,
259            Self::TimePrecision(p)
260            | Self::TimeTzPrecision(p)
261            | Self::TimestampPrecision(p)
262            | Self::TimestampTzPrecision(p) => Some(*p),
263            _ => None,
264        }
265    }
266
267    #[must_use]
268    pub const fn without_temporal_modifiers(&self) -> &Self {
269        match self {
270            Self::IntervalWithFields { .. } => &Self::Interval,
271            Self::TimePrecision(_) => &Self::Time,
272            Self::TimeTzPrecision(_) => &Self::TimeTz,
273            Self::TimestampPrecision(_) => &Self::Timestamp,
274            Self::TimestampTzPrecision(_) => &Self::TimestampTz,
275            other => other,
276        }
277    }
278
279    pub(crate) fn with_temporal_precision(
280        self,
281        precision: Option<i64>,
282    ) -> Result<Self, crate::SQLError> {
283        let Some(precision) = precision else {
284            return Ok(self);
285        };
286        if precision < 0 {
287            return Err(crate::SQLError::Routine {
288                sqlstate: "22023".into(),
289                message: format!(
290                    "{} precision must not be negative",
291                    self.regtype_name().to_uppercase()
292                ),
293            });
294        }
295        let precision = u32::try_from(precision.min(6)).expect("bounded temporal precision");
296        Ok(match self {
297            Self::Time => Self::TimePrecision(precision),
298            Self::TimeTz => Self::TimeTzPrecision(precision),
299            Self::Timestamp => Self::TimestampPrecision(precision),
300            Self::TimestampTz => Self::TimestampTzPrecision(precision),
301            other => other,
302        })
303    }
304
305    pub(crate) fn with_interval_modifiers(
306        fields: IntervalFields,
307        precision: Option<i64>,
308    ) -> Result<Self, crate::SQLError> {
309        let precision = precision
310            .map(|precision| {
311                if precision < 0 {
312                    return Err(crate::SQLError::Routine {
313                        sqlstate: "22023".into(),
314                        message: "INTERVAL precision must not be negative".into(),
315                    });
316                }
317                Ok(u32::try_from(precision.min(6)).expect("bounded interval precision"))
318            })
319            .transpose()?;
320        if fields == IntervalFields::All && precision.is_none() {
321            return Ok(Self::Interval);
322        }
323        Ok(Self::IntervalWithFields { fields, precision })
324    }
325
326    #[must_use]
327    pub fn is_integer(&self) -> bool {
328        match self {
329            Self::SmallInteger | Self::Integer | Self::BigInteger | Self::Oid | Self::Xid => true,
330            Self::Domain { base, .. } => base.is_integer(),
331            _ => false,
332        }
333    }
334
335    #[must_use]
336    pub fn is_character_string(&self) -> bool {
337        match self {
338            Self::Text
339            | Self::Name
340            | Self::Varchar(_)
341            | Self::Bpchar
342            | Self::Character(_)
343            | Self::InternalChar
344            | Self::PgNodeTree
345            | Self::AclItem => true,
346            Self::Domain { base, .. } => base.is_character_string(),
347            _ => false,
348        }
349    }
350}