OXYGENHUB

Coverage / crates/hub/src/db/mod.rs 94.6%

35 of 37 lines run, 11 of 18 functions · run #510 on main · run missed

1
//! SQLite through `sqlx` (hub spec §3.1, §17.2): WAL, foreign keys on,
2
//! migrations embedded and applied at start; or PostgreSQL, built with the
3
//! `postgres` feature (#211). One module per table group.
4
5
pub mod accounts;
6
pub mod activity;
7
#[cfg(feature = "postgres")]
8
pub mod copy;
9
pub mod flow;
10
pub mod hooks;
11
pub mod issues;
12
pub mod notify;
13
pub mod projects;
14
pub mod proposals;
15
pub mod push;
16
pub mod push_protection;
17
pub mod queue;
18
pub mod releases;
19
pub mod repos;
20
pub mod runner_updates;
21
pub mod runners;
22
pub mod sessions;
23
pub mod terraform;
24
pub mod tlog;
25
26
#[cfg(not(feature = "postgres"))]
27
pub use sqlite::{begin_write, open, Db};
28
29
#[cfg(feature = "postgres")]
30
pub use postgres::{begin_write, open, Db};
31
32
pub type Pool = sqlx::Pool<Db>;
33
34
#[cfg(not(feature = "postgres"))]
35
mod sqlite {
36
    use super::Pool;
37
    use crate::config::Config;
38
    use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions, SqliteSynchronous};
39
40
    pub type Db = sqlx::Sqlite;
41
42
    /// How long a statement waits for SQLite's write lock. Most writers are
43
    /// background clients (runners appending logs, webhook deliveries), and a
44
    /// commit can stall for seconds while a build saturates the host's disk, so
45
    /// waiting beats failing.
46
    const BUSY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
47
48
    /// Open (creating if needed) and migrate `<data>/hub.db`.
49199×
    pub async fn open(config: &Config) -> anyhow::Result<Pool> {
50199×
        let options = SqliteConnectOptions::new()
51199×
            .filename(config.db_path())
52199×
            .create_if_missing(true)
53199×
            .journal_mode(SqliteJournalMode::Wal)
54199×
            .synchronous(SqliteSynchronous::Normal)
55199×
            .foreign_keys(true)
56199×
            .busy_timeout(BUSY_TIMEOUT);
57199×
        migrate(options.clone()).await?;
58199×
        let pool = SqlitePoolOptions::new().max_connections(8).connect_with(options).await?;
59199×
        Ok(pool)
60199×
    }
61
62
    /// Apply the migrations on a connection of their own with foreign keys
63
    /// off, as SQLite's way to change a table (rebuild it, drop the old one,
64
    /// rename) needs: with them on, dropping a table its children reference
65
    /// deletes the children too. Every reference must hold afterwards.
66199×
    async fn migrate(options: SqliteConnectOptions) -> anyhow::Result<()> {
67
        use sqlx::Connection;
68199×
        let mut conn = sqlx::SqliteConnection::connect_with(&options.foreign_keys(false)).await?;
69199×
        sqlx::migrate!("./migrations").run(&mut conn).await?;
70199×
        let broken: Vec<(String,)> = sqlx::query_as("SELECT \"table\" FROM pragma_foreign_key_check").fetch_all(&mut conn).await?;
71199×
        if let Some((table,)) = broken.first() {
720×
            anyhow::bail!("after the migrations, {} rows break a foreign key (the first in {table})", broken.len());
73199×
        }
74199×
        conn.close().await?;
75199×
        Ok(())
76199×
    }
77
78
    /// A write transaction that takes SQLite's write lock at `BEGIN`
79
    /// (`BEGIN IMMEDIATE`). A deferred transaction that reads and then writes
80
    /// fails at once with "database is locked" when another writer holds the
81
    /// lock, whatever the busy timeout; an immediate one waits its turn.
821031×
    pub async fn begin_write(pool: &Pool) -> sqlx::Result<sqlx::Transaction<'static, Db>> {
831031×
        pool.begin_with("BEGIN IMMEDIATE").await
841031×
    }
85
}
86
87
/// PostgreSQL (#211), for a hub on more than one host or a managed database.
88
/// The same queries as SQLite's; the schema is `migrations-pg`, which starts
89
/// as SQLite's 0001-0072 in one and takes each later change written for it.
90
#[cfg(feature = "postgres")]
91
mod postgres {
92
    use super::Pool;
93
    use crate::config::Config;
94
    use sqlx::postgres::{PgConnectOptions, PgPoolOptions};
95
    use sqlx::Executor;
96
97
    pub type Db = sqlx::Postgres;
98
99
    /// Connect to `[database] url`, use its schema, and migrate.
100
    pub async fn open(config: &Config) -> anyhow::Result<Pool> {
101
        if config.database.url.is_empty() {
102
            anyhow::bail!("this hub is built for PostgreSQL: set [database] url (or OXYHUB_DATABASE_URL)");
103
        }
104
        let options: PgConnectOptions = config.database.url.parse()?;
105
        let schema = schema_name(config);
106
        if let Some(schema) = &schema {
107
            let pool = PgPoolOptions::new().max_connections(1).connect_with(options.clone()).await?;
108
            pool.execute(format!("CREATE SCHEMA IF NOT EXISTS \"{schema}\"").as_str()).await?;
109
            pool.close().await;
110
        }
111
        let path = match &schema {
112
            // Plain (letters, digits, `_`), so it needs no quoting here.
113
            Some(s) => format!("{s},public"),
114
            None => "public".to_string(),
115
        };
116
        let options = options.options([("search_path", path.as_str())]);
117
        let pool = PgPoolOptions::new().max_connections(16).connect_with(options).await?;
118
        extension(&pool).await?;
119
        sqlx::migrate!("./migrations-pg").run(&pool).await?;
120
        Ok(pool)
121
    }
122
123
    /// `citext`, for names compared without case, made once in `public` so
124
    /// every schema sees it. Two hubs starting at once may race to make it.
125
    async fn extension(pool: &Pool) -> anyhow::Result<()> {
126
        let made = pool.execute("CREATE EXTENSION IF NOT EXISTS citext WITH SCHEMA public").await;
127
        if let Err(e) = made {
128
            let there: bool =
129
                sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'citext')").fetch_one(pool).await?;
130
            if !there {
131
                return Err(e.into());
132
            }
133
        }
134
        Ok(())
135
    }
136
137
    /// The schema to use: none for `public`; `*` names it after the data
138
    /// directory, so hubs (and tests) can share one database.
139
    fn schema_name(config: &Config) -> Option<String> {
140
        let s = match config.database.schema.as_str() {
141
            "" | "public" => return None,
142
            "*" => {
143
                let dir = config.data.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
144
                format!("hub_{dir}")
145
            }
146
            s => s.to_string(),
147
        };
148
        Some(s.chars().map(|c| if c.is_ascii_alphanumeric() { c.to_ascii_lowercase() } else { '_' }).collect())
149
    }
150
151
    /// One writer at a time, as SQLite's `BEGIN IMMEDIATE` gives: callers
152
    /// read and then write (the next number, a check before an insert) and
153
    /// rely on nothing changing between. A transaction-scoped advisory lock.
154
    pub async fn begin_write(pool: &Pool) -> sqlx::Result<sqlx::Transaction<'static, Db>> {
155
        let mut tx = pool.begin().await?;
156
        sqlx::query("SELECT pg_advisory_xact_lock(7300211)").execute(&mut *tx).await?;
157
        Ok(tx)
158
    }
159
}
160
161
/// SQL for the text at `key` of the JSON object in column `col` (null when
162
/// the column is empty or has no such key).
163201×
pub fn json_text(col: &str, key: &str) -> String {
164201×
    if cfg!(feature = "postgres") {
1650×
        format!("(CAST(NULLIF({col}, '') AS json) ->> '{key}')")
166
    } else {
167201×
        format!("json_extract({col}, '$.{key}')")
168
    }
169201×
}
170
171
/// Milliseconds since the epoch, the hub's timestamp unit (as `oxy`'s).
17213850×
pub fn now_ms() -> i64 {
17313850×
    std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as i64).unwrap_or(0)
17413850×
}