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
9pub 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
34pub async fn run_migrations(pool: &SqlitePool) -> anyhow::Result<()> {
36 sqlx::migrate!("./migrations").run(pool).await?;
37 Ok(())
38}
39
40pub 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}