OXYGENHUB
◆ v0.2.0 oxygenhub / crates / hub / src / db / mod.rs
2.0 KiB · Rust · last changed Runners: registration, Admin -> Runners, history, drain/disable/remove 1 month ago source blame history raw
d23464c0 Andy McCall ↶ 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
19bb31ff Andy McCall ↶ 4
pub mod accounts;
25ab8c73 Andy McCall ↶ 5
pub mod activity;
42fa9554 Andy McCall ↶ 6
pub mod flow;
b64e2537 Andy McCall ↶ 7
pub mod hooks;
18e381ea Andy McCall ↶ 8
pub mod issues;
9
pub mod notify;
e1ec9fbf Andy McCall ↶ 10
pub mod projects;
de505df5 Andy McCall ↶ 11
pub mod proposals;
3f4b0ea6 Andy McCall ↶ 12
pub mod releases;
d23464c0 Andy McCall ↶ 13
pub mod repos;
b6b7e4cf Andy McCall ↶ 14
pub mod runners;
d23464c0 Andy McCall ↶ 15
16
use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions, SqliteSynchronous};
17
use sqlx::SqlitePool;
18
use std::path::Path;
19
20
pub type Pool = SqlitePool;
21
22
/// Open (creating if needed) and migrate the database at `path`.
eae4a974 Andy McCall ↶ 23
/// How long a statement waits for SQLite's write lock. Most writers are
24
/// background clients (runners appending logs, webhook deliveries), and a
25
/// commit can stall for seconds while a build saturates the host's disk, so
26
/// waiting beats failing.
27
const BUSY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
28
d23464c0 Andy McCall ↶ 29
pub async fn open(path: &Path) -> anyhow::Result<Pool> {
30
    let options = SqliteConnectOptions::new()
31
        .filename(path)
32
        .create_if_missing(true)
33
        .journal_mode(SqliteJournalMode::Wal)
34
        .synchronous(SqliteSynchronous::Normal)
35
        .foreign_keys(true)
eae4a974 Andy McCall ↶ 36
        .busy_timeout(BUSY_TIMEOUT);
d23464c0 Andy McCall ↶ 37
    let pool = SqlitePoolOptions::new().max_connections(8).connect_with(options).await?;
38
    sqlx::migrate!("./migrations").run(&pool).await?;
39
    Ok(pool)
40
}
41
42
/// Milliseconds since the epoch, the hub's timestamp unit (as `oxy`'s).
43
pub fn now_ms() -> i64 {
44
    std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as i64).unwrap_or(0)
45
}
941abdd6 Andy McCall ↶ 46
47
/// A write transaction that takes SQLite's write lock at `BEGIN`
48
/// (`BEGIN IMMEDIATE`). A deferred transaction that reads and then writes
49
/// fails at once with "database is locked" when another writer holds the
50
/// lock, whatever the busy timeout; an immediate one waits its turn.
51
pub async fn begin_write(pool: &Pool) -> sqlx::Result<sqlx::Transaction<'static, sqlx::Sqlite>> {
52
    pool.begin_with("BEGIN IMMEDIATE").await
53
}