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    /// `JSONB` columns store typed JSON values with `PostgreSQL` JSONB operators.
64    JsonB,
65    /// `BYTEA` columns store opaque bytes.
66    Bytea,
67    /// Fixed-length bit sequence; the unmodified catalog type has no length constraint.
68    Bit(Option<u32>),
69    /// Varying bit sequence with an optional maximum logical length.
70    VarBit(Option<u32>),
71    /// `PostgreSQL`'s internal single-byte `"char"` catalog type.
72    InternalChar,
73    Regproc,
74    /// `PostgreSQL` routine-signature object identifier (`pg_catalog.regprocedure`).
75    Regprocedure,
76    /// `PostgreSQL` relation object identifier (`pg_catalog.regclass`).
77    Regclass,
78    /// `PostgreSQL` namespace object identifier (`pg_catalog.regnamespace`).
79    Regnamespace,
80    /// `PostgreSQL` collation object identifier (`pg_catalog.regcollation`).
81    Regcollation,
82    /// `PostgreSQL` role object identifier (`pg_catalog.regrole`).
83    Regrole,
84    Regtype,
85    PgNodeTree,
86    AclItem,
87    Int2Vector,
88    OidVector,
89    AnyArray,
90    /// `PostgreSQL`'s anonymous composite pseudo-type (OID 2249).
91    Record,
92    /// A `PostgreSQL` array whose elements retain their declared SQL type.
93    /// Nested array bounds are represented recursively.
94    Array(Box<ColumnType>),
95    /// `DATE` columns store days since 1970-01-01.
96    Date,
97    /// `TIME` columns store microseconds since midnight.
98    Time,
99    /// `TIME(p)` with an explicit fractional-second precision.
100    TimePrecision(u32),
101    /// `TIME WITH TIME ZONE` columns store local time plus offset.
102    TimeTz,
103    /// `TIME(p) WITH TIME ZONE` with an explicit fractional-second precision.
104    TimeTzPrecision(u32),
105    /// `TIMESTAMP WITHOUT TIME ZONE` columns store naive microseconds
106    /// since 1970-01-01 00:00:00.
107    Timestamp,
108    /// `TIMESTAMP(p)` with an explicit fractional-second precision.
109    TimestampPrecision(u32),
110    /// `TIMESTAMP WITH TIME ZONE` columns store UTC microseconds since
111    /// 1970-01-01 00:00:00Z.
112    TimestampTz,
113    /// `TIMESTAMP(p) WITH TIME ZONE` with an explicit fractional-second precision.
114    TimestampTzPrecision(u32),
115    Interval,
116    /// An interval retaining its stored-field restriction and fractional-second precision.
117    IntervalWithFields {
118        fields: IntervalFields,
119        precision: Option<u32>,
120    },
121    /// One of `PostgreSQL`'s six built-in range identities. Values use a
122    /// canonical textual carrier so bounds remain durable across every
123    /// storage backend while the declared subtype stays in row metadata.
124    Range(RangeSubtype),
125    /// The `PostgreSQL` multirange paired with one built-in range subtype.
126    Multirange(RangeSubtype),
127    /// A catalog-bound range identity, independent of its endpoint type.
128    DeclaredRange(super::RangeTypeReference),
129    /// A catalog-bound multirange identity with its own name and array type.
130    DeclaredMultirange(super::RangeTypeReference),
131    /// `VECTOR(N)` columns store an `N`-dimensional `f32` embedding.
132    Vector(u32),
133    /// `TENSOR(N)` columns store an array of `N`-dimensional `f32`
134    /// embeddings. The row remains the retrieval identity; vector
135    /// indexes score against the best element in the tensor.
136    Tensor(u32),
137    /// A named `PostgreSQL` domain retaining both its own type identity and the
138    /// base type used for value conversion and operator selection.
139    Domain {
140        schema: String,
141        name: String,
142        oid: u32,
143        /// 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.
144        #[serde(default, skip_serializing_if = "Option::is_none")]
145        array_oid: Option<u32>,
146        /// Immutable default collation selected when the domain was declared. Legacy domains inherit the base type's collation.
147        #[serde(default, skip_serializing_if = "Option::is_none")]
148        collation_oid: Option<u32>,
149        base: Box<ColumnType>,
150    },
151    /// A user-defined enum type bound by catalog identity.
152    Enum(super::EnumTypeReference),
153    /// A composite type bound by catalog identity: a standalone composite type or a relation's row type.
154    Composite(super::CompositeTypeReference),
155}
156
157pub(crate) fn builtin_array_element_name(type_name: &str) -> Option<&'static str> {
158    Some(match type_name {
159        "_bool" => "bool",
160        "_bytea" => "bytea",
161        "_char" => "\"char\"",
162        "_name" => "name",
163        "_int8" => "int8",
164        "_int2" => "int2",
165        "_int2vector" => "int2vector",
166        "_int4" => "int4",
167        "_regproc" => "regproc",
168        "_regprocedure" => "regprocedure",
169        "_regclass" => "regclass",
170        "_regrole" => "regrole",
171        "_text" => "text",
172        "_refcursor" => "refcursor",
173        "_oid" => "oid",
174        "_oidvector" => "oidvector",
175        "_bpchar" => "bpchar",
176        "_varchar" => "varchar",
177        "_bit" => "\"bit\"",
178        "_varbit" => "varbit",
179        "_float4" => "float4",
180        "_float8" => "float8",
181        "_aclitem" => "aclitem",
182        "_date" => "date",
183        "_time" => "time",
184        "_timestamp" => "timestamp",
185        "_timestamptz" => "timestamptz",
186        "_interval" => "interval",
187        "_numeric" => "numeric",
188        "_timetz" => "timetz",
189        "_record" => "record",
190        "_uuid" => "uuid",
191        "_json" => "json",
192        "_jsonb" => "jsonb",
193        "_regtype" => "regtype",
194        "_xid" => "xid",
195        "_int4range" => "int4range",
196        "_int8range" => "int8range",
197        "_numrange" => "numrange",
198        "_daterange" => "daterange",
199        "_tsrange" => "tsrange",
200        "_tstzrange" => "tstzrange",
201        "_int4multirange" => "int4multirange",
202        "_int8multirange" => "int8multirange",
203        "_nummultirange" => "nummultirange",
204        "_datemultirange" => "datemultirange",
205        "_tsmultirange" => "tsmultirange",
206        "_tstzmultirange" => "tstzmultirange",
207        _ => return None,
208    })
209}
210
211impl ColumnType {
212    /// Whether modifier removal changes this type; a domain retains its declared base.
213    pub(crate) fn has_type_modifiers(&self) -> bool {
214        match self {
215            Self::Varchar(length) | Self::Bit(length) | Self::VarBit(length) => length.is_some(),
216            Self::Numeric { precision, scale } => precision.is_some() || scale.is_some(),
217            Self::Array(element) => element.has_type_modifiers(),
218            Self::Character(_)
219            | Self::TimePrecision(_)
220            | Self::TimeTzPrecision(_)
221            | Self::TimestampPrecision(_)
222            | Self::TimestampTzPrecision(_)
223            | Self::IntervalWithFields { .. } => true,
224            _ => false,
225        }
226    }
227
228    /// Retain the SQL type identity without a declaration's length, scale, or temporal precision.
229    #[must_use]
230    pub fn without_type_modifiers(&self) -> Self {
231        self.without_type_modifiers_with_control(
232            &uqa_core::memory::ProductionControl::uncontrolled(),
233        )
234        .expect("ordinary type modifier removal cannot be limited or cancelled")
235        .into_uncontrolled()
236        .expect("ordinary type modifier removal has no reservation")
237    }
238
239    #[must_use]
240    pub const fn temporal_precision(&self) -> Option<u32> {
241        match self {
242            Self::IntervalWithFields { precision, .. } => *precision,
243            Self::TimePrecision(p)
244            | Self::TimeTzPrecision(p)
245            | Self::TimestampPrecision(p)
246            | Self::TimestampTzPrecision(p) => Some(*p),
247            _ => None,
248        }
249    }
250
251    #[must_use]
252    pub const fn without_temporal_modifiers(&self) -> &Self {
253        match self {
254            Self::IntervalWithFields { .. } => &Self::Interval,
255            Self::TimePrecision(_) => &Self::Time,
256            Self::TimeTzPrecision(_) => &Self::TimeTz,
257            Self::TimestampPrecision(_) => &Self::Timestamp,
258            Self::TimestampTzPrecision(_) => &Self::TimestampTz,
259            other => other,
260        }
261    }
262
263    pub(crate) fn with_temporal_precision(
264        self,
265        precision: Option<i64>,
266    ) -> Result<Self, crate::SQLError> {
267        let Some(precision) = precision else {
268            return Ok(self);
269        };
270        if precision < 0 {
271            return Err(crate::SQLError::Routine {
272                sqlstate: "22023".into(),
273                message: format!(
274                    "{} precision must not be negative",
275                    self.regtype_name().to_uppercase()
276                ),
277            });
278        }
279        let precision = u32::try_from(precision.min(6)).expect("bounded temporal precision");
280        Ok(match self {
281            Self::Time => Self::TimePrecision(precision),
282            Self::TimeTz => Self::TimeTzPrecision(precision),
283            Self::Timestamp => Self::TimestampPrecision(precision),
284            Self::TimestampTz => Self::TimestampTzPrecision(precision),
285            other => other,
286        })
287    }
288
289    pub(crate) fn with_interval_modifiers(
290        fields: IntervalFields,
291        precision: Option<i64>,
292    ) -> Result<Self, crate::SQLError> {
293        let precision = precision
294            .map(|precision| {
295                if precision < 0 {
296                    return Err(crate::SQLError::Routine {
297                        sqlstate: "22023".into(),
298                        message: "INTERVAL precision must not be negative".into(),
299                    });
300                }
301                Ok(u32::try_from(precision.min(6)).expect("bounded interval precision"))
302            })
303            .transpose()?;
304        if fields == IntervalFields::All && precision.is_none() {
305            return Ok(Self::Interval);
306        }
307        Ok(Self::IntervalWithFields { fields, precision })
308    }
309
310    #[must_use]
311    pub fn is_integer(&self) -> bool {
312        match self {
313            Self::SmallInteger | Self::Integer | Self::BigInteger | Self::Oid | Self::Xid => true,
314            Self::Domain { base, .. } => base.is_integer(),
315            _ => false,
316        }
317    }
318
319    #[must_use]
320    pub fn is_character_string(&self) -> bool {
321        match self {
322            Self::Text
323            | Self::Name
324            | Self::Varchar(_)
325            | Self::Bpchar
326            | Self::Character(_)
327            | Self::InternalChar
328            | Self::PgNodeTree
329            | Self::AclItem => true,
330            Self::Domain { base, .. } => base.is_character_string(),
331            _ => false,
332        }
333    }
334}