OXYGENHUB

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

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