Skip to main content

uqa_engine/table_storage/constraints/
engine.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7use super::{
8    table_not_found, DocId, Engine, RelationIdentity, SQLError, StorageBackendError,
9    StorageBackendResult, TableState,
10};
11use uqa_storage::document_store::identifiers::{
12    load_legacy_document_id_watermark, restored_document_id_watermark, DocumentIdAllocator,
13};
14
15impl Engine {
16    pub fn set_column_default(
17        &self,
18        table: &str,
19        column: &str,
20        default: Option<uqa_sql::ast::Expr>,
21    ) -> StorageBackendResult<bool> {
22        self.with_implicit_storage_definition_transaction(|engine| {
23            engine.set_column_default_inner(table, column, default)
24        })
25    }
26
27    pub(crate) fn set_column_default_inner(
28        &self,
29        table: &str,
30        column: &str,
31        default: Option<uqa_sql::ast::Expr>,
32    ) -> StorageBackendResult<bool> {
33        uqa_execution::schema::publication::columns::set_column_default(
34            &self.schema_publication_context(),
35            table,
36            column,
37            default,
38        )
39    }
40
41    pub fn set_column_not_null(
42        &self,
43        table: &str,
44        column: &str,
45        not_null: bool,
46    ) -> StorageBackendResult<bool> {
47        self.with_implicit_storage_definition_transaction(|engine| {
48            engine.set_column_not_null_inner(table, column, not_null)
49        })
50    }
51
52    pub(in crate::table_storage) fn set_column_not_null_inner(
53        &self,
54        table: &str,
55        column: &str,
56        not_null: bool,
57    ) -> StorageBackendResult<bool> {
58        uqa_execution::schema::publication::columns::set_column_not_null(
59            &self.schema_publication_context(),
60            table,
61            column,
62            not_null,
63        )
64    }
65
66    pub fn set_column_type(
67        &self,
68        table: &str,
69        column: &str,
70        ty: &uqa_sql::ast::ColumnType,
71    ) -> StorageBackendResult<bool> {
72        self.with_implicit_storage_definition_transaction(|engine| {
73            engine.set_column_type_inner(table, column, ty)
74        })
75    }
76
77    pub(in crate::table_storage) fn set_column_type_inner(
78        &self,
79        table: &str,
80        column: &str,
81        ty: &uqa_sql::ast::ColumnType,
82    ) -> StorageBackendResult<bool> {
83        uqa_execution::schema::publication::columns::set_column_type(
84            &self.schema_publication_context(),
85            table,
86            column,
87            ty,
88        )
89    }
90
91    /// Register table-level CHECK, FK, PRIMARY KEY, and UNIQUE constraints. Called by the
92    /// SQL `CREATE TABLE` path after the columns are in place.
93    pub fn register_table_constraints(
94        &self,
95        table: &str,
96        checks: Vec<uqa_sql::ast::TableCheck>,
97        foreign_keys: Vec<uqa_sql::ast::ForeignKey>,
98        key_constraints: Vec<uqa_sql::ast::TableKeyConstraint>,
99    ) -> StorageBackendResult<()> {
100        self.with_implicit_storage_definition_transaction(|engine| {
101            engine.register_table_constraints_inner(table, checks, foreign_keys, key_constraints)
102        })
103    }
104
105    pub(in crate::table_storage) fn register_table_constraints_inner(
106        &self,
107        table: &str,
108        checks: Vec<uqa_sql::ast::TableCheck>,
109        foreign_keys: Vec<uqa_sql::ast::ForeignKey>,
110        key_constraints: Vec<uqa_sql::ast::TableKeyConstraint>,
111    ) -> StorageBackendResult<()> {
112        uqa_execution::schema::publication::columns::register_table_constraints(
113            &self.schema_publication_context(),
114            table,
115            checks,
116            foreign_keys,
117            key_constraints,
118        )
119    }
120
121    /// Snapshot of every CHECK constraint that applies to `table`, merging the
122    /// column-level CHECKs into the table-level list. Returns `(name, expr)`
123    /// pairs for backward API compatibility; use
124    /// [`Self::try_check_constraint_definitions`] when enforcement metadata is
125    /// required.
126    pub fn check_constraints(
127        &self,
128        table: &str,
129    ) -> StorageBackendResult<Vec<(Option<String>, uqa_sql::ast::Expr)>> {
130        self.try_check_constraints(table)
131    }
132
133    pub fn try_check_constraints(
134        &self,
135        table: &str,
136    ) -> StorageBackendResult<Vec<(Option<String>, uqa_sql::ast::Expr)>> {
137        self.with_catalog_read_snapshot(|engine| {
138            Ok(engine
139                .check_constraint_definitions_in_execution(table)?
140                .into_iter()
141                .map(|constraint| (constraint.name, constraint.expr))
142                .collect())
143        })
144    }
145
146    /// Snapshot of every CHECK constraint, including `PostgreSQL` 18 enforcement
147    /// metadata.
148    pub fn try_check_constraint_definitions(
149        &self,
150        table: &str,
151    ) -> StorageBackendResult<Vec<uqa_sql::ast::TableCheck>> {
152        self.with_catalog_read_snapshot(|engine| {
153            engine.check_constraint_definitions_in_execution(table)
154        })
155    }
156
157    pub(crate) fn check_constraint_definitions_in_execution(
158        &self,
159        table: &str,
160    ) -> StorageBackendResult<Vec<uqa_sql::ast::TableCheck>> {
161        let t = self
162            .try_table(table)?
163            .ok_or_else(|| table_not_found(table))?;
164        let mut out = uqa_sql::schema::constraint_views::column_checks(&t.columns.read());
165        out.extend(t.table_checks.read().iter().cloned());
166        Ok(out)
167    }
168
169    /// Snapshot of constraints declared at table scope, without lifting the
170    /// column-level forms into the result. Catalog synthesis uses this together
171    /// with the column definitions so every physical constraint is represented
172    /// exactly once.
173    pub(crate) fn try_declared_table_constraints(
174        &self,
175        table: &str,
176    ) -> StorageBackendResult<uqa_sql::ast::TableConstraintSet> {
177        let t = self
178            .try_table(table)?
179            .ok_or_else(|| table_not_found(table))?;
180        let checks = t.table_checks.read().clone();
181        let foreign_keys = t.foreign_keys.read().clone();
182        let key_constraints = t.key_constraints.read().clone();
183        let hierarchy = t.hierarchy.read().clone();
184        let columns_declared = *t.columns_declared.read();
185        let row_type_array_name = t.row_type_array_name.read().clone();
186        let dropped_attributes = t.dropped_attributes.read().clone();
187        Ok(uqa_sql::ast::TableConstraintSet {
188            columns_declared: Some(columns_declared),
189            persistence: t.persistence,
190            on_commit: t.on_commit,
191            checks,
192            foreign_keys,
193            key_constraints,
194            hierarchy,
195            catalog_oids: t.recorded_catalog_oids(),
196            row_type_array_name,
197            dropped_attributes,
198        })
199    }
200
201    /// Snapshot of every FOREIGN KEY constraint that applies to
202    /// `table`. Column-level `REFERENCES` are lifted to single-column
203    /// `ForeignKey` entries.
204    pub fn foreign_keys(&self, table: &str) -> StorageBackendResult<Vec<uqa_sql::ast::ForeignKey>> {
205        self.try_foreign_keys(table)
206    }
207
208    pub fn try_foreign_keys(
209        &self,
210        table: &str,
211    ) -> StorageBackendResult<Vec<uqa_sql::ast::ForeignKey>> {
212        self.with_catalog_read_snapshot(|engine| engine.foreign_keys_in_execution(table))
213    }
214
215    pub(crate) fn foreign_keys_in_execution(
216        &self,
217        table: &str,
218    ) -> StorageBackendResult<Vec<uqa_sql::ast::ForeignKey>> {
219        let t = self
220            .try_table(table)?
221            .ok_or_else(|| table_not_found(table))?;
222        let mut out: Vec<uqa_sql::ast::ForeignKey> = t.foreign_keys.read().clone();
223        uqa_sql::schema::constraint_views::append_column_foreign_keys(&t.columns.read(), &mut out);
224        uqa_sql::schema::constraint_views::bind_stored_foreign_key_targets(self, &mut out)
225            .map_err(StorageBackendError::Other)?;
226        Ok(out)
227    }
228
229    /// Tables that hold a FOREIGN KEY pointing at `table`. Used by
230    /// DELETE / DROP CASCADE to refuse the operation when a referrer
231    /// has at least one row matching the target value.
232    pub fn referrers_to(
233        &self,
234        table: &str,
235    ) -> StorageBackendResult<Vec<(String, uqa_sql::ast::ForeignKey)>> {
236        self.try_referrers_to(table)
237    }
238
239    pub fn try_referrers_to(
240        &self,
241        table: &str,
242    ) -> StorageBackendResult<Vec<(String, uqa_sql::ast::ForeignKey)>> {
243        self.with_catalog_read_snapshot(|engine| engine.referrers_in_execution(table))
244    }
245
246    pub(crate) fn referrers_in_execution(
247        &self,
248        table: &str,
249    ) -> StorageBackendResult<Vec<(String, uqa_sql::ast::ForeignKey)>> {
250        let table = self
251            .try_resolve_table_name(table)?
252            .ok_or_else(|| table_not_found(table))?;
253        let target = Self::resolved_relation_identity(&table)?;
254        self.try_table(&table)?
255            .ok_or_else(|| table_not_found(&table))?;
256        let mut out: Vec<(String, uqa_sql::ast::ForeignKey)> = Vec::new();
257        let names: Vec<String> = self
258            .storage
259            .tables
260            .read()
261            .keys()
262            .map(RelationIdentity::qualified_name)
263            .collect();
264        for other in names {
265            for fk in self.foreign_keys_in_execution(&other)? {
266                if fk.enforced && Self::foreign_key_targets(&fk, &target) {
267                    out.push((other.clone(), fk));
268                }
269            }
270        }
271        Ok(out)
272    }
273
274    /// Names of columns with a `UNIQUE` or `PRIMARY KEY` constraint
275    /// declared on the table. Auto-increment columns are excluded
276    /// because the engine guarantees their uniqueness through the
277    /// monotonic id watermark, so re-checking is redundant.
278    pub fn unique_columns(&self, table: &str) -> StorageBackendResult<Vec<String>> {
279        self.try_unique_columns(table)
280    }
281
282    pub fn try_unique_columns(&self, table: &str) -> StorageBackendResult<Vec<String>> {
283        self.with_catalog_read_snapshot(|engine| engine.unique_columns_in_execution(table))
284    }
285
286    pub(crate) fn unique_columns_in_execution(
287        &self,
288        table: &str,
289    ) -> StorageBackendResult<Vec<String>> {
290        let t = self
291            .try_table(table)?
292            .ok_or_else(|| table_not_found(table))?;
293        let auto_increment =
294            uqa_sql::schema::constraint_views::auto_increment_columns(&t.columns.read());
295        Ok(uqa_sql::schema::constraint_views::unique_scalar_columns(
296            self.key_constraints_in_execution(table)?,
297            &auto_increment,
298        ))
299    }
300
301    /// Every PRIMARY KEY / UNIQUE tuple declared on `table`. Legacy
302    /// column metadata is lifted into scalar constraints so pre-v16 and API-
303    /// created tables retain their existing behavior.
304    pub fn key_constraints(
305        &self,
306        table: &str,
307    ) -> StorageBackendResult<Vec<uqa_sql::ast::TableKeyConstraint>> {
308        self.try_key_constraints(table)
309    }
310
311    pub fn try_key_constraints(
312        &self,
313        table: &str,
314    ) -> StorageBackendResult<Vec<uqa_sql::ast::TableKeyConstraint>> {
315        self.with_catalog_read_snapshot(|engine| engine.key_constraints_in_execution(table))
316    }
317
318    pub(crate) fn key_constraints_in_execution(
319        &self,
320        table: &str,
321    ) -> StorageBackendResult<Vec<uqa_sql::ast::TableKeyConstraint>> {
322        let t = self
323            .try_table(table)?
324            .ok_or_else(|| table_not_found(table))?;
325        let mut constraints = t.key_constraints.read().clone();
326        uqa_sql::schema::constraint_views::append_column_keys(&t.columns.read(), &mut constraints);
327        Ok(constraints)
328    }
329
330    pub(crate) fn table_identifier_allocator(
331        &self,
332        state: &TableState,
333    ) -> StorageBackendResult<DocumentIdAllocator<'_>> {
334        let durable = (state.persistence != uqa_sql::ast::RelationPersistence::Temporary)
335            .then(|| self.storage.backend.as_ref()?.identifier_allocator())
336            .flatten();
337        DocumentIdAllocator::new(durable, state.object_id(), state.storage_generation())
338    }
339
340    /// Durable providers reserve identities in their storage namespace; serialized providers retain candidate locks through publication.
341    pub(crate) fn allocate_next_id(&self, table: &str) -> Result<u64, SQLError> {
342        let t = self
343            .try_table(table)
344            .map_err(|error| SQLError::Internal(format!("resolve table `{table}`: {error}")))?
345            .ok_or_else(|| SQLError::Internal(format!("unknown table `{table}`")))?;
346        let allocator = self.table_identifier_allocator(&t).map_err(|error| {
347            uqa_execution::mutation::errors::identifier_storage_error(
348                &format!("allocate document id for `{table}`"),
349                &error,
350            )
351        })?;
352        let next_candidate = || {
353            allocator.allocate(&mut t.next_id.lock()).map_err(|error| {
354                uqa_execution::mutation::errors::identifier_storage_error(
355                    &format!("allocate document id for `{table}`"),
356                    &error,
357                )
358            })
359        };
360        if allocator.is_durable()
361            || self.storage.backend.is_none()
362            || t.persistence == uqa_sql::ast::RelationPersistence::Temporary
363        {
364            return next_candidate();
365        }
366        uqa_execution::mutation::identity::reserve_document_id(
367            next_candidate,
368            |id| self.reserve_document_id_candidate(table, id),
369            |id| self.document_identity_is_occupied(table, &t, id),
370            |acquisition| self.rollback_row_lock_acquisition(acquisition),
371        )
372    }
373
374    /// Allocate an identity at or above `KEY_IDENTITY_LIMIT` for a row whose integer primary key names none. The table's floor rises to the limit first, so every later identity it generates lies there as well, where no key names one.
375    pub(crate) fn allocate_unmapped_id(&self, table: &str) -> Result<u64, SQLError> {
376        {
377            let state = self
378                .try_table(table)
379                .map_err(|error| SQLError::Internal(format!("resolve table `{table}`: {error}")))?
380                .ok_or_else(|| SQLError::Internal(format!("unknown table `{table}`")))?;
381            let mut next = state.next_id.lock();
382            *next = (*next).max(u128::from(
383                uqa_sql::semantics::key_identity::KEY_IDENTITY_LIMIT,
384            ));
385        }
386        self.allocate_next_id(table)
387    }
388
389    fn document_identity_is_occupied(
390        &self,
391        table: &str,
392        state: &TableState,
393        id: DocId,
394    ) -> Result<bool, SQLError> {
395        let contains = |store: &dyn uqa_storage::DocumentStore| {
396            store.contains_doc_id(id).map_err(|error| {
397                SQLError::Internal(format!("check document identity in `{table}`: {error}"))
398            })
399        };
400        if contains(state.document_store.read().as_ref())? {
401            return Ok(true);
402        }
403        let backend = self.storage.backend.as_ref().expect("persistent table");
404        if !self.backend_transaction_is_deferred()
405            || !backend
406                .change_version_monitor_is_nonblocking()
407                .map_err(|error| SQLError::Internal(error.to_string()))?
408        {
409            // A writer excludes other commits. A rollback-journal reader also prevents a commit while its physical snapshot remains pinned.
410            return Ok(false);
411        }
412        let canonical = self
413            .try_resolve_table_name(table)
414            .map_err(|error| SQLError::Internal(error.to_string()))?
415            .ok_or_else(|| SQLError::UnknownTable(table.to_string()))?;
416        let mut reader = self.storage.document_identity_reader.lock();
417        if reader.is_none() {
418            let session = self
419                .storage
420                .provider
421                .as_ref()
422                .map_or_else(
423                    || backend.open_session(),
424                    |provider| provider.open_session(),
425                )
426                .map_err(|error| {
427                    SQLError::Internal(format!(
428                        "open committed reader for document identity in `{table}`: {error}"
429                    ))
430                })?;
431            *reader = Some(session.backend);
432        }
433        contains(
434            reader
435                .as_ref()
436                .expect("identity reader initialized")
437                .document_store(&canonical)
438                .as_ref(),
439        )
440    }
441
442    /// Move the local watermark past `doc_id` after a supplied identity, so the next allocation of this session does not collide. The document write that publishes the row makes the identity durable.
443    pub(crate) fn advance_next_id(&self, table: &str, doc_id: DocId) -> StorageBackendResult<()> {
444        let t = self
445            .try_table(table)?
446            .ok_or_else(|| table_not_found(table))?;
447        let mut next = t.next_id.lock();
448        DocumentIdAllocator::observe(&mut next, doc_id)
449    }
450
451    pub(crate) fn persist_next_id(&self, table: &str) -> StorageBackendResult<()> {
452        let t = self
453            .try_table(table)?
454            .ok_or_else(|| table_not_found(table))?;
455        if t.persistence == uqa_sql::ast::RelationPersistence::Temporary {
456            return Ok(());
457        }
458        let Some(catalog) = self.storage.catalog.as_ref() else {
459            return Ok(());
460        };
461        let mut next = t.next_id.lock();
462        self.table_identifier_allocator(&t)?
463            .persist(catalog.as_ref(), table, &mut next)
464    }
465
466    pub(crate) fn load_persisted_next_id(
467        catalog: &dyn uqa_storage::CatalogFacade,
468        table: &str,
469    ) -> StorageBackendResult<Option<u128>> {
470        load_legacy_document_id_watermark(catalog, table)
471    }
472
473    pub(crate) fn refresh_table_next_id(
474        &self,
475        table: &str,
476        state: &TableState,
477    ) -> StorageBackendResult<()> {
478        let persisted = if state.columns.read().iter().any(|column| {
479            column
480                .auto_increment
481                .as_ref()
482                .is_some_and(uqa_sql::ast::AutoIncrement::is_legacy)
483        }) {
484            self.storage
485                .catalog
486                .as_ref()
487                .map(|catalog| Self::load_persisted_next_id(catalog.as_ref(), table))
488                .transpose()?
489                .flatten()
490        } else {
491            None
492        };
493        let maximum = state.document_store.read().max_doc_id()?;
494        let mut current = state.next_id.lock();
495        *current = restored_document_id_watermark(maximum, persisted.or(Some(*current)));
496        Ok(())
497    }
498}