1use rusqlite::{params, Connection, OptionalExtension};
11use serde::{Deserialize, Serialize};
12use serde_json::Value;
13use sha2::{Digest, Sha256};
14
15fn sha256_hex(bytes: &[u8]) -> String {
16 let mut hasher = Sha256::new();
17 hasher.update(bytes);
18 hex::encode(hasher.finalize())
19}
20
21#[derive(Debug, Clone, Serialize, Deserialize)]
22pub struct MigrationItem {
23 pub source_kind: String,
24 pub source_id: String,
25 pub source_hash: String,
26 pub target_entry_id: Option<String>,
27 pub target_rev: Option<String>,
28 pub status: String,
29 pub conflict: Option<String>,
30}
31
32#[derive(Debug, Clone, Serialize, Deserialize)]
33pub struct SourceArchive {
34 pub id: String,
35 pub source_kind: String,
36 pub source_id: Option<String>,
37 pub reason: String,
38 pub media_type: String,
39 pub bytes: Vec<u8>,
40}
41
42#[derive(Debug, Clone, Serialize, Deserialize)]
43pub struct MigrationRecord {
44 pub id: String,
45 pub source_kind: String,
46 pub source_label: String,
47 pub created_at: String,
48 pub status: String,
49 pub manifest: Value,
50 pub items: Vec<MigrationItem>,
51 pub archives: Vec<SourceArchive>,
52}
53
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub struct PreviousItem {
56 pub source_hash: String,
57 pub target_entry_id: Option<String>,
58 pub target_rev: Option<String>,
59}
60
61#[derive(Debug, Clone, Serialize)]
62pub struct ArchiveInfo {
63 pub id: String,
64 pub migration_id: String,
65 pub source_kind: String,
66 pub source_id: Option<String>,
67 pub reason: String,
68 pub media_type: String,
69 pub sha256: String,
70 pub created_at: String,
71}
72
73#[derive(Debug, Clone, Serialize)]
74pub struct MigrationInfo {
75 pub id: String,
76 pub source_kind: String,
77 pub source_label: String,
78 pub created_at: String,
79 pub status: String,
80 pub manifest: Value,
81}
82
83pub fn init_schema(conn: &Connection) -> Result<(), String> {
87 conn.execute_batch(
88 "CREATE TABLE IF NOT EXISTS migrations (
89 id TEXT PRIMARY KEY,
90 source_kind TEXT NOT NULL,
91 source_label TEXT NOT NULL,
92 created_at TEXT NOT NULL,
93 status TEXT NOT NULL,
94 manifest TEXT NOT NULL
95 );
96 CREATE TABLE IF NOT EXISTS migration_items (
97 migration_id TEXT NOT NULL REFERENCES migrations(id) ON DELETE CASCADE,
98 source_kind TEXT NOT NULL,
99 source_id TEXT NOT NULL,
100 source_hash TEXT NOT NULL,
101 target_entry_id TEXT,
102 target_rev TEXT,
103 status TEXT NOT NULL,
104 conflict TEXT,
105 PRIMARY KEY (migration_id, source_kind, source_id)
106 );
107 CREATE INDEX IF NOT EXISTS migration_items_identity
108 ON migration_items(source_kind, source_id, migration_id);
109 CREATE TABLE IF NOT EXISTS vault_blobs (
110 id TEXT PRIMARY KEY,
111 sha256 TEXT NOT NULL,
112 media_type TEXT NOT NULL,
113 bytes BLOB NOT NULL,
114 created_at TEXT NOT NULL
115 );
116 CREATE TABLE IF NOT EXISTS source_archives (
117 id TEXT PRIMARY KEY,
118 migration_id TEXT NOT NULL REFERENCES migrations(id) ON DELETE CASCADE,
119 source_kind TEXT NOT NULL,
120 source_id TEXT,
121 reason TEXT NOT NULL,
122 blob_id TEXT NOT NULL REFERENCES vault_blobs(id),
123 created_at TEXT NOT NULL
124 );
125 CREATE INDEX IF NOT EXISTS source_archives_migration
126 ON source_archives(migration_id);",
127 )
128 .map_err(|e| e.to_string())
129}
130
131pub fn previous_item(
133 conn: &Connection,
134 source_kind: &str,
135 source_id: &str,
136) -> Result<Option<PreviousItem>, String> {
137 conn.query_row(
138 "SELECT source_hash, target_entry_id, target_rev
139 FROM migration_items
140 WHERE source_kind = ?1 AND source_id = ?2
141 ORDER BY rowid DESC LIMIT 1",
142 params![source_kind, source_id],
143 |row| {
144 Ok(PreviousItem {
145 source_hash: row.get(0)?,
146 target_entry_id: row.get(1)?,
147 target_rev: row.get(2)?,
148 })
149 },
150 )
151 .optional()
152 .map_err(|e| e.to_string())
153}
154
155pub fn record_txn(conn: &Connection, record: &MigrationRecord) -> Result<(), String> {
157 let manifest = serde_json::to_string(&record.manifest).map_err(|e| e.to_string())?;
158 conn.execute(
159 "INSERT INTO migrations (id, source_kind, source_label, created_at, status, manifest)
160 VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
161 params![
162 record.id,
163 record.source_kind,
164 record.source_label,
165 record.created_at,
166 record.status,
167 manifest,
168 ],
169 )
170 .map_err(|e| e.to_string())?;
171 for item in &record.items {
172 conn.execute(
173 "INSERT INTO migration_items
174 (migration_id, source_kind, source_id, source_hash, target_entry_id, target_rev, status, conflict)
175 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
176 params![
177 record.id,
178 item.source_kind,
179 item.source_id,
180 item.source_hash,
181 item.target_entry_id,
182 item.target_rev,
183 item.status,
184 item.conflict,
185 ],
186 )
187 .map_err(|e| e.to_string())?;
188 }
189 for archive in &record.archives {
190 let hash = sha256_hex(&archive.bytes);
191 conn.execute(
192 "INSERT INTO vault_blobs (id, sha256, media_type, bytes, created_at)
193 VALUES (?1, ?2, ?3, ?4, ?5)",
194 params![
195 archive.id,
196 hash,
197 archive.media_type,
198 archive.bytes,
199 record.created_at
200 ],
201 )
202 .map_err(|e| e.to_string())?;
203 conn.execute(
204 "INSERT INTO source_archives
205 (id, migration_id, source_kind, source_id, reason, blob_id, created_at)
206 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
207 params![
208 archive.id,
209 record.id,
210 archive.source_kind,
211 archive.source_id,
212 archive.reason,
213 archive.id,
214 record.created_at,
215 ],
216 )
217 .map_err(|e| e.to_string())?;
218 }
219 Ok(())
220}
221
222pub fn archives(conn: &Connection) -> Result<Vec<ArchiveInfo>, String> {
223 let mut stmt = conn
224 .prepare(
225 "SELECT a.id, a.migration_id, a.source_kind, a.source_id, a.reason,
226 b.media_type, b.sha256, a.created_at
227 FROM source_archives a JOIN vault_blobs b ON b.id = a.blob_id
228 ORDER BY a.created_at, a.id",
229 )
230 .map_err(|e| e.to_string())?;
231 let rows = stmt
232 .query_map([], |row| {
233 Ok(ArchiveInfo {
234 id: row.get(0)?,
235 migration_id: row.get(1)?,
236 source_kind: row.get(2)?,
237 source_id: row.get(3)?,
238 reason: row.get(4)?,
239 media_type: row.get(5)?,
240 sha256: row.get(6)?,
241 created_at: row.get(7)?,
242 })
243 })
244 .map_err(|e| e.to_string())?;
245 rows.collect::<Result<Vec<_>, _>>()
246 .map_err(|e| e.to_string())
247}
248
249pub fn migrations(conn: &Connection) -> Result<Vec<MigrationInfo>, String> {
250 let mut stmt = conn
251 .prepare(
252 "SELECT id, source_kind, source_label, created_at, status, manifest
253 FROM migrations ORDER BY created_at, id",
254 )
255 .map_err(|e| e.to_string())?;
256 let rows = stmt
257 .query_map([], |row| {
258 let manifest: String = row.get(5)?;
259 Ok(MigrationInfo {
260 id: row.get(0)?,
261 source_kind: row.get(1)?,
262 source_label: row.get(2)?,
263 created_at: row.get(3)?,
264 status: row.get(4)?,
265 manifest: serde_json::from_str(&manifest).unwrap_or(Value::Null),
266 })
267 })
268 .map_err(|e| e.to_string())?;
269 rows.collect::<Result<Vec<_>, _>>()
270 .map_err(|e| e.to_string())
271}
272
273pub fn migration(conn: &Connection, id: &str) -> Result<Option<MigrationInfo>, String> {
274 conn.query_row(
275 "SELECT id, source_kind, source_label, created_at, status, manifest FROM migrations WHERE id = ?1",
276 [id],
277 |row| {
278 let manifest: String = row.get(5)?;
279 Ok(MigrationInfo {
280 id: row.get(0)?,
281 source_kind: row.get(1)?,
282 source_label: row.get(2)?,
283 created_at: row.get(3)?,
284 status: row.get(4)?,
285 manifest: serde_json::from_str(&manifest).unwrap_or(Value::Null),
286 })
287 },
288 )
289 .optional()
290 .map_err(|e| e.to_string())
291}
292
293pub fn known_source_ids(conn: &Connection, source_kind: &str) -> Result<Vec<String>, String> {
297 let mut stmt = conn
298 .prepare(
299 "SELECT source_id FROM migration_items m
300 WHERE source_kind = ?1 AND target_entry_id IS NOT NULL
301 AND rowid = (SELECT MAX(rowid) FROM migration_items
302 WHERE source_kind = m.source_kind AND source_id = m.source_id)
303 ORDER BY source_id",
304 )
305 .map_err(|e| e.to_string())?;
306 let rows = stmt
307 .query_map([source_kind], |row| row.get::<_, String>(0))
308 .map_err(|e| e.to_string())?;
309 rows.collect::<Result<Vec<_>, _>>()
310 .map_err(|e| e.to_string())
311}
312
313pub fn archive_bytes(conn: &Connection, id: &str) -> Result<Option<Vec<u8>>, String> {
314 conn.query_row(
315 "SELECT b.bytes FROM source_archives a JOIN vault_blobs b ON b.id = a.blob_id WHERE a.id = ?1",
316 [id],
317 |row| row.get(0),
318 )
319 .optional()
320 .map_err(|e| e.to_string())
321}
322
323#[cfg(test)]
324mod tests {
325 use super::*;
326
327 #[test]
328 fn stores_identity_and_encrypted_archive_rows_together() {
329 let conn = Connection::open_in_memory().unwrap();
330 init_schema(&conn).unwrap();
331 conn.execute_batch("BEGIN IMMEDIATE").unwrap();
332 record_txn(
333 &conn,
334 &MigrationRecord {
335 id: "m1".into(),
336 source_kind: "env".into(),
337 source_label: "fixture.env".into(),
338 created_at: "2026-10-14T00:00:00Z".into(),
339 status: "applied".into(),
340 manifest: serde_json::json!({"read": 1}),
341 items: vec![MigrationItem {
342 source_kind: "env".into(),
343 source_id: "env:fixture:A".into(),
344 source_hash: "abc".into(),
345 target_entry_id: Some("e1".into()),
346 target_rev: Some("r1".into()),
347 status: "imported".into(),
348 conflict: None,
349 }],
350 archives: vec![SourceArchive {
351 id: "a1".into(),
352 source_kind: "env".into(),
353 source_id: None,
354 reason: "comments preserved".into(),
355 media_type: "text/plain".into(),
356 bytes: b"# comment\nA=value\n".to_vec(),
357 }],
358 },
359 )
360 .unwrap();
361 conn.execute_batch("COMMIT").unwrap();
362
363 assert_eq!(
364 archive_bytes(&conn, "a1").unwrap().unwrap(),
365 b"# comment\nA=value\n"
366 );
367 assert_eq!(archives(&conn).unwrap().len(), 1);
368 assert_eq!(
369 previous_item(&conn, "env", "env:fixture:A").unwrap(),
370 Some(PreviousItem {
371 source_hash: "abc".into(),
372 target_entry_id: Some("e1".into()),
373 target_rev: Some("r1".into()),
374 })
375 );
376 }
377}