uqa-storage-sqlite 0.6.2

SQLite catalog, indexes, compressed storage, graph and key/value providers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! On-disk database format detection.
//!
//! `usql` and embedding applications need to decide which `Engine`
//! open variant fits an existing file before they have a key in hand:
//! plaintext `SQLite` and UQA compressed containers carry cleartext
//! magic bytes, while `SQLCipher` encrypts the whole file (including the
//! `SQLite` header), so an encrypted catalog is indistinguishable from a
//! non-database file without attempting a keyed open.

use std::fs::File;
use std::io::Read;
use std::path::Path;

use crate::compressed_vfs::{FLAG_ENCRYPTED, HEADER_FLAGS_OFFSET, LEGACY_MAGIC, MAGIC};
use crate::{
    ManagedConnection, SQLiteCompressedContainerAnchor, SQLiteCompressionOptions, SQLiteError,
};

/// First 16 bytes of every plaintext `SQLite` database file.
const SQLITE_MAGIC: &[u8; 16] = b"SQLite format 3\0";

/// Number of leading bytes required to classify a file: the `SQLite`
/// magic is 16 bytes and the compressed-container flags word ends at
/// byte 16 as well.
const DETECT_PREFIX_LEN: usize = 16;

/// On-disk format of a database file, detected from its header bytes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DatabaseFileFormat {
    /// The file does not exist or is empty. Opening it creates a new
    /// database.
    Missing,
    /// A plaintext `SQLite` database (`SQLite format 3\0` magic).
    PlainSQLite,
    /// A UQA compressed container (`UQACDB2\0`, or legacy `UQACDB1\0`,
    /// magic). `encrypted` reflects the header flag: when set, opening
    /// requires a key.
    CompressedContainer { encrypted: bool },
    /// No recognizable magic. Either a `SQLCipher`-encrypted database or
    /// not a database at all; the two cannot be told apart without
    /// attempting an open with a key.
    Unrecognized,
}

impl DatabaseFileFormat {
    /// Whether opening this file is known to require an encryption
    /// key. `Unrecognized` returns `true` because the dominant cause
    /// for an unrecognized header on a database path is `SQLCipher`
    /// encryption.
    #[must_use]
    pub fn requires_key(self) -> bool {
        matches!(
            self,
            Self::CompressedContainer { encrypted: true } | Self::Unrecognized
        )
    }
}

/// Classify the on-disk format of `path` by reading its first bytes.
///
/// Only returns `Err` for I/O failures other than "file not found";
/// a missing or empty file is reported as [`DatabaseFileFormat::Missing`].
pub fn detect_database_file_format(path: &Path) -> std::io::Result<DatabaseFileFormat> {
    let mut file = match File::open(path) {
        Ok(file) => file,
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
            return Ok(DatabaseFileFormat::Missing);
        }
        Err(err) => return Err(err),
    };
    let mut prefix = [0_u8; DETECT_PREFIX_LEN];
    let mut read = 0;
    while read < prefix.len() {
        let n = file.read(&mut prefix[read..])?;
        if n == 0 {
            break;
        }
        read += n;
    }
    if read == 0 {
        return Ok(DatabaseFileFormat::Missing);
    }
    if read < DETECT_PREFIX_LEN {
        // Too short for any valid database header.
        return Ok(DatabaseFileFormat::Unrecognized);
    }
    if &prefix == SQLITE_MAGIC {
        return Ok(DatabaseFileFormat::PlainSQLite);
    }
    if &prefix[..MAGIC.len()] == MAGIC || &prefix[..LEGACY_MAGIC.len()] == LEGACY_MAGIC {
        let flags = u32::from_le_bytes([
            prefix[HEADER_FLAGS_OFFSET],
            prefix[HEADER_FLAGS_OFFSET + 1],
            prefix[HEADER_FLAGS_OFFSET + 2],
            prefix[HEADER_FLAGS_OFFSET + 3],
        ]);
        return Ok(DatabaseFileFormat::CompressedContainer {
            encrypted: flags & FLAG_ENCRYPTED != 0,
        });
    }
    Ok(DatabaseFileFormat::Unrecognized)
}

impl ManagedConnection {
    /// Open the detected `SQLite` file format, preserving encryption requirements.
    ///
    /// Missing files use `SQLCipher` when a key is supplied and plain `SQLite` otherwise. Existing compressed files retain their recorded codec. A key on an unencrypted file is rejected; encrypted or unrecognized files require a key. New compressed files require an explicit compression constructor.
    pub fn open_auto(path: &Path, key: Option<&str>) -> Result<Self, SQLiteError> {
        Self::open_detected(path, key, None)
    }

    /// Detect an existing encrypted compressed container and enforce its externally retained identity and committed state before opening it. Missing and other file formats are rejected without creating a database.
    pub fn open_auto_with_anchor(
        path: &Path,
        key: &str,
        trusted_anchor: SQLiteCompressedContainerAnchor,
    ) -> Result<Self, SQLiteError> {
        Self::open_detected(path, Some(key), Some(trusted_anchor))
    }

    fn open_detected(
        path: &Path,
        key: Option<&str>,
        anchor: Option<SQLiteCompressedContainerAnchor>,
    ) -> Result<Self, SQLiteError> {
        let key = match key {
            Some("") => return Err(SQLiteError::EmptyEncryptionKey),
            other => other,
        };
        let format = detect_database_file_format(path)?;
        if anchor.is_some()
            && format != (DatabaseFileFormat::CompressedContainer { encrypted: true })
        {
            return Err(SQLiteError::StorageBackend(
                "a trusted anchor requires an existing encrypted compressed container".into(),
            ));
        }
        match format {
            DatabaseFileFormat::Missing => match key {
                Some(key) => Self::open_encrypted(path, key),
                None => Self::open(path),
            },
            DatabaseFileFormat::PlainSQLite => match key {
                Some(_) => Err(SQLiteError::NotEncrypted),
                None => Self::open(path),
            },
            DatabaseFileFormat::CompressedContainer { encrypted: true } => match key {
                Some(key) => match anchor {
                    Some(anchor) => Self::open_compressed_encrypted_with_anchor(
                        path,
                        key,
                        SQLiteCompressionOptions::default(),
                        anchor,
                    ),
                    None => Self::open_compressed_encrypted(
                        path,
                        key,
                        SQLiteCompressionOptions::default(),
                    ),
                },
                None => Err(SQLiteError::EncryptionKeyRequired),
            },
            DatabaseFileFormat::CompressedContainer { encrypted: false } => match key {
                Some(_) => Err(SQLiteError::NotEncrypted),
                None => Self::open_compressed(path, SQLiteCompressionOptions::default()),
            },
            DatabaseFileFormat::Unrecognized => match key {
                Some(key) => Self::open_encrypted(path, key),
                None => Err(SQLiteError::EncryptionKeyRequired),
            },
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use crate::compressed_vfs::SQLiteCompressionOptions;
    use crate::connection::ManagedConnection;

    fn temp_dir() -> tempfile::TempDir {
        tempfile::tempdir().expect("tempdir")
    }

    #[test]
    fn automatic_anchored_open_preserves_exact_state_and_rejects_missing_files() {
        let directory = temp_dir();
        for (index, compression) in [
            SQLiteCompressionOptions::lz4(),
            SQLiteCompressionOptions::zstd(),
        ]
        .into_iter()
        .enumerate()
        {
            let path = directory.path().join(format!("anchored-{index}"));
            let old_file = directory.path().join(format!("old-{index}"));
            let key = "automatic-anchor-key";
            let connection =
                ManagedConnection::open_compressed_encrypted(&path, key, compression).unwrap();
            connection
                .with(|sql| {
                    Ok(sql.execute_batch("CREATE TABLE t (n INTEGER); INSERT INTO t VALUES (7)")?)
                })
                .unwrap();
            drop(connection);
            let first = crate::read_authenticated_anchor(&path, key).unwrap();
            std::fs::copy(&path, &old_file).unwrap();
            for part in 0..3 {
                let mut invalid = first;
                match part {
                    0 => invalid.database_id[0] ^= 1,
                    1 => invalid.generation ^= 1,
                    _ => invalid.state_tag[0] ^= 1,
                }
                assert!(ManagedConnection::open_auto_with_anchor(&path, key, invalid).is_err());
            }
            let connection = ManagedConnection::open_auto_with_anchor(&path, key, first).unwrap();
            connection
                .with(|sql| Ok(sql.execute_batch("INSERT INTO t VALUES (8)")?))
                .unwrap();
            drop(connection);
            let current = crate::read_authenticated_anchor(&path, key).unwrap();
            assert_eq!(first.database_id, current.database_id);
            assert!(current.generation > first.generation);
            assert_ne!(current.state_tag, first.state_tag);
            assert!(ManagedConnection::open_auto_with_anchor(&path, key, first).is_err());
            let connection = ManagedConnection::open_auto_with_anchor(&path, key, current).unwrap();
            let count: i64 = connection
                .with(|sql| Ok(sql.query_row("SELECT count(*) FROM t", [], |row| row.get(0))?))
                .unwrap();
            assert_eq!(count, 2);
            drop(connection);
            std::fs::copy(&old_file, &path).unwrap();
            assert!(ManagedConnection::open_auto_with_anchor(&path, key, current).is_err());
            let missing = directory.path().join(format!("missing-{index}"));
            assert!(ManagedConnection::open_auto_with_anchor(&missing, key, current).is_err());
            assert!(!missing.exists());
            let plain = directory.path().join(format!("plain-{index}"));
            let connection = ManagedConnection::open(&plain).unwrap();
            connection
                .with(|sql| Ok(sql.execute_batch("CREATE TABLE retained (n INTEGER)")?))
                .unwrap();
            drop(connection);
            let before = std::fs::read(&plain).unwrap();
            assert!(ManagedConnection::open_auto_with_anchor(&plain, key, current).is_err());
            assert_eq!(std::fs::read(&plain).unwrap(), before);
        }
    }

    #[test]
    fn automatic_connections_preserve_data_and_encryption_across_all_codecs() {
        let directory = temp_dir();
        for (index, compression) in [
            None,
            Some(SQLiteCompressionOptions::zstd()),
            Some(SQLiteCompressionOptions::lz4()),
        ]
        .into_iter()
        .enumerate()
        {
            for key in [None, Some("automatic-open-test-key")] {
                let path = directory.path().join(format!("{index}-{}", key.is_some()));
                let connection = match (compression, key) {
                    (None, key) => ManagedConnection::open_auto(&path, key),
                    (Some(options), None) => ManagedConnection::open_compressed(&path, options),
                    (Some(options), Some(key)) => {
                        ManagedConnection::open_compressed_encrypted(&path, key, options)
                    }
                }
                .unwrap();
                connection
                    .with(|sqlite| {
                        Ok(sqlite.execute_batch(
                            "CREATE TABLE retained (n INTEGER); INSERT INTO retained VALUES (101)",
                        )?)
                    })
                    .unwrap();
                drop(connection);
                let reopened = ManagedConnection::open_auto(&path, key).unwrap();
                let value = reopened
                    .with(|sqlite| {
                        Ok(sqlite
                            .query_row("SELECT n FROM retained", [], |row| row.get::<_, i64>(0))?)
                    })
                    .unwrap();
                assert_eq!(value, 101);
                drop(reopened);
                if key.is_some() {
                    assert!(matches!(
                        ManagedConnection::open_auto(&path, None),
                        Err(SQLiteError::EncryptionKeyRequired)
                    ));
                    assert!(ManagedConnection::open_auto(&path, Some("wrong-key")).is_err());
                } else {
                    assert!(matches!(
                        ManagedConnection::open_auto(&path, Some("unused-key")),
                        Err(SQLiteError::NotEncrypted)
                    ));
                }
            }
        }
    }

    #[test]
    fn automatic_connections_reject_empty_keys_before_creating_files() {
        let directory = temp_dir();
        let path = directory.path().join("absent.db");
        assert!(matches!(
            ManagedConnection::open_auto(&path, Some("")),
            Err(SQLiteError::EmptyEncryptionKey)
        ));
        assert!(!path.exists());
        std::fs::write(&path, b"a foreign file with an unrecognized header").unwrap();
        assert!(matches!(
            ManagedConnection::open_auto(&path, None),
            Err(SQLiteError::EncryptionKeyRequired)
        ));
    }

    #[test]
    fn missing_file_detects_as_missing() {
        let dir = temp_dir();
        let path = dir.path().join("absent.db");
        assert_eq!(
            detect_database_file_format(&path).unwrap(),
            DatabaseFileFormat::Missing
        );
    }

    #[test]
    fn empty_file_detects_as_missing() {
        let dir = temp_dir();
        let path = dir.path().join("empty.db");
        std::fs::write(&path, b"").unwrap();
        assert_eq!(
            detect_database_file_format(&path).unwrap(),
            DatabaseFileFormat::Missing
        );
    }

    #[test]
    fn plaintext_sqlite_detects_as_plain() {
        let dir = temp_dir();
        let path = dir.path().join("plain.db");
        {
            let conn = ManagedConnection::open(&path).unwrap();
            conn.with(|c| Ok(c.execute_batch("CREATE TABLE t (id INTEGER)")?))
                .unwrap();
        }
        assert_eq!(
            detect_database_file_format(&path).unwrap(),
            DatabaseFileFormat::PlainSQLite
        );
    }

    #[test]
    fn sqlcipher_database_detects_as_unrecognized() {
        let dir = temp_dir();
        let path = dir.path().join("cipher.db");
        {
            let conn = ManagedConnection::open_encrypted(&path, "secret").unwrap();
            conn.with(|c| Ok(c.execute_batch("CREATE TABLE t (id INTEGER)")?))
                .unwrap();
        }
        assert_eq!(
            detect_database_file_format(&path).unwrap(),
            DatabaseFileFormat::Unrecognized
        );
    }

    #[test]
    fn compressed_container_detects_with_encryption_flag() {
        let dir = temp_dir();
        let plain = dir.path().join("container.db");
        {
            let conn =
                ManagedConnection::open_compressed(&plain, SQLiteCompressionOptions::default())
                    .unwrap();
            conn.with(|c| Ok(c.execute_batch("CREATE TABLE t (id INTEGER)")?))
                .unwrap();
        }
        assert_eq!(
            detect_database_file_format(&plain).unwrap(),
            DatabaseFileFormat::CompressedContainer { encrypted: false }
        );

        let encrypted = dir.path().join("container-enc.db");
        {
            let conn = ManagedConnection::open_compressed_encrypted(
                &encrypted,
                "secret",
                SQLiteCompressionOptions::default(),
            )
            .unwrap();
            conn.with(|c| Ok(c.execute_batch("CREATE TABLE t (id INTEGER)")?))
                .unwrap();
        }
        assert_eq!(
            detect_database_file_format(&encrypted).unwrap(),
            DatabaseFileFormat::CompressedContainer { encrypted: true }
        );
    }

    #[test]
    fn legacy_compressed_header_is_classified_for_an_explicit_migration_error() {
        let dir = temp_dir();
        let path = dir.path().join("legacy-container.db");
        let mut prefix = [0_u8; DETECT_PREFIX_LEN];
        prefix[..LEGACY_MAGIC.len()].copy_from_slice(LEGACY_MAGIC);
        prefix[8..12].copy_from_slice(&1_u32.to_le_bytes());
        prefix[HEADER_FLAGS_OFFSET..HEADER_FLAGS_OFFSET + 4]
            .copy_from_slice(&FLAG_ENCRYPTED.to_le_bytes());
        std::fs::write(&path, prefix).unwrap();
        assert_eq!(
            detect_database_file_format(&path).unwrap(),
            DatabaseFileFormat::CompressedContainer { encrypted: true }
        );
    }

    #[test]
    fn short_or_foreign_files_detect_as_unrecognized() {
        let dir = temp_dir();
        let short = dir.path().join("short.bin");
        std::fs::write(&short, b"abc").unwrap();
        assert_eq!(
            detect_database_file_format(&short).unwrap(),
            DatabaseFileFormat::Unrecognized
        );

        let foreign = dir.path().join("foreign.bin");
        std::fs::write(&foreign, vec![0xAB_u8; 64]).unwrap();
        assert_eq!(
            detect_database_file_format(&foreign).unwrap(),
            DatabaseFileFormat::Unrecognized
        );
    }

    #[test]
    fn requires_key_reflects_format() {
        assert!(!DatabaseFileFormat::Missing.requires_key());
        assert!(!DatabaseFileFormat::PlainSQLite.requires_key());
        assert!(!DatabaseFileFormat::CompressedContainer { encrypted: false }.requires_key());
        assert!(DatabaseFileFormat::CompressedContainer { encrypted: true }.requires_key());
        assert!(DatabaseFileFormat::Unrecognized.requires_key());
    }
}