Skip to main content

uqa_sql/catalog/
analysis.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Catalog descriptions required by static SQL binding.
8
9use super::resolution::RelationNameResolution;
10use crate::ast::ColumnDef;
11use crate::plan::QueryPlan;
12use crate::routines::SQLUserFunction;
13use crate::{ColumnType, SQLError};
14use std::sync::Arc;
15mod owned;
16
17pub type VirtualRelationSchema = Vec<(String, ColumnType)>;
18
19#[derive(Clone)]
20pub struct TableDefinition {
21    pub columns: Arc<Vec<ColumnDef>>,
22    pub columns_declared: bool,
23}
24
25#[derive(Clone)]
26pub struct ViewDefinition {
27    pub query: QueryPlan,
28    pub output_columns: Option<Vec<String>>,
29    pub materialized: bool,
30    pub materialized_column_types: Vec<Option<ColumnType>>,
31    pub materialized_column_collations: Option<Vec<u32>>,
32}
33
34#[derive(Clone, Copy)]
35pub struct ViewDefinitionRef<'a> {
36    pub query: &'a QueryPlan,
37    pub output_columns: Option<&'a [String]>,
38    pub materialized: bool,
39    pub materialized_column_types: &'a [Option<ColumnType>],
40    pub materialized_column_collations: Option<&'a [u32]>,
41}
42
43impl<'a> From<&'a ViewDefinition> for ViewDefinitionRef<'a> {
44    fn from(view: &'a ViewDefinition) -> Self {
45        Self {
46            query: &view.query,
47            output_columns: view.output_columns.as_deref(),
48            materialized: view.materialized,
49            materialized_column_types: &view.materialized_column_types,
50            materialized_column_collations: view.materialized_column_collations.as_deref(),
51        }
52    }
53}
54
55/// Immutable namespace-aware lookup for SQL analysis. This contract exposes definitions only; it grants no row access, mutation, locking, or transaction services.
56pub trait AnalysisCatalog: Send + Sync {
57    /// The actual row type of a selected catalog relation. Anonymous query sources and catalog fixtures without identities leave this unavailable.
58    fn relation_row_type(
59        &self,
60        _resolution: &RelationNameResolution,
61        _name: &str,
62    ) -> Result<Option<crate::ast::CompositeTypeReference>, SQLError> {
63        Ok(None)
64    }
65
66    fn relation_row_type_with_control(
67        &self,
68        resolution: &RelationNameResolution,
69        name: &str,
70        control: &uqa_core::memory::ProductionControl<'_>,
71    ) -> Result<Option<uqa_core::memory::Produced<crate::ast::CompositeTypeReference>>, SQLError>
72    {
73        control.check()?;
74        self.relation_row_type(resolution, name)?
75            .map(|ty| ty.clone_with_control(control).map_err(Into::into))
76            .transpose()
77    }
78
79    fn sequence_exists_with_control(
80        &self,
81        resolution: &RelationNameResolution,
82        name: &str,
83        control: &uqa_core::memory::ProductionControl<'_>,
84    ) -> Result<bool, SQLError> {
85        control.check()?;
86        let exists = self.sequence_exists(resolution, name)?;
87        control.check()?;
88        Ok(exists)
89    }
90
91    fn virtual_relation_schema_with_control(
92        &self,
93        resolution: &RelationNameResolution,
94        name: &str,
95        control: &uqa_core::memory::ProductionControl<'_>,
96    ) -> Result<Option<uqa_core::memory::Produced<VirtualRelationSchema>>, SQLError> {
97        control.check()?;
98        let Some(schema) = self.virtual_relation_schema(resolution, name)? else {
99            return Ok(None);
100        };
101        let mut output = uqa_core::memory::ProductionVec::new(*control);
102        for (name, ty) in &schema {
103            let (name, name_memory) = control.copy_text(name)?.into_parts();
104            let (ty, type_memory) = ty.clone_with_control(control)?.into_parts();
105            output.push_produced(
106                control.finish((name, ty), control.combine(name_memory, type_memory))?,
107            )?;
108        }
109        Ok(Some(output.finish()?))
110    }
111
112    /// Exact revisions of the requested identities in this catalog view. Return `None` only when the catalog has no revision capability; within an available snapshot, include every requested identity and use a missing value for an absent object.
113    fn prepared_dependency_snapshot(
114        &self,
115        _dependencies: &crate::prepared::dependencies::PreparedAnalysisDependencies,
116    ) -> Result<Option<crate::prepared::dependencies::PreparedDependencySnapshot>, SQLError> {
117        Ok(None)
118    }
119
120    fn prepared_dependency_snapshot_with_control(
121        &self,
122        dependencies: &crate::prepared::dependencies::PreparedAnalysisDependencies,
123        control: &uqa_core::memory::ProductionControl<'_>,
124    ) -> Result<Option<crate::prepared::dependencies::PreparedDependencySnapshot>, SQLError> {
125        control.check()?;
126        self.prepared_dependency_snapshot(dependencies)?
127            .map(|snapshot| snapshot.copy_with_control(control))
128            .transpose()
129    }
130
131    /// The OID of a relation successfully selected in this same immutable namespace. The binder calls this after selecting a catalog relation, never for a CTE or an unsuccessful lookup candidate. Catalog fixtures without identities may leave this unavailable.
132    fn relation_dependency(
133        &self,
134        _resolution: &RelationNameResolution,
135        _name: &str,
136    ) -> Result<Option<u32>, SQLError> {
137        Ok(None)
138    }
139
140    /// Observe a selected relation identity within the caller's planning control.
141    fn relation_dependency_with_control(
142        &self,
143        resolution: &RelationNameResolution,
144        name: &str,
145        control: &uqa_core::memory::ProductionControl<'_>,
146    ) -> Result<Option<u32>, SQLError> {
147        control.check()?;
148        let dependency = self.relation_dependency(resolution, name)?;
149        control.check()?;
150        Ok(dependency)
151    }
152
153    /// The schemas that exist and that the analyzing role may use, including implicit namespaces, and its creation namespace. Catalogs without namespace state leave this unavailable.
154    fn effective_search_path(
155        &self,
156        _resolution: &RelationNameResolution,
157    ) -> Result<Option<super::resolution::EffectiveSearchPath>, SQLError> {
158        Ok(None)
159    }
160
161    fn effective_search_path_with_control(
162        &self,
163        resolution: &RelationNameResolution,
164        control: &uqa_core::memory::ProductionControl<'_>,
165    ) -> Result<uqa_core::memory::Produced<Option<super::resolution::EffectiveSearchPath>>, SQLError>
166    {
167        use uqa_core::memory::ProductionVec;
168        control.check()?;
169        let Some(path) = self.effective_search_path(resolution)? else {
170            return Ok(control.finish(None, control.empty_reservation())?);
171        };
172        let mut schemas = ProductionVec::new(*control);
173        for schema in &path.schemas {
174            schemas.push_produced(control.copy_text(schema)?)?;
175        }
176        let creation = path
177            .creation_namespace
178            .as_ref()
179            .map(|name| control.copy_text(name))
180            .transpose()?;
181        let (schemas, schema_memory) = schemas.finish()?.into_parts();
182        let (creation_namespace, creation_memory) = creation.map_or_else(
183            || (None, control.empty_reservation()),
184            |name| {
185                let (name, memory) = name.into_parts();
186                (Some(name), memory)
187            },
188        );
189        Ok(control.finish(
190            Some(super::resolution::EffectiveSearchPath {
191                schemas,
192                creation_namespace,
193            }),
194            control.combine(schema_memory, creation_memory),
195        )?)
196    }
197
198    fn table_resolved(
199        &self,
200        resolution: &RelationNameResolution,
201        name: &str,
202    ) -> Result<Option<TableDefinition>, SQLError>;
203    /// Native implementations share already retained declarations and admit namespace lookup scratch before producing it.
204    fn table_resolved_with_control(
205        &self,
206        resolution: &RelationNameResolution,
207        name: &str,
208        control: &uqa_core::memory::ProductionControl<'_>,
209    ) -> Result<Option<TableDefinition>, SQLError> {
210        control.check()?;
211        let table = self.table_resolved(resolution, name)?;
212        control.check()?;
213        Ok(table)
214    }
215
216    fn table_name_resolved_with_control(
217        &self,
218        resolution: &RelationNameResolution,
219        name: &str,
220        control: &uqa_core::memory::ProductionControl<'_>,
221    ) -> Result<Option<uqa_core::memory::Produced<String>>, SQLError> {
222        control.check()?;
223        self.table_name_resolved(resolution, name)?
224            .map(|name| control.copy_text(&name).map_err(Into::into))
225            .transpose()
226    }
227
228    fn table_name_resolved(
229        &self,
230        resolution: &RelationNameResolution,
231        name: &str,
232    ) -> Result<Option<String>, SQLError>;
233    fn view_resolved(
234        &self,
235        resolution: &RelationNameResolution,
236        name: &str,
237    ) -> Result<Option<ViewDefinition>, SQLError>;
238
239    /// Native catalogs lend one selected retained declaration; the default preserves ordinary catalog adapters.
240    fn with_view_definition_with_control(
241        &self,
242        resolution: &RelationNameResolution,
243        name: &str,
244        control: &uqa_core::memory::ProductionControl<'_>,
245        read: &mut dyn FnMut(ViewDefinitionRef<'_>) -> Result<(), SQLError>,
246    ) -> Result<(), SQLError> {
247        control.check()?;
248        if let Some(view) = self.view_resolved(resolution, name)? {
249            read((&view).into())?;
250        }
251        control.check()?;
252        Ok(())
253    }
254
255    /// Native catalogs lend column declarations without copying foreign options or unrelated metadata.
256    fn with_foreign_table_columns_with_control(
257        &self,
258        resolution: &RelationNameResolution,
259        name: &str,
260        control: &uqa_core::memory::ProductionControl<'_>,
261        read: &mut dyn FnMut(&[ColumnDef]) -> Result<(), SQLError>,
262    ) -> Result<(), SQLError> {
263        control.check()?;
264        if let Some(table) = self.foreign_table_resolved(resolution, name)? {
265            read(&table.columns)?;
266        }
267        control.check()?;
268        Ok(())
269    }
270
271    fn virtual_relation_columns_with_control(
272        &self,
273        resolution: &RelationNameResolution,
274        name: &str,
275        control: &uqa_core::memory::ProductionControl<'_>,
276    ) -> Result<Option<uqa_core::memory::Produced<Vec<String>>>, SQLError> {
277        control.check()?;
278        let Some(schema) = self.virtual_relation_schema(resolution, name)? else {
279            return Ok(None);
280        };
281        let mut columns = uqa_core::memory::ProductionVec::new(*control);
282        for (name, _) in &schema {
283            columns.push_produced(control.copy_text(name)?)?;
284        }
285        Ok(Some(columns.finish()?))
286    }
287    fn foreign_table_resolved(
288        &self,
289        resolution: &RelationNameResolution,
290        name: &str,
291    ) -> Result<Option<TableDefinition>, SQLError>;
292    fn sequence_exists(
293        &self,
294        resolution: &RelationNameResolution,
295        name: &str,
296    ) -> Result<bool, SQLError>;
297    fn virtual_relation_schema(
298        &self,
299        resolution: &RelationNameResolution,
300        name: &str,
301    ) -> Result<Option<Vec<(String, ColumnType)>>, SQLError>;
302    fn sql_functions(
303        &self,
304        resolution: &RelationNameResolution,
305        name: &str,
306    ) -> Result<Option<Vec<Arc<SQLUserFunction>>>, SQLError>;
307
308    fn unopenable_relation_with_control(
309        &self,
310        resolution: &RelationNameResolution,
311        name: &str,
312        control: &uqa_core::memory::ProductionControl<'_>,
313    ) -> Result<Option<uqa_core::memory::Produced<UnopenableRelation>>, SQLError> {
314        control.check()?;
315        self.unopenable_relation(resolution, name)?
316            .map(|relation| {
317                let (name, memory) = control.copy_text(&relation.name)?.into_parts();
318                Ok(control.finish(
319                    UnopenableRelation {
320                        name,
321                        kinds: relation.kinds,
322                    },
323                    memory,
324                )?)
325            })
326            .transpose()
327    }
328
329    /// A relation that a query cannot open, such as a composite type's relation: its unqualified name and the kind `PostgreSQL`'s detail names.
330    fn unopenable_relation(
331        &self,
332        _resolution: &RelationNameResolution,
333        _name: &str,
334    ) -> Result<Option<UnopenableRelation>, SQLError> {
335        Ok(None)
336    }
337}
338
339/// `errdetail_relkind_not_supported`: the detail naming a relation kind that an operation refuses.
340#[must_use]
341pub fn relkind_not_supported_detail(kind: &str) -> Option<String> {
342    let plural = match kind {
343        "table" => "tables",
344        "index" => "indexes",
345        "sequence" => "sequences",
346        "view" => "views",
347        "materialized view" => "materialized views",
348        "composite type" => "composite types",
349        "foreign table" => "foreign tables",
350        "partitioned table" => "partitioned tables",
351        _ => return None,
352    };
353    Some(format!("This operation is not supported for {plural}."))
354}
355
356/// A relation that holds no rows a query or command can read or change.
357#[derive(Debug, Clone, PartialEq, Eq)]
358pub struct UnopenableRelation {
359    pub name: String,
360    /// The relation kind in the plural, as `errdetail_relkind_not_supported` names it.
361    pub kinds: &'static str,
362}
363
364impl UnopenableRelation {
365    pub fn error_with_control(
366        &self,
367        control: &uqa_core::memory::ProductionControl<'_>,
368    ) -> SQLError {
369        let output = (|| {
370            let message = control.format(format_args!("cannot open relation \"{}\"", self.name))?;
371            let detail = control.format(format_args!(
372                "This operation is not supported for {}.",
373                self.kinds
374            ))?;
375            Ok::<_, uqa_core::ValueRetentionError>(SQLError::Diagnostic {
376                sqlstate: "42809".into(),
377                message: message.into_parts().0,
378                detail: Some(detail.into_parts().0),
379                hint: None,
380            })
381        })();
382        output.unwrap_or_else(Into::into)
383    }
384
385    /// `table_open`'s refusal of a relation that is not a table.
386    #[must_use]
387    pub fn error(&self) -> SQLError {
388        SQLError::Diagnostic {
389            sqlstate: "42809".into(),
390            message: format!("cannot open relation \"{}\"", self.name),
391            detail: Some(format!(
392                "This operation is not supported for {}.",
393                self.kinds
394            )),
395            hint: None,
396        }
397    }
398}
399
400pub type CatalogReadView = Arc<dyn AnalysisCatalog>;