OXYGENHUB
# eae4a97475f1 oxygenhub / crates / hub / src / db / mod.rs
1.4 KiB · Rust · last changed Wait up to 30 seconds for SQLite's write lock 1 month ago source blame history raw
1
//! SQLite through `sqlx` (hub spec §3.1, §17.2): WAL, foreign keys on,
2
//! migrations embedded and applied at start. One module per table group.
3
4
pub mod repos;
5
6
use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions, SqliteSynchronous};
7
use sqlx::SqlitePool;
8
use std::path::Path;
9
10
pub type Pool = SqlitePool;
11
12
/// Open (creating if needed) and migrate the database at `path`.
13
/// How long a statement waits for SQLite's write lock. Most writers are
14
/// background clients (runners appending logs, webhook deliveries), and a
15
/// commit can stall for seconds while a build saturates the host's disk, so
16
/// waiting beats failing.
17
const BUSY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
18
19
pub async fn open(path: &Path) -> anyhow::Result<Pool> {
20
    let options = SqliteConnectOptions::new()
21
        .filename(path)
22
        .create_if_missing(true)
23
        .journal_mode(SqliteJournalMode::Wal)
24
        .synchronous(SqliteSynchronous::Normal)
25
        .foreign_keys(true)
26
        .busy_timeout(BUSY_TIMEOUT);
27
    let pool = SqlitePoolOptions::new().max_connections(8).connect_with(options).await?;
28
    sqlx::migrate!("./migrations").run(&pool).await?;
29
    Ok(pool)
30
}
31
32
/// Milliseconds since the epoch, the hub's timestamp unit (as `oxy`'s).
33
pub fn now_ms() -> i64 {
34
    std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as i64).unwrap_or(0)
35
}