| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | use std::path::Path; |
| 10 | |
| 11 | use turso::{Builder, Connection, Database, IntoParams, Value}; |
| 12 | |
| 13 | use super::migrate::MIGRATIONS; |
| 14 | use super::{col_text, db_err, fetch_all}; |
| 15 | use crate::error::{Error, Result}; |
| 16 | |
| 17 | |
| 18 | pub struct ReadOnly { |
| 19 | |
| 20 | _db: Database, |
| 21 | conn: Connection, |
| 22 | } |
| 23 | |
| 24 | |
| 25 | |
| 26 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 27 | pub struct AttachmentRow { |
| 28 | |
| 29 | pub id: String, |
| 30 | |
| 31 | pub task_id: String, |
| 32 | |
| 33 | pub name: String, |
| 34 | |
| 35 | pub mime: String, |
| 36 | |
| 37 | pub size: u64, |
| 38 | |
| 39 | pub sha256: String, |
| 40 | |
| 41 | pub uploaded_by: String, |
| 42 | |
| 43 | pub created_at: String, |
| 44 | |
| 45 | pub location: String, |
| 46 | } |
| 47 | |
| 48 | |
| 49 | #[derive(Debug, Clone, PartialEq)] |
| 50 | pub struct BoardDump { |
| 51 | |
| 52 | pub board: serde_json::Value, |
| 53 | |
| 54 | pub columns: Vec<serde_json::Value>, |
| 55 | |
| 56 | pub tags: Vec<serde_json::Value>, |
| 57 | |
| 58 | pub tasks: Vec<serde_json::Value>, |
| 59 | |
| 60 | pub assignees: Vec<serde_json::Value>, |
| 61 | |
| 62 | pub dependencies: Vec<serde_json::Value>, |
| 63 | |
| 64 | pub comments: Vec<serde_json::Value>, |
| 65 | |
| 66 | pub activity: Vec<serde_json::Value>, |
| 67 | |
| 68 | pub members: Vec<serde_json::Value>, |
| 69 | } |
| 70 | |
| 71 | |
| 72 | |
| 73 | pub 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 | |
| 98 | const 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 | |
| 101 | fn 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 | |
| 122 | fn 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 | |
| 135 | |
| 136 | async 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 | |
| 153 | impl ReadOnly { |
| 154 | |
| 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 | |
| 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 | |
| 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 | |
| 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 | |
| 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 | |
| 218 | |
| 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 | |
| 227 | |
| 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 | } |