ctb_storage/migrations/
m2026_07_01_1_consolidate_users.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 consolidating user roles and credential tables.
21
22use crate::migrations::DbSchemaType;
23use crate::utilities::Result;
24use turso::{Connection, Value};
25
26pub const DB_TYPE: DbSchemaType = DbSchemaType::Users;
27pub const NAME: &str = "2026_07_01_1_consolidate_users";
28pub const DESCRIPTION: &str =
29    "Consolidate fragmented user tables into a single users table";
30pub const UP_SQL: Option<&str> = None;
31
32pub async fn run_rust_migration(conn: &Connection) -> Result<()> {
33    // 1. Check if the old users_ids_rev table exists
34    let has_ids_table = {
35        let mut stmt = conn.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='users_ids_rev'").await?;
36        let mut rows = stmt.query(()).await?;
37        rows.next().await?.is_some()
38    };
39
40    if !has_ids_table {
41        // Just create the users table directly if we are starting fresh
42        conn.execute(
43            "CREATE TABLE IF NOT EXISTS users (
44                id INTEGER PRIMARY KEY,
45                username TEXT UNIQUE NOT NULL,
46                uuid BLOB,
47                auth TEXT,
48                display_name BLOB,
49                picture BLOB,
50                key_encryption_key_params BLOB,
51                wrapped_dek BLOB,
52                pubkey BLOB,
53                subscription_expiry INTEGER,
54                token_quota INTEGER
55            )",
56            (),
57        )
58        .await?;
59
60        conn.execute(
61            "CREATE UNIQUE INDEX IF NOT EXISTS idx_users_username ON users (username)",
62            (),
63        )
64        .await?;
65
66        return Ok(());
67    }
68
69    // 2. Create the temporary users_new table
70    conn.execute(
71        "CREATE TABLE IF NOT EXISTS users_new (
72            id INTEGER PRIMARY KEY,
73            username TEXT UNIQUE NOT NULL,
74            uuid BLOB,
75            auth TEXT,
76            display_name BLOB,
77            picture BLOB,
78            key_encryption_key_params BLOB,
79            wrapped_dek BLOB,
80            pubkey BLOB,
81            subscription_expiry INTEGER,
82            token_quota INTEGER
83        )",
84        (),
85    )
86    .await?;
87
88    // 3. Query all user IDs and usernames
89    let mut stmt = conn.prepare("SELECT key, value FROM users_ids_rev").await?;
90    let mut rows = stmt.query(()).await?;
91    let mut user_records = Vec::new();
92    while let Some(row) = rows.next().await? {
93        let id = match row.get_value(0)? {
94            Value::Integer(v) => v,
95            _ => continue,
96        };
97        let username = match row.get_value(1)? {
98            Value::Text(s) => s,
99            _ => continue,
100        };
101        user_records.push((id, username));
102    }
103    drop(rows);
104    drop(stmt);
105
106    // 4. Migrate user records
107    for (id, username) in user_records {
108        let uuid = query_blob_helper(conn, "users_uuids", id).await?;
109        let auth = query_text_helper(conn, "users_auth", id).await?;
110        let display_name =
111            query_blob_helper(conn, "users_display_names", id).await?;
112        let picture = query_blob_helper(conn, "users_pictures", id).await?;
113        let kek_params =
114            query_blob_helper(conn, "users_key_encryption_key_params", id)
115                .await?;
116        let wrapped_dek =
117            query_blob_helper(conn, "users_wrapped_dek", id).await?;
118        let pubkey = query_blob_helper(conn, "users_pubkeys", id).await?;
119        let subscription_expiry =
120            query_int_helper(conn, "users_subscriptions", id).await?;
121        let token_quota =
122            query_int_helper(conn, "users_token_quota", id).await?;
123
124        conn.execute(
125            "INSERT INTO users_new (id, username, uuid, auth, display_name, picture, key_encryption_key_params, wrapped_dek, pubkey, subscription_expiry, token_quota)
126             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",
127            (
128                id,
129                username,
130                uuid,
131                auth,
132                display_name,
133                picture,
134                kek_params,
135                wrapped_dek,
136                pubkey,
137                subscription_expiry,
138                token_quota,
139            ),
140        )
141        .await?;
142    }
143
144    // 5. Drop old tables
145    let tables_to_drop = [
146        "users_ids",
147        "users_ids_rev",
148        "users_uuids",
149        "users_auth",
150        "users_display_names",
151        "users_pictures",
152        "users_key_encryption_key_params",
153        "users_wrapped_dek",
154        "users_pubkeys",
155        "users_subscriptions",
156        "users_token_quota",
157    ];
158    for table in tables_to_drop {
159        conn.execute(&format!("DROP TABLE IF EXISTS {table}"), ())
160            .await?;
161    }
162
163    // 6. Rename temporary table to users
164    conn.execute("ALTER TABLE users_new RENAME TO users", ())
165        .await?;
166
167    // 7. Create index on username
168    conn.execute(
169        "CREATE UNIQUE INDEX IF NOT EXISTS idx_users_username ON users (username)",
170        (),
171    )
172    .await?;
173
174    Ok(())
175}
176
177async fn query_blob_helper(
178    conn: &Connection,
179    table: &str,
180    id: i64,
181) -> Result<Option<Vec<u8>>> {
182    // Check if table exists first to avoid sqlite errors on clean environments
183    let table_exists = {
184        let mut stmt = conn
185            .prepare(
186                "SELECT name FROM sqlite_master WHERE type='table' AND name=?1",
187            )
188            .await?;
189        let mut rows = stmt.query((table,)).await?;
190        rows.next().await?.is_some()
191    };
192    if !table_exists {
193        return Ok(None);
194    }
195
196    let sql = format!("SELECT value FROM {table} WHERE key = ?1");
197    let mut stmt = conn.prepare(&sql).await?;
198    let mut rows = stmt.query((id,)).await?;
199    if let Some(row) = rows.next().await? {
200        if let Ok(Value::Blob(b)) = row.get_value(0) {
201            return Ok(Some(b));
202        }
203    }
204    Ok(None)
205}
206
207async fn query_text_helper(
208    conn: &Connection,
209    table: &str,
210    id: i64,
211) -> Result<Option<String>> {
212    // Check if table exists first
213    let table_exists = {
214        let mut stmt = conn
215            .prepare(
216                "SELECT name FROM sqlite_master WHERE type='table' AND name=?1",
217            )
218            .await?;
219        let mut rows = stmt.query((table,)).await?;
220        rows.next().await?.is_some()
221    };
222    if !table_exists {
223        return Ok(None);
224    }
225
226    let sql = format!("SELECT value FROM {table} WHERE key = ?1");
227    let mut stmt = conn.prepare(&sql).await?;
228    let mut rows = stmt.query((id,)).await?;
229    if let Some(row) = rows.next().await? {
230        if let Ok(Value::Text(s)) = row.get_value(0) {
231            return Ok(Some(s));
232        }
233    }
234    Ok(None)
235}
236
237async fn query_int_helper(
238    conn: &Connection,
239    table: &str,
240    id: i64,
241) -> Result<Option<i64>> {
242    let table_exists = {
243        let mut stmt = conn
244            .prepare(
245                "SELECT name FROM sqlite_master WHERE type='table' AND name=?1",
246            )
247            .await?;
248        let mut rows = stmt.query((table,)).await?;
249        rows.next().await?.is_some()
250    };
251    if !table_exists {
252        return Ok(None);
253    }
254
255    let sql = format!("SELECT value FROM {table} WHERE key = ?1");
256    let mut stmt = conn.prepare(&sql).await?;
257    let mut rows = stmt.query((id,)).await?;
258    if let Some(row) = rows.next().await? {
259        if let Ok(Value::Integer(v)) = row.get_value(0) {
260            return Ok(Some(v));
261        }
262    }
263    Ok(None)
264}