Skip to main content

vault_core/
migrate_schema.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! Ordered, recorded SQLCipher schema migrations.
4//!
5//! Migration 0001 captures the complete pre-R05 schema, including the explicit
6//! column additions that older builds used to attempt on every open. Later
7//! migrations can therefore be additive without re-running ad hoc DDL.
8
9use crate::{config_history, ics_feeds, lifecycle, migration, ops, storage, users};
10use rusqlite::{Connection, OptionalExtension};
11
12/// Add one known column only when this known table does not already have it.
13///
14/// The table and column names are compile-time migration constants. This is not
15/// a general SQL builder and must never receive user input.
16pub(crate) fn add_column_if_missing(
17    conn: &Connection,
18    table: &str,
19    column: &str,
20    definition: &str,
21) -> Result<(), String> {
22    let mut stmt = conn
23        .prepare(&format!("PRAGMA table_info({table})"))
24        .map_err(|e| e.to_string())?;
25    let found = stmt
26        .query_map([], |row| row.get::<_, String>(1))
27        .map_err(|e| e.to_string())?
28        .collect::<Result<Vec<_>, _>>()
29        .map_err(|e| e.to_string())?
30        .iter()
31        .any(|name| name == column);
32    if !found {
33        conn.execute_batch(&format!(
34            "ALTER TABLE {table} ADD COLUMN {column} {definition};"
35        ))
36        .map_err(|e| e.to_string())?;
37    }
38    Ok(())
39}
40
41fn migration_0001(conn: &Connection) -> Result<(), String> {
42    conn.execute_batch(
43        "CREATE TABLE IF NOT EXISTS vault (
44             id   INTEGER PRIMARY KEY CHECK (id = 1),
45             data TEXT    NOT NULL
46         );
47         CREATE TABLE IF NOT EXISTS vault_audit (
48             id             INTEGER PRIMARY KEY AUTOINCREMENT,
49             action         TEXT    NOT NULL,
50             entry_provider TEXT,
51             timestamp      TEXT    NOT NULL,
52             details        TEXT
53         );
54         CREATE TABLE IF NOT EXISTS vault_meta (
55             key   TEXT PRIMARY KEY,
56             value TEXT NOT NULL
57         );",
58    )
59    .map_err(|e| e.to_string())?;
60    add_column_if_missing(conn, "vault_audit", "entry_hash", "TEXT")?;
61    add_column_if_missing(conn, "vault_audit", "prev_hash", "TEXT")?;
62    add_column_if_missing(conn, "vault_audit", "actor", "TEXT")?;
63    conn.execute_batch(
64        "CREATE INDEX IF NOT EXISTS vault_audit_provider ON vault_audit (entry_provider);
65         CREATE INDEX IF NOT EXISTS vault_audit_time ON vault_audit (timestamp);",
66    )
67    .map_err(|e| e.to_string())?;
68    storage::init_schema(conn)?;
69    users::init_users_schema(conn)?;
70    ics_feeds::init_schema(conn)?;
71    config_history::init_schema(conn)?;
72    Ok(())
73}
74
75fn migration_0002(conn: &Connection) -> Result<(), String> {
76    ops::init_schema(conn)
77}
78
79fn migration_0003(conn: &Connection) -> Result<(), String> {
80    lifecycle::init_schema(conn)
81}
82
83fn migration_0004(conn: &Connection) -> Result<(), String> {
84    migration::init_schema(conn)
85}
86
87/// A vault gets its `vault_id`, an `instance_id`, an epoch and a role (see `identity`).
88fn migration_0005(conn: &Connection) -> Result<(), String> {
89    crate::identity::ensure(conn).map(|_| ())
90}
91
92/// Applies every pending migration in one immediate transaction.
93pub fn migrate_schema(conn: &Connection) -> Result<(), String> {
94    conn.execute_batch("BEGIN IMMEDIATE;")
95        .map_err(|e| e.to_string())?;
96    let result = (|| {
97        conn.execute_batch(
98            "CREATE TABLE IF NOT EXISTS schema_migrations (
99                 id          INTEGER PRIMARY KEY,
100                 name        TEXT NOT NULL,
101                 applied_at  TEXT NOT NULL,
102                 app_version TEXT NOT NULL
103             );",
104        )
105        .map_err(|e| e.to_string())?;
106        for (id, name, apply) in [
107            (
108                1_i64,
109                "baseline",
110                migration_0001 as fn(&Connection) -> Result<(), String>,
111            ),
112            (
113                2_i64,
114                "ops_records",
115                migration_0002 as fn(&Connection) -> Result<(), String>,
116            ),
117            (
118                3_i64,
119                "metadata_lifecycle",
120                migration_0003 as fn(&Connection) -> Result<(), String>,
121            ),
122            (
123                4_i64,
124                "migration_core",
125                migration_0004 as fn(&Connection) -> Result<(), String>,
126            ),
127            (
128                5_i64,
129                "vault_identity",
130                migration_0005 as fn(&Connection) -> Result<(), String>,
131            ),
132        ] {
133            let done: Option<i64> = conn
134                .query_row(
135                    "SELECT id FROM schema_migrations WHERE id = ?1",
136                    [id],
137                    |row| row.get(0),
138                )
139                .optional()
140                .map_err(|e| e.to_string())?;
141            if done.is_none() {
142                apply(conn)?;
143                conn.execute(
144                    "INSERT INTO schema_migrations (id, name, applied_at, app_version) \
145                     VALUES (?1, ?2, ?3, ?4)",
146                    (id, name, crate::iso_now(), env!("CARGO_PKG_VERSION")),
147                )
148                .map_err(|e| e.to_string())?;
149            }
150        }
151        Ok(())
152    })();
153    match result {
154        Ok(()) => conn.execute_batch("COMMIT;").map_err(|e| e.to_string()),
155        Err(err) => {
156            let _ = conn.execute_batch("ROLLBACK;");
157            Err(err)
158        }
159    }
160}