Onset: version control where nobody waits and nothing gets lost. The on command, its core and onset-server.
| 6 | use std::path::{Path, PathBuf}; |
| 7 |
| 8 | use anyhow::{Context, Result}; |
| 9 | use rusqlite::{Connection, OptionalExtension, params}; |
| 10 | use serde::{Deserialize, Serialize}; |
| 11 | use vcs_core::Id; |
| 12 | use vcs_core::version::Version; |
| 13 |
| 14 | use crate::ids; |
| 15 |
| 16 | const SCHEMA: &str = r#" |
| 17 | CREATE TABLE IF NOT EXISTS projects ( |
| 18 | id TEXT PRIMARY KEY, |
| 19 | address TEXT NOT NULL UNIQUE, |
| 20 | kind TEXT NOT NULL, |
| 21 | api TEXT, |
| 22 | checked INTEGER NOT NULL DEFAULT 0, |
| 23 | created INTEGER NOT NULL |
| 24 | ); |
| 25 | CREATE TABLE IF NOT EXISTS versions ( |
| 26 | project TEXT NOT NULL, |
| 27 | n INTEGER NOT NULL, |
| 28 | id TEXT NOT NULL, |
| 29 | tree TEXT NOT NULL, |
| 30 | prev TEXT, |
| 31 | change TEXT NOT NULL, |
| 32 | author TEXT NOT NULL, |
| 33 | time INTEGER NOT NULL, |
| 34 | title TEXT NOT NULL, |
| 35 | body TEXT NOT NULL, |
| 36 | git TEXT, |
| 37 | PRIMARY KEY (project, n) |
| 38 | ); |
| 39 | CREATE INDEX IF NOT EXISTS versions_change ON versions(project, change); |
| 40 | CREATE TABLE IF NOT EXISTS workspaces ( |
| 41 | id TEXT PRIMARY KEY, |
| 42 | project TEXT NOT NULL, |
| 43 | path TEXT NOT NULL UNIQUE, |
| 44 | change TEXT NOT NULL, |
| 45 | only TEXT NOT NULL DEFAULT '[]', |
| 46 | created INTEGER NOT NULL, |
| 47 | used INTEGER NOT NULL |
| 48 | ); |
| 49 | CREATE TABLE IF NOT EXISTS changes ( |
| 50 | id TEXT PRIMARY KEY, |
| 51 | project TEXT NOT NULL, |
| 52 | title TEXT NOT NULL DEFAULT '', |
| 53 | body TEXT NOT NULL DEFAULT '', |
| 54 | base_tree TEXT NOT NULL, |
| 55 | base_version INTEGER, |
| 56 | on_change TEXT, |
| 57 | after_change TEXT, |
| 58 | head_tree TEXT, |
| 59 | saves INTEGER NOT NULL DEFAULT 0, |
| 60 | state TEXT NOT NULL DEFAULT 'open', |
| 61 | version INTEGER, |
| 62 | author TEXT NOT NULL DEFAULT '', |
| 63 | conflicts TEXT NOT NULL DEFAULT '[]', |
| 64 | workspace TEXT, |
| 65 | shared TEXT NOT NULL DEFAULT '[]', |
| 66 | remote_rev INTEGER NOT NULL DEFAULT 0, |
| 67 | created INTEGER NOT NULL, |
| 68 | updated INTEGER NOT NULL |
| 69 | ); |
| 70 | CREATE INDEX IF NOT EXISTS changes_project ON changes(project, state); |
| 71 | CREATE TABLE IF NOT EXISTS saves ( |
| 72 | change TEXT NOT NULL, |
| 73 | n INTEGER NOT NULL, |
| 74 | tree TEXT NOT NULL, |
| 75 | base_tree TEXT NOT NULL, |
| 76 | at INTEGER NOT NULL, |
| 77 | workspace TEXT, |
| 78 | uploaded INTEGER NOT NULL DEFAULT 0, |
| 79 | PRIMARY KEY (change, n) |
| 80 | ); |
| 81 | CREATE INDEX IF NOT EXISTS saves_time ON saves(workspace, at); |
| 82 | CREATE TABLE IF NOT EXISTS ops ( |
| 83 | id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 84 | workspace TEXT NOT NULL, |
| 85 | at INTEGER NOT NULL, |
| 86 | kind TEXT NOT NULL, |
| 87 | data TEXT NOT NULL, |
| 88 | undone INTEGER NOT NULL DEFAULT 0 |
| 89 | ); |
| 90 | CREATE INDEX IF NOT EXISTS ops_workspace ON ops(workspace, id); |
| 91 | CREATE TABLE IF NOT EXISTS complete ( |
| 92 | tree TEXT PRIMARY KEY |
| 93 | ); |
| 94 | CREATE TABLE IF NOT EXISTS personal ( |
| 95 | project TEXT PRIMARY KEY, |
| 96 | patterns TEXT NOT NULL |
| 97 | ); |
| 98 | CREATE TABLE IF NOT EXISTS mine ( |
| 99 | project TEXT NOT NULL, |
| 100 | path TEXT NOT NULL, |
| 101 | file TEXT NOT NULL, |
| 102 | exec INTEGER NOT NULL DEFAULT 0, |
| 103 | at INTEGER NOT NULL, |
| 104 | PRIMARY KEY (project, path) |
| 105 | ); |
| 106 | CREATE INDEX IF NOT EXISTS versions_git ON versions(project, git); |
| 107 | CREATE INDEX IF NOT EXISTS versions_tree ON versions(project, tree); |
| 108 | CREATE TABLE IF NOT EXISTS imports ( |
| 109 | project TEXT PRIMARY KEY, |
| 110 | source TEXT NOT NULL, |
| 111 | branch TEXT NOT NULL |
| 112 | ); |
| 113 | CREATE TABLE IF NOT EXISTS uploaded ( |
| 114 | project TEXT NOT NULL, |
| 115 | tree TEXT NOT NULL, |
| 116 | PRIMARY KEY (project, tree) |
| 117 | ); |
| 118 | CREATE TABLE IF NOT EXISTS git_ids ( |
| 119 | project TEXT NOT NULL, |
| 120 | native TEXT NOT NULL, |
| 121 | git TEXT NOT NULL, |
| 122 | PRIMARY KEY (project, native) |
| 123 | ); |
| 124 | "#; |
| 125 |
| 126 | pub struct Db { |
| 127 | pub conn: Connection, |
| 128 | } |
| 129 |
| 130 | #[derive(Debug, Clone)] |
| 131 | pub struct Project { |
| 132 | pub id: String, |
| 133 | /// `host/owner/name` for hosted projects, the folder for local ones. |
| 134 | pub address: String, |
| 135 | /// "local" or "hosted". |
| 136 | pub kind: String, |
| 137 | pub api: Option<String>, |
| 138 | /// When main was last checked with the host (seconds). |
| 139 | pub checked: i64, |
| 140 | } |
| 141 |
| 142 | impl Project { |
| 143 | pub fn hosted(&self) -> bool { |
| 144 | self.kind == "hosted" |
| 145 | } |
| 146 | } |
| 147 |
| 148 | #[derive(Debug, Clone)] |
| 149 | pub struct Workspace { |
| 150 | pub id: String, |
| 151 | pub project: String, |
| 152 | pub path: PathBuf, |
| 153 | pub change: String, |
| 154 | pub only: Vec<String>, |
| 155 | } |
| 156 |
| 157 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] |
| 158 | pub struct Conflict { |
| 159 | pub path: String, |
| 160 | #[serde(default)] |
| 161 | pub version: Option<u64>, |
| 162 | } |
| 163 |
| 164 | #[derive(Debug, Clone)] |
| 165 | pub struct Change { |
| 166 | pub id: String, |
| 167 | pub project: String, |
| 168 | pub title: String, |
| 169 | pub body: String, |
| 170 | /// The tree the change starts from. |
| 171 | pub base_tree: Id, |
| 172 | /// Set when the base is a version of main. |
| 173 | pub base_version: Option<u64>, |
| 174 | /// Set when stacked on an unlanded change. |
| 175 | pub on_change: Option<String>, |
| 176 | /// Set when the change continues after one that landed from the same workspace. |
| 177 | pub after_change: Option<String>, |
| 178 | /// The latest save (None: nothing saved, same as the base). |
| 179 | pub head_tree: Option<Id>, |
| 180 | pub saves: i64, |
| 181 | /// open, waiting, landed, dropped. |
| 182 | pub state: String, |
| 183 | pub version: Option<u64>, |
| 184 | pub author: String, |
| 185 | pub conflicts: Vec<Conflict>, |
| 186 | pub workspace: Option<String>, |
| 187 | pub shared: Vec<String>, |
| 188 | pub remote_rev: i64, |
| 189 | pub created: i64, |
| 190 | pub updated: i64, |
| 191 | } |
| 192 |
| 193 | impl Change { |
| 194 | pub fn new(id: String, project: &str, base_tree: Id, base_version: Option<u64>, author: &str) -> Change { |
| 195 | let now = ids::now(); |
| 196 | Change { |
| 197 | id, |
| 198 | project: project.to_string(), |
| 199 | title: String::new(), |
| 200 | body: String::new(), |
| 201 | base_tree, |
| 202 | base_version, |
| 203 | on_change: None, |
| 204 | after_change: None, |
| 205 | head_tree: None, |
| 206 | saves: 0, |
| 207 | state: "open".into(), |
| 208 | version: None, |
| 209 | author: author.to_string(), |
| 210 | conflicts: Vec::new(), |
| 211 | workspace: None, |
| 212 | shared: Vec::new(), |
| 213 | remote_rev: 0, |
| 214 | created: now, |
| 215 | updated: now, |
| 216 | } |
| 217 | } |
| 218 |
| 219 | /// The change's content: its latest save, or its base. |
| 220 | pub fn tree(&self) -> Id { |
| 221 | self.head_tree.unwrap_or(self.base_tree) |
| 222 | } |
| 223 |
| 224 | pub fn is_empty(&self) -> bool { |
| 225 | self.tree() == self.base_tree |
| 226 | } |
| 227 |
| 228 | pub fn message(&self) -> String { |
| 229 | if self.body.is_empty() { self.title.clone() } else { format!("{}\n\n{}", self.title, self.body) } |
| 230 | } |
| 231 | } |
| 232 |
| 233 | #[derive(Debug, Clone)] |
| 234 | pub struct Save { |
| 235 | pub change: String, |
| 236 | pub n: i64, |
| 237 | pub tree: Id, |
| 238 | pub base_tree: Id, |
| 239 | pub at: i64, |
| 240 | pub uploaded: bool, |
| 241 | } |
| 242 |
| 243 | #[derive(Debug, Clone)] |
| 244 | pub struct Op { |
| 245 | pub id: i64, |
| 246 | pub at: i64, |
| 247 | pub kind: String, |
| 248 | pub data: serde_json::Value, |
| 249 | } |
| 250 |
| 251 | fn id_col(row: &rusqlite::Row, i: usize) -> rusqlite::Result<Id> { |
| 252 | let text: String = row.get(i)?; |
| 253 | Id::parse(&text).ok_or_else(|| rusqlite::Error::InvalidColumnType(i, "id".into(), rusqlite::types::Type::Text)) |
| 254 | } |
| 255 |
| 256 | fn opt_id_col(row: &rusqlite::Row, i: usize) -> rusqlite::Result<Option<Id>> { |
| 257 | let text: Option<String> = row.get(i)?; |
| 258 | Ok(text.and_then(|t| Id::parse(&t))) |
| 259 | } |
| 260 |
| 261 | impl Db { |
| 262 | pub fn open(home: &Path) -> Result<Db> { |
| 263 | std::fs::create_dir_all(home).with_context(|| format!("creating {}", home.display()))?; |
| 264 | let conn = Connection::open(home.join("vcs.db")).context("opening the vcs database")?; |
| 265 | Self::setup(conn) |
| 266 | } |
| 267 |
| 268 | pub fn setup(conn: Connection) -> Result<Db> { |
| 269 | // Many agents on one machine share this database. SQLite's own |
| 270 | // busy wait sleeps up to 100 ms between tries; this one tries again |
| 271 | // within a millisecond, for up to a minute. |
| 272 | conn.busy_handler(Some(|tries: i32| { |
| 273 | std::thread::sleep(std::time::Duration::from_micros(300 + (tries as u64 % 5) * 150)); |
| 274 | tries < 120_000 |
| 275 | }))?; |
| 276 | conn.pragma_update(None, "journal_mode", "WAL")?; |
| 277 | conn.pragma_update(None, "synchronous", "NORMAL")?; |
| 278 | conn.execute_batch(SCHEMA)?; |
| 279 | Ok(Db { conn }) |
| 280 | } |
| 281 |
| 282 | // Projects. |
| 283 |
| 284 | pub fn put_project(&self, p: &Project) -> Result<()> { |
| 285 | self.conn.execute( |
| 286 | "INSERT INTO projects (id, address, kind, api, checked, created) VALUES (?1, ?2, ?3, ?4, ?5, ?6) |
| 287 | ON CONFLICT(id) DO UPDATE SET address=excluded.address, kind=excluded.kind, api=excluded.api, checked=excluded.checked", |
| 288 | params![p.id, p.address, p.kind, p.api, p.checked, ids::now()], |
| 289 | )?; |
| 290 | Ok(()) |
| 291 | } |
| 292 |
| 293 | fn project_row(row: &rusqlite::Row) -> rusqlite::Result<Project> { |
| 294 | Ok(Project { id: row.get(0)?, address: row.get(1)?, kind: row.get(2)?, api: row.get(3)?, checked: row.get(4)? }) |
| 295 | } |
| 296 |
| 297 | pub fn project(&self, id: &str) -> Result<Option<Project>> { |
| 298 | Ok(self |
| 299 | .conn |
| 300 | .query_row("SELECT id, address, kind, api, checked FROM projects WHERE id = ?1", [id], Self::project_row) |
| 301 | .optional()?) |
| 302 | } |
| 303 |
| 304 | pub fn project_by_address(&self, address: &str) -> Result<Option<Project>> { |
| 305 | Ok(self |
| 306 | .conn |
| 307 | .query_row("SELECT id, address, kind, api, checked FROM projects WHERE address = ?1", [address], Self::project_row) |
| 308 | .optional()?) |
| 309 | } |
| 310 |
| 311 | pub fn set_checked(&self, project: &str, at: i64) -> Result<()> { |
| 312 | self.conn.execute("UPDATE projects SET checked = ?2 WHERE id = ?1", params![project, at])?; |
| 313 | Ok(()) |
| 314 | } |
| 315 |
| 316 | // Versions. |
| 317 |
| 318 | pub fn put_version(&self, project: &str, v: &Version) -> Result<()> { |
| 319 | self.conn.execute( |
| 320 | "INSERT OR REPLACE INTO versions (project, n, id, tree, prev, change, author, time, title, body, git) |
| 321 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)", |
| 322 | params![ |
| 323 | project, |
| 324 | v.n as i64, |
| 325 | v.id(project).hex(), |
| 326 | v.tree.hex(), |
| 327 | v.prev.map(|p| p.hex()), |
| 328 | v.change, |
| 329 | v.author, |
| 330 | v.time, |
| 331 | v.title, |
| 332 | v.body, |
| 333 | v.git |
| 334 | ], |
| 335 | )?; |
| 336 | Ok(()) |
| 337 | } |
| 338 |
| 339 | fn version_row(row: &rusqlite::Row) -> rusqlite::Result<Version> { |
| 340 | Ok(Version { |
| 341 | n: row.get::<_, i64>(0)? as u64, |
| 342 | tree: id_col(row, 1)?, |
| 343 | prev: opt_id_col(row, 2)?, |
| 344 | change: row.get(3)?, |
| 345 | author: row.get(4)?, |
| 346 | time: row.get(5)?, |
| 347 | title: row.get(6)?, |
| 348 | body: row.get(7)?, |
| 349 | git: row.get(8)?, |
| 350 | }) |
| 351 | } |
| 352 |
| 353 | const VERSION_COLUMNS: &'static str = "n, tree, prev, change, author, time, title, body, git"; |
| 354 |
| 355 | pub fn version(&self, project: &str, n: u64) -> Result<Option<Version>> { |
| 356 | let sql = format!("SELECT {} FROM versions WHERE project = ?1 AND n = ?2", Self::VERSION_COLUMNS); |
| 357 | Ok(self.conn.query_row(&sql, params![project, n as i64], Self::version_row).optional()?) |
| 358 | } |
| 359 |
| 360 | pub fn latest_version(&self, project: &str) -> Result<Option<Version>> { |
| 361 | let sql = format!("SELECT {} FROM versions WHERE project = ?1 ORDER BY n DESC LIMIT 1", Self::VERSION_COLUMNS); |
| 362 | Ok(self.conn.query_row(&sql, [project], Self::version_row).optional()?) |
| 363 | } |
| 364 |
| 365 | pub fn versions(&self, project: &str, limit: i64) -> Result<Vec<Version>> { |
| 366 | let sql = format!("SELECT {} FROM versions WHERE project = ?1 ORDER BY n DESC LIMIT ?2", Self::VERSION_COLUMNS); |
| 367 | let mut stmt = self.conn.prepare(&sql)?; |
| 368 | let rows = stmt.query_map(params![project, limit], Self::version_row)?; |
| 369 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 370 | } |
| 371 |
| 372 | pub fn version_of_change(&self, project: &str, change: &str) -> Result<Option<Version>> { |
| 373 | let sql = format!("SELECT {} FROM versions WHERE project = ?1 AND change = ?2 ORDER BY n DESC LIMIT 1", Self::VERSION_COLUMNS); |
| 374 | Ok(self.conn.query_row(&sql, params![project, change], Self::version_row).optional()?) |
| 375 | } |
| 376 |
| 377 | // Workspaces. |
| 378 |
| 379 | pub fn put_workspace(&self, w: &Workspace) -> Result<()> { |
| 380 | let now = ids::now(); |
| 381 | // A folder holds one workspace: any other one recorded at this path |
| 382 | // was deleted with its folder. Its change stays. |
| 383 | self.conn.execute("DELETE FROM workspaces WHERE path = ?1 AND id != ?2", params![w.path.to_string_lossy(), w.id])?; |
| 384 | self.conn.execute( |
| 385 | "INSERT INTO workspaces (id, project, path, change, only, created, used) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?6) |
| 386 | ON CONFLICT(id) DO UPDATE SET project=excluded.project, path=excluded.path, change=excluded.change, |
| 387 | only=excluded.only, used=excluded.used", |
| 388 | params![w.id, w.project, w.path.to_string_lossy(), w.change, serde_json::to_string(&w.only)?, now], |
| 389 | )?; |
| 390 | Ok(()) |
| 391 | } |
| 392 |
| 393 | fn workspace_row(row: &rusqlite::Row) -> rusqlite::Result<Workspace> { |
| 394 | let only: String = row.get(4)?; |
| 395 | Ok(Workspace { |
| 396 | id: row.get(0)?, |
| 397 | project: row.get(1)?, |
| 398 | path: PathBuf::from(row.get::<_, String>(2)?), |
| 399 | change: row.get(3)?, |
| 400 | only: serde_json::from_str(&only).unwrap_or_default(), |
| 401 | }) |
| 402 | } |
| 403 |
| 404 | pub fn workspace(&self, id: &str) -> Result<Option<Workspace>> { |
| 405 | Ok(self |
| 406 | .conn |
| 407 | .query_row("SELECT id, project, path, change, only FROM workspaces WHERE id = ?1", [id], Self::workspace_row) |
| 408 | .optional()?) |
| 409 | } |
| 410 |
| 411 | pub fn project_workspaces(&self, project: &str) -> Result<Vec<Workspace>> { |
| 412 | let mut stmt = |
| 413 | self.conn.prepare("SELECT id, project, path, change, only FROM workspaces WHERE project = ?1 ORDER BY used DESC")?; |
| 414 | let rows = stmt.query_map([project], Self::workspace_row)?; |
| 415 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 416 | } |
| 417 |
| 418 | pub fn all_workspaces(&self) -> Result<Vec<Workspace>> { |
| 419 | let mut stmt = self.conn.prepare("SELECT id, project, path, change, only FROM workspaces ORDER BY used DESC")?; |
| 420 | let rows = stmt.query_map([], Self::workspace_row)?; |
| 421 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 422 | } |
| 423 |
| 424 | pub fn workspace_holding(&self, change: &str) -> Result<Option<Workspace>> { |
| 425 | Ok(self |
| 426 | .conn |
| 427 | .query_row( |
| 428 | "SELECT id, project, path, change, only FROM workspaces WHERE change = ?1 ORDER BY used DESC LIMIT 1", |
| 429 | [change], |
| 430 | Self::workspace_row, |
| 431 | ) |
| 432 | .optional()?) |
| 433 | } |
| 434 |
| 435 | pub fn delete_workspace(&self, id: &str) -> Result<()> { |
| 436 | self.conn.execute("DELETE FROM workspaces WHERE id = ?1", [id])?; |
| 437 | Ok(()) |
| 438 | } |
| 439 |
| 440 | // Changes. |
| 441 |
| 442 | pub fn put_change(&self, c: &Change) -> Result<()> { |
| 443 | self.conn.execute( |
| 444 | "INSERT INTO changes (id, project, title, body, base_tree, base_version, on_change, after_change, head_tree, |
| 445 | saves, state, version, author, conflicts, workspace, shared, remote_rev, created, updated) |
| 446 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19) |
| 447 | ON CONFLICT(id) DO UPDATE SET title=excluded.title, body=excluded.body, base_tree=excluded.base_tree, |
| 448 | base_version=excluded.base_version, on_change=excluded.on_change, after_change=excluded.after_change, |
| 449 | head_tree=excluded.head_tree, saves=excluded.saves, state=excluded.state, version=excluded.version, |
| 450 | author=excluded.author, conflicts=excluded.conflicts, workspace=excluded.workspace, |
| 451 | shared=excluded.shared, remote_rev=excluded.remote_rev, updated=excluded.updated", |
| 452 | params![ |
| 453 | c.id, |
| 454 | c.project, |
| 455 | c.title, |
| 456 | c.body, |
| 457 | c.base_tree.hex(), |
| 458 | c.base_version.map(|v| v as i64), |
| 459 | c.on_change, |
| 460 | c.after_change, |
| 461 | c.head_tree.map(|t| t.hex()), |
| 462 | c.saves, |
| 463 | c.state, |
| 464 | c.version.map(|v| v as i64), |
| 465 | c.author, |
| 466 | serde_json::to_string(&c.conflicts)?, |
| 467 | c.workspace, |
| 468 | serde_json::to_string(&c.shared)?, |
| 469 | c.remote_rev, |
| 470 | c.created, |
| 471 | ids::now() |
| 472 | ], |
| 473 | )?; |
| 474 | Ok(()) |
| 475 | } |
| 476 |
| 477 | const CHANGE_COLUMNS: &'static str = "id, project, title, body, base_tree, base_version, on_change, after_change, head_tree, saves, state, version, author, conflicts, workspace, shared, remote_rev, created, updated"; |
| 478 |
| 479 | fn change_row(row: &rusqlite::Row) -> rusqlite::Result<Change> { |
| 480 | let conflicts: String = row.get(13)?; |
| 481 | let shared: String = row.get(15)?; |
| 482 | Ok(Change { |
| 483 | id: row.get(0)?, |
| 484 | project: row.get(1)?, |
| 485 | title: row.get(2)?, |
| 486 | body: row.get(3)?, |
| 487 | base_tree: id_col(row, 4)?, |
| 488 | base_version: row.get::<_, Option<i64>>(5)?.map(|v| v as u64), |
| 489 | on_change: row.get(6)?, |
| 490 | after_change: row.get(7)?, |
| 491 | head_tree: opt_id_col(row, 8)?, |
| 492 | saves: row.get(9)?, |
| 493 | state: row.get(10)?, |
| 494 | version: row.get::<_, Option<i64>>(11)?.map(|v| v as u64), |
| 495 | author: row.get(12)?, |
| 496 | conflicts: serde_json::from_str(&conflicts).unwrap_or_default(), |
| 497 | workspace: row.get(14)?, |
| 498 | shared: serde_json::from_str(&shared).unwrap_or_default(), |
| 499 | remote_rev: row.get(16)?, |
| 500 | created: row.get(17)?, |
| 501 | updated: row.get(18)?, |
| 502 | }) |
| 503 | } |
| 504 |
| 505 | pub fn change(&self, id: &str) -> Result<Option<Change>> { |
| 506 | let sql = format!("SELECT {} FROM changes WHERE id = ?1", Self::CHANGE_COLUMNS); |
| 507 | Ok(self.conn.query_row(&sql, [id], Self::change_row).optional()?) |
| 508 | } |
| 509 |
| 510 | pub fn changes(&self, project: &str) -> Result<Vec<Change>> { |
| 511 | let sql = format!("SELECT {} FROM changes WHERE project = ?1 ORDER BY updated DESC", Self::CHANGE_COLUMNS); |
| 512 | let mut stmt = self.conn.prepare(&sql)?; |
| 513 | let rows = stmt.query_map([project], Self::change_row)?; |
| 514 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 515 | } |
| 516 |
| 517 | pub fn change_ids(&self, project: &str) -> Result<Vec<String>> { |
| 518 | let mut stmt = self.conn.prepare("SELECT id FROM changes WHERE project = ?1")?; |
| 519 | let rows = stmt.query_map([project], |r| r.get::<_, String>(0))?; |
| 520 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 521 | } |
| 522 |
| 523 | pub fn changes_by_prefix(&self, project: &str, prefix: &str) -> Result<Vec<Change>> { |
| 524 | let sql = format!("SELECT {} FROM changes WHERE project = ?1 AND id LIKE ?2 || '%'", Self::CHANGE_COLUMNS); |
| 525 | let mut stmt = self.conn.prepare(&sql)?; |
| 526 | let rows = stmt.query_map(params![project, prefix], Self::change_row)?; |
| 527 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 528 | } |
| 529 |
| 530 | // Saves. |
| 531 |
| 532 | pub fn add_save(&self, s: &Save, workspace: &str) -> Result<()> { |
| 533 | self.conn.execute( |
| 534 | "INSERT OR REPLACE INTO saves (change, n, tree, base_tree, at, workspace, uploaded) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", |
| 535 | params![s.change, s.n, s.tree.hex(), s.base_tree.hex(), s.at, workspace, s.uploaded as i64], |
| 536 | )?; |
| 537 | Ok(()) |
| 538 | } |
| 539 |
| 540 | fn save_row(row: &rusqlite::Row) -> rusqlite::Result<Save> { |
| 541 | Ok(Save { |
| 542 | change: row.get(0)?, |
| 543 | n: row.get(1)?, |
| 544 | tree: id_col(row, 2)?, |
| 545 | base_tree: id_col(row, 3)?, |
| 546 | at: row.get(4)?, |
| 547 | uploaded: row.get::<_, i64>(5)? != 0, |
| 548 | }) |
| 549 | } |
| 550 |
| 551 | pub fn saves(&self, change: &str) -> Result<Vec<Save>> { |
| 552 | let mut stmt = self |
| 553 | .conn |
| 554 | .prepare("SELECT change, n, tree, base_tree, at, uploaded FROM saves WHERE change = ?1 ORDER BY n")?; |
| 555 | let rows = stmt.query_map([change], Self::save_row)?; |
| 556 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 557 | } |
| 558 |
| 559 | pub fn save(&self, change: &str, n: i64) -> Result<Option<Save>> { |
| 560 | Ok(self |
| 561 | .conn |
| 562 | .query_row( |
| 563 | "SELECT change, n, tree, base_tree, at, uploaded FROM saves WHERE change = ?1 AND n = ?2", |
| 564 | params![change, n], |
| 565 | Self::save_row, |
| 566 | ) |
| 567 | .optional()?) |
| 568 | } |
| 569 |
| 570 | /// The latest save made in `workspace` at or before `at`, across changes. |
| 571 | pub fn save_at(&self, workspace: &str, at: i64) -> Result<Option<Save>> { |
| 572 | Ok(self |
| 573 | .conn |
| 574 | .query_row( |
| 575 | "SELECT change, n, tree, base_tree, at, uploaded FROM saves WHERE workspace = ?1 AND at <= ?2 |
| 576 | ORDER BY at DESC, rowid DESC LIMIT 1", |
| 577 | params![workspace, at], |
| 578 | Self::save_row, |
| 579 | ) |
| 580 | .optional()?) |
| 581 | } |
| 582 |
| 583 | pub fn unuploaded_saves(&self, change: &str) -> Result<Vec<Save>> { |
| 584 | let mut stmt = self.conn.prepare( |
| 585 | "SELECT change, n, tree, base_tree, at, uploaded FROM saves WHERE change = ?1 AND uploaded = 0 ORDER BY n", |
| 586 | )?; |
| 587 | let rows = stmt.query_map([change], Self::save_row)?; |
| 588 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 589 | } |
| 590 |
| 591 | pub fn mark_uploaded(&self, change: &str, n: i64) -> Result<()> { |
| 592 | self.conn.execute("UPDATE saves SET uploaded = 1 WHERE change = ?1 AND n = ?2", params![change, n])?; |
| 593 | Ok(()) |
| 594 | } |
| 595 |
| 596 | /// Drops saves (the secret scrub): every save of `change` goes, and the |
| 597 | /// caller records a fresh one. |
| 598 | pub fn delete_saves(&self, change: &str) -> Result<()> { |
| 599 | self.conn.execute("DELETE FROM saves WHERE change = ?1", [change])?; |
| 600 | Ok(()) |
| 601 | } |
| 602 |
| 603 | // Operations. |
| 604 |
| 605 | pub fn add_op(&self, workspace: &str, kind: &str, data: &serde_json::Value) -> Result<i64> { |
| 606 | self.conn.execute( |
| 607 | "INSERT INTO ops (workspace, at, kind, data) VALUES (?1, ?2, ?3, ?4)", |
| 608 | params![workspace, ids::now(), kind, data.to_string()], |
| 609 | )?; |
| 610 | Ok(self.conn.last_insert_rowid()) |
| 611 | } |
| 612 |
| 613 | fn op_row(row: &rusqlite::Row) -> rusqlite::Result<Op> { |
| 614 | let data: String = row.get(3)?; |
| 615 | Ok(Op { id: row.get(0)?, at: row.get(1)?, kind: row.get(2)?, data: serde_json::from_str(&data).unwrap_or_default() }) |
| 616 | } |
| 617 |
| 618 | pub fn last_op(&self, workspace: &str) -> Result<Option<Op>> { |
| 619 | Ok(self |
| 620 | .conn |
| 621 | .query_row( |
| 622 | "SELECT id, at, kind, data FROM ops WHERE workspace = ?1 AND undone = 0 ORDER BY id DESC LIMIT 1", |
| 623 | [workspace], |
| 624 | Self::op_row, |
| 625 | ) |
| 626 | .optional()?) |
| 627 | } |
| 628 |
| 629 | pub fn ops(&self, workspace: &str, limit: i64) -> Result<Vec<(Op, bool)>> { |
| 630 | let mut stmt = |
| 631 | self.conn.prepare("SELECT id, at, kind, data, undone FROM ops WHERE workspace = ?1 ORDER BY id DESC LIMIT ?2")?; |
| 632 | let rows = stmt.query_map(params![workspace, limit], |row| Ok((Self::op_row(row)?, row.get::<_, i64>(4)? != 0)))?; |
| 633 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 634 | } |
| 635 |
| 636 | pub fn mark_undone(&self, id: i64) -> Result<()> { |
| 637 | self.conn.execute("UPDATE ops SET undone = 1 WHERE id = ?1", [id])?; |
| 638 | Ok(()) |
| 639 | } |
| 640 |
| 641 | // Mine files: what the user's own files looked like when last saved. |
| 642 |
| 643 | pub fn put_mine(&self, project: &str, path: &str, file: &Id, exec: bool) -> Result<()> { |
| 644 | self.conn.execute( |
| 645 | "INSERT OR REPLACE INTO mine (project, path, file, exec, at) VALUES (?1, ?2, ?3, ?4, ?5)", |
| 646 | params![project, path, file.hex(), exec as i64, ids::now()], |
| 647 | )?; |
| 648 | Ok(()) |
| 649 | } |
| 650 |
| 651 | pub fn mine(&self, project: &str) -> Result<Vec<(String, Id, bool)>> { |
| 652 | let mut stmt = self.conn.prepare("SELECT path, file, exec FROM mine WHERE project = ?1 ORDER BY path")?; |
| 653 | let rows = stmt.query_map([project], |r| Ok((r.get::<_, String>(0)?, id_col(r, 1)?, r.get::<_, i64>(2)? != 0)))?; |
| 654 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 655 | } |
| 656 |
| 657 | /// The newest version this machine has every version up to. A landing |
| 658 | /// stores its own version before the ones others landed just ahead of |
| 659 | /// it, so the newest version alone can leave a gap. |
| 660 | pub fn versions_complete_to(&self, project: &str) -> Result<u64> { |
| 661 | let first: Option<i64> = self.conn.query_row("SELECT 1 FROM versions WHERE project = ?1 AND n = 1", [project], |r| r.get(0)).optional()?; |
| 662 | if first.is_none() { |
| 663 | return Ok(0); |
| 664 | } |
| 665 | let n: i64 = self.conn.query_row( |
| 666 | "SELECT MIN(n) FROM versions v WHERE project = ?1 AND NOT EXISTS (SELECT 1 FROM versions w WHERE w.project = v.project AND w.n = v.n + 1)", |
| 667 | [project], |
| 668 | |r| r.get(0), |
| 669 | )?; |
| 670 | Ok(n as u64) |
| 671 | } |
| 672 |
| 673 | /// Whether some version of main has this tree. |
| 674 | pub fn versions_with_tree(&self, project: &str, tree: &Id) -> Result<bool> { |
| 675 | Ok(self.conn.query_row("SELECT 1 FROM versions WHERE project = ?1 AND tree = ?2 LIMIT 1", params![project, tree.hex()], |_| Ok(())).optional()?.is_some()) |
| 676 | } |
| 677 |
| 678 | /// A tree whose objects all reached the project's host. |
| 679 | pub fn mark_uploaded_tree(&self, project: &str, tree: &Id) -> Result<()> { |
| 680 | self.conn.execute("INSERT OR IGNORE INTO uploaded (project, tree) VALUES (?1, ?2)", params![project, tree.hex()])?; |
| 681 | Ok(()) |
| 682 | } |
| 683 |
| 684 | pub fn uploaded_tree(&self, project: &str, tree: &Id) -> Result<bool> { |
| 685 | Ok(self.conn.query_row("SELECT 1 FROM uploaded WHERE project = ?1 AND tree = ?2", params![project, tree.hex()], |_| Ok(())).optional()?.is_some()) |
| 686 | } |
| 687 |
| 688 | /// Where an imported project's git history came from. |
| 689 | pub fn set_import(&self, project: &str, source: &str, branch: &str) -> Result<()> { |
| 690 | self.conn.execute("INSERT OR REPLACE INTO imports (project, source, branch) VALUES (?1, ?2, ?3)", params![project, source, branch])?; |
| 691 | Ok(()) |
| 692 | } |
| 693 |
| 694 | pub fn import_source(&self, project: &str) -> Result<Option<(String, String)>> { |
| 695 | Ok(self |
| 696 | .conn |
| 697 | .query_row("SELECT source, branch FROM imports WHERE project = ?1", [project], |r| Ok((r.get(0)?, r.get(1)?))) |
| 698 | .optional()?) |
| 699 | } |
| 700 |
| 701 | /// Native object → git object, for objects an import read from git. |
| 702 | pub fn put_git_ids(&self, project: &str, ids: &[(Id, String)]) -> Result<()> { |
| 703 | let tx = self.conn.unchecked_transaction()?; |
| 704 | { |
| 705 | let mut stmt = tx.prepare("INSERT OR REPLACE INTO git_ids (project, native, git) VALUES (?1, ?2, ?3)")?; |
| 706 | for (native, git) in ids { |
| 707 | stmt.execute(params![project, native.hex(), git])?; |
| 708 | } |
| 709 | } |
| 710 | tx.commit()?; |
| 711 | Ok(()) |
| 712 | } |
| 713 |
| 714 | pub fn git_ids(&self, project: &str) -> Result<Vec<(String, String)>> { |
| 715 | let mut stmt = self.conn.prepare("SELECT native, git FROM git_ids WHERE project = ?1")?; |
| 716 | let rows = stmt.query_map([project], |r| Ok((r.get(0)?, r.get(1)?)))?; |
| 717 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 718 | } |
| 719 |
| 720 | pub fn version_by_git(&self, project: &str, git: &str) -> Result<Option<Version>> { |
| 721 | let sql = format!("SELECT {} FROM versions WHERE project = ?1 AND git = ?2 ORDER BY n DESC LIMIT 1", Self::VERSION_COLUMNS); |
| 722 | Ok(self.conn.query_row(&sql, params![project, git], Self::version_row).optional()?) |
| 723 | } |
| 724 | } |
| 725 |