Skip to main content

uqa_sql/ast/types/
names.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Type names stream into the caller's ordinary or admitted destination without intermediate owned names.
8
9use super::ColumnType;
10use std::fmt;
11use uqa_core::{
12    memory::{Produced, ProductionControl},
13    ValueRetentionError,
14};
15
16impl ColumnType {
17    #[must_use]
18    pub fn sql_name(&self) -> String {
19        TypeName {
20            ty: self,
21            regtype: false,
22        }
23        .to_string()
24    }
25
26    /// Name emitted by `PostgreSQL`'s regtype output, including `pg_typeof`.
27    #[must_use]
28    pub fn regtype_name(&self) -> String {
29        TypeName {
30            ty: self,
31            regtype: true,
32        }
33        .to_string()
34    }
35
36    pub fn sql_name_with_control(
37        &self,
38        control: &ProductionControl<'_>,
39    ) -> Result<Produced<String>, ValueRetentionError> {
40        control.format(format_args!(
41            "{}",
42            TypeName {
43                ty: self,
44                regtype: false
45            }
46        ))
47    }
48
49    pub fn regtype_name_with_control(
50        &self,
51        control: &ProductionControl<'_>,
52    ) -> Result<Produced<String>, ValueRetentionError> {
53        control.format(format_args!(
54            "{}",
55            TypeName {
56                ty: self,
57                regtype: true
58            }
59        ))
60    }
61}
62
63struct TypeName<'a> {
64    ty: &'a ColumnType,
65    regtype: bool,
66}
67
68impl fmt::Display for TypeName<'_> {
69    #[expect(
70        clippy::too_many_lines,
71        reason = "one formatter preserves exhaustive SQL and regtype spellings"
72    )]
73    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74        if self.regtype {
75            if matches!(self.ty, ColumnType::IntervalWithFields { .. }) {
76                return f.write_str("interval");
77            }
78            if self.ty.temporal_precision().is_some() {
79                return TypeName {
80                    ty: self.ty.without_temporal_modifiers(),
81                    regtype: true,
82                }
83                .fmt(f);
84            }
85            match self.ty {
86                ColumnType::Varchar(_) => return f.write_str("character varying"),
87                ColumnType::Bit(_) => return f.write_str("bit"),
88                ColumnType::VarBit(_) => return f.write_str("bit varying"),
89                ColumnType::Bpchar | ColumnType::Character(_) => return f.write_str("character"),
90                ColumnType::Numeric { .. } => return f.write_str("numeric"),
91                ColumnType::Vector(_) => return f.write_str("vector"),
92                ColumnType::Tensor(_) => return f.write_str("tensor"),
93                ColumnType::Array(element) => {
94                    return write!(
95                        f,
96                        "{}[]",
97                        TypeName {
98                            ty: element,
99                            regtype: true
100                        }
101                    )
102                }
103                _ => {}
104            }
105        }
106        match self.ty {
107            ColumnType::Named(name) => f.write_str(name),
108            // Regtype output qualifies a user-defined type whose schema is not visible, as `format_type_be` does; other spellings name an enum without its schema.
109            ColumnType::Enum(reference) if self.regtype => f.write_str(
110                &super::display::visible_type_name(&reference.schema, &reference.name),
111            ),
112            ColumnType::Enum(reference) => f.write_str(&crate::expr::quote_ident(&reference.name)),
113            ColumnType::Composite(reference) if self.regtype => f.write_str(
114                &super::display::visible_type_name(&reference.schema, &reference.name),
115            ),
116            ColumnType::Composite(reference) => {
117                f.write_str(&crate::expr::quote_ident(&reference.name))
118            }
119            ColumnType::DeclaredRange(reference) | ColumnType::DeclaredMultirange(reference)
120                if self.regtype =>
121            {
122                f.write_str(&super::display::visible_type_name(
123                    &reference.schema,
124                    &reference.name,
125                ))
126            }
127            ColumnType::DeclaredRange(reference) | ColumnType::DeclaredMultirange(reference) => {
128                f.write_str(&crate::expr::quote_ident(&reference.name))
129            }
130            ColumnType::SmallInteger => f.write_str("smallint"),
131            ColumnType::Integer => f.write_str("integer"),
132            ColumnType::BigInteger => f.write_str("bigint"),
133            ColumnType::Oid => f.write_str("oid"),
134            ColumnType::Xid => f.write_str("xid"),
135            ColumnType::Boolean => f.write_str("boolean"),
136            ColumnType::Void => f.write_str("void"),
137            ColumnType::Text => f.write_str("text"),
138            ColumnType::RefCursor => f.write_str("refcursor"),
139            ColumnType::Name => f.write_str("name"),
140            ColumnType::Uuid => f.write_str("uuid"),
141            ColumnType::Varchar(Some(length)) => write!(f, "character varying({length})"),
142            ColumnType::Varchar(None) => f.write_str("character varying"),
143            ColumnType::Bpchar => f.write_str("bpchar"),
144            ColumnType::Character(length) => write!(f, "character({length})"),
145            ColumnType::Real => f.write_str("real"),
146            ColumnType::DoublePrecision => f.write_str("double precision"),
147            ColumnType::Numeric {
148                precision: Some(precision),
149                scale: Some(scale),
150            } => write!(f, "numeric({precision},{scale})"),
151            ColumnType::Numeric { .. } => f.write_str("numeric"),
152            ColumnType::Json => f.write_str("json"),
153            ColumnType::JsonB => f.write_str("jsonb"),
154            ColumnType::Bytea => f.write_str("bytea"),
155            ColumnType::Bit(Some(length)) => write!(f, "bit({length})"),
156            ColumnType::Bit(None) => f.write_str("\"bit\""),
157            ColumnType::VarBit(Some(length)) => write!(f, "bit varying({length})"),
158            ColumnType::VarBit(None) => f.write_str("bit varying"),
159            ColumnType::InternalChar => f.write_str("\"char\""),
160            ColumnType::Regproc => f.write_str("regproc"),
161            ColumnType::Regprocedure => f.write_str("regprocedure"),
162            ColumnType::Regclass => f.write_str("regclass"),
163            ColumnType::Regcollation => f.write_str("regcollation"),
164            ColumnType::Regnamespace => f.write_str("regnamespace"),
165            ColumnType::Regrole => f.write_str("regrole"),
166            ColumnType::Regtype => f.write_str("regtype"),
167            ColumnType::PgNodeTree => f.write_str("pg_node_tree"),
168            ColumnType::AclItem => f.write_str("aclitem"),
169            ColumnType::Int2Vector => f.write_str("int2vector"),
170            ColumnType::OidVector => f.write_str("oidvector"),
171            ColumnType::AnyArray => f.write_str("anyarray"),
172            ColumnType::Record => f.write_str("record"),
173            ColumnType::Array(element) => write!(
174                f,
175                "{}[]",
176                TypeName {
177                    ty: element,
178                    regtype: false
179                }
180            ),
181            ColumnType::Date => f.write_str("date"),
182            ColumnType::Time => f.write_str("time without time zone"),
183            ColumnType::TimePrecision(p) => write!(f, "time({p}) without time zone"),
184            ColumnType::TimeTz => f.write_str("time with time zone"),
185            ColumnType::TimeTzPrecision(p) => write!(f, "time({p}) with time zone"),
186            ColumnType::Timestamp => f.write_str("timestamp without time zone"),
187            ColumnType::TimestampPrecision(p) => write!(f, "timestamp({p}) without time zone"),
188            ColumnType::TimestampTz => f.write_str("timestamp with time zone"),
189            ColumnType::TimestampTzPrecision(p) => write!(f, "timestamp({p}) with time zone"),
190            ColumnType::Interval => f.write_str("interval"),
191            ColumnType::IntervalWithFields { fields, precision } => {
192                write!(f, "interval{}", fields.sql_suffix())?;
193                if let Some(precision) = precision {
194                    write!(f, "({precision})")?;
195                }
196                Ok(())
197            }
198            ColumnType::Range(subtype) => f.write_str(subtype.range_name()),
199            ColumnType::Multirange(subtype) => f.write_str(subtype.multirange_name()),
200            ColumnType::Vector(dimension) => write!(f, "vector({dimension})"),
201            ColumnType::Tensor(dimension) => write!(f, "tensor({dimension})"),
202            ColumnType::Domain { schema, name, .. } if self.regtype => {
203                f.write_str(&super::display::visible_type_name(schema, name))
204            }
205            ColumnType::Domain { schema, name, .. } => {
206                crate::compiler::write_relation_component(schema, f)?;
207                f.write_str(".")?;
208                crate::compiler::write_relation_component(name, f)
209            }
210        }
211    }
212}
213
214#[cfg(test)]
215mod tests;