//! Read-only access to a database file, for the operator commands (`iz export`, `iz restore`, `iz fsck`). //! //! What it is: a connection that never migrates, never writes and reads a board as JSON rows with the //! column names the export file uses. What it is not: the server's store. Opening through [`Store::open`] //! would apply migrations, so a check of a damaged or foreign file would change it. The invariant: nothing //! in this module writes to the database, and the migration history is checked by [`migrations_problem`] //! against the versions this build knows. use std::path::Path; use turso::{Builder, Connection, Database, IntoParams, Value}; use super::migrate::MIGRATIONS; use super::{col_text, db_err, fetch_all}; use crate::error::{Error, Result}; /// A database file opened read-only. Keep it alive while its rows are used. pub struct ReadOnly { /// Keeps the database handle alive as long as the connection exists. _db: Database, conn: Connection, } /// One attachment row as stored. `location` is `local` (bytes on this disk), `in` (bytes in another /// service) or `moving`. #[derive(Debug, Clone, PartialEq, Eq)] pub struct AttachmentRow { /// Attachment id (ULID). pub id: String, /// The task it belongs to. pub task_id: String, /// File name as uploaded. pub name: String, /// Sniffed MIME type. pub mime: String, /// Length in bytes as recorded. pub size: u64, /// Lowercase hex SHA-256 as recorded. pub sha256: String, /// Uploader's member id. pub uploaded_by: String, /// UTC stamp of the upload. pub created_at: String, /// Where the bytes are: `local`, `in` or `moving`. pub location: String, } /// A board as JSON rows, one list per table. Each row is an object keyed by the column names. #[derive(Debug, Clone, PartialEq)] pub struct BoardDump { /// The board row (a single object). pub board: serde_json::Value, /// Columns, retired ones included, in position order. pub columns: Vec, /// Tags (projects), in position order. pub tags: Vec, /// Tasks, deleted ones included (with `deleted_at`), oldest first. pub tasks: Vec, /// Assignments of tasks. pub assignees: Vec, /// Dependency links, cleared ones included (with `cleared_at`). pub dependencies: Vec, /// Comments, deleted ones included (with `deleted_at`). pub comments: Vec, /// Activity of the board's tasks, oldest first. pub activity: Vec, /// Members named by any row above: `sub`, `name` and `email` only. pub members: Vec, } /// The first problem with a migration history, as the user reads it, or `None` when the versions are /// exactly `1..=N` and `N` is no newer than this build. An empty history is a problem too. pub fn migrations_problem(versions: &[i64]) -> Option { if versions.is_empty() { return Some("the database has no migration history".into()); } for (index, version) in versions.iter().enumerate() { let expected = i64::try_from(index + 1).unwrap_or(i64::MAX); if *version != expected { return Some(format!( "migration history is not contiguous: expected version {expected}, found {version}" )); } } let known = MIGRATIONS .last() .map_or(0, |(version, _)| i64::from(*version)); let newest = versions.last().copied().unwrap_or(0); if newest > known { return Some(format!( "the database is at migration {newest}, this build knows up to {known}" )); } None } /// Column names of an attachment row, in the order `attachment_rows` selects them. const ATTACHMENT_SQL: &str = "SELECT a.id, a.task_id, a.name, a.mime, a.size, a.sha256, a.uploaded_by, \ a.created_at, a.location FROM attachments a"; fn map_attachment(row: &turso::Row) -> Result { let size = match row.get_value(4).map_err(db_err)? { Value::Integer(n) => { u64::try_from(n).map_err(|_| Error::Database("attachment size is negative".into()))? } _ => return Err(Error::Database("attachment size is not an integer".into())), }; Ok(AttachmentRow { id: col_text(row, 0)?, task_id: col_text(row, 1)?, name: col_text(row, 2)?, mime: col_text(row, 3)?, size, sha256: col_text(row, 5)?, uploaded_by: col_text(row, 6)?, created_at: col_text(row, 7)?, location: col_text(row, 8)?, }) } /// Converts one SQL value to JSON. Blobs are refused: no column of this schema holds one. fn to_json(value: Value) -> Result { Ok(match value { Value::Null => serde_json::Value::Null, Value::Integer(n) => serde_json::Value::from(n), Value::Real(f) => serde_json::Number::from_f64(f) .map(serde_json::Value::Number) .ok_or_else(|| Error::Database("a real column holds NaN or infinity".into()))?, Value::Text(s) => serde_json::Value::String(s), Value::Blob(_) => return Err(Error::Database("unexpected blob in a row".into())), }) } /// Runs a query and returns each row as an object keyed by `cols`, which name the selected columns in /// order. async fn json_rows( conn: &Connection, sql: &str, params: impl IntoParams, cols: &[&str], ) -> Result> { fetch_all(conn, sql, params, |row| { let mut object = serde_json::Map::new(); for (i, name) in cols.iter().enumerate() { let value = row.get_value(i).map_err(db_err)?; object.insert((*name).to_owned(), to_json(value)?); } Ok(serde_json::Value::Object(object)) }) .await } impl ReadOnly { /// Opens the database file read-only. A missing file is an error: nothing is created. pub async fn open(path: &Path) -> Result { let text = path.to_str().ok_or_else(|| { Error::Config(format!("database path is not UTF-8: {}", path.display())) })?; let db = Builder::new_local(text) .read_only(true) .build() .await .map_err(db_err)?; let conn = db.connect().map_err(db_err)?; Ok(ReadOnly { _db: db, conn }) } /// The rows `PRAGMA integrity_check` returns. A healthy database returns exactly `ok`. pub async fn integrity_check(&self) -> Result> { fetch_all(&self.conn, "PRAGMA integrity_check", (), |row| { col_text(row, 0) }) .await } /// The migration versions recorded, ascending. pub async fn migration_versions(&self) -> Result> { fetch_all( &self.conn, "SELECT version FROM schema_migrations ORDER BY version", (), |row| match row.get_value(0).map_err(db_err)? { Value::Integer(n) => Ok(n), _ => Err(Error::Database( "schema_migrations.version is not an integer".into(), )), }, ) .await } /// Every attachment row of the database, oldest first. pub async fn attachment_rows(&self) -> Result> { fetch_all( &self.conn, &format!("{ATTACHMENT_SQL} ORDER BY a.id"), (), map_attachment, ) .await } /// The attachment rows of the tasks of `board_id`, oldest first. pub async fn board_attachment_rows(&self, board_id: &str) -> Result> { fetch_all( &self.conn, &format!( "{ATTACHMENT_SQL} JOIN tasks t ON t.id = a.task_id WHERE t.board_id = ?1 \ ORDER BY a.created_at, a.id" ), (board_id.to_owned(),), map_attachment, ) .await } /// The ids of the boards in the database. One board per instance is the rule, but the export names /// the board it reads, so it checks. pub async fn board_ids(&self) -> Result> { fetch_all(&self.conn, "SELECT id FROM boards ORDER BY id", (), |row| { col_text(row, 0) }) .await } /// Reads a board, its tasks and everything hanging off them, as JSON rows. Every query names its /// columns, so the export file does not depend on the column order of the schema. pub async fn export_board(&self, board_id: &str) -> Result { let conn = &self.conn; let board_param = || (board_id.to_owned(),); let board = json_rows( conn, "SELECT id, name, key_prefix, next_task_number, created_at FROM boards WHERE id = ?1", board_param(), &["id", "name", "key_prefix", "next_task_number", "created_at"], ) .await? .into_iter() .next() .ok_or(Error::NotFound)?; let columns = json_rows( conn, "SELECT id, name, position, is_done, created_at, deleted_at FROM columns \ WHERE board_id = ?1 ORDER BY position, id", board_param(), &[ "id", "name", "position", "is_done", "created_at", "deleted_at", ], ) .await?; let tags = json_rows( conn, "SELECT id, name, position, is_default, color, created_at FROM tags \ WHERE board_id = ?1 ORDER BY position, id", board_param(), &[ "id", "name", "position", "is_default", "color", "created_at", ], ) .await?; let tasks = json_rows( conn, "SELECT id, key, parent_id, title, description, column_id, tag_id, deadline, meeting_at, \ position, created_by, created_at, updated_at, done_at, deleted_at FROM tasks \ WHERE board_id = ?1 ORDER BY created_at, id", board_param(), &[ "id", "key", "parent_id", "title", "description", "column_id", "tag_id", "deadline", "meeting_at", "position", "created_by", "created_at", "updated_at", "done_at", "deleted_at", ], ) .await?; let assignees = json_rows( conn, "SELECT a.task_id, a.sub, a.assigned_at FROM task_assignees a \ JOIN tasks t ON t.id = a.task_id WHERE t.board_id = ?1 ORDER BY a.task_id, a.sub", board_param(), &["task_id", "sub", "assigned_at"], ) .await?; let dependencies = json_rows( conn, "SELECT d.blocked_id, d.blocking_id, d.created_at, d.cleared_at FROM dependencies d \ JOIN tasks t ON t.id = d.blocked_id WHERE t.board_id = ?1 ORDER BY d.created_at", board_param(), &["blocked_id", "blocking_id", "created_at", "cleared_at"], ) .await?; let comments = json_rows( conn, "SELECT c.id, c.task_id, c.author, c.body, c.created_at, c.edited_at, c.deleted_at \ FROM comments c JOIN tasks t ON t.id = c.task_id WHERE t.board_id = ?1 \ ORDER BY c.created_at, c.id", board_param(), &[ "id", "task_id", "author", "body", "created_at", "edited_at", "deleted_at", ], ) .await?; let activity = json_rows( conn, "SELECT x.id, x.task_id, x.actor, x.subject, x.kind, x.detail, x.at FROM activity x \ JOIN tasks t ON t.id = x.task_id WHERE t.board_id = ?1 ORDER BY x.at, x.id", board_param(), &["id", "task_id", "actor", "subject", "kind", "detail", "at"], ) .await?; let members = json_rows( conn, "SELECT sub, name, email FROM members WHERE sub IN (\ SELECT created_by FROM tasks WHERE board_id = ?1 \ UNION SELECT a.sub FROM task_assignees a JOIN tasks t ON t.id = a.task_id WHERE t.board_id = ?1 \ UNION SELECT c.author FROM comments c JOIN tasks t ON t.id = c.task_id WHERE t.board_id = ?1 \ UNION SELECT x.actor FROM activity x JOIN tasks t ON t.id = x.task_id \ WHERE t.board_id = ?1 AND x.actor IS NOT NULL \ UNION SELECT x.subject FROM activity x JOIN tasks t ON t.id = x.task_id \ WHERE t.board_id = ?1 AND x.subject IS NOT NULL \ UNION SELECT at.uploaded_by FROM attachments at JOIN tasks t ON t.id = at.task_id \ WHERE t.board_id = ?1) ORDER BY sub", board_param(), &["sub", "name", "email"], ) .await?; Ok(BoardDump { board, columns, tags, tasks, assignees, dependencies, comments, activity, members, }) } }