Skip to main content

uqa_execution/catalog/index/
enforced_key_cache.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! The enforced keys of the tables a session writes, kept while the definitions they were read from are the same objects.
8
9use std::{collections::BTreeMap, sync::Arc};
10
11use parking_lot::Mutex;
12use uqa_core::RelationIdentity;
13use uqa_sql::{ast::TableKeyConstraint, catalog::index::EnforcedKey};
14use uqa_storage::{CatalogIndexRow, StorageBackendResult};
15
16type IndexRows = BTreeMap<RelationIdentity, CatalogIndexRow>;
17
18/// Tables whose keys are kept. A statement writes its target and the tables its referential actions reach.
19const TABLES: usize = 8;
20
21struct Entry {
22    table: String,
23    constraints: Vec<TableKeyConstraint>,
24    indexes: Arc<IndexRows>,
25    keys: Vec<EnforcedKey>,
26}
27
28/// Every written row asks for its table's enforced keys twice, and finding them decodes each index definition of the catalog. The keys of a table depend on its declared constraints and on the index rows, so they are kept for the same constraints and the same index rows. Arc identity follows copy-on-write catalog publication, refresh and rollback; no independent invalidation counter can omit a mutation path. The keys of a partition's index also name its ancestors, which other tables' definitions decide, and are not kept.
29#[derive(Default)]
30pub struct EnforcedKeyCache {
31    entries: Mutex<Vec<Entry>>,
32}
33
34impl EnforcedKeyCache {
35    pub fn keys(
36        &self,
37        table: &str,
38        constraints: Vec<TableKeyConstraint>,
39        indexes: &Arc<IndexRows>,
40        find: impl FnOnce(Vec<TableKeyConstraint>) -> StorageBackendResult<Vec<EnforcedKey>>,
41    ) -> StorageBackendResult<Vec<EnforcedKey>> {
42        if let Some(entry) = self.entries.lock().iter().find(|entry| {
43            entry.table == table
44                && Arc::ptr_eq(&entry.indexes, indexes)
45                && entry.constraints == constraints
46        }) {
47            return Ok(entry.keys.clone());
48        }
49        let keys = find(constraints.clone())?;
50        if keys.iter().all(|key| key.index_ancestors.is_empty()) {
51            let mut entries = self.entries.lock();
52            entries.retain(|entry| entry.table != table);
53            if entries.len() == TABLES {
54                entries.remove(0);
55            }
56            entries.push(Entry {
57                table: table.to_owned(),
58                constraints,
59                indexes: Arc::clone(indexes),
60                keys: keys.clone(),
61            });
62        }
63        Ok(keys)
64    }
65}
66
67#[cfg(test)]
68mod tests;