ctb_storage/migrations/
m2026_06_30_3_checksum.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 adding checksum columns to stored blobs and nodes.
21
22use crate::migrations::DbSchemaType;
23use crate::utilities::Result;
24use turso::{Connection, Value};
25
26pub const DB_TYPE: DbSchemaType = DbSchemaType::Nodes;
27pub const NAME: &str = "2026_06_30_3_checksum";
28pub const DESCRIPTION: &str = "Add indexed checksum column to nodes table";
29pub const UP_SQL: &str = "ALTER TABLE nodes ADD COLUMN checksum BLOB";
30
31pub async fn run_rust_migration(conn: &Connection) -> Result<()> {
32    // 1. Fetch all nodes that don't have a checksum yet
33    let mut stmt = conn
34        .prepare("SELECT id, data FROM nodes WHERE checksum IS NULL")
35        .await?;
36    let mut rows = stmt.query(()).await?;
37    let mut updates = Vec::new();
38    while let Some(row) = rows.next().await? {
39        let id_val = if let Ok(Value::Integer(v)) = row.get_value(0) {
40            v
41        } else {
42            continue;
43        };
44        let data_val = if let Ok(Value::Blob(b)) = row.get_value(1) {
45            b
46        } else {
47            continue;
48        };
49
50        use sha2::{Digest, Sha256};
51        let hash = Sha256::digest(&data_val).to_vec();
52        updates.push((id_val, hash));
53    }
54    drop(rows);
55    drop(stmt);
56
57    // 2. Perform updates
58    for (id, hash) in updates {
59        conn.execute(
60            "UPDATE nodes SET checksum = ?1 WHERE id = ?2",
61            (hash, id),
62        )
63        .await?;
64    }
65
66    // 3. Create index on the checksum column
67    conn.execute(
68        "CREATE INDEX IF NOT EXISTS idx_nodes_checksum ON nodes (checksum)",
69        (),
70    )
71    .await?;
72
73    Ok(())
74}