agentmux_srv_core/backend/storage/
db_copy.rs1use std::path::Path;
17
18pub fn copy_database(src: &Path, dst: &Path) -> Result<(), String> {
21 let tmp = dst.with_extension("db.copying");
22 let _ = std::fs::remove_file(&tmp);
23 let result = (|| {
24 let conn = rusqlite::Connection::open_with_flags(
25 src,
26 rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
27 )
28 .map_err(|e| format!("open {}: {e}", src.display()))?;
29 conn.busy_timeout(std::time::Duration::from_secs(5)).map_err(|e| e.to_string())?;
30 let tmp_str = tmp.to_str().ok_or("the data path isn't UTF-8")?;
31 conn.execute("VACUUM INTO ?1", [tmp_str])
32 .map_err(|e| format!("copy {}: {e}", src.display()))?;
33 drop(conn);
34 std::fs::rename(&tmp, dst).map_err(|e| format!("rename into {}: {e}", dst.display()))
35 })();
36 if result.is_err() {
37 let _ = std::fs::remove_file(&tmp);
38 }
39 result
40}
41
42pub fn copy_database_excluding_zones(
55 src: &Path,
56 dst: &Path,
57 zone_prefix: &str,
58 zone_tables: &[&str],
59) -> Result<(), String> {
60 use rusqlite::types::Value;
61
62 let tmp = dst.with_extension("db.copying");
63 let _ = std::fs::remove_file(&tmp);
64 let result = (|| {
65 let from = rusqlite::Connection::open_with_flags(
66 src,
67 rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
68 )
69 .map_err(|e| format!("open {}: {e}", src.display()))?;
70 from.busy_timeout(std::time::Duration::from_secs(5)).map_err(|e| e.to_string())?;
71 let to = rusqlite::Connection::open(&tmp).map_err(|e| format!("create {}: {e}", tmp.display()))?;
72
73 from.execute_batch("BEGIN").map_err(|e| e.to_string())?;
74 to.execute_batch("BEGIN").map_err(|e| e.to_string())?;
75
76 let objects: Vec<(String, String, String)> = {
77 let mut stmt = from
78 .prepare("SELECT type, name, sql FROM sqlite_master WHERE sql IS NOT NULL AND name NOT LIKE 'sqlite_%' ORDER BY rowid")
79 .map_err(|e| e.to_string())?;
80 let rows = stmt
81 .query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))
82 .map_err(|e| e.to_string())?;
83 rows.collect::<Result<_, _>>().map_err(|e: rusqlite::Error| e.to_string())?
84 };
85 if objects.iter().any(|(_, _, sql)| sql.trim_start().to_ascii_uppercase().starts_with("CREATE VIRTUAL")) {
86 return Err("a virtual table can't be copied row by row".to_string());
87 }
88 let quote = |name: &str| format!("\"{}\"", name.replace('"', "\"\""));
89
90 for (kind, name, sql) in &objects {
91 if kind != "table" {
92 continue;
93 }
94 to.execute_batch(sql).map_err(|e| format!("create table {name}: {e}"))?;
95 let columns: Vec<String> = {
96 let mut stmt = from.prepare(&format!("PRAGMA table_info({})", quote(name))).map_err(|e| e.to_string())?;
97 let names = stmt.query_map([], |r| r.get::<_, String>(1)).map_err(|e| e.to_string())?;
98 names.collect::<Result<_, _>>().map_err(|e: rusqlite::Error| e.to_string())?
99 };
100 let list = columns.iter().map(|c| quote(c)).collect::<Vec<_>>().join(", ");
101 let filtered = zone_tables.contains(&name.as_str());
102 if filtered && !columns.iter().any(|c| c == "zoneid") {
103 return Err(format!("{name} has no zoneid column to filter on"));
104 }
105 let select = if filtered {
106 format!("SELECT {list} FROM {} WHERE substr(\"zoneid\", 1, ?1) IS NOT ?2", quote(name))
107 } else {
108 format!("SELECT {list} FROM {}", quote(name))
109 };
110 let marks = vec!["?"; columns.len()].join(", ");
111 let mut insert = to
112 .prepare(&format!("INSERT INTO {} ({list}) VALUES ({marks})", quote(name)))
113 .map_err(|e| e.to_string())?;
114 let mut stmt = from.prepare(&select).map_err(|e| e.to_string())?;
115 let queried = if filtered {
116 stmt.query(rusqlite::params![zone_prefix.chars().count() as i64, zone_prefix])
117 } else {
118 stmt.query([])
119 };
120 let mut rows = queried.map_err(|e| format!("read {name}: {e}"))?;
121 while let Some(row) = rows.next().map_err(|e| format!("read {name}: {e}"))? {
122 let values: Vec<Value> =
123 (0..columns.len()).map(|i| row.get(i)).collect::<Result<_, _>>().map_err(|e| e.to_string())?;
124 insert.execute(rusqlite::params_from_iter(values)).map_err(|e| format!("write {name}: {e}"))?;
125 }
126 }
127 for (kind, name, sql) in &objects {
128 if kind != "table" {
129 to.execute_batch(sql).map_err(|e| format!("create {kind} {name}: {e}"))?;
130 }
131 }
132 for pragma in ["user_version", "application_id"] {
133 let value: i64 = from.query_row(&format!("PRAGMA {pragma}"), [], |r| r.get(0)).map_err(|e| e.to_string())?;
134 to.execute_batch(&format!("PRAGMA {pragma} = {value}")).map_err(|e| e.to_string())?;
135 }
136 to.execute_batch("COMMIT").map_err(|e| e.to_string())?;
137 from.execute_batch("COMMIT").map_err(|e| e.to_string())?;
138 drop(to);
139 drop(from);
140 std::fs::rename(&tmp, dst).map_err(|e| format!("rename into {}: {e}", dst.display()))
141 })();
142 if result.is_err() {
143 let _ = std::fs::remove_file(&tmp);
144 }
145 result
146}
147
148#[cfg(test)]
149mod tests {
150 use super::*;
151 use rusqlite::Connection;
152
153 fn wal_db_with_uncheckpointed_row(path: &Path) -> Connection {
154 let conn = Connection::open(path).unwrap();
155 conn.execute_batch(
156 "PRAGMA journal_mode=WAL;
157 PRAGMA wal_autocheckpoint=0;
158 CREATE TABLE t (v TEXT);
159 INSERT INTO t VALUES ('committed');",
160 )
161 .unwrap();
162 conn
163 }
164
165 #[test]
166 fn the_copy_includes_writes_still_in_the_wal() {
167 let dir = tempfile::tempdir().unwrap();
168 let src = dir.path().join("src.db");
169 let _writer = wal_db_with_uncheckpointed_row(&src);
171
172 let plain = dir.path().join("plain.db");
173 std::fs::copy(&src, &plain).unwrap();
174 let plain_rows: Result<i64, _> =
175 Connection::open(&plain).unwrap().query_row("SELECT COUNT(*) FROM t", [], |r| r.get(0));
176 assert!(plain_rows.is_err() || plain_rows.unwrap() == 0, "a plain copy misses the WAL");
177
178 let dst = dir.path().join("dst.db");
179 copy_database(&src, &dst).unwrap();
180 let v: String = Connection::open(&dst).unwrap().query_row("SELECT v FROM t", [], |r| r.get(0)).unwrap();
181 assert_eq!(v, "committed");
182 assert!(!dst.with_extension("db.copying").exists(), "no temporary file is left behind");
183 }
184
185 fn zoned_db(path: &Path) {
186 let conn = Connection::open(path).unwrap();
187 conn.execute_batch(
188 "CREATE TABLE zone_rows (zoneid TEXT NOT NULL, name TEXT NOT NULL, data BLOB, PRIMARY KEY (zoneid, name));
189 CREATE TABLE other (zoneid TEXT, v TEXT);
190 CREATE TABLE log (n INTEGER PRIMARY KEY, why TEXT);
191 CREATE INDEX zone_rows_name ON zone_rows (name);
192 CREATE TRIGGER zone_rows_log AFTER INSERT ON zone_rows BEGIN INSERT INTO log (why) VALUES ('insert'); END;
193 INSERT INTO zone_rows VALUES ('agent:a:current', 'output', x'4d41524b45522d41');
194 INSERT INTO zone_rows VALUES ('agent:a:archive:1', 'output', 'MARKER-B');
195 INSERT INTO zone_rows VALUES ('block-1', 'term', 'terminal text');
196 INSERT INTO zone_rows VALUES ('AGENT:upper', 'x', 'kept: the prefix is case sensitive');
197 INSERT INTO other VALUES ('agent:a:current', 'not a zone table, copied whole');
198 DELETE FROM log;
199 PRAGMA user_version = 7;",
200 )
201 .unwrap();
202 }
203
204 #[test]
205 fn a_copy_without_zones_leaves_the_excluded_rows_out_of_every_byte() {
206 let dir = tempfile::tempdir().unwrap();
207 let src = dir.path().join("src.db");
208 zoned_db(&src);
209 let dst = dir.path().join("dst.db");
210 copy_database_excluding_zones(&src, &dst, "agent:", &["zone_rows"]).unwrap();
211
212 let conn = Connection::open(&dst).unwrap();
213 let kept: Vec<String> = conn
214 .prepare("SELECT zoneid FROM zone_rows ORDER BY zoneid")
215 .unwrap()
216 .query_map([], |r| r.get(0))
217 .unwrap()
218 .collect::<Result<_, _>>()
219 .unwrap();
220 assert_eq!(kept, vec!["AGENT:upper", "block-1"]);
221 let other: i64 = conn.query_row("SELECT COUNT(*) FROM other", [], |r| r.get(0)).unwrap();
222 assert_eq!(other, 1, "a table that is not named is copied whole");
223 let v: i64 = conn.query_row("PRAGMA user_version", [], |r| r.get(0)).unwrap();
224 assert_eq!(v, 7);
225 let schema: i64 = conn
227 .query_row("SELECT COUNT(*) FROM sqlite_master WHERE name IN ('zone_rows_name', 'zone_rows_log')", [], |r| r.get(0))
228 .unwrap();
229 assert_eq!(schema, 2);
230 let fired: i64 = conn.query_row("SELECT COUNT(*) FROM log", [], |r| r.get(0)).unwrap();
231 assert_eq!(fired, 0);
232 drop(conn);
233
234 for entry in std::fs::read_dir(dir.path()).unwrap().flatten() {
235 if entry.path() == src || entry.path().to_string_lossy().contains("src.db") {
236 continue;
237 }
238 let bytes = std::fs::read(entry.path()).unwrap();
239 assert!(!bytes.windows(8).any(|w| w == b"MARKER-B" || w == b"MARKER-A"), "{:?} holds an excluded row", entry.path());
240 }
241 assert!(!dst.with_extension("db.copying").exists());
242 }
243
244 #[test]
245 fn a_zone_table_without_a_zoneid_column_is_refused_and_leaves_nothing() {
246 let dir = tempfile::tempdir().unwrap();
247 let src = dir.path().join("src.db");
248 zoned_db(&src);
249 let dst = dir.path().join("dst.db");
250 assert!(copy_database_excluding_zones(&src, &dst, "agent:", &["log"]).is_err());
251 assert!(!dst.exists());
252 assert!(!dst.with_extension("db.copying").exists());
253 }
254
255 #[test]
256 fn a_failed_copy_leaves_nothing_behind() {
257 let dir = tempfile::tempdir().unwrap();
258 let dst = dir.path().join("dst.db");
259 assert!(copy_database(&dir.path().join("missing.db"), &dst).is_err());
260 assert!(!dst.exists());
261 assert!(!dst.with_extension("db.copying").exists());
262 }
263}