Skip to main content

uqa_engine/table_storage/
table_lifecycle.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Public table metadata APIs and their existing transaction boundaries.
8
9use super::{table_not_found, Engine, RelationIdentity, StorageBackendResult};
10
11fn table_metadata_error(error: uqa_sql::SQLError) -> uqa_storage::StorageBackendError {
12    uqa_storage::StorageBackendError::backend("table metadata query", error)
13}
14
15impl Engine {
16    /// Drop a table from the catalog and release its in-memory state.
17    /// Returns `true` if the table existed.
18    pub fn drop_table(&self, name: &str) -> StorageBackendResult<bool> {
19        self.try_drop_table(name)
20    }
21
22    pub(crate) fn try_drop_table(&self, name: &str) -> StorageBackendResult<bool> {
23        self.with_implicit_definition_transaction(|engine| {
24            uqa_execution::schema::removal::direct::drop_table(
25                &engine.relation_removal_context(),
26                name,
27            )
28        })
29        .map_err(|error| uqa_storage::StorageBackendError::backend("DROP TABLE", error))
30    }
31
32    pub(crate) fn drop_temporary_table_on_commit_inner(
33        &self,
34        name: &str,
35    ) -> StorageBackendResult<()> {
36        use uqa_execution::schema::deletion::CatalogRemovalInputs;
37        uqa_execution::schema::deletion::drop_table_on_commit(&self.catalog_removal_context(), name)
38            .map_err(|error| uqa_storage::StorageBackendError::backend("ON COMMIT DROP", error))
39    }
40
41    pub fn has_table(&self, name: &str) -> StorageBackendResult<bool> {
42        self.try_has_table(name)
43    }
44
45    pub fn try_has_table(&self, name: &str) -> StorageBackendResult<bool> {
46        self.with_direct_query_snapshot(
47            true,
48            |engine| engine.has_table_in_execution(name),
49            table_metadata_error,
50        )
51    }
52
53    pub(crate) fn has_table_in_execution(&self, name: &str) -> StorageBackendResult<bool> {
54        Ok(self.try_resolve_table_name(name)?.is_some())
55    }
56
57    pub(crate) fn try_query_has_table(&self, name: &str) -> StorageBackendResult<bool> {
58        Ok(self.try_resolve_query_table_name(name)?.is_some())
59    }
60
61    /// All schema-declared columns for `table`, in declaration order.
62    pub fn table_columns(&self, table: &str) -> StorageBackendResult<Vec<String>> {
63        self.try_table_columns(table)
64    }
65
66    pub fn try_table_columns(&self, table: &str) -> StorageBackendResult<Vec<String>> {
67        self.with_direct_query_snapshot(
68            true,
69            |engine| engine.table_columns_in_execution(table),
70            table_metadata_error,
71        )
72    }
73
74    pub(crate) fn table_columns_in_execution(
75        &self,
76        table: &str,
77    ) -> StorageBackendResult<Vec<String>> {
78        let table_state = self
79            .try_table(table)?
80            .ok_or_else(|| table_not_found(table))?;
81        let columns = table_state
82            .columns
83            .read()
84            .iter()
85            .map(|column| column.name.clone())
86            .collect();
87        Ok(columns)
88    }
89
90    pub(crate) fn try_query_table_columns(&self, table: &str) -> StorageBackendResult<Vec<String>> {
91        let table_state = self
92            .try_query_table(table)?
93            .ok_or_else(|| table_not_found(table))?;
94        let columns = table_state
95            .columns
96            .read()
97            .iter()
98            .map(|column| column.name.clone())
99            .collect();
100        Ok(columns)
101    }
102
103    pub fn table_has_column(&self, table: &str, column: &str) -> StorageBackendResult<bool> {
104        self.try_table_has_column(table, column)
105    }
106
107    pub fn try_table_has_column(&self, table: &str, column: &str) -> StorageBackendResult<bool> {
108        self.with_direct_query_snapshot(
109            true,
110            |engine| engine.table_has_column_in_execution(table, column),
111            table_metadata_error,
112        )
113    }
114
115    pub(crate) fn table_has_column_in_execution(
116        &self,
117        table: &str,
118        column: &str,
119    ) -> StorageBackendResult<bool> {
120        let t = self
121            .try_table(table)?
122            .ok_or_else(|| table_not_found(table))?;
123        let cols = t.columns.read();
124        Ok(cols.iter().any(|c| c.name == column))
125    }
126
127    pub(crate) fn try_query_table_has_column(
128        &self,
129        table: &str,
130        column: &str,
131    ) -> StorageBackendResult<bool> {
132        let table = self
133            .try_query_table(table)?
134            .ok_or_else(|| table_not_found(table))?;
135        let found = table
136            .columns
137            .read()
138            .iter()
139            .any(|candidate| candidate.name == column);
140        Ok(found)
141    }
142
143    pub(crate) fn column_type(
144        &self,
145        table: &str,
146        column: &str,
147    ) -> StorageBackendResult<Option<uqa_sql::ast::ColumnType>> {
148        let t = self
149            .try_table(table)?
150            .ok_or_else(|| table_not_found(table))?;
151        let cols = t.columns.read();
152        Ok(cols.iter().find(|c| c.name == column).map(|c| c.ty.clone()))
153    }
154
155    /// Return the first SERIAL or identity column name for `table`, if any.
156    pub(crate) fn auto_increment_column(
157        &self,
158        table: &str,
159    ) -> StorageBackendResult<Option<String>> {
160        let t = self
161            .try_table(table)?
162            .ok_or_else(|| table_not_found(table))?;
163        let cols = t.columns.read();
164        Ok(cols
165            .iter()
166            .find(|c| c.auto_increment.is_some())
167            .map(|c| c.name.clone()))
168    }
169
170    /// Sequence-generating columns and their durable provenance, in schema order. More than one `SERIAL`/identity column may exist on a table; none of them names a row's physical document unless it is the table's single primary key.
171    pub(crate) fn auto_increment_columns(
172        &self,
173        table: &str,
174    ) -> StorageBackendResult<Vec<(String, uqa_sql::ast::AutoIncrement)>> {
175        let t = self
176            .try_table(table)?
177            .ok_or_else(|| table_not_found(table))?;
178        let columns = t
179            .columns
180            .read()
181            .iter()
182            .filter_map(|column| {
183                column
184                    .auto_increment
185                    .clone()
186                    .map(|provenance| (column.name.clone(), provenance))
187            })
188            .collect();
189        Ok(columns)
190    }
191
192    /// Sorted list of every registered table name.
193    pub fn table_names(&self) -> StorageBackendResult<Vec<String>> {
194        self.with_direct_query_snapshot(true, Self::table_names_in_execution, table_metadata_error)
195    }
196
197    pub(crate) fn table_names_in_execution(&self) -> StorageBackendResult<Vec<String>> {
198        self.synchronize_table_catalog()?;
199        Ok(self
200            .storage
201            .tables
202            .read()
203            .keys()
204            .map(RelationIdentity::qualified_name)
205            .collect())
206    }
207
208    /// Snapshot the column schema of `table`. Returns `None` when no
209    /// table by that name is registered.
210    pub fn describe_table(
211        &self,
212        table: &str,
213    ) -> StorageBackendResult<Option<Vec<uqa_sql::ast::ColumnDef>>> {
214        self.try_describe_table(table)
215    }
216
217    pub fn try_describe_table(
218        &self,
219        table: &str,
220    ) -> StorageBackendResult<Option<Vec<uqa_sql::ast::ColumnDef>>> {
221        self.with_direct_query_snapshot(
222            true,
223            |engine| engine.describe_table_in_execution(table),
224            table_metadata_error,
225        )
226    }
227
228    pub(crate) fn describe_table_in_execution(
229        &self,
230        table: &str,
231    ) -> StorageBackendResult<Option<Vec<uqa_sql::ast::ColumnDef>>> {
232        let Some(table) = self.try_table(table)? else {
233            return Ok(None);
234        };
235        let mut columns = table.columns.read().clone();
236        for column in &mut columns {
237            if let Some(default) = &mut column.default {
238                self.resolve_stored_sequence_references_in_expr(default)?;
239            }
240            if let Some(generated) = &mut column.generated {
241                self.resolve_stored_sequence_references_in_expr(&mut generated.expression)?;
242            }
243        }
244        Ok(Some(columns))
245    }
246
247    pub(crate) fn try_describe_query_table(
248        &self,
249        table: &str,
250    ) -> StorageBackendResult<Option<Vec<uqa_sql::ast::ColumnDef>>> {
251        let Some(table) = self.try_query_table(table)? else {
252            return Ok(None);
253        };
254        let mut columns = table.columns.read().clone();
255        for column in &mut columns {
256            if let Some(default) = &mut column.default {
257                self.resolve_stored_sequence_references_in_expr(default)?;
258            }
259            if let Some(generated) = &mut column.generated {
260                self.resolve_stored_sequence_references_in_expr(&mut generated.expression)?;
261            }
262        }
263        Ok(Some(columns))
264    }
265
266    /// Snapshot catalog column definitions without resolving executable
267    /// default or generated expressions. Static row-type validation uses this
268    /// while catalog registries are reloaded under the backend transaction
269    /// mutex, where opening a sequence session would recursively acquire that
270    /// mutex.
271    pub(crate) fn try_describe_table_row_type(
272        &self,
273        table: &str,
274    ) -> StorageBackendResult<Option<Vec<uqa_sql::ast::ColumnDef>>> {
275        let Some(table) = self.try_table(table)? else {
276            return Ok(None);
277        };
278        let columns = table.columns.read().clone();
279        Ok(Some(columns))
280    }
281
282    /// DEFAULT expression for `column` on `table`, when one was
283    /// declared via `... <col> <type> DEFAULT <expr>`.
284    pub fn column_default_expr(
285        &self,
286        table: &str,
287        column: &str,
288    ) -> StorageBackendResult<Option<uqa_sql::ast::Expr>> {
289        self.try_column_default_expr(table, column)
290    }
291
292    pub fn try_column_default_expr(
293        &self,
294        table: &str,
295        column: &str,
296    ) -> StorageBackendResult<Option<uqa_sql::ast::Expr>> {
297        self.with_catalog_read_snapshot(|engine| {
298            engine.column_default_expr_in_execution(table, column)
299        })
300    }
301
302    pub(crate) fn column_default_expr_in_execution(
303        &self,
304        table: &str,
305        column: &str,
306    ) -> StorageBackendResult<Option<uqa_sql::ast::Expr>> {
307        let t = self
308            .try_table(table)?
309            .ok_or_else(|| table_not_found(table))?;
310        let cols = t.columns.read();
311        let mut default = cols
312            .iter()
313            .find(|c| c.name == column)
314            .and_then(|c| c.default.clone());
315        drop(cols);
316        if let Some(default) = &mut default {
317            self.resolve_stored_sequence_references_in_expr(default)?;
318        }
319        Ok(default)
320    }
321}