ctb_storage/migrations/
m2026_06_30_4_id_u128_blob.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 migrating IDs to 128-bit representations.
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_4_id_u128_blob";
28pub const DESCRIPTION: &str =
29    "Convert node id and graph_id to 16-byte BLOB for u128 support";
30pub const UP_SQL: Option<&str> = None;
31
32pub async fn run_rust_migration(conn: &Connection) -> Result<()> {
33    // 1. Create temporary table
34    conn.execute(
35        "CREATE TABLE IF NOT EXISTS nodes_new (
36            id BLOB NOT NULL,
37            graph_id BLOB NOT NULL,
38            type INTEGER NOT NULL,
39            data BLOB NOT NULL,
40            checksum BLOB,
41            PRIMARY KEY (id, graph_id)
42        )",
43        (),
44    )
45    .await?;
46
47    // 2. Fetch all nodes from the old nodes table (if it exists)
48    let mut stmt = conn
49        .prepare("SELECT id, graph_id, type, data, checksum FROM nodes")
50        .await?;
51    let mut rows = stmt.query(()).await?;
52    let mut updates = Vec::new();
53    while let Some(row) = rows.next().await? {
54        let old_id = match row.get_value(0)? {
55            // Reason for fallback: negative integer ID values during migration fallback to 0
56            Value::Integer(v) => u128::try_from(v).unwrap_or(0),
57            Value::Blob(b) => {
58                if b.len() == 16 {
59                    // Reason for fallback: slice conversion error during 16-byte blob conversion defaults to 0 u128
60                    u128::from_be_bytes(b.try_into().unwrap_or([0; 16]))
61                } else {
62                    0
63                }
64            }
65            _ => 0,
66        };
67        let old_graph_id = match row.get_value(1)? {
68            // Reason for fallback: negative integer ID values during migration fallback to 0
69            Value::Integer(v) => u128::try_from(v).unwrap_or(0),
70            Value::Blob(b) => {
71                if b.len() == 16 {
72                    // Reason for fallback: slice conversion error during 16-byte blob conversion defaults to 0 u128
73                    u128::from_be_bytes(b.try_into().unwrap_or([0; 16]))
74                } else {
75                    0
76                }
77            }
78            _ => 0,
79        };
80        let type_int = match row.get_value(2)? {
81            Value::Integer(i) => i,
82            Value::Text(t) => match t.as_str() {
83                "data" => 1,
84                "statements" => 2,
85                "system" => 3,
86                _ => 1,
87            },
88            _ => 1,
89        };
90        let data_val = match row.get_value(3)? {
91            Value::Blob(b) => b,
92            _ => Vec::new(),
93        };
94        let checksum_val = match row.get_value(4)? {
95            Value::Blob(b) => Some(b),
96            _ => None,
97        };
98        updates.push((old_id, old_graph_id, type_int, data_val, checksum_val));
99    }
100    drop(rows);
101    drop(stmt);
102
103    // 3. Insert converted rows into nodes_new
104    for (id, graph_id, type_int, data, checksum) in updates {
105        let id_blob = id.to_be_bytes().to_vec();
106        let graph_id_blob = graph_id.to_be_bytes().to_vec();
107        conn.execute(
108            "INSERT INTO nodes_new (id, graph_id, type, data, checksum) VALUES (?1, ?2, ?3, ?4, ?5)",
109            (id_blob, graph_id_blob, type_int, data, checksum),
110        )
111        .await?;
112    }
113
114    // 4. Swap tables
115    conn.execute("DROP TABLE nodes", ()).await?;
116    conn.execute("ALTER TABLE nodes_new RENAME TO nodes", ())
117        .await?;
118
119    // 5. Re-create index
120    conn.execute(
121        "CREATE INDEX IF NOT EXISTS idx_nodes_checksum ON nodes (checksum)",
122        (),
123    )
124    .await?;
125
126    Ok(())
127}