capsid-database 0.1.0-alpha.1

The schema version check, record encoding, errors, targets, and transaction helpers that Capsid's SQLite databases share.
Documentation
use std::{path::Path, time::Duration};

use capsid_host::{FileKind, file_kind};
use capsid_model::versions;
use rusqlite::{Connection, OpenFlags};

use crate::{Result, StoreError, sql::Transactions};

const BUSY_TIMEOUT: Duration = Duration::from_secs(5);

pub fn connect(path: &Path) -> Result<Connection> {
    let connection = Connection::open(path)?;
    connection.busy_timeout(BUSY_TIMEOUT)?;
    connection.pragma_update(None, "journal_mode", "WAL")?;
    connection.pragma_update(None, "synchronous", "FULL")?;
    connection.pragma_update(None, "foreign_keys", true)?;
    let version = version(&connection)?;
    if version != 0 && version != versions::STORE_SCHEMA {
        return Err(StoreError::conflict(format!(
            "unsupported database schema {version}"
        )));
    }
    Ok(connection)
}

pub fn version(connection: &Connection) -> Result<u32> {
    Ok(connection.pragma_query_value(None, "user_version", |row| row.get(0))?)
}

pub fn create(connection: &Connection, schema: &str) -> Result<()> {
    connection.execute_batch(schema)?;
    connection.pragma_update(None, "user_version", versions::STORE_SCHEMA)?;
    Ok(())
}

pub fn open(path: &Path, schema: &str) -> Result<Connection> {
    open_with(path, schema, |_| Ok(()))
}

// Opens a database, creating its schema on the first open and running
// `initialize` in the same transaction. A database that exists keeps its rows
// as they are, so a damaged one is refused instead of refilled.
pub fn open_with(
    path: &Path,
    schema: &str,
    initialize: impl FnOnce(&Connection) -> Result<()>,
) -> Result<Connection> {
    let mut connection = connect(path)?;
    let tx = connection.write()?;
    if version(&tx)? == 0 {
        create(&tx, schema)?;
        initialize(&tx)?;
    }

    tx.commit()?;
    Ok(connection)
}

// Opens a database read-only for inspection while its owner is stopped. A
// missing file, or one that was never initialized, holds no records.
pub fn open_read_only(path: &Path) -> Result<Option<Connection>> {
    match file_kind(path)? {
        FileKind::Missing => return Ok(None),
        FileKind::Regular => {}
        FileKind::Other => {
            return Err(StoreError::corrupt(format!(
                "database is not a regular file: {}",
                path.display()
            )));
        }
    }

    let connection = Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_ONLY)?;
    match version(&connection)? {
        0 => Ok(None),
        versions::STORE_SCHEMA => Ok(Some(connection)),
        version => Err(StoreError::conflict(format!(
            "unsupported database schema {version}: {}",
            path.display()
        ))),
    }
}