Skip to main content

uqa_storage_sqlite/connection/
logical.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Connection clones and store handles share one logical transaction context.
8
9use uqa_storage::mvcc::{DatabaseId, VersionError, VersionedSessionOptions};
10use uqa_storage::read_control::StorageReadControl;
11use uqa_storage::StorageBackendResult;
12
13use super::{
14    Arc, Connection, KeyValueStore, ManagedConnection, Result, SQLiteError, SessionState,
15    VersionedKeyValueStore,
16};
17
18pub(super) struct BoundRecordSession {
19    pub(super) store: Arc<VersionedKeyValueStore>,
20    /// Stable native data namespace, separate from the store's transaction history identity.
21    pub(super) native: Option<DatabaseId>,
22}
23
24impl std::ops::Deref for BoundRecordSession {
25    type Target = VersionedKeyValueStore;
26
27    fn deref(&self) -> &Self::Target {
28        &self.store
29    }
30}
31
32impl BoundRecordSession {
33    pub(super) fn new_session_with_cancellation(
34        &self,
35        cancellation: &uqa_core::CancellationToken,
36    ) -> Self {
37        Self {
38            store: Arc::new(self.store.new_session_with_cancellation(cancellation)),
39            native: self.native,
40        }
41    }
42}
43
44impl ManagedConnection {
45    pub(crate) fn snapshot_registry(
46        &self,
47        identity: DatabaseId,
48    ) -> uqa_storage::mvcc::VersionResult<Arc<uqa_storage::mvcc::SnapshotRegistry>> {
49        let mut retained = self.pool.snapshot_registry.lock();
50        if let Some((old_identity, registry)) = retained.as_ref() {
51            if let Some(registry) = registry.upgrade() {
52                if *old_identity != identity {
53                    return Err(VersionError::WrongDatabase);
54                }
55                return Ok(registry);
56            }
57        }
58        let registry = Arc::new(uqa_storage::mvcc::SnapshotRegistry::default());
59        *retained = Some((identity, Arc::downgrade(&registry)));
60        Ok(registry)
61    }
62
63    /// Create an independent logical session over the same database pool.
64    /// Explicit transactions started on either session are isolated and never
65    /// capture operations issued through the other session.
66    #[must_use]
67    pub fn new_session(&self) -> Self {
68        self.new_session_with_cancellation(&uqa_core::CancellationToken::new())
69    }
70
71    /// Use a fresh transaction context while sharing the invoking execution's write cancellation. Existing sessions and clones keep their original token.
72    #[must_use]
73    pub fn new_session_with_cancellation(
74        &self,
75        cancellation: &uqa_core::CancellationToken,
76    ) -> Self {
77        let _gate = self.session.gate.read();
78        let session = SessionState::with_cancellation(cancellation.clone());
79        if let Some(logical) = self.session.logical.get() {
80            let _ = session.logical.set(Arc::new(
81                logical.new_session_with_cancellation(cancellation),
82            ));
83        }
84        Self {
85            pool: Arc::clone(&self.pool),
86            session: Arc::new(session),
87            record_access: self.record_access,
88        }
89    }
90
91    /// Keep the bound record view and its logical reader attribution in an independent read-only connection. The source session retains ownership of publication and transaction completion.
92    pub(crate) fn new_retained_read_session(
93        &self,
94        cancellation: &uqa_core::CancellationToken,
95    ) -> Result<Self> {
96        self.surface_cleanup_failure()?;
97        let _gate = self.session.gate.read();
98        let logical = self
99            .session
100            .logical
101            .get()
102            .ok_or(SQLiteError::LogicalSessionRequired)?;
103        let store = logical.new_retained_read_session(cancellation)?;
104        let session = SessionState::with_cancellation(cancellation.clone());
105        let _ = session.logical.set(Arc::new(BoundRecordSession {
106            store: Arc::new(store),
107            native: logical.native,
108        }));
109        Ok(Self {
110            pool: Arc::clone(&self.pool),
111            session: Arc::new(session),
112            record_access: self.record_access,
113        })
114    }
115
116    /// Share the token used for autonomous allocation and record publication. Cleanup reads and rollback remain independent of this flag.
117    pub fn write_cancellation(&self) -> uqa_core::CancellationToken {
118        self.session.write_cancellation.clone()
119    }
120
121    /// Transaction ownership selected for this connection and inherited by its independent sessions.
122    pub fn transaction_model(&self) -> uqa_storage::StorageTransactionModel {
123        let _gate = self.session.gate.read();
124        self.session.logical.get().map_or(
125            uqa_storage::StorageTransactionModel::ProviderSerialized,
126            |logical| logical.transaction_model(),
127        )
128    }
129
130    pub(crate) fn record_connection(&self) -> Self {
131        Self {
132            pool: Arc::clone(&self.pool),
133            session: Arc::new(SessionState::new()),
134            record_access: true,
135        }
136    }
137
138    pub(crate) fn with_record_connection<R>(
139        &self,
140        control: &StorageReadControl,
141        operation: impl FnOnce(&Connection) -> Result<R>,
142    ) -> Result<R> {
143        self.surface_cleanup_failure()?;
144        let _gate = self.session.gate.read();
145        if !self.record_access || self.session.transaction.lock().is_some() {
146            return Err(SQLiteError::SessionMappingMismatch);
147        }
148        let connection = self
149            .pool
150            .checkout_with_cancellation(Some(control.cancellation()))?;
151        operation(connection.connection()?)
152    }
153
154    pub(crate) fn bind_records(
155        &self,
156        options: VersionedSessionOptions,
157    ) -> Result<Arc<VersionedKeyValueStore>> {
158        self.surface_cleanup_failure()?;
159        let _gate = self.session.gate.write();
160        if let Some(logical) = self.session.logical.get() {
161            if logical.native.is_some() {
162                return Err(SQLiteError::SessionMappingMismatch);
163            }
164            if logical.options().retained_bytes != options.retained_bytes {
165                return Err(SQLiteError::SessionOptionsMismatch);
166            }
167            return Ok(Arc::clone(&logical.store));
168        }
169        if self.session.transaction.lock().is_some() {
170            return Err(SQLiteError::TransactionAlreadyActive);
171        }
172        let identity = self.storage_identity()?;
173        let records = crate::SQLiteRecordStore::for_key_value(
174            self,
175            &StorageReadControl::with_limit(options.retained_bytes),
176        )
177        .map_err(VersionError::into_storage_error)?;
178        let logical = Arc::new(VersionedKeyValueStore::new_with_cancellation(
179            Arc::new(records),
180            identity,
181            options,
182            self.write_cancellation(),
183        ));
184        self.session
185            .logical
186            .set(Arc::new(BoundRecordSession {
187                store: Arc::clone(&logical),
188                native: None,
189            }))
190            .map_err(|_| SQLiteError::SessionOptionsMismatch)?;
191        Ok(logical)
192    }
193
194    pub(crate) fn with_records<R>(
195        &self,
196        operation: impl FnOnce(&VersionedKeyValueStore) -> StorageBackendResult<R>,
197    ) -> StorageBackendResult<R> {
198        self.surface_cleanup_failure()?;
199        let _gate = self.session.gate.read();
200        let logical = self
201            .session
202            .logical
203            .get()
204            .ok_or(SQLiteError::LogicalSessionRequired)?;
205        if logical.native.is_some() {
206            return Err(SQLiteError::SessionMappingMismatch.into());
207        }
208        operation(logical)
209    }
210
211    pub(crate) fn retention_control(
212        &self,
213    ) -> Option<uqa_storage::read_control::StorageReadControl> {
214        self.session
215            .logical
216            .get()
217            .map(|logical| logical.retention_control())
218    }
219
220    pub(crate) fn begin_record_read(&self) -> Result<()> {
221        self.surface_cleanup_failure()?;
222        let _gate = self.session.gate.write();
223        let logical = self
224            .session
225            .logical
226            .get()
227            .ok_or(SQLiteError::LogicalSessionRequired)?;
228        if logical.in_transaction() {
229            return Err(SQLiteError::TransactionAlreadyActive);
230        }
231        logical.begin_read_transaction().map_err(Into::into)
232    }
233
234    /// Advance a bound native or Key/Value command view through the common session, without opening a physical writer. Legacy physical transactions require their existing transaction boundary instead.
235    pub fn refresh_transaction_snapshot(
236        &self,
237        cancellation: &uqa_core::CancellationToken,
238    ) -> Result<()> {
239        self.surface_cleanup_failure()?;
240        let _gate = self.session.gate.write();
241        self.session
242            .logical
243            .get()
244            .ok_or(SQLiteError::LogicalSessionRequired)?
245            .refresh_transaction_snapshot(cancellation)
246            .map_err(Into::into)
247    }
248
249    pub(super) fn check_native_access(&self, connection: &Connection) -> Result<()> {
250        if self.record_access {
251            return Ok(());
252        }
253        let versioned: bool = connection.prepare_cached(
254            "SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE (name = '_key_value' AND type = 'view') OR name GLOB '_uqa_mvcc_native_*')",
255        )?.query_row([], |row| row.get(0))?;
256        if versioned {
257            return Err(SQLiteError::LogicalSessionRequired);
258        }
259        Ok(())
260    }
261
262    /// Access physical `SQLite` state for explicit diagnostics or maintenance outside any session transaction. This does not read private logical changes; ordinary stores must use their owning transaction interface. Record-table write guards remain active.
263    pub fn with_physical<R>(&self, operation: impl FnOnce(&Connection) -> Result<R>) -> Result<R> {
264        self.surface_cleanup_failure()?;
265        let _gate = self.session.gate.write();
266        if self.session.transaction.lock().is_some()
267            || self
268                .session
269                .logical
270                .get()
271                .is_some_and(|logical| logical.in_transaction())
272        {
273            return Err(SQLiteError::TransactionAlreadyActive);
274        }
275        let connection = self.pool.checkout()?;
276        operation(connection.connection()?)
277    }
278}
279
280#[cfg(test)]
281mod tests {
282    use super::*;
283    use uqa_storage::mvcc::{CommitErrorOutcome, CommitFailure, DatabaseId, StorageTransactionId};
284    use uqa_storage::StorageBackendError;
285
286    #[test]
287    fn record_checkout_cancellation_does_not_wait_for_a_retained_pool_connection() {
288        use std::{sync::mpsc, thread, time::Duration};
289
290        let connection = ManagedConnection::open_in_memory()
291            .unwrap()
292            .record_connection();
293        let held = connection.pool.checkout().unwrap();
294        let control = StorageReadControl::with_limit(1 << 20);
295        let cancellation = control.cancellation().clone();
296        let (started_tx, started_rx) = mpsc::channel();
297        let (finished_tx, finished_rx) = mpsc::channel();
298        thread::scope(|scope| {
299            let worker = scope.spawn(|| {
300                started_tx.send(()).unwrap();
301                let result = connection.with_record_connection(&control, |_| {
302                    panic!("cancelled checkout must not enter the operation")
303                });
304                finished_tx.send(result).unwrap();
305            });
306            started_rx.recv_timeout(Duration::from_secs(30)).unwrap();
307            cancellation.cancel();
308            let result = finished_rx.recv_timeout(Duration::from_secs(30));
309            drop(held);
310            worker.join().unwrap();
311            assert!(matches!(
312                result.unwrap(),
313                Err::<(), _>(SQLiteError::Cancelled(_))
314            ));
315        });
316    }
317
318    #[test]
319    fn storage_error_conversion_preserves_an_indeterminate_commit_identity() {
320        let transaction = StorageTransactionId::new(DatabaseId::from_bytes([7; 16]), 3).unwrap();
321        let original = StorageBackendError::backend(
322            "MVCC",
323            CommitFailure::Indeterminate {
324                transaction,
325                source: StorageBackendError::Other("commit reply lost".into()),
326            },
327        );
328        let converted = StorageBackendError::from(SQLiteError::from(original));
329        assert_eq!(
330            converted.commit_outcome(),
331            Some(CommitErrorOutcome::Indeterminate(transaction))
332        );
333        let StorageBackendError::Backend { backend, source } = converted else {
334            panic!("typed commit outcome was lost");
335        };
336        assert_eq!(backend, "MVCC");
337        assert!(
338            matches!(source.downcast_ref::<CommitFailure>(), Some(CommitFailure::Indeterminate { transaction: found, .. }) if *found == transaction)
339        );
340    }
341}