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        let schema = context.namespace(schema);
127        if context.catalog.schema_security(&schema).is_none() {
128            return Err(SQLError::Routine {
129                sqlstate: "3F000".into(),
130                message: format!("schema \"{schema}\" does not exist"),
131            });
132        }
133        if !context
134            .authority
135            .schema_usage(&schema, &context.session.current_role())
136        {
137            return Err(SQLError::Routine {
138                sqlstate: "42501".into(),
139                message: format!("permission denied for schema {schema}"),
140            });
141        }
142    }
143    let oid = context
144        .catalog
145        .resolve_drop_type_oid(name)?
146        .ok_or_else(|| SQLError::Routine {
147            sqlstate: "42704".into(),
148            message: format!("type \"{label}\" does not exist"),
149        })?;
150    let oid = u32::try_from(oid)
151        .map_err(|_| SQLError::Internal(format!("type OID {oid} is out of range")))?;
152    Ok(ResolvedTypeObject {
153        oid,
154        kind: classify(context, oid),
155    })
156}
157
158fn classify(context: &TypeObjectBinding<'_>, oid: u32) -> ResolvedKind {
159    if let Some(definition) = context.catalog.shell_by_type_oid(oid) {
160        return ResolvedKind::User(TypeObject::Shell(definition));
161    }
162    if let Some(domain) = context.catalog.domain_by_oid(oid) {
163        return ResolvedKind::User(TypeObject::Domain(Box::new(domain)));
164    }
165    if let Some(definition) = context.catalog.enum_by_type_oid(oid) {
166        if definition.array_oid == oid {
167            return ResolvedKind::Array {
168                element: definition.oid,
169            };
170        }
171        return ResolvedKind::User(TypeObject::Enum(definition));
172    }
173    if let Some(definition) = context.catalog.composite_by_type_oid(oid) {
174        if definition.array_oid == oid {
175            return ResolvedKind::Array {
176                element: definition.oid,
177            };
178        }
179        return ResolvedKind::User(TypeObject::Composite(Box::new(definition)));
180    }
181    if let Some(element) = context.catalog.user_array_element(oid) {
182        return ResolvedKind::Array { element };
183    }
184    if let Some(relation) = context.catalog.row_type_relation(oid) {
185        return ResolvedKind::RowType(relation);
186    }
187    ResolvedKind::System
188}
189
190impl ResolvedTypeObject {
191    /// ALTER TYPE name and namespace operations require a completed type, while owner and ACL operations can name a shell.
192    pub fn require_defined(&self, name: &str) -> Result<(), SQLError> {
193        if matches!(self.kind, ResolvedKind::User(TypeObject::Shell(_))) {
194            let label = crate::parse_regtype_name(name)?
195                .map_or_else(|| name.to_owned(), |parsed| parsed.names.join("."));
196            return Err(SQLError::Routine {
197                sqlstate: "42704".into(),
198                message: format!("type \"{label}\" is only a shell"),
199            });
200        }
201        Ok(())
202    }
203
204    #[must_use]
205    pub fn oid(&self) -> u32 {
206        self.oid
207    }
208
209    fn owner(&self, context: &TypeObjectBinding<'_>) -> RoleIdentity {
210        match &self.kind {
211            ResolvedKind::User(object) => object.owner(),
212            ResolvedKind::Array { element } => context
213                .catalog
214                .domain_by_oid(*element)
215                .map(|domain| domain.owner)
216                .or_else(|| {
217                    context
218                        .catalog
219                        .enum_by_type_oid(*element)
220                        .map(|definition| definition.owner)
221                })
222                .or_else(|| {
223                    context
224                        .catalog
225                        .composite_by_type_oid(*element)
226                        .map(|definition| definition.owner)
227                })
228                .unwrap_or(RoleIdentity::BOOTSTRAP),
229            ResolvedKind::RowType(relation) => relation.owner,
230            ResolvedKind::System => RoleIdentity::BOOTSTRAP,
231        }
232    }
233
234    /// `ALTER DOMAIN` and `GRANT ... ON DOMAIN` name only domains.
235    pub fn require_domain_keyword(
236        &self,
237        context: &TypeObjectBinding<'_>,
238        kind: TypeObjectKind,
239    ) -> Result<(), SQLError> {
240        if kind == TypeObjectKind::Domain
241            && !matches!(self.kind, ResolvedKind::User(TypeObject::Domain(_)))
242        {
243            return Err(SQLError::Routine {
244                sqlstate: "42809".into(),
245                message: format!("{} is not a domain", format_type(context, self.oid)?),
246            });
247        }
248        Ok(())
249    }
250
251    /// `COMMENT ON DOMAIN` quotes the parsed type name, unlike ALTER's formatted type diagnostic.
252    pub fn require_comment_kind(&self, kind: TypeObjectKind, name: &str) -> Result<(), SQLError> {
253        if kind == TypeObjectKind::Domain
254            && !matches!(self.kind, ResolvedKind::User(TypeObject::Domain(_)))
255        {
256            let parsed = crate::parse_regtype_name(name)?
257                .ok_or_else(|| SQLError::Internal("COMMENT has no type name".into()))?;
258            let label = format!(
259                "{}{}",
260                parsed.names.join("."),
261                "[]".repeat(parsed.array_dimensions)
262            );
263            return Err(SQLError::Routine {
264                sqlstate: "42809".into(),
265                message: format!("\"{label}\" is not a domain"),
266            });
267        }
268        Ok(())
269    }
270
271    /// `object_ownercheck` on the type: the current role must have the owner's privileges. An array type is owned by its element's owner.
272    pub fn require_owner(&self, context: &TypeObjectBinding<'_>) -> Result<(), SQLError> {
273        if context
274            .authority
275            .current_user_has_role_privileges(&self.owner(context))
276        {
277            return Ok(());
278        }
279        Err(SQLError::Routine {
280            sqlstate: "42501".into(),
281            message: format!(
282                "must be owner of type {}",
283                format_type(context, self.array_element().unwrap_or(self.oid))?
284            ),
285        })
286    }
287
288    /// The relation of a table row type, which `SET SCHEMA` reports after its duplicate-name check.
289    #[must_use]
290    pub fn row_type_identity(&self) -> Option<RelationIdentity> {
291        match &self.kind {
292            ResolvedKind::RowType(relation) => Some(RelationIdentity::new(
293                &relation.schema,
294                &relation.local_name,
295            )),
296            _ => None,
297        }
298    }
299
300    fn array_element(&self) -> Option<u32> {
301        match self.kind {
302            ResolvedKind::Array { element } => Some(element),
303            _ => None,
304        }
305    }
306
307    /// A table's row type is altered through `ALTER TABLE`.
308    pub fn reject_row_type(&self, context: &TypeObjectBinding<'_>) -> Result<(), SQLError> {
309        if let ResolvedKind::RowType(_) = self.kind {
310            return Err(SQLError::Diagnostic {
311                sqlstate: "42809".into(),
312                message: format!("{} is a table's row type", format_type(context, self.oid)?),
313                detail: None,
314                hint: Some("Use ALTER TABLE instead.".into()),
315            });
316        }
317        Ok(())
318    }
319
320    /// A generated array type follows its element type.
321    pub fn reject_array(&self, context: &TypeObjectBinding<'_>) -> Result<(), SQLError> {
322        if let Some(element) = self.array_element() {
323            return Err(SQLError::Diagnostic {
324                sqlstate: "42809".into(),
325                message: format!(
326                    "cannot alter array type {}",
327                    format_type(context, self.oid)?
328                ),
329                detail: None,
330                hint: Some(format!(
331                    "You can alter type {}, which will alter the array type as well.",
332                    format_type(context, element)?
333                )),
334            });
335        }
336        Ok(())
337    }
338
339    /// `ExecGrant_Type_check`: array types have no privileges of their own, and `ON DOMAIN` names only domains.
340    pub fn require_grant_target(
341        &self,
342        context: &TypeObjectBinding<'_>,
343        kind: TypeObjectKind,
344    ) -> Result<(), SQLError> {
345        if self.array_element().is_some() {
346            return Err(SQLError::Diagnostic {
347                sqlstate: "0LP01".into(),
348                message: "cannot set privileges of array types".into(),
349                detail: None,
350                hint: Some("Set the privileges of the element type instead.".into()),
351            });
352        }
353        if kind == TypeObjectKind::Domain
354            && !matches!(self.kind, ResolvedKind::User(TypeObject::Domain(_)))
355        {
356            return Err(SQLError::Routine {
357                sqlstate: "42809".into(),
358                message: format!("\"{}\" is not a domain", format_type(context, self.oid)?),
359            });
360        }
361        Ok(())
362    }
363
364    /// The user-defined type to change. Built-in types, system catalog domains and relation row types have fixed definitions here.
365    pub fn into_type_object(self, context: &TypeObjectBinding<'_>) -> Result<TypeObject, SQLError> {
366        match self.kind {
367            ResolvedKind::User(object) => Ok(object),
368            ResolvedKind::Array { .. } | ResolvedKind::RowType(_) | ResolvedKind::System => {
369                Err(SQLError::Routine {
370                    sqlstate: "0A000".into(),
371                    message: format!(
372                        "type {} has a fixed system definition",
373                        format_type(context, self.oid)?
374                    ),
375                })
376            }
377        }
378    }
379}
380
381fn format_type(context: &TypeObjectBinding<'_>, oid: u32) -> Result<String, SQLError> {
382    context
383        .catalog
384        .format_drop_type(i64::from(oid))
385        .map_err(SQLError::Internal)?
386        .ok_or_else(|| SQLError::Internal(format!("type {oid} disappeared")))
387}
388
389#[cfg(test)]
390mod tests;