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 | -- Names for versions of main (vcs tag), for local projects and vcs-server. |
| 131 | CREATE TABLE IF NOT EXISTS tags ( |
| 132 | project TEXT NOT NULL, |
| 133 | name TEXT NOT NULL, |
| 134 | n INTEGER NOT NULL, |
| 135 | by TEXT NOT NULL, |
| 136 | time INTEGER NOT NULL, |
| 137 | PRIMARY KEY (project, name) |
| 138 | ); |
| 139 | -- Release lines: named lines of versions next to main, each from a version |
| 140 | -- of main, with their own numbered versions (line_versions). |
| 141 | CREATE TABLE IF NOT EXISTS lines ( |
| 142 | project TEXT NOT NULL, |
| 143 | name TEXT NOT NULL, |
| 144 | from_n INTEGER NOT NULL, |
| 145 | created INTEGER NOT NULL, |
| 146 | PRIMARY KEY (project, name) |
| 147 | ); |
| 148 | CREATE TABLE IF NOT EXISTS line_versions ( |
| 149 | project TEXT NOT NULL, |
| 150 | line TEXT NOT NULL, |
| 151 | n INTEGER NOT NULL, |
| 152 | tree TEXT NOT NULL, |
| 153 | change TEXT NOT NULL, |
| 154 | author TEXT NOT NULL, |
| 155 | time INTEGER NOT NULL, |
| 156 | title TEXT NOT NULL, |
| 157 | body TEXT NOT NULL, |
| 158 | PRIMARY KEY (project, line, n) |
| 159 | ); |
| 160 | -- Changes the host sent through review: their change request (number and link). |
| 161 | CREATE TABLE IF NOT EXISTS reviews ( |
| 162 | change TEXT PRIMARY KEY, |
| 163 | link TEXT NOT NULL |
| 164 | ); |
| 165 | -- vcs purge on a host: how many purges the host has done, and how many this |
| 166 | -- machine has taken in (taking out the paths here too). |
| 167 | CREATE TABLE IF NOT EXISTS purges ( |
| 168 | project TEXT PRIMARY KEY, |
| 169 | seen INTEGER NOT NULL DEFAULT 0, |
| 170 | host INTEGER NOT NULL DEFAULT 0 |
| 171 | ); |
| 172 | "#; |
| 173 |
| 174 | pub struct Db { |
| 175 | pub conn: Connection, |
| 176 | } |
| 177 |
| 178 | #[derive(Debug, Clone)] |
| 179 | pub struct Project { |
| 180 | pub id: String, |
| 181 | /// `host/owner/name` for hosted projects, the folder for local ones. |
| 182 | pub address: String, |
| 183 | /// "local" or "hosted". |
| 184 | pub kind: String, |
| 185 | pub api: Option<String>, |
| 186 | /// When main was last checked with the host (seconds). |
| 187 | pub checked: i64, |
| 188 | } |
| 189 |
| 190 | impl Project { |
| 191 | pub fn hosted(&self) -> bool { |
| 192 | self.kind == "hosted" |
| 193 | } |
| 194 | } |
| 195 |
| 196 | /// A release line: from version `from` of main, with versions 1 to `head` of its own. |
| 197 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] |
| 198 | pub struct Line { |
| 199 | pub name: String, |
| 200 | pub from: u64, |
| 201 | pub head: u64, |
| 202 | } |
| 203 |
| 204 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] |
| 205 | pub struct LineVersion { |
| 206 | pub line: String, |
| 207 | pub n: u64, |
| 208 | pub tree: Id, |
| 209 | pub change: String, |
| 210 | pub author: String, |
| 211 | pub time: i64, |
| 212 | pub title: String, |
| 213 | pub body: String, |
| 214 | } |
| 215 |
| 216 | #[derive(Debug, Clone)] |
| 217 | pub struct Workspace { |
| 218 | pub id: String, |
| 219 | pub project: String, |
| 220 | pub path: PathBuf, |
| 221 | pub change: String, |
| 222 | pub only: Vec<String>, |
| 223 | } |
| 224 |
| 225 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] |
| 226 | pub struct Conflict { |
| 227 | pub path: String, |
| 228 | #[serde(default)] |
| 229 | pub version: Option<u64>, |
| 230 | } |
| 231 |
| 232 | #[derive(Debug, Clone)] |
| 233 | pub struct Change { |
| 234 | pub id: String, |
| 235 | pub project: String, |
| 236 | pub title: String, |
| 237 | pub body: String, |
| 238 | /// The tree the change starts from. |
| 239 | pub base_tree: Id, |
| 240 | /// Set when the base is a version of main. |
| 241 | pub base_version: Option<u64>, |
| 242 | /// Set when stacked on an unlanded change. |
| 243 | pub on_change: Option<String>, |
| 244 | /// Set when the change continues after one that landed from the same workspace. |
| 245 | pub after_change: Option<String>, |
| 246 | /// The latest save (None: nothing saved, same as the base). |
| 247 | pub head_tree: Option<Id>, |
| 248 | pub saves: i64, |
| 249 | /// open, waiting, landed, dropped. |
| 250 | pub state: String, |
| 251 | pub version: Option<u64>, |
| 252 | pub author: String, |
| 253 | pub conflicts: Vec<Conflict>, |
| 254 | pub workspace: Option<String>, |
| 255 | pub shared: Vec<String>, |
| 256 | pub remote_rev: i64, |
| 257 | pub created: i64, |
| 258 | pub updated: i64, |
| 259 | /// The release line it lands on (None: main). |
| 260 | pub line: Option<String>, |
| 261 | } |
| 262 |
| 263 | impl Change { |
| 264 | pub fn new(id: String, project: &str, base_tree: Id, base_version: Option<u64>, author: &str) -> Change { |
| 265 | let now = ids::now(); |
| 266 | Change { |
| 267 | id, |
| 268 | project: project.to_string(), |
| 269 | title: String::new(), |
| 270 | body: String::new(), |
| 271 | base_tree, |
| 272 | base_version, |
| 273 | on_change: None, |
| 274 | after_change: None, |
| 275 | head_tree: None, |
| 276 | saves: 0, |
| 277 | state: "open".into(), |
| 278 | version: None, |
| 279 | author: author.to_string(), |
| 280 | conflicts: Vec::new(), |
| 281 | workspace: None, |
| 282 | shared: Vec::new(), |
| 283 | remote_rev: 0, |
| 284 | created: now, |
| 285 | updated: now, |
| 286 | line: None, |
| 287 | } |
| 288 | } |
| 289 |
| 290 | /// The change's content: its latest save, or its base. |
| 291 | pub fn tree(&self) -> Id { |
| 292 | self.head_tree.unwrap_or(self.base_tree) |
| 293 | } |
| 294 |
| 295 | pub fn is_empty(&self) -> bool { |
| 296 | self.tree() == self.base_tree |
| 297 | } |
| 298 |
| 299 | pub fn message(&self) -> String { |
| 300 | if self.body.is_empty() { self.title.clone() } else { format!("{}\n\n{}", self.title, self.body) } |
| 301 | } |
| 302 | } |
| 303 |
| 304 | #[derive(Debug, Clone)] |
| 305 | pub struct Save { |
| 306 | pub change: String, |
| 307 | pub n: i64, |
| 308 | pub tree: Id, |
| 309 | pub base_tree: Id, |
| 310 | pub at: i64, |
| 311 | pub uploaded: bool, |
| 312 | } |
| 313 |
| 314 | #[derive(Debug, Clone)] |
| 315 | pub struct Op { |
| 316 | pub id: i64, |
| 317 | pub at: i64, |
| 318 | pub kind: String, |
| 319 | pub data: serde_json::Value, |
| 320 | } |
| 321 |
| 322 | fn id_col(row: &rusqlite::Row, i: usize) -> rusqlite::Result<Id> { |
| 323 | let text: String = row.get(i)?; |
| 324 | Id::parse(&text).ok_or_else(|| rusqlite::Error::InvalidColumnType(i, "id".into(), rusqlite::types::Type::Text)) |
| 325 | } |
| 326 |
| 327 | fn opt_id_col(row: &rusqlite::Row, i: usize) -> rusqlite::Result<Option<Id>> { |
| 328 | let text: Option<String> = row.get(i)?; |
| 329 | Ok(text.and_then(|t| Id::parse(&t))) |
| 330 | } |
| 331 |
| 332 | impl Db { |
| 333 | pub fn open(home: &Path) -> Result<Db> { |
| 334 | std::fs::create_dir_all(home).with_context(|| format!("creating {}", home.display()))?; |
| 335 | let conn = Connection::open(home.join("vcs.db")).context("opening the vcs database")?; |
| 336 | Self::setup(conn) |
| 337 | } |
| 338 |
| 339 | pub fn setup(conn: Connection) -> Result<Db> { |
| 340 | // Many agents on one machine share this database. SQLite's own |
| 341 | // busy wait sleeps up to 100 ms between tries; this one tries again |
| 342 | // within a millisecond, for up to a minute. |
| 343 | conn.busy_handler(Some(|tries: i32| { |
| 344 | std::thread::sleep(std::time::Duration::from_micros(300 + (tries as u64 % 5) * 150)); |
| 345 | tries < 120_000 |
| 346 | }))?; |
| 347 | conn.pragma_update(None, "journal_mode", "WAL")?; |
| 348 | conn.pragma_update(None, "synchronous", "NORMAL")?; |
| 349 | conn.execute_batch(SCHEMA)?; |
| 350 | // The paths each version changed (see history::fill_touched), for |
| 351 | // databases made before it. Another process may add it first. |
| 352 | let has: bool = conn.query_row("SELECT count(*) > 0 FROM pragma_table_info('versions') WHERE name = 'touched'", [], |r| r.get(0))?; |
| 353 | if !has { |
| 354 | if let Err(e) = conn.execute("ALTER TABLE versions ADD COLUMN touched TEXT", []) |
| 355 | && !e.to_string().contains("duplicate column") |
| 356 | { |
| 357 | return Err(e.into()); |
| 358 | } |
| 359 | conn.execute("CREATE INDEX IF NOT EXISTS versions_untouched ON versions(project, n) WHERE touched IS NULL", [])?; |
| 360 | } |
| 361 | // The release line a change lands on, for databases made before lines. |
| 362 | let has: bool = conn.query_row("SELECT count(*) > 0 FROM pragma_table_info('changes') WHERE name = 'line'", [], |r| r.get(0))?; |
| 363 | if !has |
| 364 | && let Err(e) = conn.execute("ALTER TABLE changes ADD COLUMN line TEXT", []) |
| 365 | && !e.to_string().contains("duplicate column") |
| 366 | { |
| 367 | return Err(e.into()); |
| 368 | } |
| 369 | Ok(Db { conn }) |
| 370 | } |
| 371 |
| 372 | // Projects. |
| 373 |
| 374 | pub fn put_project(&self, p: &Project) -> Result<()> { |
| 375 | self.conn.execute( |
| 376 | "INSERT INTO projects (id, address, kind, api, checked, created) VALUES (?1, ?2, ?3, ?4, ?5, ?6) |
| 377 | ON CONFLICT(id) DO UPDATE SET address=excluded.address, kind=excluded.kind, api=excluded.api, checked=excluded.checked", |
| 378 | params![p.id, p.address, p.kind, p.api, p.checked, ids::now()], |
| 379 | )?; |
| 380 | Ok(()) |
| 381 | } |
| 382 |
| 383 | fn project_row(row: &rusqlite::Row) -> rusqlite::Result<Project> { |
| 384 | Ok(Project { id: row.get(0)?, address: row.get(1)?, kind: row.get(2)?, api: row.get(3)?, checked: row.get(4)? }) |
| 385 | } |
| 386 |
| 387 | pub fn project(&self, id: &str) -> Result<Option<Project>> { |
| 388 | Ok(self |
| 389 | .conn |
| 390 | .query_row("SELECT id, address, kind, api, checked FROM projects WHERE id = ?1", [id], Self::project_row) |
| 391 | .optional()?) |
| 392 | } |
| 393 |
| 394 | pub fn project_by_address(&self, address: &str) -> Result<Option<Project>> { |
| 395 | Ok(self |
| 396 | .conn |
| 397 | .query_row("SELECT id, address, kind, api, checked FROM projects WHERE address = ?1", [address], Self::project_row) |
| 398 | .optional()?) |
| 399 | } |
| 400 |
| 401 | pub fn set_checked(&self, project: &str, at: i64) -> Result<()> { |
| 402 | self.conn.execute("UPDATE projects SET checked = ?2 WHERE id = ?1", params![project, at])?; |
| 403 | Ok(()) |
| 404 | } |
| 405 |
| 406 | // Purges (vcs purge): (taken in here, done on the host). |
| 407 |
| 408 | pub fn purges(&self, project: &str) -> Result<(u64, u64)> { |
| 409 | let row: Option<(i64, i64)> = self.conn.query_row("SELECT seen, host FROM purges WHERE project = ?1", [project], |r| Ok((r.get(0)?, r.get(1)?))).optional()?; |
| 410 | Ok(row.map_or((0, 0), |(s, h)| (s as u64, h as u64))) |
| 411 | } |
| 412 |
| 413 | pub fn set_purges(&self, project: &str, seen: Option<u64>, host: Option<u64>) -> Result<()> { |
| 414 | let (s, h) = self.purges(project)?; |
| 415 | self.conn.execute( |
| 416 | "INSERT OR REPLACE INTO purges (project, seen, host) VALUES (?1, ?2, ?3)", |
| 417 | params![project, seen.unwrap_or(s) as i64, host.unwrap_or(h).max(seen.unwrap_or(s)) as i64], |
| 418 | )?; |
| 419 | Ok(()) |
| 420 | } |
| 421 |
| 422 | // Versions. |
| 423 |
| 424 | /// Forgets versions after `n` (the host's project was rolled back). |
| 425 | pub fn drop_versions_after(&self, project: &str, n: u64) -> Result<usize> { |
| 426 | Ok(self.conn.execute("DELETE FROM versions WHERE project = ?1 AND n > ?2", params![project, n as i64])?) |
| 427 | } |
| 428 |
| 429 | pub fn put_version(&self, project: &str, v: &Version) -> Result<()> { |
| 430 | self.conn.execute( |
| 431 | "INSERT OR REPLACE INTO versions (project, n, id, tree, prev, change, author, time, title, body, git) |
| 432 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)", |
| 433 | params![ |
| 434 | project, |
| 435 | v.n as i64, |
| 436 | v.id(project).hex(), |
| 437 | v.tree.hex(), |
| 438 | v.prev.map(|p| p.hex()), |
| 439 | v.change, |
| 440 | v.author, |
| 441 | v.time, |
| 442 | v.title, |
| 443 | v.body, |
| 444 | v.git |
| 445 | ], |
| 446 | )?; |
| 447 | Ok(()) |
| 448 | } |
| 449 |
| 450 | fn version_row(row: &rusqlite::Row) -> rusqlite::Result<Version> { |
| 451 | Ok(Version { |
| 452 | n: row.get::<_, i64>(0)? as u64, |
| 453 | tree: id_col(row, 1)?, |
| 454 | prev: opt_id_col(row, 2)?, |
| 455 | change: row.get(3)?, |
| 456 | author: row.get(4)?, |
| 457 | time: row.get(5)?, |
| 458 | title: row.get(6)?, |
| 459 | body: row.get(7)?, |
| 460 | git: row.get(8)?, |
| 461 | }) |
| 462 | } |
| 463 |
| 464 | const VERSION_COLUMNS: &'static str = "n, tree, prev, change, author, time, title, body, git"; |
| 465 |
| 466 | pub fn version(&self, project: &str, n: u64) -> Result<Option<Version>> { |
| 467 | let sql = format!("SELECT {} FROM versions WHERE project = ?1 AND n = ?2", Self::VERSION_COLUMNS); |
| 468 | Ok(self.conn.query_row(&sql, params![project, n as i64], Self::version_row).optional()?) |
| 469 | } |
| 470 |
| 471 | pub fn latest_version(&self, project: &str) -> Result<Option<Version>> { |
| 472 | let sql = format!("SELECT {} FROM versions WHERE project = ?1 ORDER BY n DESC LIMIT 1", Self::VERSION_COLUMNS); |
| 473 | Ok(self.conn.query_row(&sql, [project], Self::version_row).optional()?) |
| 474 | } |
| 475 |
| 476 | // Tags. |
| 477 |
| 478 | pub fn tags(&self, project: &str) -> Result<Vec<crate::tags::Tag>> { |
| 479 | let mut stmt = self.conn.prepare("SELECT name, n, by, time FROM tags WHERE project = ?1 ORDER BY n DESC, name")?; |
| 480 | let rows = stmt.query_map([project], |r| Ok(crate::tags::Tag { name: r.get(0)?, n: r.get::<_, i64>(1)? as u64, by: r.get(2)?, time: r.get(3)? }))?; |
| 481 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 482 | } |
| 483 |
| 484 | pub fn tag(&self, project: &str, name: &str) -> Result<Option<crate::tags::Tag>> { |
| 485 | Ok(self |
| 486 | .conn |
| 487 | .query_row("SELECT name, n, by, time FROM tags WHERE project = ?1 AND name = ?2", params![project, name], |r| { |
| 488 | Ok(crate::tags::Tag { name: r.get(0)?, n: r.get::<_, i64>(1)? as u64, by: r.get(2)?, time: r.get(3)? }) |
| 489 | }) |
| 490 | .optional()?) |
| 491 | } |
| 492 |
| 493 | pub fn put_tag(&self, project: &str, t: &crate::tags::Tag) -> Result<()> { |
| 494 | self.conn.execute("INSERT INTO tags (project, name, n, by, time) VALUES (?1, ?2, ?3, ?4, ?5)", params![project, t.name, t.n as i64, t.by, t.time])?; |
| 495 | Ok(()) |
| 496 | } |
| 497 |
| 498 | pub fn drop_tag(&self, project: &str, name: &str) -> Result<bool> { |
| 499 | Ok(self.conn.execute("DELETE FROM tags WHERE project = ?1 AND name = ?2", params![project, name])? > 0) |
| 500 | } |
| 501 |
| 502 | // Release lines. |
| 503 |
| 504 | pub fn lines(&self, project: &str) -> Result<Vec<Line>> { |
| 505 | let mut stmt = self.conn.prepare( |
| 506 | "SELECT l.name, l.from_n, (SELECT max(n) FROM line_versions v WHERE v.project = l.project AND v.line = l.name) FROM lines l WHERE l.project = ?1 ORDER BY l.created", |
| 507 | )?; |
| 508 | let rows = stmt.query_map([project], |r| Ok(Line { name: r.get(0)?, from: r.get::<_, i64>(1)? as u64, head: r.get::<_, Option<i64>>(2)?.unwrap_or(0) as u64 }))?; |
| 509 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 510 | } |
| 511 |
| 512 | pub fn line(&self, project: &str, name: &str) -> Result<Option<Line>> { |
| 513 | Ok(self.lines(project)?.into_iter().find(|l| l.name == name)) |
| 514 | } |
| 515 |
| 516 | pub fn put_line(&self, project: &str, name: &str, from: u64) -> Result<()> { |
| 517 | self.conn.execute("INSERT OR IGNORE INTO lines (project, name, from_n, created) VALUES (?1, ?2, ?3, ?4)", params![project, name, from as i64, ids::now()])?; |
| 518 | Ok(()) |
| 519 | } |
| 520 |
| 521 | /// The tree at a line's version `n` (0: the version of main it started from). |
| 522 | pub fn line_tree(&self, project: &str, line: &Line, n: u64) -> Result<Option<Id>> { |
| 523 | if n == 0 { |
| 524 | return self.version_tree(project, line.from); |
| 525 | } |
| 526 | Ok(self.conn.query_row("SELECT tree FROM line_versions WHERE project = ?1 AND line = ?2 AND n = ?3", params![project, line.name, n as i64], |r| id_col(r, 0)).optional()?) |
| 527 | } |
| 528 |
| 529 | pub fn put_line_version(&self, project: &str, v: &LineVersion) -> Result<()> { |
| 530 | self.conn.execute( |
| 531 | "INSERT OR REPLACE INTO line_versions (project, line, n, tree, change, author, time, title, body) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", |
| 532 | params![project, v.line, v.n as i64, v.tree.hex(), v.change, v.author, v.time, v.title, v.body], |
| 533 | )?; |
| 534 | Ok(()) |
| 535 | } |
| 536 |
| 537 | /// A line's versions, newest first. |
| 538 | pub fn line_versions(&self, project: &str, line: &str, limit: i64) -> Result<Vec<LineVersion>> { |
| 539 | let mut stmt = self.conn.prepare("SELECT line, n, tree, change, author, time, title, body FROM line_versions WHERE project = ?1 AND line = ?2 ORDER BY n DESC LIMIT ?3")?; |
| 540 | let rows = stmt.query_map(params![project, line, limit], |r| { |
| 541 | Ok(LineVersion { line: r.get(0)?, n: r.get::<_, i64>(1)? as u64, tree: id_col(r, 2)?, change: r.get(3)?, author: r.get(4)?, time: r.get(5)?, title: r.get(6)?, body: r.get(7)? }) |
| 542 | })?; |
| 543 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 544 | } |
| 545 |
| 546 | /// Forgets a hosted project this machine only just looked up (it has no |
| 547 | /// workspaces here yet), so an import can take its address. |
| 548 | pub fn forget_project(&self, id: &str) -> Result<()> { |
| 549 | self.conn.execute("DELETE FROM versions WHERE project = ?1", [id])?; |
| 550 | self.conn.execute("DELETE FROM projects WHERE id = ?1", [id])?; |
| 551 | Ok(()) |
| 552 | } |
| 553 |
| 554 | /// The change request a change is in review as (None: it isn't). |
| 555 | pub fn review(&self, change: &str) -> Result<Option<String>> { |
| 556 | Ok(self.conn.query_row("SELECT link FROM reviews WHERE change = ?1", [change], |r| r.get(0)).optional()?) |
| 557 | } |
| 558 |
| 559 | pub fn set_review(&self, change: &str, link: Option<&str>) -> Result<()> { |
| 560 | match link { |
| 561 | Some(l) => self.conn.execute("INSERT OR REPLACE INTO reviews (change, link) VALUES (?1, ?2)", params![change, l])?, |
| 562 | None => self.conn.execute("DELETE FROM reviews WHERE change = ?1", [change])?, |
| 563 | }; |
| 564 | Ok(()) |
| 565 | } |
| 566 |
| 567 | pub fn version_tree(&self, project: &str, n: u64) -> Result<Option<Id>> { |
| 568 | 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()?) |
| 569 | } |
| 570 |
| 571 | /// Versions whose changed paths aren't worked out yet, newest first: |
| 572 | /// (n, tree, the tree of the version before it, when this machine has it). |
| 573 | pub fn untouched(&self, project: &str, limit: i64) -> Result<Vec<(u64, Id, Option<Id>)>> { |
| 574 | let mut stmt = self.conn.prepare( |
| 575 | "SELECT v.n, v.tree, (SELECT p.tree FROM versions p WHERE p.project = v.project AND p.n = v.n - 1) |
| 576 | FROM versions v WHERE v.project = ?1 AND v.touched IS NULL ORDER BY v.n DESC LIMIT ?2", |
| 577 | )?; |
| 578 | 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)?)))?; |
| 579 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 580 | } |
| 581 |
| 582 | pub fn set_touched(&self, project: &str, rows: &[(u64, String)]) -> Result<()> { |
| 583 | let tx = self.conn.unchecked_transaction()?; |
| 584 | { |
| 585 | let mut stmt = tx.prepare("UPDATE versions SET touched = ?3 WHERE project = ?1 AND n = ?2")?; |
| 586 | for (n, touched) in rows { |
| 587 | stmt.execute(params![project, *n as i64, touched])?; |
| 588 | } |
| 589 | } |
| 590 | tx.commit()?; |
| 591 | Ok(()) |
| 592 | } |
| 593 |
| 594 | /// Versions before `before` that may have changed `path`, newest first, |
| 595 | /// as (n, tree): their changed paths include it, something under it, or |
| 596 | /// a folder holding it, or weren't listed (too many, or not worked out). |
| 597 | pub fn may_touch(&self, project: &str, path: &str, before: u64, limit: i64) -> Result<Vec<(u64, Id)>> { |
| 598 | use rusqlite::types::Value; |
| 599 | let parts: Vec<&str> = path.split('/').filter(|p| !p.is_empty()).collect(); |
| 600 | let mut args: Vec<Value> = vec![project.to_string().into(), (before.min(i64::MAX as u64) as i64).into(), limit.into()]; |
| 601 | let filter = if parts.is_empty() { |
| 602 | "1".to_string() |
| 603 | } else { |
| 604 | let line = |i: usize| format!("instr(char(10) || touched || char(10), char(10) || ?{i} || char(10)) > 0"); |
| 605 | args.push(path.to_string().into()); |
| 606 | let mut any = vec!["touched IS NULL".to_string(), "touched = '*'".to_string(), line(4), "instr(char(10) || touched, char(10) || ?4 || '/') > 0".to_string()]; |
| 607 | for i in 1..parts.len() { |
| 608 | args.push(parts[..i].join("/").into()); |
| 609 | any.push(line(args.len())); |
| 610 | } |
| 611 | any.join(" OR ") |
| 612 | }; |
| 613 | let sql = format!("SELECT n, tree FROM versions WHERE project = ?1 AND n < ?2 AND ({filter}) ORDER BY n DESC LIMIT ?3"); |
| 614 | let mut stmt = self.conn.prepare(&sql)?; |
| 615 | let rows = stmt.query_map(rusqlite::params_from_iter(args), |r| Ok((r.get::<_, i64>(0)? as u64, id_col(r, 1)?)))?; |
| 616 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 617 | } |
| 618 |
| 619 | pub fn versions(&self, project: &str, limit: i64) -> Result<Vec<Version>> { |
| 620 | let sql = format!("SELECT {} FROM versions WHERE project = ?1 ORDER BY n DESC LIMIT ?2", Self::VERSION_COLUMNS); |
| 621 | let mut stmt = self.conn.prepare(&sql)?; |
| 622 | let rows = stmt.query_map(params![project, limit], Self::version_row)?; |
| 623 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 624 | } |
| 625 |
| 626 | pub fn version_of_change(&self, project: &str, change: &str) -> Result<Option<Version>> { |
| 627 | let sql = format!("SELECT {} FROM versions WHERE project = ?1 AND change = ?2 ORDER BY n DESC LIMIT 1", Self::VERSION_COLUMNS); |
| 628 | Ok(self.conn.query_row(&sql, params![project, change], Self::version_row).optional()?) |
| 629 | } |
| 630 |
| 631 | // Workspaces. |
| 632 |
| 633 | pub fn put_workspace(&self, w: &Workspace) -> Result<()> { |
| 634 | let now = ids::now(); |
| 635 | // A folder holds one workspace: any other one recorded at this path |
| 636 | // was deleted with its folder. Its change stays. |
| 637 | self.conn.execute("DELETE FROM workspaces WHERE path = ?1 AND id != ?2", params![w.path.to_string_lossy(), w.id])?; |
| 638 | self.conn.execute( |
| 639 | "INSERT INTO workspaces (id, project, path, change, only, created, used) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?6) |
| 640 | ON CONFLICT(id) DO UPDATE SET project=excluded.project, path=excluded.path, change=excluded.change, |
| 641 | only=excluded.only, used=excluded.used", |
| 642 | params![w.id, w.project, w.path.to_string_lossy(), w.change, serde_json::to_string(&w.only)?, now], |
| 643 | )?; |
| 644 | Ok(()) |
| 645 | } |
| 646 |
| 647 | fn workspace_row(row: &rusqlite::Row) -> rusqlite::Result<Workspace> { |
| 648 | let only: String = row.get(4)?; |
| 649 | Ok(Workspace { |
| 650 | id: row.get(0)?, |
| 651 | project: row.get(1)?, |
| 652 | path: PathBuf::from(row.get::<_, String>(2)?), |
| 653 | change: row.get(3)?, |
| 654 | only: serde_json::from_str(&only).unwrap_or_default(), |
| 655 | }) |
| 656 | } |
| 657 |
| 658 | pub fn workspace(&self, id: &str) -> Result<Option<Workspace>> { |
| 659 | Ok(self |
| 660 | .conn |
| 661 | .query_row("SELECT id, project, path, change, only FROM workspaces WHERE id = ?1", [id], Self::workspace_row) |
| 662 | .optional()?) |
| 663 | } |
| 664 |
| 665 | pub fn project_workspaces(&self, project: &str) -> Result<Vec<Workspace>> { |
| 666 | let mut stmt = |
| 667 | self.conn.prepare("SELECT id, project, path, change, only FROM workspaces WHERE project = ?1 ORDER BY used DESC")?; |
| 668 | let rows = stmt.query_map([project], Self::workspace_row)?; |
| 669 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 670 | } |
| 671 |
| 672 | pub fn all_workspaces(&self) -> Result<Vec<Workspace>> { |
| 673 | let mut stmt = self.conn.prepare("SELECT id, project, path, change, only FROM workspaces ORDER BY used DESC")?; |
| 674 | let rows = stmt.query_map([], Self::workspace_row)?; |
| 675 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 676 | } |
| 677 |
| 678 | pub fn workspace_holding(&self, change: &str) -> Result<Option<Workspace>> { |
| 679 | Ok(self |
| 680 | .conn |
| 681 | .query_row( |
| 682 | "SELECT id, project, path, change, only FROM workspaces WHERE change = ?1 ORDER BY used DESC LIMIT 1", |
| 683 | [change], |
| 684 | Self::workspace_row, |
| 685 | ) |
| 686 | .optional()?) |
| 687 | } |
| 688 |
| 689 | pub fn delete_workspace(&self, id: &str) -> Result<()> { |
| 690 | self.conn.execute("DELETE FROM workspaces WHERE id = ?1", [id])?; |
| 691 | Ok(()) |
| 692 | } |
| 693 |
| 694 | // Changes. |
| 695 |
| 696 | pub fn put_change(&self, c: &Change) -> Result<()> { |
| 697 | self.conn.execute( |
| 698 | "INSERT INTO changes (id, project, title, body, base_tree, base_version, on_change, after_change, head_tree, |
| 699 | saves, state, version, author, conflicts, workspace, shared, remote_rev, created, updated, line) |
| 700 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20) |
| 701 | ON CONFLICT(id) DO UPDATE SET title=excluded.title, body=excluded.body, base_tree=excluded.base_tree, |
| 702 | base_version=excluded.base_version, on_change=excluded.on_change, after_change=excluded.after_change, |
| 703 | head_tree=excluded.head_tree, saves=excluded.saves, state=excluded.state, version=excluded.version, |
| 704 | author=excluded.author, conflicts=excluded.conflicts, workspace=excluded.workspace, |
| 705 | shared=excluded.shared, remote_rev=excluded.remote_rev, updated=excluded.updated, line=excluded.line", |
| 706 | params![ |
| 707 | c.id, |
| 708 | c.project, |
| 709 | c.title, |
| 710 | c.body, |
| 711 | c.base_tree.hex(), |
| 712 | c.base_version.map(|v| v as i64), |
| 713 | c.on_change, |
| 714 | c.after_change, |
| 715 | c.head_tree.map(|t| t.hex()), |
| 716 | c.saves, |
| 717 | c.state, |
| 718 | c.version.map(|v| v as i64), |
| 719 | c.author, |
| 720 | serde_json::to_string(&c.conflicts)?, |
| 721 | c.workspace, |
| 722 | serde_json::to_string(&c.shared)?, |
| 723 | c.remote_rev, |
| 724 | c.created, |
| 725 | ids::now(), |
| 726 | c.line |
| 727 | ], |
| 728 | )?; |
| 729 | Ok(()) |
| 730 | } |
| 731 |
| 732 | 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, line"; |
| 733 |
| 734 | fn change_row(row: &rusqlite::Row) -> rusqlite::Result<Change> { |
| 735 | let conflicts: String = row.get(13)?; |
| 736 | let shared: String = row.get(15)?; |
| 737 | Ok(Change { |
| 738 | id: row.get(0)?, |
| 739 | project: row.get(1)?, |
| 740 | title: row.get(2)?, |
| 741 | body: row.get(3)?, |
| 742 | base_tree: id_col(row, 4)?, |
| 743 | base_version: row.get::<_, Option<i64>>(5)?.map(|v| v as u64), |
| 744 | on_change: row.get(6)?, |
| 745 | after_change: row.get(7)?, |
| 746 | head_tree: opt_id_col(row, 8)?, |
| 747 | saves: row.get(9)?, |
| 748 | state: row.get(10)?, |
| 749 | version: row.get::<_, Option<i64>>(11)?.map(|v| v as u64), |
| 750 | author: row.get(12)?, |
| 751 | conflicts: serde_json::from_str(&conflicts).unwrap_or_default(), |
| 752 | workspace: row.get(14)?, |
| 753 | shared: serde_json::from_str(&shared).unwrap_or_default(), |
| 754 | remote_rev: row.get(16)?, |
| 755 | created: row.get(17)?, |
| 756 | updated: row.get(18)?, |
| 757 | line: row.get(19)?, |
| 758 | }) |
| 759 | } |
| 760 |
| 761 | pub fn change(&self, id: &str) -> Result<Option<Change>> { |
| 762 | let sql = format!("SELECT {} FROM changes WHERE id = ?1", Self::CHANGE_COLUMNS); |
| 763 | Ok(self.conn.query_row(&sql, [id], Self::change_row).optional()?) |
| 764 | } |
| 765 |
| 766 | pub fn changes(&self, project: &str) -> Result<Vec<Change>> { |
| 767 | let sql = format!("SELECT {} FROM changes WHERE project = ?1 ORDER BY updated DESC", Self::CHANGE_COLUMNS); |
| 768 | let mut stmt = self.conn.prepare(&sql)?; |
| 769 | let rows = stmt.query_map([project], Self::change_row)?; |
| 770 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 771 | } |
| 772 |
| 773 | pub fn change_ids(&self, project: &str) -> Result<Vec<String>> { |
| 774 | let mut stmt = self.conn.prepare("SELECT id FROM changes WHERE project = ?1")?; |
| 775 | let rows = stmt.query_map([project], |r| r.get::<_, String>(0))?; |
| 776 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 777 | } |
| 778 |
| 779 | pub fn changes_by_prefix(&self, project: &str, prefix: &str) -> Result<Vec<Change>> { |
| 780 | let sql = format!("SELECT {} FROM changes WHERE project = ?1 AND id LIKE ?2 || '%'", Self::CHANGE_COLUMNS); |
| 781 | let mut stmt = self.conn.prepare(&sql)?; |
| 782 | let rows = stmt.query_map(params![project, prefix], Self::change_row)?; |
| 783 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 784 | } |
| 785 |
| 786 | // Saves. |
| 787 |
| 788 | pub fn add_save(&self, s: &Save, workspace: &str) -> Result<()> { |
| 789 | self.conn.execute( |
| 790 | "INSERT OR REPLACE INTO saves (change, n, tree, base_tree, at, workspace, uploaded) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", |
| 791 | params![s.change, s.n, s.tree.hex(), s.base_tree.hex(), s.at, workspace, s.uploaded as i64], |
| 792 | )?; |
| 793 | Ok(()) |
| 794 | } |
| 795 |
| 796 | fn save_row(row: &rusqlite::Row) -> rusqlite::Result<Save> { |
| 797 | Ok(Save { |
| 798 | change: row.get(0)?, |
| 799 | n: row.get(1)?, |
| 800 | tree: id_col(row, 2)?, |
| 801 | base_tree: id_col(row, 3)?, |
| 802 | at: row.get(4)?, |
| 803 | uploaded: row.get::<_, i64>(5)? != 0, |
| 804 | }) |
| 805 | } |
| 806 |
| 807 | pub fn saves(&self, change: &str) -> Result<Vec<Save>> { |
| 808 | let mut stmt = self |
| 809 | .conn |
| 810 | .prepare("SELECT change, n, tree, base_tree, at, uploaded FROM saves WHERE change = ?1 ORDER BY n")?; |
| 811 | let rows = stmt.query_map([change], Self::save_row)?; |
| 812 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 813 | } |
| 814 |
| 815 | pub fn save(&self, change: &str, n: i64) -> Result<Option<Save>> { |
| 816 | Ok(self |
| 817 | .conn |
| 818 | .query_row( |
| 819 | "SELECT change, n, tree, base_tree, at, uploaded FROM saves WHERE change = ?1 AND n = ?2", |
| 820 | params![change, n], |
| 821 | Self::save_row, |
| 822 | ) |
| 823 | .optional()?) |
| 824 | } |
| 825 |
| 826 | /// The latest save made in `workspace` at or before `at`, across changes. |
| 827 | pub fn save_at(&self, workspace: &str, at: i64) -> Result<Option<Save>> { |
| 828 | Ok(self |
| 829 | .conn |
| 830 | .query_row( |
| 831 | "SELECT change, n, tree, base_tree, at, uploaded FROM saves WHERE workspace = ?1 AND at <= ?2 |
| 832 | ORDER BY at DESC, rowid DESC LIMIT 1", |
| 833 | params![workspace, at], |
| 834 | Self::save_row, |
| 835 | ) |
| 836 | .optional()?) |
| 837 | } |
| 838 |
| 839 | pub fn unuploaded_saves(&self, change: &str) -> Result<Vec<Save>> { |
| 840 | let mut stmt = self.conn.prepare( |
| 841 | "SELECT change, n, tree, base_tree, at, uploaded FROM saves WHERE change = ?1 AND uploaded = 0 ORDER BY n", |
| 842 | )?; |
| 843 | let rows = stmt.query_map([change], Self::save_row)?; |
| 844 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 845 | } |
| 846 |
| 847 | pub fn mark_uploaded(&self, change: &str, n: i64) -> Result<()> { |
| 848 | self.conn.execute("UPDATE saves SET uploaded = 1 WHERE change = ?1 AND n = ?2", params![change, n])?; |
| 849 | Ok(()) |
| 850 | } |
| 851 |
| 852 | /// Drops saves (the secret scrub): every save of `change` goes, and the |
| 853 | /// caller records a fresh one. |
| 854 | pub fn delete_saves(&self, change: &str) -> Result<()> { |
| 855 | self.conn.execute("DELETE FROM saves WHERE change = ?1", [change])?; |
| 856 | Ok(()) |
| 857 | } |
| 858 |
| 859 | // Operations. |
| 860 |
| 861 | pub fn add_op(&self, workspace: &str, kind: &str, data: &serde_json::Value) -> Result<i64> { |
| 862 | self.conn.execute( |
| 863 | "INSERT INTO ops (workspace, at, kind, data) VALUES (?1, ?2, ?3, ?4)", |
| 864 | params![workspace, ids::now(), kind, data.to_string()], |
| 865 | )?; |
| 866 | Ok(self.conn.last_insert_rowid()) |
| 867 | } |
| 868 |
| 869 | fn op_row(row: &rusqlite::Row) -> rusqlite::Result<Op> { |
| 870 | let data: String = row.get(3)?; |
| 871 | Ok(Op { id: row.get(0)?, at: row.get(1)?, kind: row.get(2)?, data: serde_json::from_str(&data).unwrap_or_default() }) |
| 872 | } |
| 873 |
| 874 | pub fn last_op(&self, workspace: &str) -> Result<Option<Op>> { |
| 875 | Ok(self |
| 876 | .conn |
| 877 | .query_row( |
| 878 | "SELECT id, at, kind, data FROM ops WHERE workspace = ?1 AND undone = 0 ORDER BY id DESC LIMIT 1", |
| 879 | [workspace], |
| 880 | Self::op_row, |
| 881 | ) |
| 882 | .optional()?) |
| 883 | } |
| 884 |
| 885 | pub fn ops(&self, workspace: &str, limit: i64) -> Result<Vec<(Op, bool)>> { |
| 886 | let mut stmt = |
| 887 | self.conn.prepare("SELECT id, at, kind, data, undone FROM ops WHERE workspace = ?1 ORDER BY id DESC LIMIT ?2")?; |
| 888 | let rows = stmt.query_map(params![workspace, limit], |row| Ok((Self::op_row(row)?, row.get::<_, i64>(4)? != 0)))?; |
| 889 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 890 | } |
| 891 |
| 892 | pub fn mark_undone(&self, id: i64) -> Result<()> { |
| 893 | self.conn.execute("UPDATE ops SET undone = 1 WHERE id = ?1", [id])?; |
| 894 | Ok(()) |
| 895 | } |
| 896 |
| 897 | // Mine files: what the user's own files looked like when last saved. |
| 898 |
| 899 | pub fn put_mine(&self, project: &str, path: &str, file: &Id, exec: bool) -> Result<()> { |
| 900 | self.conn.execute( |
| 901 | "INSERT OR REPLACE INTO mine (project, path, file, exec, at) VALUES (?1, ?2, ?3, ?4, ?5)", |
| 902 | params![project, path, file.hex(), exec as i64, ids::now()], |
| 903 | )?; |
| 904 | Ok(()) |
| 905 | } |
| 906 |
| 907 | pub fn mine(&self, project: &str) -> Result<Vec<(String, Id, bool)>> { |
| 908 | let mut stmt = self.conn.prepare("SELECT path, file, exec FROM mine WHERE project = ?1 ORDER BY path")?; |
| 909 | let rows = stmt.query_map([project], |r| Ok((r.get::<_, String>(0)?, id_col(r, 1)?, r.get::<_, i64>(2)? != 0)))?; |
| 910 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 911 | } |
| 912 |
| 913 | /// The newest version this machine has every version up to. A landing |
| 914 | /// stores its own version before the ones others landed just ahead of |
| 915 | /// it, so the newest version alone can leave a gap. |
| 916 | pub fn versions_complete_to(&self, project: &str) -> Result<u64> { |
| 917 | let start = self.history_from(project)?; |
| 918 | let first: Option<i64> = |
| 919 | self.conn.query_row("SELECT 1 FROM versions WHERE project = ?1 AND n = ?2", params![project, start as i64], |r| r.get(0)).optional()?; |
| 920 | if first.is_none() { |
| 921 | return Ok(start - 1); |
| 922 | } |
| 923 | let n: i64 = self.conn.query_row( |
| 924 | "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)", |
| 925 | params![project, start as i64], |
| 926 | |r| r.get(0), |
| 927 | )?; |
| 928 | Ok(n as u64) |
| 929 | } |
| 930 |
| 931 | /// The first version of main this machine keeps (1 unless it started |
| 932 | /// with recent history only). |
| 933 | pub fn history_from(&self, project: &str) -> Result<u64> { |
| 934 | let start: Option<i64> = self.conn.query_row("SELECT start FROM history WHERE project = ?1", [project], |r| r.get(0)).optional()?; |
| 935 | Ok(start.map_or(1, |n| n.max(1) as u64)) |
| 936 | } |
| 937 |
| 938 | pub fn set_history_from(&self, project: &str, n: u64) -> Result<()> { |
| 939 | if n <= 1 { |
| 940 | self.conn.execute("DELETE FROM history WHERE project = ?1", [project])?; |
| 941 | } else { |
| 942 | self.conn.execute("INSERT OR REPLACE INTO history (project, start) VALUES (?1, ?2)", params![project, n as i64])?; |
| 943 | } |
| 944 | Ok(()) |
| 945 | } |
| 946 |
| 947 | /// Whether some version of main has this tree. |
| 948 | pub fn versions_with_tree(&self, project: &str, tree: &Id) -> Result<bool> { |
| 949 | 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()) |
| 950 | } |
| 951 |
| 952 | /// A tree whose objects all reached the project's host. |
| 953 | pub fn mark_uploaded_tree(&self, project: &str, tree: &Id) -> Result<()> { |
| 954 | self.conn.execute("INSERT OR IGNORE INTO uploaded (project, tree) VALUES (?1, ?2)", params![project, tree.hex()])?; |
| 955 | Ok(()) |
| 956 | } |
| 957 |
| 958 | pub fn uploaded_tree(&self, project: &str, tree: &Id) -> Result<bool> { |
| 959 | Ok(self.conn.query_row("SELECT 1 FROM uploaded WHERE project = ?1 AND tree = ?2", params![project, tree.hex()], |_| Ok(())).optional()?.is_some()) |
| 960 | } |
| 961 |
| 962 | /// Where an imported project's git history came from. |
| 963 | pub fn set_import(&self, project: &str, source: &str, branch: &str) -> Result<()> { |
| 964 | self.conn.execute("INSERT OR REPLACE INTO imports (project, source, branch) VALUES (?1, ?2, ?3)", params![project, source, branch])?; |
| 965 | Ok(()) |
| 966 | } |
| 967 |
| 968 | pub fn import_source(&self, project: &str) -> Result<Option<(String, String)>> { |
| 969 | Ok(self |
| 970 | .conn |
| 971 | .query_row("SELECT source, branch FROM imports WHERE project = ?1", [project], |r| Ok((r.get(0)?, r.get(1)?))) |
| 972 | .optional()?) |
| 973 | } |
| 974 |
| 975 | /// Native object → git object, for objects an import read from git. |
| 976 | pub fn put_git_ids(&self, project: &str, ids: &[(Id, String)]) -> Result<()> { |
| 977 | let tx = self.conn.unchecked_transaction()?; |
| 978 | { |
| 979 | let mut stmt = tx.prepare("INSERT OR REPLACE INTO git_ids (project, native, git) VALUES (?1, ?2, ?3)")?; |
| 980 | for (native, git) in ids { |
| 981 | stmt.execute(params![project, native.hex(), git])?; |
| 982 | } |
| 983 | } |
| 984 | tx.commit()?; |
| 985 | Ok(()) |
| 986 | } |
| 987 |
| 988 | pub fn git_ids(&self, project: &str) -> Result<Vec<(String, String)>> { |
| 989 | let mut stmt = self.conn.prepare("SELECT native, git FROM git_ids WHERE project = ?1")?; |
| 990 | let rows = stmt.query_map([project], |r| Ok((r.get(0)?, r.get(1)?)))?; |
| 991 | Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) |
| 992 | } |
| 993 |
| 994 | pub fn version_by_git(&self, project: &str, git: &str) -> Result<Option<Version>> { |
| 995 | let sql = format!("SELECT {} FROM versions WHERE project = ?1 AND git = ?2 ORDER BY n DESC LIMIT 1", Self::VERSION_COLUMNS); |
| 996 | Ok(self.conn.query_row(&sql, params![project, git], Self::version_row).optional()?) |
| 997 | } |
| 998 | } |
| 999 |