Skip to main content

capsid_database/
schema.rs

1use std::{path::Path, time::Duration};
2
3use capsid_host::{FileKind, file_kind};
4use capsid_model::versions;
5use rusqlite::{Connection, OpenFlags};
6
7use crate::{Result, StoreError, sql::Transactions};
8
9const BUSY_TIMEOUT: Duration = Duration::from_secs(5);
10
11pub fn connect(path: &Path) -> Result<Connection> {
12    let connection = Connection::open(path)?;
13    connection.busy_timeout(BUSY_TIMEOUT)?;
14    connection.pragma_update(None, "journal_mode", "WAL")?;
15    connection.pragma_update(None, "synchronous", "FULL")?;
16    connection.pragma_update(None, "foreign_keys", true)?;
17    let version = version(&connection)?;
18    if version != 0 && version != versions::STORE_SCHEMA {
19        return Err(StoreError::conflict(format!(
20            "unsupported database schema {version}"
21        )));
22    }
23    Ok(connection)
24}
25
26pub fn version(connection: &Connection) -> Result<u32> {
27    Ok(connection.pragma_query_value(None, "user_version", |row| row.get(0))?)
28}
29
30pub fn create(connection: &Connection, schema: &str) -> Result<()> {
31    connection.execute_batch(schema)?;
32    connection.pragma_update(None, "user_version", versions::STORE_SCHEMA)?;
33    Ok(())
34}
35
36pub fn open(path: &Path, schema: &str) -> Result<Connection> {
37    open_with(path, schema, |_| Ok(()))
38}
39
40// Opens a database, creating its schema on the first open and running
41// `initialize` in the same transaction. A database that exists keeps its rows
42// as they are, so a damaged one is refused instead of refilled.
43pub fn open_with(
44    path: &Path,
45    schema: &str,
46    initialize: impl FnOnce(&Connection) -> Result<()>,
47) -> Result<Connection> {
48    let mut connection = connect(path)?;
49    let tx = connection.write()?;
50    if version(&tx)? == 0 {
51        create(&tx, schema)?;
52        initialize(&tx)?;
53    }
54
55    tx.commit()?;
56    Ok(connection)
57}
58
59// Opens a database read-only for inspection while its owner is stopped. A
60// missing file, or one that was never initialized, holds no records.
61pub fn open_read_only(path: &Path) -> Result<Option<Connection>> {
62    match file_kind(path)? {
63        FileKind::Missing => return Ok(None),
64        FileKind::Regular => {}
65        FileKind::Other => {
66            return Err(StoreError::corrupt(format!(
67                "database is not a regular file: {}",
68                path.display()
69            )));
70        }
71    }
72
73    let connection = Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_ONLY)?;
74    match version(&connection)? {
75        0 => Ok(None),
76        versions::STORE_SCHEMA => Ok(Some(connection)),
77        version => Err(StoreError::conflict(format!(
78            "unsupported database schema {version}: {}",
79            path.display()
80        ))),
81    }
82}