Skip to main content

engram_storage/
database.rs

1use rusqlite::{Connection, OpenFlags};
2
3use crate::error::StorageError;
4use crate::schema;
5
6pub struct Database {
7    connection: Connection,
8}
9
10impl Database {
11    /// Open or create database at the given path.
12    pub fn open(path: &str) -> Result<Self, StorageError> {
13        let connection = Connection::open(path)?;
14        schema::apply_schema(&connection)?;
15        Ok(Self { connection })
16    }
17
18    /// Open an existing database in read-only mode.
19    ///
20    /// Skips schema application: the caller must ensure the schema already exists
21    /// (a read-only connection cannot run `CREATE TABLE` or set `PRAGMA journal_mode`).
22    /// Intended for defense-in-depth scenarios where the source database must not
23    /// be mutated (e.g. `engram migrate`).
24    pub fn open_read_only(path: &str) -> Result<Self, StorageError> {
25        let connection = Connection::open_with_flags(
26            path,
27            OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_URI,
28        )?;
29        Ok(Self { connection })
30    }
31
32    /// Create an in-memory database (for testing).
33    pub fn in_memory() -> Result<Self, StorageError> {
34        Self::open(":memory:")
35    }
36
37    pub fn connection(&self) -> &Connection {
38        &self.connection
39    }
40}