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