Skip to main content

uqa_engine/capabilities/
enums.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Bind enum DDL to namespace, identity, publication and transaction visibility state.
8
9use crate::Engine;
10use std::collections::BTreeMap;
11use uqa_execution::catalog::enum_type::{EnumRegistry, EnumRegistryPublication, EnumRegistryRead};
12use uqa_execution::schema::enums::{EnumLabelVisibility, EnumTypeContext};
13use uqa_sql::catalog::roles::RoleDefinition;
14use uqa_sql::expr::enums::{EnumLabelCatalog, EnumTypeLabels};
15use uqa_sql::schema::domains::removal::TypeObjectBinding;
16use uqa_sql::SQLError;
17
18impl Engine {
19    pub(crate) fn enum_type_context(&self) -> EnumTypeContext<'_> {
20        EnumTypeContext {
21            creation: self.relation_creation_context(),
22            identities: self.catalog_identity_reservation_context(),
23            writer: self,
24            binding: TypeObjectBinding {
25                catalog: self,
26                authority: self,
27                session: self,
28            },
29            allocate_identity: || {
30                crate::new_nonzero_catalog_identity("enum", "object identity")
31                    .map_err(|error| SQLError::Internal(error.to_string()))
32            },
33            publication: self,
34            domains: self,
35            composites: self,
36            changes: self,
37            visibility: self,
38            notices: self,
39        }
40    }
41}
42
43impl Engine {
44    /// Enum definitions restore before domains and relations, whose declared types can refer to them.
45    pub(crate) fn restore_enums_from_catalog(
46        &self,
47        catalog: &dyn uqa_storage::CatalogFacade,
48    ) -> uqa_storage::StorageBackendResult<()> {
49        let registry =
50            uqa_execution::catalog::enum_type::restore(catalog, &self.durable.roles.read())?;
51        *self.durable.enums.write() = registry;
52        Ok(())
53    }
54}
55
56impl Engine {
57    /// The enum registry generation of the running statement: the pinned query snapshot when one exists, otherwise the session's current definitions.
58    pub(crate) fn enum_registry_snapshot(&self) -> std::sync::Arc<EnumRegistry> {
59        self.query_catalog_snapshot.as_ref().map_or_else(
60            || self.durable.enums.snapshot(),
61            |snapshot| std::sync::Arc::clone(&snapshot.enums),
62        )
63    }
64}
65
66impl Engine {
67    /// Replace the enum values of a query result by their current labels, as `PostgreSQL` clients receive them from the type's output function. Declared column types keep the enum type.
68    ///
69    /// # Errors
70    ///
71    /// Returns an error when a result value names an enum type or label that this session's catalog no longer contains.
72    pub fn render_enum_labels(&self, result: &mut uqa_sql::SQLResult) -> Result<(), SQLError> {
73        uqa_sql::result::render_result_enum_labels(Some(self), result)
74    }
75}
76
77impl EnumLabelCatalog for Engine {
78    fn value_type_by_oid(&self, oid: u32) -> Result<Option<uqa_sql::ColumnType>, SQLError> {
79        uqa_sql::expr::EngineHook::resolve_type_oid(self, oid).map_err(SQLError::Internal)
80    }
81
82    fn value_composite_type(
83        &self,
84        oid: u32,
85    ) -> Result<Option<std::sync::Arc<uqa_sql::expr::composites::CompositeTypeDescriptor>>, SQLError>
86    {
87        uqa_sql::expr::composites::CompositeTypeCatalog::composite_type(self, oid)
88    }
89
90    fn enum_type_comparison_states(
91        &self,
92    ) -> Option<&uqa_sql::expr::enums::EnumTypeComparisonStates> {
93        Some(&self.session.enum_type_comparison_states)
94    }
95
96    fn enum_label_position(&self, label_oid: u32) -> Result<Option<(u32, usize)>, SQLError> {
97        Ok(self
98            .runtime
99            .enum_label_cache
100            .position(&self.enum_registry_snapshot(), label_oid))
101    }
102
103    fn enum_value_by_oid(&self, label_oid: u32) -> Result<Option<uqa_core::EnumValue>, SQLError> {
104        Ok(self
105            .runtime
106            .enum_label_cache
107            .value(&self.enum_registry_snapshot(), label_oid))
108    }
109
110    fn enum_type_labels(
111        &self,
112        type_oid: u32,
113    ) -> Result<Option<std::sync::Arc<EnumTypeLabels>>, SQLError> {
114        Ok(self
115            .runtime
116            .enum_label_cache
117            .labels(&self.enum_registry_snapshot(), type_oid))
118    }
119
120    /// Labels added by the outermost transaction to a type it did not create stay unusable until commit.
121    fn enum_label_uncommitted(&self, label_oid: u32) -> bool {
122        self.session
123            .uncommitted_enum_labels
124            .lock()
125            .is_uncommitted(label_oid)
126    }
127
128    /// The regtype spelling of an enum, read from the enum registry alone: label errors are raised while catalog restoration holds transaction state, where building the complete catalog projection must not be attempted.
129    fn enum_type_name(&self, type_oid: u32) -> Result<Option<String>, SQLError> {
130        let registry = self.enum_registry_snapshot();
131        let Some(definition) = registry
132            .values()
133            .find(|definition| definition.oid == type_oid)
134        else {
135            return Ok(None);
136        };
137        let name = uqa_sql::expr::quote_ident(&definition.identity.name);
138        let schema = &definition.identity.schema;
139        let visible = schema == "pg_catalog"
140            || self
141                .session
142                .state
143                .read()
144                .search_path
145                .iter()
146                .any(|entry| entry == schema);
147        Ok(Some(if visible {
148            name
149        } else {
150            format!("{}.{name}", uqa_sql::expr::quote_ident(schema))
151        }))
152    }
153
154    fn has_enum_types(&self) -> bool {
155        !self.enum_registry_snapshot().is_empty()
156    }
157}
158
159impl EnumRegistryPublication for Engine {
160    fn enum_registry(&self) -> EnumRegistryRead<'_> {
161        Box::new(self.durable.enums.read())
162    }
163    fn enum_catalog(&self) -> Option<&dyn uqa_storage::CatalogFacade> {
164        self.storage.catalog.as_deref()
165    }
166    fn enum_role_definitions(&self) -> BTreeMap<String, RoleDefinition> {
167        self.durable.roles.read().clone()
168    }
169    fn publish_enum_definitions(&self, registry: EnumRegistry) {
170        *self.durable.enums.write() = registry;
171    }
172}
173
174impl EnumLabelVisibility for Engine {
175    fn enum_type_created(&self, type_oid: u32) {
176        if !self.session.transactions.lock().is_empty() {
177            self.session
178                .uncommitted_enum_labels
179                .lock()
180                .type_created(type_oid);
181        }
182    }
183    fn enum_label_added(&self, type_oid: u32, label_oid: u32) {
184        if !self.session.transactions.lock().is_empty() {
185            self.session
186                .uncommitted_enum_labels
187                .lock()
188                .label_added(type_oid, label_oid);
189        }
190    }
191}