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