Skip to main content

uqa_storage_sqlite/connection/
restore.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Closed-backup constructors retain exclusive physical ownership through history publication.
8
9use std::{path::Path, sync::Arc};
10
11use uqa_storage::{mvcc::DatabaseRestore, read_control::StorageReadControl, StorageEncryptionKey};
12
13use super::{
14    compressed_vfs, default_pool_connections, ownership::RestoreAdmission, ConnectionPool,
15    ConnectionSpec, ManagedConnection, Result, SQLiteCompressedContainerAnchor,
16    SQLiteCompressionOptions, SQLiteError, SessionState,
17};
18
19impl ManagedConnection {
20    /// Restore an existing, closed consistent backup into the request's new transaction-history incarnation. Persist the request outside the database first; retry that same request after any error. Intermediate durable states reject ordinary opens. All connections, sessions, snapshots and SSI participants must be released first. A completed retry preserves later work. The returned connection can be bound to its original native or Key/Value mapping.
21    pub fn open_restored(
22        path: &Path,
23        request: DatabaseRestore,
24        control: &StorageReadControl,
25    ) -> Result<Self> {
26        Self::restore_with_spec(path, request, control, || {
27            Ok(ConnectionSpec::File {
28                path: path.to_path_buf(),
29                key: None,
30            })
31        })
32    }
33
34    /// `SQLCipher` counterpart of [`Self::open_restored`], using the same credential for its SSI database.
35    pub fn open_encrypted_restored(
36        path: &Path,
37        key: &str,
38        request: DatabaseRestore,
39        control: &StorageReadControl,
40    ) -> Result<Self> {
41        if key.is_empty() {
42            return Err(SQLiteError::EmptyEncryptionKey);
43        }
44        Self::restore_with_spec(path, request, control, || {
45            Ok(ConnectionSpec::File {
46                path: path.to_path_buf(),
47                key: Some(StorageEncryptionKey::new(key)),
48            })
49        })
50    }
51
52    /// Compressed-container counterpart of [`Self::open_restored`].
53    pub fn open_compressed_restored(
54        path: &Path,
55        compression: SQLiteCompressionOptions,
56        request: DatabaseRestore,
57        control: &StorageReadControl,
58    ) -> Result<Self> {
59        Self::restore_compressed(path, compression, None, None, request, control)
60    }
61
62    /// Encrypted compressed-container counterpart of [`Self::open_restored`].
63    pub fn open_compressed_encrypted_restored(
64        path: &Path,
65        key: &str,
66        compression: SQLiteCompressionOptions,
67        request: DatabaseRestore,
68        control: &StorageReadControl,
69    ) -> Result<Self> {
70        Self::restore_compressed(path, compression, Some(key), None, request, control)
71    }
72
73    /// Enforce the caller's trusted current container anchor before restoring. As with ordinary anchored opening, retain an updated anchor after a successful write; an old anchor cannot authorize a retry against a changed container.
74    pub fn open_compressed_encrypted_restored_with_anchor(
75        path: &Path,
76        key: &str,
77        compression: SQLiteCompressionOptions,
78        trusted_anchor: SQLiteCompressedContainerAnchor,
79        request: DatabaseRestore,
80        control: &StorageReadControl,
81    ) -> Result<Self> {
82        Self::restore_compressed(
83            path,
84            compression,
85            Some(key),
86            Some(trusted_anchor),
87            request,
88            control,
89        )
90    }
91
92    fn restore_compressed(
93        path: &Path,
94        compression: SQLiteCompressionOptions,
95        key: Option<&str>,
96        anchor: Option<SQLiteCompressedContainerAnchor>,
97        request: DatabaseRestore,
98        control: &StorageReadControl,
99    ) -> Result<Self> {
100        if key == Some("") {
101            return Err(SQLiteError::EmptyEncryptionKey);
102        }
103        let compression = compression
104            .validate()
105            .map_err(SQLiteError::CompressedContainer)?;
106        Self::restore_with_spec(path, request, control, || {
107            match anchor {
108                Some(anchor) => compressed_vfs::register_database_with_anchor(
109                    path,
110                    compression,
111                    key.ok_or(SQLiteError::EncryptionKeyRequired)?,
112                    anchor,
113                ),
114                None => compressed_vfs::register_database(path, compression, key),
115            }
116            .map_err(SQLiteError::CompressedContainer)?;
117            Ok(ConnectionSpec::Compressed {
118                path: path.to_path_buf(),
119                compression,
120                key: key.map(StorageEncryptionKey::new),
121            })
122        })
123    }
124
125    fn restore_with_spec(
126        path: &Path,
127        request: DatabaseRestore,
128        control: &StorageReadControl,
129        spec: impl FnOnce() -> Result<ConnectionSpec>,
130    ) -> Result<Self> {
131        control.check()?;
132        let admission = RestoreAdmission::acquire(path, control)?;
133        if path.metadata()?.len() == 0 {
134            return Err(SQLiteError::StorageBackend(
135                "database restoration requires an initialized record history".into(),
136            ));
137        }
138        // Allocate the returned owner before any durable transition, and install it under exclusive admission.
139        let owner = admission.retain(control)?;
140        let spec = spec()?;
141        let initial = spec.open(false)?;
142        let connection = Self {
143            pool: ConnectionPool::new(spec, initial, default_pool_connections(), Some(owner))?,
144            session: Arc::new(SessionState::new()),
145            record_access: false,
146        };
147        crate::mvcc::restore::publish(&connection, request, control)?;
148        Ok(connection)
149    }
150}