Skip to main content

uqa_sql/schema/
type_objects.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Targets of `ALTER TYPE | DOMAIN` and `GRANT | REVOKE ... ON TYPE | DOMAIN`: the user-defined type a name resolves to, and `PostgreSQL`'s diagnostics for the types a command cannot change. Each command applies the checks in its own `PostgreSQL` order.
8
9use crate::ast::{ObjectAclEntry, TypeObjectKind};
10use crate::catalog::{
11    composite_type::StoredComposite, domain::StoredDomain, enum_type::StoredEnum,
12};
13use crate::schema::domains::removal::{RowTypeRelation, TypeObjectBinding};
14use crate::SQLError;
15use uqa_core::{catalog_role::RoleIdentity, RelationIdentity};
16
17/// A user-defined type whose catalog definition a lifecycle command changes. A completed type's generated array follows it.
18#[derive(Debug, Clone)]
19pub enum TypeObject {
20    Shell(crate::catalog::shell_type::StoredShellType),
21    Enum(StoredEnum),
22    Domain(Box<StoredDomain>),
23    /// A standalone composite type, whose relation follows it.
24    Composite(Box<StoredComposite>),
25}
26
27impl TypeObject {
28    #[must_use]
29    pub fn oid(&self) -> u32 {
30        match self {
31            Self::Shell(definition) => definition.oid,
32            Self::Enum(definition) => definition.oid,
33            Self::Domain(domain) => domain.oid,
34            Self::Composite(definition) => definition.oid,
35        }
36    }
37
38    #[must_use]
39    pub fn identity(&self) -> &RelationIdentity {
40        match self {
41            Self::Shell(definition) => &definition.identity,
42            Self::Enum(definition) => &definition.identity,
43            Self::Domain(domain) => &domain.identity,
44            Self::Composite(definition) => &definition.identity,
45        }
46    }
47
48    #[must_use]
49    pub fn owner(&self) -> RoleIdentity {
50        match self {
51            Self::Shell(definition) => definition.owner,
52            Self::Enum(definition) => definition.owner,
53            Self::Domain(domain) => domain.owner,
54            Self::Composite(definition) => definition.owner,
55        }
56    }
57
58    #[must_use]
59    pub fn array_name(&self) -> Option<String> {
60        match self {
61            Self::Shell(_) => None,
62            Self::Enum(definition) => Some(definition.array_name.clone()),
63            Self::Domain(domain) => Some(domain.array_type_name()),
64            Self::Composite(definition) => Some(definition.array_name.clone()),
65        }
66    }
67
68    #[must_use]
69    pub fn usage_acl(&self) -> Option<&[ObjectAclEntry]> {
70        match self {
71            Self::Shell(definition) => definition.usage_acl.as_deref(),
72            Self::Enum(definition) => definition.usage_acl.as_deref(),
73            Self::Domain(domain) => domain.usage_acl.as_deref(),
74            Self::Composite(definition) => definition.usage_acl.as_deref(),
75        }
76    }
77}
78
79/// What a type name resolved to before command-specific checks.
80#[derive(Debug, Clone)]
81enum ResolvedKind {
82    User(TypeObject),
83    /// The generated array type of a user-defined type or relation row type.
84    Array {
85        element: u32,
86    },
87    RowType(RowTypeRelation),
88    /// A type that no role created: built-in types and fixed system catalog domains.
89    System,
90}
91
92#[derive(Debug, Clone)]
93pub struct ResolvedTypeObject {
94    oid: u32,
95    kind: ResolvedKind,
96}
97
98/// Resolve an `any_name` type-object target as identifiers, without interpreting SQL type aliases such as `integer`. The lookup uses quoted components while the ordinary resolver preserves namespace checks and diagnostics.
99pub fn resolve_named_type_object(
100    context: &TypeObjectBinding<'_>,
101    name: &str,
102) -> Result<ResolvedTypeObject, SQLError> {
103    let parts = crate::parse_regobject_name(name)
104        .ok_or_else(|| SQLError::Internal("type object target has no valid name".into()))?;
105    let lookup = parts
106        .iter()
107        .map(|part| format!("\"{}\"", part.replace('"', "\"\"")))
108        .collect::<Vec<_>>()
109        .join(".");
110    resolve_type_object(context, &lookup)
111}
112
113/// Resolve a type name as `typenameTypeId` does: a missing schema is 3F000 and a schema without USAGE is 42501 before the type lookup reports 42704.
114pub fn resolve_type_object(
115    context: &TypeObjectBinding<'_>,
116    name: &str,
117) -> Result<ResolvedTypeObject, SQLError> {
118    let parsed = crate::parse_regtype_name(name)?
119        .ok_or_else(|| SQLError::Internal("ALTER TYPE has no type name".into()))?;
120    let label = format!(
121        "{}{}",
122        parsed.names.join("."),
123        "[]".repeat(parsed.array_dimensions)
124    );
125    if let [schema, _] = parsed.names.as_slice() {
126        if context.catalog.schema_security(schema).is_none() {
127            return Err(SQLError::Routine {
128                sqlstate: "3F000".into(),
129                message: format!("schema \"{schema}\" does not exist"),
130            });
131        }
132        if !context
133            .authority
134            .schema_usage(schema, &context.session.current_role())
135        {
136            return Err(SQLError::Routine {
137                sqlstate: "42501".into(),
138                message: format!("permission denied for schema {schema}"),
139            });
140        }
141    }
142    let oid = context
143        .catalog
144        .resolve_drop_type_oid(name)?
145        .ok_or_else(|| SQLError::Routine {
146            sqlstate: "42704".into(),
147            message: format!("type \"{label}\" does not exist"),
148        })?;
149    let oid = u32::try_from(oid)
150        .map_err(|_| SQLError::Internal(format!("type OID {oid} is out of range")))?;
151    Ok(ResolvedTypeObject {
152        oid,
153        kind: classify(context, oid),
154    })
155}
156
157fn classify(context: &TypeObjectBinding<'_>, oid: u32) -> ResolvedKind {
158    if let Some(definition) = context.catalog.shell_by_type_oid(oid) {
159        return ResolvedKind::User(TypeObject::Shell(definition));
160    }
161    if let Some(domain) = context.catalog.domain_by_oid(oid) {
162        return ResolvedKind::User(TypeObject::Domain(Box::new(domain)));
163    }
164    if let Some(definition) = context.catalog.enum_by_type_oid(oid) {
165        if definition.array_oid == oid {
166            return ResolvedKind::Array {
167                element: definition.oid,
168            };
169        }
170        return ResolvedKind::User(TypeObject::Enum(definition));
171    }
172    if let Some(definition) = context.catalog.composite_by_type_oid(oid) {
173        if definition.array_oid == oid {
174            return ResolvedKind::Array {
175                element: definition.oid,
176            };
177        }
178        return ResolvedKind::User(TypeObject::Composite(Box::new(definition)));
179    }
180    if let Some(element) = context.catalog.user_array_element(oid) {
181        return ResolvedKind::Array { element };
182    }
183    if let Some(relation) = context.catalog.row_type_relation(oid) {
184        return ResolvedKind::RowType(relation);
185    }
186    ResolvedKind::System
187}
188
189impl ResolvedTypeObject {
190    /// ALTER TYPE name and namespace operations require a completed type, while owner and ACL operations can name a shell.
191    pub fn require_defined(&self, name: &str) -> Result<(), SQLError> {
192        if matches!(self.kind, ResolvedKind::User(TypeObject::Shell(_))) {
193            let label = crate::parse_regtype_name(name)?
194                .map_or_else(|| name.to_owned(), |parsed| parsed.names.join("."));
195            return Err(SQLError::Routine {
196                sqlstate: "42704".into(),
197                message: format!("type \"{label}\" is only a shell"),
198            });
199        }
200        Ok(())
201    }
202
203    #[must_use]
204    pub fn oid(&self) -> u32 {
205        self.oid
206    }
207
208    fn owner(&self, context: &TypeObjectBinding<'_>) -> RoleIdentity {
209        match &self.kind {
210            ResolvedKind::User(object) => object.owner(),
211            ResolvedKind::Array { element } => context
212                .catalog
213                .domain_by_oid(*element)
214                .map(|domain| domain.owner)
215                .or_else(|| {
216                    context
217                        .catalog
218                        .enum_by_type_oid(*element)
219                        .map(|definition| definition.owner)
220                })
221                .or_else(|| {
222                    context
223                        .catalog
224                        .composite_by_type_oid(*element)
225                        .map(|definition| definition.owner)
226                })
227                .unwrap_or(RoleIdentity::BOOTSTRAP),
228            ResolvedKind::RowType(relation) => relation.owner,
229            ResolvedKind::System => RoleIdentity::BOOTSTRAP,
230        }
231    }
232
233    /// `ALTER DOMAIN` and `GRANT ... ON DOMAIN` name only domains.
234    pub fn require_domain_keyword(
235        &self,
236        context: &TypeObjectBinding<'_>,
237        kind: TypeObjectKind,
238    ) -> Result<(), SQLError> {
239        if kind == TypeObjectKind::Domain
240            && !matches!(self.kind, ResolvedKind::User(TypeObject::Domain(_)))
241        {
242            return Err(SQLError::Routine {
243                sqlstate: "42809".into(),
244                message: format!("{} is not a domain", format_type(context, self.oid)?),
245            });
246        }
247        Ok(())
248    }
249
250    /// `COMMENT ON DOMAIN` quotes the parsed type name, unlike ALTER's formatted type diagnostic.
251    pub fn require_comment_kind(&self, kind: TypeObjectKind, name: &str) -> Result<(), SQLError> {
252        if kind == TypeObjectKind::Domain
253            && !matches!(self.kind, ResolvedKind::User(TypeObject::Domain(_)))
254        {
255            let parsed = crate::parse_regtype_name(name)?
256                .ok_or_else(|| SQLError::Internal("COMMENT has no type name".into()))?;
257            let label = format!(
258                "{}{}",
259                parsed.names.join("."),
260                "[]".repeat(parsed.array_dimensions)
261            );
262            return Err(SQLError::Routine {
263                sqlstate: "42809".into(),
264                message: format!("\"{label}\" is not a domain"),
265            });
266        }
267        Ok(())
268    }
269
270    /// `object_ownercheck` on the type: the current role must have the owner's privileges. An array type is owned by its element's owner.
271    pub fn require_owner(&self, context: &TypeObjectBinding<'_>) -> Result<(), SQLError> {
272        if context
273            .authority
274            .current_user_has_role_privileges(&self.owner(context))
275        {
276            return Ok(());
277        }
278        Err(SQLError::Routine {
279            sqlstate: "42501".into(),
280            message: format!(
281                "must be owner of type {}",
282                format_type(context, self.array_element().unwrap_or(self.oid))?
283            ),
284        })
285    }
286
287    /// The relation of a table row type, which `SET SCHEMA` reports after its duplicate-name check.
288    #[must_use]
289    pub fn row_type_identity(&self) -> Option<RelationIdentity> {
290        match &self.kind {
291            ResolvedKind::RowType(relation) => Some(RelationIdentity::new(
292                &relation.schema,
293                &relation.local_name,
294            )),
295            _ => None,
296        }
297    }
298
299    fn array_element(&self) -> Option<u32> {
300        match self.kind {
301            ResolvedKind::Array { element } => Some(element),
302            _ => None,
303        }
304    }
305
306    /// A table's row type is altered through `ALTER TABLE`.
307    pub fn reject_row_type(&self, context: &TypeObjectBinding<'_>) -> Result<(), SQLError> {
308        if let ResolvedKind::RowType(_) = self.kind {
309            return Err(SQLError::Diagnostic {
310                sqlstate: "42809".into(),
311                message: format!("{} is a table's row type", format_type(context, self.oid)?),
312                detail: None,
313                hint: Some("Use ALTER TABLE instead.".into()),
314            });
315        }
316        Ok(())
317    }
318
319    /// A generated array type follows its element type.
320    pub fn reject_array(&self, context: &TypeObjectBinding<'_>) -> Result<(), SQLError> {
321        if let Some(element) = self.array_element() {
322            return Err(SQLError::Diagnostic {
323                sqlstate: "42809".into(),
324                message: format!(
325                    "cannot alter array type {}",
326                    format_type(context, self.oid)?
327                ),
328                detail: None,
329                hint: Some(format!(
330                    "You can alter type {}, which will alter the array type as well.",
331                    format_type(context, element)?
332                )),
333            });
334        }
335        Ok(())
336    }
337
338    /// `ExecGrant_Type_check`: array types have no privileges of their own, and `ON DOMAIN` names only domains.
339    pub fn require_grant_target(
340        &self,
341        context: &TypeObjectBinding<'_>,
342        kind: TypeObjectKind,
343    ) -> Result<(), SQLError> {
344        if self.array_element().is_some() {
345            return Err(SQLError::Diagnostic {
346                sqlstate: "0LP01".into(),
347                message: "cannot set privileges of array types".into(),
348                detail: None,
349                hint: Some("Set the privileges of the element type instead.".into()),
350            });
351        }
352        if kind == TypeObjectKind::Domain
353            && !matches!(self.kind, ResolvedKind::User(TypeObject::Domain(_)))
354        {
355            return Err(SQLError::Routine {
356                sqlstate: "42809".into(),
357                message: format!("\"{}\" is not a domain", format_type(context, self.oid)?),
358            });
359        }
360        Ok(())
361    }
362
363    /// The user-defined type to change. Built-in types, system catalog domains and relation row types have fixed definitions here.
364    pub fn into_type_object(self, context: &TypeObjectBinding<'_>) -> Result<TypeObject, SQLError> {
365        match self.kind {
366            ResolvedKind::User(object) => Ok(object),
367            ResolvedKind::Array { .. } | ResolvedKind::RowType(_) | ResolvedKind::System => {
368                Err(SQLError::Routine {
369                    sqlstate: "0A000".into(),
370                    message: format!(
371                        "type {} has a fixed system definition",
372                        format_type(context, self.oid)?
373                    ),
374                })
375            }
376        }
377    }
378}
379
380fn format_type(context: &TypeObjectBinding<'_>, oid: u32) -> Result<String, SQLError> {
381    context
382        .catalog
383        .format_drop_type(i64::from(oid))
384        .map_err(SQLError::Internal)?
385        .ok_or_else(|| SQLError::Internal(format!("type {oid} disappeared")))
386}
387
388#[cfg(test)]
389mod tests;