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