forge
Explore
Log in

Don't you dare go Hollow

iz

Clone
★ 0

0 watching0 forksRustAGPL-3.0567.3 KiB3950aceTahinli27 days ago34 commits

export.rs365 lines, 13.3 KiBHistoryRawDownload
1//! Read-only access to a database file, for the operator commands (`iz export`, `iz restore`, `iz fsck`).
2//!
3//! What it is: a connection that never migrates, never writes and reads a board as JSON rows with the
4//! column names the export file uses. What it is not: the server's store. Opening through [`Store::open`]
5//! would apply migrations, so a check of a damaged or foreign file would change it. The invariant: nothing
6//! in this module writes to the database, and the migration history is checked by [`migrations_problem`]
7//! against the versions this build knows.
8
9use std::path::Path;
10
11use turso::{Builder, Connection, Database, IntoParams, Value};
12
13use super::migrate::MIGRATIONS;
14use super::{col_text, db_err, fetch_all};
15use crate::error::{Error, Result};
16
17/// A database file opened read-only. Keep it alive while its rows are used.
18pub struct ReadOnly {
19 /// Keeps the database handle alive as long as the connection exists.
20 _db: Database,
21 conn: Connection,
22}
23
24/// One attachment row as stored. `location` is `local` (bytes on this disk), `in` (bytes in another
25/// service) or `moving`.
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct AttachmentRow {
28 /// Attachment id (ULID).
29 pub id: String,
30 /// The task it belongs to.
31 pub task_id: String,
32 /// File name as uploaded.
33 pub name: String,
34 /// Sniffed MIME type.
35 pub mime: String,
36 /// Length in bytes as recorded.
37 pub size: u64,
38 /// Lowercase hex SHA-256 as recorded.
39 pub sha256: String,
40 /// Uploader's member id.
41 pub uploaded_by: String,
42 /// UTC stamp of the upload.
43 pub created_at: String,
44 /// Where the bytes are: `local`, `in` or `moving`.
45 pub location: String,
46}
47
48/// A board as JSON rows, one list per table. Each row is an object keyed by the column names.
49#[derive(Debug, Clone, PartialEq)]
50pub struct BoardDump {
51 /// The board row (a single object).
52 pub board: serde_json::Value,
53 /// Columns, retired ones included, in position order.
54 pub columns: Vec<serde_json::Value>,
55 /// Tags (projects), in position order.
56 pub tags: Vec<serde_json::Value>,
57 /// Tasks, deleted ones included (with `deleted_at`), oldest first.
58 pub tasks: Vec<serde_json::Value>,
59 /// Assignments of tasks.
60 pub assignees: Vec<serde_json::Value>,
61 /// Dependency links, cleared ones included (with `cleared_at`).
62 pub dependencies: Vec<serde_json::Value>,
63 /// Comments, deleted ones included (with `deleted_at`).
64 pub comments: Vec<serde_json::Value>,
65 /// Activity of the board's tasks, oldest first.
66 pub activity: Vec<serde_json::Value>,
67 /// Members named by any row above: `sub`, `name` and `email` only.
68 pub members: Vec<serde_json::Value>,
69}
70
71/// The first problem with a migration history, as the user reads it, or `None` when the versions are
72/// exactly `1..=N` and `N` is no newer than this build. An empty history is a problem too.
73pub fn migrations_problem(versions: &[i64]) -> Option<String> {
74 if versions.is_empty() {
75 return Some("the database has no migration history".into());
76 }
77 for (index, version) in versions.iter().enumerate() {
78 let expected = i64::try_from(index + 1).unwrap_or(i64::MAX);
79 if *version != expected {
80 return Some(format!(
81 "migration history is not contiguous: expected version {expected}, found {version}"
82 ));
83 }
84 }
85 let known = MIGRATIONS
86 .last()
87 .map_or(0, |(version, _)| i64::from(*version));
88 let newest = versions.last().copied().unwrap_or(0);
89 if newest > known {
90 return Some(format!(
91 "the database is at migration {newest}, this build knows up to {known}"
92 ));
93 }
94 None
95}
96
97/// Column names of an attachment row, in the order `attachment_rows` selects them.
98const ATTACHMENT_SQL: &str = "SELECT a.id, a.task_id, a.name, a.mime, a.size, a.sha256, a.uploaded_by, \
99 a.created_at, a.location FROM attachments a";
100
101fn map_attachment(row: &turso::Row) -> Result<AttachmentRow> {
102 let size = match row.get_value(4).map_err(db_err)? {
103 Value::Integer(n) => {
104 u64::try_from(n).map_err(|_| Error::Database("attachment size is negative".into()))?
105 }
106 _ => return Err(Error::Database("attachment size is not an integer".into())),
107 };
108 Ok(AttachmentRow {
109 id: col_text(row, 0)?,
110 task_id: col_text(row, 1)?,
111 name: col_text(row, 2)?,
112 mime: col_text(row, 3)?,
113 size,
114 sha256: col_text(row, 5)?,
115 uploaded_by: col_text(row, 6)?,
116 created_at: col_text(row, 7)?,
117 location: col_text(row, 8)?,
118 })
119}
120
121/// Converts one SQL value to JSON. Blobs are refused: no column of this schema holds one.
122fn to_json(value: Value) -> Result<serde_json::Value> {
123 Ok(match value {
124 Value::Null => serde_json::Value::Null,
125 Value::Integer(n) => serde_json::Value::from(n),
126 Value::Real(f) => serde_json::Number::from_f64(f)
127 .map(serde_json::Value::Number)
128 .ok_or_else(|| Error::Database("a real column holds NaN or infinity".into()))?,
129 Value::Text(s) => serde_json::Value::String(s),
130 Value::Blob(_) => return Err(Error::Database("unexpected blob in a row".into())),
131 })
132}
133
134/// Runs a query and returns each row as an object keyed by `cols`, which name the selected columns in
135/// order.
136async fn json_rows(
137 conn: &Connection,
138 sql: &str,
139 params: impl IntoParams,
140 cols: &[&str],
141) -> Result<Vec<serde_json::Value>> {
142 fetch_all(conn, sql, params, |row| {
143 let mut object = serde_json::Map::new();
144 for (i, name) in cols.iter().enumerate() {
145 let value = row.get_value(i).map_err(db_err)?;
146 object.insert((*name).to_owned(), to_json(value)?);
147 }
148 Ok(serde_json::Value::Object(object))
149 })
150 .await
151}
152
153impl ReadOnly {
154 /// Opens the database file read-only. A missing file is an error: nothing is created.
155 pub async fn open(path: &Path) -> Result<ReadOnly> {
156 let text = path.to_str().ok_or_else(|| {
157 Error::Config(format!("database path is not UTF-8: {}", path.display()))
158 })?;
159 let db = Builder::new_local(text)
160 .read_only(true)
161 .build()
162 .await
163 .map_err(db_err)?;
164 let conn = db.connect().map_err(db_err)?;
165 Ok(ReadOnly { _db: db, conn })
166 }
167
168 /// The rows `PRAGMA integrity_check` returns. A healthy database returns exactly `ok`.
169 pub async fn integrity_check(&self) -> Result<Vec<String>> {
170 fetch_all(&self.conn, "PRAGMA integrity_check", (), |row| {
171 col_text(row, 0)
172 })
173 .await
174 }
175
176 /// The migration versions recorded, ascending.
177 pub async fn migration_versions(&self) -> Result<Vec<i64>> {
178 fetch_all(
179 &self.conn,
180 "SELECT version FROM schema_migrations ORDER BY version",
181 (),
182 |row| match row.get_value(0).map_err(db_err)? {
183 Value::Integer(n) => Ok(n),
184 _ => Err(Error::Database(
185 "schema_migrations.version is not an integer".into(),
186 )),
187 },
188 )
189 .await
190 }
191
192 /// Every attachment row of the database, oldest first.
193 pub async fn attachment_rows(&self) -> Result<Vec<AttachmentRow>> {
194 fetch_all(
195 &self.conn,
196 &format!("{ATTACHMENT_SQL} ORDER BY a.id"),
197 (),
198 map_attachment,
199 )
200 .await
201 }
202
203 /// The attachment rows of the tasks of `board_id`, oldest first.
204 pub async fn board_attachment_rows(&self, board_id: &str) -> Result<Vec<AttachmentRow>> {
205 fetch_all(
206 &self.conn,
207 &format!(
208 "{ATTACHMENT_SQL} JOIN tasks t ON t.id = a.task_id WHERE t.board_id = ?1 \
209 ORDER BY a.created_at, a.id"
210 ),
211 (board_id.to_owned(),),
212 map_attachment,
213 )
214 .await
215 }
216
217 /// The ids of the boards in the database. One board per instance is the rule, but the export names
218 /// the board it reads, so it checks.
219 pub async fn board_ids(&self) -> Result<Vec<String>> {
220 fetch_all(&self.conn, "SELECT id FROM boards ORDER BY id", (), |row| {
221 col_text(row, 0)
222 })
223 .await
224 }
225
226 /// Reads a board, its tasks and everything hanging off them, as JSON rows. Every query names its
227 /// columns, so the export file does not depend on the column order of the schema.
228 pub async fn export_board(&self, board_id: &str) -> Result<BoardDump> {
229 let conn = &self.conn;
230 let board_param = || (board_id.to_owned(),);
231 let board = json_rows(
232 conn,
233 "SELECT id, name, key_prefix, next_task_number, created_at FROM boards WHERE id = ?1",
234 board_param(),
235 &["id", "name", "key_prefix", "next_task_number", "created_at"],
236 )
237 .await?
238 .into_iter()
239 .next()
240 .ok_or(Error::NotFound)?;
241 let columns = json_rows(
242 conn,
243 "SELECT id, name, position, is_done, created_at, deleted_at FROM columns \
244 WHERE board_id = ?1 ORDER BY position, id",
245 board_param(),
246 &[
247 "id",
248 "name",
249 "position",
250 "is_done",
251 "created_at",
252 "deleted_at",
253 ],
254 )
255 .await?;
256 let tags = json_rows(
257 conn,
258 "SELECT id, name, position, is_default, color, created_at FROM tags \
259 WHERE board_id = ?1 ORDER BY position, id",
260 board_param(),
261 &[
262 "id",
263 "name",
264 "position",
265 "is_default",
266 "color",
267 "created_at",
268 ],
269 )
270 .await?;
271 let tasks = json_rows(
272 conn,
273 "SELECT id, key, parent_id, title, description, column_id, tag_id, deadline, meeting_at, \
274 position, created_by, created_at, updated_at, done_at, deleted_at FROM tasks \
275 WHERE board_id = ?1 ORDER BY created_at, id",
276 board_param(),
277 &[
278 "id",
279 "key",
280 "parent_id",
281 "title",
282 "description",
283 "column_id",
284 "tag_id",
285 "deadline",
286 "meeting_at",
287 "position",
288 "created_by",
289 "created_at",
290 "updated_at",
291 "done_at",
292 "deleted_at",
293 ],
294 )
295 .await?;
296 let assignees = json_rows(
297 conn,
298 "SELECT a.task_id, a.sub, a.assigned_at FROM task_assignees a \
299 JOIN tasks t ON t.id = a.task_id WHERE t.board_id = ?1 ORDER BY a.task_id, a.sub",
300 board_param(),
301 &["task_id", "sub", "assigned_at"],
302 )
303 .await?;
304 let dependencies = json_rows(
305 conn,
306 "SELECT d.blocked_id, d.blocking_id, d.created_at, d.cleared_at FROM dependencies d \
307 JOIN tasks t ON t.id = d.blocked_id WHERE t.board_id = ?1 ORDER BY d.created_at",
308 board_param(),
309 &["blocked_id", "blocking_id", "created_at", "cleared_at"],
310 )
311 .await?;
312 let comments = json_rows(
313 conn,
314 "SELECT c.id, c.task_id, c.author, c.body, c.created_at, c.edited_at, c.deleted_at \
315 FROM comments c JOIN tasks t ON t.id = c.task_id WHERE t.board_id = ?1 \
316 ORDER BY c.created_at, c.id",
317 board_param(),
318 &[
319 "id",
320 "task_id",
321 "author",
322 "body",
323 "created_at",
324 "edited_at",
325 "deleted_at",
326 ],
327 )
328 .await?;
329 let activity = json_rows(
330 conn,
331 "SELECT x.id, x.task_id, x.actor, x.subject, x.kind, x.detail, x.at FROM activity x \
332 JOIN tasks t ON t.id = x.task_id WHERE t.board_id = ?1 ORDER BY x.at, x.id",
333 board_param(),
334 &["id", "task_id", "actor", "subject", "kind", "detail", "at"],
335 )
336 .await?;
337 let members = json_rows(
338 conn,
339 "SELECT sub, name, email FROM members WHERE sub IN (\
340 SELECT created_by FROM tasks WHERE board_id = ?1 \
341 UNION SELECT a.sub FROM task_assignees a JOIN tasks t ON t.id = a.task_id WHERE t.board_id = ?1 \
342 UNION SELECT c.author FROM comments c JOIN tasks t ON t.id = c.task_id WHERE t.board_id = ?1 \
343 UNION SELECT x.actor FROM activity x JOIN tasks t ON t.id = x.task_id \
344 WHERE t.board_id = ?1 AND x.actor IS NOT NULL \
345 UNION SELECT x.subject FROM activity x JOIN tasks t ON t.id = x.task_id \
346 WHERE t.board_id = ?1 AND x.subject IS NOT NULL \
347 UNION SELECT at.uploaded_by FROM attachments at JOIN tasks t ON t.id = at.task_id \
348 WHERE t.board_id = ?1) ORDER BY sub",
349 board_param(),
350 &["sub", "name", "email"],
351 )
352 .await?;
353 Ok(BoardDump {
354 board,
355 columns,
356 tags,
357 tasks,
358 assignees,
359 dependencies,
360 comments,
361 activity,
362 members,
363 })
364 }
365}