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