Skip to main content

heldar_kernel/
db.rs

1use std::str::FromStr;
2use std::time::Duration;
3
4use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions, SqliteSynchronous};
5use sqlx::SqlitePool;
6
7use crate::config::Config;
8
9/// Open the SQLite pool with WAL + sane concurrency settings, creating the file if needed.
10pub async fn init_pool(cfg: &Config) -> anyhow::Result<SqlitePool> {
11    if !cfg.database_url.starts_with("sqlite") {
12        anyhow::bail!(
13            "Stage 0 supports sqlite only; got `{}`. Postgres is planned via SQLx.",
14            cfg.database_url
15        );
16    }
17
18    let opts = SqliteConnectOptions::from_str(&cfg.database_url)?
19        .create_if_missing(true)
20        .journal_mode(SqliteJournalMode::Wal)
21        .synchronous(SqliteSynchronous::Normal)
22        .busy_timeout(Duration::from_secs(15))
23        .foreign_keys(true);
24
25    let pool = SqlitePoolOptions::new()
26        .max_connections(cfg.db_max_connections)
27        .acquire_timeout(Duration::from_secs(20))
28        .connect_with(opts)
29        .await?;
30
31    Ok(pool)
32}
33
34/// Apply embedded migrations from `./migrations`.
35pub async fn run_migrations(pool: &SqlitePool) -> anyhow::Result<()> {
36    sqlx::migrate!("./migrations").run(pool).await?;
37    Ok(())
38}
39
40/// Clear any transient segment read-locks left over from a crash. clip/snapshot export set
41/// `segments.locked = 1` while ffmpeg reads a segment and release it afterwards; if the process died
42/// mid-read those segments would stay locked (and never be pruned by retention). Clearing at startup
43/// makes the read-lock crash-safe. NOTE: this means `locked` is reserved for transient read-locks —
44/// a future durable evidence-hold must use a separate column, not this one.
45pub async fn clear_segment_read_locks(pool: &SqlitePool) -> anyhow::Result<()> {
46    let n = sqlx::query("UPDATE segments SET locked = 0 WHERE locked <> 0")
47        .execute(pool)
48        .await?
49        .rows_affected();
50    if n > 0 {
51        tracing::info!(cleared = n, "startup: cleared stale segment read-locks");
52    }
53    Ok(())
54}