1use 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 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 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 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 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 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 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 conn.execute("ALTER TABLE users_new RENAME TO users", ())
165 .await?;
166
167 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 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 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}