Skip to main content

uqa_sql/ast/types/
parsing.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Canonical type parsing keeps normalized spelling and nested result constructors in distinct resource owners.
8
9use super::{builtin_array_element_name, split_type_modifier_with_control, ColumnType};
10use crate::ast::{IntervalFields, RangeSubtype};
11use std::borrow::Cow;
12use uqa_core::memory::{Produced, ProductionControl, ProductionString};
13use uqa_core::ValueRetentionError;
14
15impl ColumnType {
16    /// Parse the canonical or accepted spelling of one implemented SQL type.
17    pub fn from_sql_name(name: &str) -> Result<Self, crate::SQLError> {
18        Self::from_sql_name_with_control(name, &ProductionControl::uncontrolled()).map(|value| {
19            value
20                .into_uncontrolled()
21                .expect("ordinary type parsing has no reservation")
22        })
23    }
24
25    /// Parse through the same grammar while each temporary name and nested result allocation uses the caller's allowance.
26    #[expect(
27        clippy::too_many_lines,
28        reason = "one type grammar preserves every accepted spelling and diagnostic"
29    )]
30    pub fn from_sql_name_with_control(
31        name: &str,
32        control: &ProductionControl<'_>,
33    ) -> Result<Produced<Self>, crate::SQLError> {
34        let normalized = normalized_type_name(name, control)?;
35        if let Some(element) = builtin_array_element_name(&normalized) {
36            return Self::array_with_control(
37                Self::from_sql_name_with_control(element, control)?,
38                control,
39            )
40            .map_err(Into::into);
41        }
42        if let Some(element) = normalized.strip_suffix("[]") {
43            let element_type = Self::from_sql_name_with_control(element, control)?;
44            if matches!(*element_type, Self::Void | Self::PgNodeTree) {
45                return Err(crate::SQLError::Routine {
46                    sqlstate: "42704".into(),
47                    message: format!("type \"{}\" does not exist", normalized.as_ref()),
48                });
49            }
50            return Self::array_with_control(element_type, control).map_err(Into::into);
51        }
52        let (base, modifier) = split_type_modifier_with_control(&normalized, control)?;
53        let catalog_name = base
54            .strip_prefix("pg_catalog.")
55            .or_else(|| base.strip_prefix("\"pg_catalog\"."));
56        let catalog_modifiers = catalog_name.is_some() || base.starts_with('"');
57        let catalog_type;
58        let base = if let Some(name) =
59            catalog_name.or_else(|| base.strip_prefix('"').map(|_| &**base))
60        {
61            let name = name
62                .strip_prefix('"')
63                .and_then(|name| name.strip_suffix('"'))
64                .unwrap_or(name);
65            if let Some(element) = builtin_array_element_name(name) {
66                return Self::array_with_control(
67                    Self::from_sql_name_with_control(element, control)?,
68                    control,
69                )
70                .map_err(Into::into);
71            }
72            let ty = crate::catalog::type_metadata::builtin_scalar_type_by_name(name).ok_or_else(
73                || crate::SQLError::Unsupported(format!("SQL type `{}` is not supported", &**base)),
74            )?;
75            // Catalog identity without a modifier already determines the type. Regtype output is display syntax: bpchar prints as character, whose input spelling implies a length of one.
76            if modifier.is_none() && !matches!(ty, Self::Vector(_) | Self::Tensor(_)) {
77                return ty.clone_with_control(control).map_err(Into::into);
78            }
79            catalog_type = ty.regtype_name_with_control(control)?;
80            catalog_type.as_str()
81        } else {
82            &base
83        };
84        let temporal_precision = || {
85            modifier
86                .map(|value| {
87                    value.trim().parse::<i64>().map_err(|_| {
88                        crate::SQLError::TypeMismatch(format!(
89                            "invalid temporal precision: {value}"
90                        ))
91                    })
92                })
93                .transpose()
94        };
95        let character_length = || -> Result<Option<u32>, crate::SQLError> {
96            modifier
97                .map(|value| {
98                    value
99                        .parse::<u32>()
100                        .ok()
101                        .filter(|length| *length > 0)
102                        .ok_or_else(|| {
103                            crate::SQLError::TypeMismatch(format!(
104                                "character length must be greater than zero, got {value}"
105                            ))
106                        })
107                })
108                .transpose()
109        };
110        let parsed = match base {
111            "smallint" | "int2" => Ok(Self::SmallInteger),
112            "integer" | "int" | "int4" => Ok(Self::Integer),
113            "bigint" | "int8" => Ok(Self::BigInteger),
114            "oid" => Ok(Self::Oid),
115            "xid" => Ok(Self::Xid),
116            "boolean" | "bool" => Ok(Self::Boolean),
117            "void" => Ok(Self::Void),
118            "text" => Ok(Self::Text),
119            "refcursor" => Ok(Self::RefCursor),
120            "name" => Ok(Self::Name),
121            "uuid" => Ok(Self::Uuid),
122            "varchar" | "character varying" => Ok(Self::Varchar(character_length()?)),
123            "character" | "char" => Ok(Self::Character(character_length()?.unwrap_or(1))),
124            "bpchar" => Ok(character_length()?.map_or(Self::Bpchar, Self::Character)),
125            "real" | "float4" => Ok(Self::Real),
126            "double" | "double precision" | "float8" => Ok(Self::DoublePrecision),
127            "numeric" | "decimal" => {
128                let (precision, scale) = match modifier {
129                    None => (None, None),
130                    Some(modifier) => {
131                        let mut parts = modifier.split(',').map(str::trim);
132                        let precision = parts
133                            .next()
134                            .and_then(|value| value.parse::<u32>().ok())
135                            .ok_or_else(|| {
136                                crate::SQLError::TypeMismatch(format!(
137                                    "invalid numeric modifier `{modifier}`"
138                                ))
139                            })?;
140                        let scale = parts
141                            .next()
142                            .map(|value| value.parse::<i32>())
143                            .transpose()
144                            .map_err(|_| {
145                                crate::SQLError::TypeMismatch(format!(
146                                    "invalid numeric modifier `{modifier}`"
147                                ))
148                            })?
149                            .unwrap_or(0);
150                        if parts.next().is_some() {
151                            return Err(crate::SQLError::TypeMismatch(format!(
152                                "invalid numeric modifier `{modifier}`"
153                            )));
154                        }
155                        (Some(precision), Some(scale))
156                    }
157                };
158                Ok(Self::Numeric { precision, scale })
159            }
160            "json" => Ok(Self::Json),
161            "jsonb" => Ok(Self::JsonB),
162            "bytea" => Ok(Self::Bytea),
163            "bit" | "bit varying" | "varbit" => {
164                use crate::expr::bit_string::BitStringKind;
165                let kind = if base == "bit" {
166                    BitStringKind::Fixed
167                } else {
168                    BitStringKind::Varying
169                };
170                let length = modifier
171                    .map(|text| {
172                        let length = text.parse::<i64>().map_err(|_| crate::SQLError::Routine {
173                            sqlstate: "22023".into(),
174                            message: "invalid type modifier".into(),
175                        })?;
176                        kind.validate_length(length)
177                    })
178                    .transpose()?;
179                Ok(if kind == BitStringKind::Fixed {
180                    Self::Bit(length.or(Some(1)))
181                } else {
182                    Self::VarBit(length)
183                })
184            }
185            "\"char\"" => Ok(Self::InternalChar),
186            "regproc" => Ok(Self::Regproc),
187            "regprocedure" => Ok(Self::Regprocedure),
188            "regclass" => Ok(Self::Regclass),
189            "regcollation" => Ok(Self::Regcollation),
190            "regnamespace" => Ok(Self::Regnamespace),
191            "regrole" => Ok(Self::Regrole),
192            "regtype" => Ok(Self::Regtype),
193            "pg_node_tree" => Ok(Self::PgNodeTree),
194            "aclitem" => Ok(Self::AclItem),
195            "int2vector" => Ok(Self::Int2Vector),
196            "oidvector" => Ok(Self::OidVector),
197            "anyarray" => Ok(Self::AnyArray),
198            "record" => Ok(Self::Record),
199            "date" => Ok(Self::Date),
200            "time" | "time without time zone" => {
201                Self::Time.with_temporal_precision(temporal_precision()?)
202            }
203            "timetz" | "time with time zone" => {
204                Self::TimeTz.with_temporal_precision(temporal_precision()?)
205            }
206            "timestamp" | "datetime" | "timestamp without time zone" => {
207                Self::Timestamp.with_temporal_precision(temporal_precision()?)
208            }
209            "timestamptz" | "timestamp with time zone" => {
210                Self::TimestampTz.with_temporal_precision(temporal_precision()?)
211            }
212            "interval" if catalog_modifiers => catalog_interval_type(modifier),
213            "interval" => Self::with_interval_modifiers(IntervalFields::All, temporal_precision()?),
214            other if other.starts_with("interval ") => {
215                let fields = IntervalFields::from_sql_suffix(&other[9..]).ok_or_else(|| {
216                    crate::SQLError::TypeMismatch(format!("invalid interval fields: {other}"))
217                })?;
218                Self::with_interval_modifiers(fields, temporal_precision()?)
219            }
220            "int4range" => Ok(Self::Range(RangeSubtype::Integer)),
221            "int8range" => Ok(Self::Range(RangeSubtype::BigInteger)),
222            "numrange" => Ok(Self::Range(RangeSubtype::Numeric)),
223            "daterange" => Ok(Self::Range(RangeSubtype::Date)),
224            "tsrange" => Ok(Self::Range(RangeSubtype::Timestamp)),
225            "tstzrange" => Ok(Self::Range(RangeSubtype::TimestampTz)),
226            "int4multirange" => Ok(Self::Multirange(RangeSubtype::Integer)),
227            "int8multirange" => Ok(Self::Multirange(RangeSubtype::BigInteger)),
228            "nummultirange" => Ok(Self::Multirange(RangeSubtype::Numeric)),
229            "datemultirange" => Ok(Self::Multirange(RangeSubtype::Date)),
230            "tsmultirange" => Ok(Self::Multirange(RangeSubtype::Timestamp)),
231            "tstzmultirange" => Ok(Self::Multirange(RangeSubtype::TimestampTz)),
232            "vector" => modifier
233                .and_then(|value| value.parse::<u32>().ok())
234                .filter(|dimension| *dimension > 0)
235                .map(Self::Vector)
236                .ok_or_else(|| crate::SQLError::TypeMismatch("VECTOR requires a dimension".into())),
237            "tensor" => modifier
238                .and_then(|value| value.parse::<u32>().ok())
239                .filter(|dimension| *dimension > 0)
240                .map(Self::Tensor)
241                .ok_or_else(|| crate::SQLError::TypeMismatch("TENSOR requires a dimension".into())),
242            other => Err(crate::SQLError::Unsupported(format!(
243                "SQL type `{other}` is not supported"
244            ))),
245        }?;
246        control
247            .finish(parsed, control.empty_reservation())
248            .map_err(Into::into)
249    }
250}
251
252fn normalized_type_name<'a>(
253    name: &'a str,
254    control: &ProductionControl<'_>,
255) -> Result<Produced<Cow<'a, str>>, ValueRetentionError> {
256    control.check()?;
257    let name = name.trim();
258    let mut uppercase = false;
259    for chunk in name.as_bytes().chunks(4096) {
260        control.check()?;
261        if chunk.iter().any(u8::is_ascii_uppercase) {
262            uppercase = true;
263            break;
264        }
265    }
266    if !uppercase {
267        return control.finish(Cow::Borrowed(name), control.empty_reservation());
268    }
269    let mut normalized = ProductionString::new(*control);
270    normalized.reserve(name.len())?;
271    let mut quoted = false;
272    for character in name.chars() {
273        if character == '"' {
274            quoted = !quoted;
275        }
276        normalized.push(if quoted {
277            character
278        } else {
279            character.to_ascii_lowercase()
280        })?;
281    }
282    let (normalized, memory) = normalized.finish()?.into_parts();
283    control.finish(Cow::Owned(normalized), memory)
284}
285
286fn catalog_interval_type(modifier: Option<&str>) -> Result<ColumnType, crate::SQLError> {
287    let Some(modifier) = modifier else {
288        return Ok(ColumnType::Interval);
289    };
290    let mut parts = modifier.split(',').map(str::trim);
291    let mask = parts
292        .next()
293        .and_then(|mask| mask.parse::<i64>().ok())
294        .and_then(IntervalFields::from_modifier_mask)
295        .ok_or_else(|| crate::SQLError::TypeMismatch("invalid interval fields".into()))?;
296    let precision = parts
297        .next()
298        .map(|precision| {
299            precision.parse::<i64>().map_err(|_| {
300                crate::SQLError::TypeMismatch(format!("invalid temporal precision: {precision}"))
301            })
302        })
303        .transpose()?;
304    if parts.next().is_some() {
305        return Err(crate::SQLError::TypeMismatch(
306            "invalid interval type modifier".into(),
307        ));
308    }
309    ColumnType::with_interval_modifiers(mask, precision)
310}