ctb_storage/
migrations.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Database migration registry and version tracking for relational schemas.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use anyhow::Result;
30use turso::{Connection, Value};
31
32pub mod m2026_06_30_1_create_users;
33pub mod m2026_06_30_2_create_nodes;
34pub mod m2026_06_30_3_checksum;
35pub mod m2026_06_30_4_id_u128_blob;
36pub mod m2026_07_01_1_consolidate_users;
37pub mod m2026_07_02_1_add_user_subscription;
38pub mod m2026_07_05_1_add_client_sync_tables;
39pub mod m2026_07_05_2_create_server_sync_tables;
40pub mod m2026_07_05_3_add_user_remote_status;
41pub mod m2026_08_06_1_add_node_timestamp;
42pub mod m2026_10_24_1_migrate_nodes_to_dctf;
43
44/// Represents a database schema migration.
45pub struct Migration {
46    pub name: &'static str,
47    pub description: &'static str,
48    pub up_sql: Option<&'static str>,
49}
50
51/// Identifies the schema type of a database to determine which migrations to apply.
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum DbSchemaType {
54    Users,
55    Nodes,
56    Sync,
57}
58
59/// Registry of migrations for nodes (`user_data`) databases.
60pub static NODES_MIGRATIONS: &[Migration] = &[
61    Migration {
62        name: m2026_06_30_2_create_nodes::NAME,
63        description: m2026_06_30_2_create_nodes::DESCRIPTION,
64        up_sql: Some(m2026_06_30_2_create_nodes::UP_SQL),
65    },
66    Migration {
67        name: m2026_06_30_3_checksum::NAME,
68        description: m2026_06_30_3_checksum::DESCRIPTION,
69        up_sql: Some(m2026_06_30_3_checksum::UP_SQL),
70    },
71    Migration {
72        name: m2026_06_30_4_id_u128_blob::NAME,
73        description: m2026_06_30_4_id_u128_blob::DESCRIPTION,
74        up_sql: m2026_06_30_4_id_u128_blob::UP_SQL,
75    },
76    Migration {
77        name: m2026_07_05_1_add_client_sync_tables::NAME,
78        description: m2026_07_05_1_add_client_sync_tables::DESCRIPTION,
79        up_sql: m2026_07_05_1_add_client_sync_tables::UP_SQL,
80    },
81    Migration {
82        name: m2026_08_06_1_add_node_timestamp::NAME,
83        description: m2026_08_06_1_add_node_timestamp::DESCRIPTION,
84        up_sql: m2026_08_06_1_add_node_timestamp::UP_SQL,
85    },
86    Migration {
87        name: m2026_10_24_1_migrate_nodes_to_dctf::NAME,
88        description: m2026_10_24_1_migrate_nodes_to_dctf::DESCRIPTION,
89        up_sql: m2026_10_24_1_migrate_nodes_to_dctf::UP_SQL,
90    },
91];
92
93/// Registry of migrations for the sync database.
94pub static SYNC_MIGRATIONS: &[Migration] = &[Migration {
95    name: m2026_07_05_2_create_server_sync_tables::NAME,
96    description: m2026_07_05_2_create_server_sync_tables::DESCRIPTION,
97    up_sql: m2026_07_05_2_create_server_sync_tables::UP_SQL,
98}];
99
100/// Registry of migrations for the global users database.
101pub static USERS_MIGRATIONS: &[Migration] = &[
102    Migration {
103        name: m2026_06_30_1_create_users::NAME,
104        description: m2026_06_30_1_create_users::DESCRIPTION,
105        up_sql: m2026_06_30_1_create_users::UP_SQL,
106    },
107    Migration {
108        name: m2026_07_01_1_consolidate_users::NAME,
109        description: m2026_07_01_1_consolidate_users::DESCRIPTION,
110        up_sql: m2026_07_01_1_consolidate_users::UP_SQL,
111    },
112    Migration {
113        name: m2026_07_02_1_add_user_subscription::NAME,
114        description: m2026_07_02_1_add_user_subscription::DESCRIPTION,
115        up_sql: m2026_07_02_1_add_user_subscription::UP_SQL,
116    },
117    Migration {
118        name: m2026_07_05_3_add_user_remote_status::NAME,
119        description: m2026_07_05_3_add_user_remote_status::DESCRIPTION,
120        up_sql: m2026_07_05_3_add_user_remote_status::UP_SQL,
121    },
122];
123
124/// Checks if a column exists in a table.
125pub(crate) async fn check_column_exists(
126    conn: &Connection,
127    table: &str,
128    column: &str,
129) -> Result<bool> {
130    let sql = format!("PRAGMA table_info({table})");
131    let mut stmt = conn.prepare(sql).await?;
132    let mut rows = stmt.query(()).await?;
133    let mut exists = false;
134    while let Some(row) = rows.next().await? {
135        if let Ok(Value::Text(col_name)) = row.get_value(1) {
136            if col_name == column {
137                exists = true;
138                break;
139            }
140        }
141    }
142    Ok(exists)
143}
144
145/// Execute custom Rust code for complex migrations (e.g., checksum backfilling).
146async fn run_rust_migration(
147    conn: &Connection,
148    schema_type: DbSchemaType,
149    name: &str,
150) -> Result<()> {
151    match (schema_type, name) {
152        (DbSchemaType::Users, m2026_06_30_1_create_users::NAME) => {
153            m2026_06_30_1_create_users::run_rust_migration(conn).await?;
154        }
155        (DbSchemaType::Users, m2026_07_01_1_consolidate_users::NAME) => {
156            m2026_07_01_1_consolidate_users::run_rust_migration(conn).await?;
157        }
158        (DbSchemaType::Users, m2026_07_02_1_add_user_subscription::NAME) => {
159            m2026_07_02_1_add_user_subscription::run_rust_migration(conn)
160                .await?;
161        }
162        (DbSchemaType::Users, m2026_07_05_3_add_user_remote_status::NAME) => {
163            m2026_07_05_3_add_user_remote_status::run_rust_migration(conn)
164                .await?;
165        }
166        (DbSchemaType::Nodes, m2026_06_30_2_create_nodes::NAME) => {
167            m2026_06_30_2_create_nodes::run_rust_migration(conn).await?;
168        }
169        (DbSchemaType::Nodes, m2026_06_30_3_checksum::NAME) => {
170            m2026_06_30_3_checksum::run_rust_migration(conn).await?;
171        }
172        (DbSchemaType::Nodes, m2026_06_30_4_id_u128_blob::NAME) => {
173            m2026_06_30_4_id_u128_blob::run_rust_migration(conn).await?;
174        }
175        (DbSchemaType::Nodes, m2026_07_05_1_add_client_sync_tables::NAME) => {
176            m2026_07_05_1_add_client_sync_tables::run_rust_migration(conn)
177                .await?;
178        }
179        (DbSchemaType::Nodes, m2026_08_06_1_add_node_timestamp::NAME) => {
180            m2026_08_06_1_add_node_timestamp::run_rust_migration(conn).await?;
181        }
182        (DbSchemaType::Nodes, m2026_10_24_1_migrate_nodes_to_dctf::NAME) => {
183            m2026_10_24_1_migrate_nodes_to_dctf::run_rust_migration(conn)
184                .await?;
185        }
186        (DbSchemaType::Sync, m2026_07_05_2_create_server_sync_tables::NAME) => {
187            m2026_07_05_2_create_server_sync_tables::run_rust_migration(conn)
188                .await?;
189        }
190        _ => {}
191    }
192    Ok(())
193}
194
195/// Run all pending migrations for the specified database connection and schema type.
196pub async fn run_migrations(
197    conn: &Connection,
198    schema_type: DbSchemaType,
199) -> Result<()> {
200    // Drop old format table if it exists with version column (from older development versions)
201    let has_version_col = {
202        let mut stmt =
203            conn.prepare("PRAGMA table_info(schema_migrations)").await?;
204        let mut rows = stmt.query(()).await?;
205        let mut found = false;
206        while let Some(row) = rows.next().await? {
207            if let Ok(Value::Text(col_name)) = row.get_value(1) {
208                if col_name == "version" {
209                    found = true;
210                    break;
211                }
212            }
213        }
214        found
215    };
216    if has_version_col {
217        conn.execute("DROP TABLE schema_migrations", ()).await?;
218    }
219
220    // 1. Ensure schema_migrations table exists with name TEXT PRIMARY KEY
221    conn.execute(
222        "CREATE TABLE IF NOT EXISTS schema_migrations (
223            name TEXT PRIMARY KEY,
224            applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL
225        )",
226        (),
227    )
228    .await?;
229
230    // 2. Query applied migrations
231    let mut stmt = conn
232        .prepare("SELECT name FROM schema_migrations ORDER BY name ASC")
233        .await?;
234    let mut rows = stmt.query(()).await?;
235    let mut applied = std::collections::HashSet::new();
236    while let Some(row) = rows.next().await? {
237        if let Ok(Value::Text(s)) = row.get_value(0) {
238            applied.insert(s);
239        }
240    }
241    drop(rows);
242    drop(stmt);
243
244    let migrations = match schema_type {
245        DbSchemaType::Users => USERS_MIGRATIONS,
246        DbSchemaType::Nodes => NODES_MIGRATIONS,
247        DbSchemaType::Sync => SYNC_MIGRATIONS,
248    };
249
250    for m in migrations {
251        if !applied.contains(&m.name.to_string()) {
252            log!(format!("Applying database migration: {}", m.name));
253            conn.execute("BEGIN IMMEDIATE TRANSACTION", ()).await?;
254
255            let res = async {
256                let already_applied = {
257                    let mut stmt = conn.prepare("SELECT name FROM schema_migrations WHERE name = ?1").await?;
258                    let mut rows = stmt.query([m.name]).await?;
259                    rows.next().await?.is_some()
260                };
261
262                if !already_applied {
263                    if let Some(sql) = m.up_sql {
264                        // Defensive check in case the column already exists
265                        if m.name == m2026_06_30_3_checksum::NAME {
266                            let has_checksum = check_column_exists(conn, "nodes", "checksum").await?;
267                            if !has_checksum {
268                                conn.execute(sql, ()).await?;
269                            }
270                        } else if m.name == m2026_08_06_1_add_node_timestamp::NAME {
271                            let has_timestamp = check_column_exists(conn, "nodes", "timestamp").await?;
272                            if !has_timestamp {
273                                conn.execute(sql, ()).await?;
274                            }
275                        } else {
276                            conn.execute(sql, ()).await?;
277                        }
278                    }
279
280                    run_rust_migration(conn, schema_type, m.name).await?;
281
282                    conn.execute(
283                        "INSERT INTO schema_migrations (name) VALUES (?1)",
284                        [m.name],
285                    )
286                    .await?;
287                }
288                Ok::<(), anyhow::Error>(())
289            }
290            .await;
291
292            match res {
293                Ok(()) => {
294                    conn.execute("COMMIT", ()).await?;
295                }
296                Err(e) => {
297                    conn.execute("ROLLBACK", ()).await?;
298                    return Err(e);
299                }
300            }
301        }
302    }
303
304    Ok(())
305}