Skip to main content

uqa_engine/capabilities/
schema_analysis.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Catalog metadata adapters for SQL declaration analysis and physical index validation.
8
9use crate::Engine;
10use std::{collections::BTreeMap, sync::Arc};
11use uqa_core::RelationIdentity;
12use uqa_execution::schema::constraints::names::catalog::{
13    ConstraintNameCatalog, ConstraintTableMetadata,
14};
15use uqa_sql::{
16    ast::{ColumnDef, Expr, FunctionVolatility},
17    SQLError,
18};
19
20fn constraint_table_metadata(table: &crate::TableState) -> ConstraintTableMetadata {
21    ConstraintTableMetadata {
22        object_id: table.object_id(),
23        columns: table.columns.snapshot(),
24        checks: table.table_checks.snapshot(),
25        foreign_keys: table.foreign_keys.snapshot(),
26        keys: table.key_constraints.snapshot(),
27        hierarchy: table.hierarchy.snapshot(),
28    }
29}
30
31impl ConstraintNameCatalog for Engine {
32    fn constraint_table(&self, relation: &RelationIdentity) -> Option<ConstraintTableMetadata> {
33        let table = self.storage.tables.read().get(relation).cloned()?;
34        Some(constraint_table_metadata(&table))
35    }
36    fn constraint_owner(
37        &self,
38        object_id: [u8; 16],
39    ) -> Option<(RelationIdentity, ConstraintTableMetadata)> {
40        let (relation, table) = self
41            .storage
42            .tables
43            .read()
44            .iter()
45            .find(|(_, table)| table.object_id() == object_id)
46            .map(|(relation, table)| (relation.clone(), Arc::clone(table)))?;
47        Some((relation, constraint_table_metadata(&table)))
48    }
49    fn constraint_schema_tables(&self, schema: &str) -> Vec<ConstraintTableMetadata> {
50        // Release the registry before reading per-table declarations, as catalog capture does.
51        let tables = self
52            .storage
53            .tables
54            .read()
55            .iter()
56            .filter(|(relation, _)| relation.schema == schema)
57            .map(|(_, table)| Arc::clone(table))
58            .collect::<Vec<_>>();
59        tables
60            .iter()
61            .map(|table| constraint_table_metadata(table))
62            .collect()
63    }
64    fn constraint_foreign_tables(
65        &self,
66    ) -> Arc<BTreeMap<RelationIdentity, uqa_execution::catalog::foreign::StoredForeignTable>> {
67        self.durable.foreign_tables.snapshot()
68    }
69    fn constraint_domains(&self) -> Arc<uqa_execution::catalog::domain::DomainRegistry> {
70        self.durable.domains.snapshot()
71    }
72    fn constraint_triggers(&self) -> Arc<uqa_sql::catalog::events::TriggerCatalog> {
73        self.durable.triggers.snapshot()
74    }
75}
76
77impl uqa_sql::assignment::AssignmentContext for Engine {
78    fn evaluate_domain_check_with_control(
79        &self,
80        expression: &Expr,
81        row: &dyn uqa_sql::expr::RowLookup,
82        schema: &uqa_sql::RowSchema,
83        control: &uqa_core::memory::ProductionControl<'_>,
84    ) -> Result<uqa_core::memory::Produced<uqa_core::Value>, SQLError> {
85        let scope =
86            crate::capabilities::query_scope::new_for_current_routine_with_control(self, control)?;
87        let hook = crate::capabilities::query_expressions::ScopedEngineHook::new(self, &scope);
88        uqa_execution::query::catalog_expression::evaluate_catalog_scalar_with_control(
89            uqa_sql::plan::ExpressionPlan::lower_scalar_for_rewrite(expression, control)?,
90            row,
91            schema,
92            &[],
93            &hook,
94            control,
95            |expression| {
96                uqa_planner::statement_planning::schema_expressions::optimize_owned_catalog_scalar(
97                    &self.statement_planning_context(),
98                    expression,
99                    control,
100                )
101            },
102        )
103    }
104
105    fn domain_display_name_with_control(
106        &self,
107        oid: u32,
108        control: &uqa_core::memory::ProductionControl<'_>,
109    ) -> Result<uqa_core::memory::Produced<String>, SQLError> {
110        let context = self.catalog_execution();
111        let ty = uqa_execution::catalog::projection::resolve_catalog_user_type_by_oid_with_control(
112            &context, oid, control,
113        )?
114        .ok_or_else(|| SQLError::Internal("domain type has no catalog display name".into()))?;
115        uqa_execution::catalog::projection::format_type_name_with_control(&context, &ty, control)
116    }
117
118    fn evaluate_domain_check(
119        &self,
120        expression: &Expr,
121        row: &dyn uqa_sql::expr::RowLookup,
122        schema: &uqa_sql::RowSchema,
123    ) -> Result<uqa_core::Value, SQLError> {
124        crate::capabilities::query_expressions::eval_lowered_expression_with_schema(
125            self,
126            expression,
127            row,
128            schema,
129            &[],
130        )
131    }
132}
133
134impl uqa_sql::schema::SchemaExpressionCatalog for Engine {
135    fn plan_schema_expression(
136        &self,
137        expression: &Expr,
138        columns: &[ColumnDef],
139    ) -> Result<uqa_sql::schema::expressions::PlannedSchemaExpression, SQLError> {
140        uqa_planner::statement_planning::schema_expressions::plan_schema_expression(
141            &self.statement_planning_context(),
142            self,
143            expression,
144            columns,
145        )
146    }
147
148    fn registered_runtime_function_volatility(&self, name: &str) -> Option<FunctionVolatility> {
149        Engine::registered_runtime_function_volatility(self, name)
150    }
151    fn schema_expression_columns(&self, table: &str) -> Result<Option<Vec<ColumnDef>>, SQLError> {
152        self.describe_table_in_execution(table)
153            .map_err(|error| SQLError::Internal(error.to_string()))
154    }
155}
156
157impl uqa_sql::schema::inheritance::InheritanceCatalog for Engine {
158    fn resolve_parent(&self, name: &str) -> Result<String, SQLError> {
159        uqa_sql::schema::inheritance::inheritance_parent_target(
160            self.resolve_visible_relation_kind(name)?,
161            name,
162        )
163    }
164    fn declared_constraints(
165        &self,
166        table: &str,
167    ) -> Result<uqa_sql::ast::TableConstraintSet, String> {
168        self.try_declared_table_constraints(table)
169            .map_err(|error| error.to_string())
170    }
171    fn check_definitions(&self, table: &str) -> Result<Vec<uqa_sql::ast::TableCheck>, String> {
172        self.check_constraint_definitions_in_execution(table)
173            .map_err(|error| error.to_string())
174    }
175    fn unique_index_keys(&self, table: &str) -> Result<Vec<Vec<uqa_sql::ast::IndexKey>>, String> {
176        uqa_execution::schema::indexes::registry::lifecycle::standalone_unique_index_keys(
177            &self
178                .catalog_read_view()
179                .snapshot()
180                .definitions
181                .catalog_indexes,
182            table,
183        )
184        .map_err(|error| error.to_string())
185    }
186}
187
188impl uqa_sql::schema::indexes::names::IndexNameCatalog for Engine {
189    fn automatic_constraint_names(
190        &self,
191        table: &str,
192    ) -> Result<std::collections::BTreeSet<String>, SQLError> {
193        self.schema_publication_context()
194            .constraint_names()
195            .automatic_names(table)
196    }
197    fn existing_constraint_names(
198        &self,
199        table: &str,
200    ) -> Result<std::collections::BTreeSet<String>, SQLError> {
201        self.schema_publication_context()
202            .constraint_names()
203            .existing_names(table)
204    }
205    fn existing_constraint_keys(
206        &self,
207        table: &str,
208    ) -> Result<Vec<uqa_sql::ast::TableKeyConstraint>, SQLError> {
209        if self.try_resolve_bound_table_name(table)?.is_some() {
210            self.key_constraints_in_execution(table)
211                .map_err(|error| SQLError::Internal(error.to_string()))
212        } else {
213            Ok(Vec::new())
214        }
215    }
216    fn relation_name_available(&self, qualified_name: &str) -> Result<bool, SQLError> {
217        Ok(matches!(
218            self.resolve_bound_relation_kind(qualified_name)?,
219            super::RelationResolution::MissingRelation
220        ))
221    }
222}
223
224impl uqa_execution::schema::indexes::IndexBuildCatalog for Engine {
225    fn table_hierarchy(&self, table: &str) -> Result<uqa_sql::ast::TableHierarchy, SQLError> {
226        self.try_table_hierarchy(table)
227            .map_err(|error| uqa_sql::catalog::errors::storage_error("CREATE UNIQUE INDEX", &error))
228    }
229    fn scan_tables(&self, table: &str) -> Result<Vec<String>, SQLError> {
230        self.hierarchy_scan_tables(table, true)
231    }
232    fn partition_tree(
233        &self,
234        table: &str,
235    ) -> Result<Vec<uqa_sql::semantics::partition::PartitionTreeNode>, SQLError> {
236        uqa_sql::semantics::partition::partition_tree(&self.partition_context(), table, false)
237    }
238}
239
240impl uqa_execution::schema::indexes::unique_build::IndexKeyDescription for Engine {
241    fn describe_index_key(
242        &self,
243        table: &str,
244        keys: &[uqa_sql::ast::IndexKey],
245        key_types: &[uqa_sql::ColumnType],
246        values: &[uqa_core::Value],
247    ) -> Result<Option<String>, SQLError> {
248        self.constraint_execution_context()
249            .describe_index_key(table, keys, key_types, values)
250    }
251}
252
253impl Engine {
254    pub(crate) fn foreign_key_definition_context(
255        &self,
256    ) -> uqa_sql::schema::foreign_keys::ForeignKeyDefinitionContext<'_> {
257        uqa_sql::schema::foreign_keys::ForeignKeyDefinitionContext {
258            catalog: self,
259            columns: self,
260        }
261    }
262}
263impl uqa_sql::schema::foreign_keys::ForeignKeyDefinitionCatalog for Engine {
264    fn resolve_table_reference(&self, name: &str) -> Result<String, SQLError> {
265        self.resolve_visible_table_reference(name)
266    }
267    fn bound_table_name(&self, name: &str) -> Result<Option<String>, SQLError> {
268        self.try_resolve_bound_table_name(name)
269    }
270    fn referenceable_keys(
271        &self,
272        table: &str,
273    ) -> Result<
274        Vec<uqa_sql::ast::TableKeyConstraint>,
275        uqa_sql::assignment::columns::ColumnCatalogError,
276    > {
277        Engine::referenceable_keys(self, table).map_err(|error| Box::new(error) as _)
278    }
279    fn ensure_reference_privilege(&self, table: &str, column: &str) -> Result<(), SQLError> {
280        self.ensure_column_privilege(
281            table,
282            column,
283            uqa_sql::catalog::security::table::TableAclPrivilege::References,
284        )
285    }
286}
287
288impl uqa_execution::schema::columns::ColumnRewritePublication for Engine {
289    fn update_fields(
290        &self,
291        table: &str,
292        id: uqa_core::DocId,
293        values: std::collections::BTreeMap<String, uqa_core::Value>,
294        vectors: uqa_execution::mutation::publication::DocumentVectors,
295    ) -> Result<bool, SQLError> {
296        uqa_execution::schema::columns::generated::update_rewritten_fields(
297            &self.generated_rewrite_context(),
298            table,
299            id,
300            values,
301            vectors,
302        )
303    }
304}
305
306impl Engine {
307    pub(crate) fn schema_dependency_binding_context(
308        &self,
309    ) -> uqa_sql::schema::dependencies::registration::SchemaDependencyBindingContext<'_> {
310        uqa_sql::schema::dependencies::registration::SchemaDependencyBindingContext {
311            references: self,
312            schema: self,
313            bindings: self,
314        }
315    }
316}
317impl uqa_sql::schema::dependencies::regclass::SchemaReferenceCatalog for Engine {
318    fn loaded_relation_name(&self, reference: &str) -> Result<Option<String>, String> {
319        self.resolve_loaded_visible_relation_kind(reference)
320            .map(|resolution| resolution.into_found().map(|(canonical, _)| canonical))
321            .map_err(|error| error.to_string())
322    }
323    fn bound_relation_oid(&self, canonical: &str) -> Result<Option<i64>, String> {
324        uqa_execution::catalog::projection::resolve_bound_regclass_oid(
325            &self.catalog_execution(),
326            canonical,
327        )
328        .map_err(|error| error.to_string())
329    }
330    fn visible_relation_oid(&self, reference: &str) -> Result<Option<i64>, String> {
331        uqa_execution::catalog::projection::resolve_regclass_oid(
332            &self.catalog_execution(),
333            reference,
334        )
335        .map_err(|error| error.to_string())
336    }
337    fn sequence_for_binding(&self, reference: &str) -> Result<String, String> {
338        self.resolve_sequence_reference_for_binding(reference)
339            .map_err(|error| error.to_string())
340    }
341}
342
343impl uqa_sql::schema::constraint_views::StoredTableNames for Engine {
344    fn stored_table_exists(&self, relation: &uqa_core::RelationIdentity) -> bool {
345        self.storage.tables.read().contains_key(relation)
346    }
347    fn stored_table_names(&self) -> Vec<uqa_core::RelationIdentity> {
348        self.storage.tables.read().keys().cloned().collect()
349    }
350}