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