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            "xml" => Ok(Self::Xml),
162            "jsonb" => Ok(Self::JsonB),
163            "bytea" => Ok(Self::Bytea),
164            "bit" | "bit varying" | "varbit" => {
165                use crate::expr::bit_string::BitStringKind;
166                let kind = if base == "bit" {
167                    BitStringKind::Fixed
168                } else {
169                    BitStringKind::Varying
170                };
171                let length = modifier
172                    .map(|text| {
173                        let length = text.parse::<i64>().map_err(|_| crate::SQLError::Routine {
174                            sqlstate: "22023".into(),
175                            message: "invalid type modifier".into(),
176                        })?;
177                        kind.validate_length(length)
178                    })
179                    .transpose()?;
180                Ok(if kind == BitStringKind::Fixed {
181                    Self::Bit(length.or(Some(1)))
182                } else {
183                    Self::VarBit(length)
184                })
185            }
186            "\"char\"" => Ok(Self::InternalChar),
187            "regproc" => Ok(Self::Regproc),
188            "regprocedure" => Ok(Self::Regprocedure),
189            "regclass" => Ok(Self::Regclass),
190            "regcollation" => Ok(Self::Regcollation),
191            "regnamespace" => Ok(Self::Regnamespace),
192            "regrole" => Ok(Self::Regrole),
193            "regtype" => Ok(Self::Regtype),
194            "pg_node_tree" => Ok(Self::PgNodeTree),
195            "aclitem" => Ok(Self::AclItem),
196            "int2vector" => Ok(Self::Int2Vector),
197            "oidvector" => Ok(Self::OidVector),
198            "anyarray" => Ok(Self::AnyArray),
199            "record" => Ok(Self::Record),
200            "date" => Ok(Self::Date),
201            "time" | "time without time zone" => {
202                Self::Time.with_temporal_precision(temporal_precision()?)
203            }
204            "timetz" | "time with time zone" => {
205                Self::TimeTz.with_temporal_precision(temporal_precision()?)
206            }
207            "timestamp" | "datetime" | "timestamp without time zone" => {
208                Self::Timestamp.with_temporal_precision(temporal_precision()?)
209            }
210            "timestamptz" | "timestamp with time zone" => {
211                Self::TimestampTz.with_temporal_precision(temporal_precision()?)
212            }
213            "interval" if catalog_modifiers => catalog_interval_type(modifier),
214            "interval" => Self::with_interval_modifiers(IntervalFields::All, temporal_precision()?),
215            other if other.starts_with("interval ") => {
216                let fields = IntervalFields::from_sql_suffix(&other[9..]).ok_or_else(|| {
217                    crate::SQLError::TypeMismatch(format!("invalid interval fields: {other}"))
218                })?;
219                Self::with_interval_modifiers(fields, temporal_precision()?)
220            }
221            "int4range" => Ok(Self::Range(RangeSubtype::Integer)),
222            "int8range" => Ok(Self::Range(RangeSubtype::BigInteger)),
223            "numrange" => Ok(Self::Range(RangeSubtype::Numeric)),
224            "daterange" => Ok(Self::Range(RangeSubtype::Date)),
225            "tsrange" => Ok(Self::Range(RangeSubtype::Timestamp)),
226            "tstzrange" => Ok(Self::Range(RangeSubtype::TimestampTz)),
227            "int4multirange" => Ok(Self::Multirange(RangeSubtype::Integer)),
228            "int8multirange" => Ok(Self::Multirange(RangeSubtype::BigInteger)),
229            "nummultirange" => Ok(Self::Multirange(RangeSubtype::Numeric)),
230            "datemultirange" => Ok(Self::Multirange(RangeSubtype::Date)),
231            "tsmultirange" => Ok(Self::Multirange(RangeSubtype::Timestamp)),
232            "tstzmultirange" => Ok(Self::Multirange(RangeSubtype::TimestampTz)),
233            "vector" => modifier
234                .and_then(|value| value.parse::<u32>().ok())
235                .filter(|dimension| *dimension > 0)
236                .map(Self::Vector)
237                .ok_or_else(|| crate::SQLError::TypeMismatch("VECTOR requires a dimension".into())),
238            "tensor" => modifier
239                .and_then(|value| value.parse::<u32>().ok())
240                .filter(|dimension| *dimension > 0)
241                .map(Self::Tensor)
242                .ok_or_else(|| crate::SQLError::TypeMismatch("TENSOR requires a dimension".into())),
243            other => Err(crate::SQLError::Unsupported(format!(
244                "SQL type `{other}` is not supported"
245            ))),
246        }?;
247        control
248            .finish(parsed, control.empty_reservation())
249            .map_err(Into::into)
250    }
251}
252
253fn normalized_type_name<'a>(
254    name: &'a str,
255    control: &ProductionControl<'_>,
256) -> Result<Produced<Cow<'a, str>>, ValueRetentionError> {
257    control.check()?;
258    let name = name.trim();
259    let mut uppercase = false;
260    for chunk in name.as_bytes().chunks(4096) {
261        control.check()?;
262        if chunk.iter().any(u8::is_ascii_uppercase) {
263            uppercase = true;
264            break;
265        }
266    }
267    if !uppercase {
268        return control.finish(Cow::Borrowed(name), control.empty_reservation());
269    }
270    let mut normalized = ProductionString::new(*control);
271    normalized.reserve(name.len())?;
272    let mut quoted = false;
273    for character in name.chars() {
274        if character == '"' {
275            quoted = !quoted;
276        }
277        normalized.push(if quoted {
278            character
279        } else {
280            character.to_ascii_lowercase()
281        })?;
282    }
283    let (normalized, memory) = normalized.finish()?.into_parts();
284    control.finish(Cow::Owned(normalized), memory)
285}
286
287fn catalog_interval_type(modifier: Option<&str>) -> Result<ColumnType, crate::SQLError> {
288    let Some(modifier) = modifier else {
289        return Ok(ColumnType::Interval);
290    };
291    let mut parts = modifier.split(',').map(str::trim);
292    let mask = parts
293        .next()
294        .and_then(|mask| mask.parse::<i64>().ok())
295        .and_then(IntervalFields::from_modifier_mask)
296        .ok_or_else(|| crate::SQLError::TypeMismatch("invalid interval fields".into()))?;
297    let precision = parts
298        .next()
299        .map(|precision| {
300            precision.parse::<i64>().map_err(|_| {
301                crate::SQLError::TypeMismatch(format!("invalid temporal precision: {precision}"))
302            })
303        })
304        .transpose()?;
305    if parts.next().is_some() {
306        return Err(crate::SQLError::TypeMismatch(
307            "invalid interval type modifier".into(),
308        ));
309    }
310    ColumnType::with_interval_modifiers(mask, precision)
311}