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