use std::path::{Path, PathBuf};
use rusqlite::Connection;
use crate::error::Result;
use crate::repo::{
Deps, Events, Footings, Memory, Plans, Questions, Recall, Recesses, Recusals, Requirements,
Scopes, Tasks, Verdicts, Witnessed,
};
const MIGRATIONS: &[&str] = &[
r#"
CREATE TABLE tasks (
id TEXT PRIMARY KEY,
seq INTEGER UNIQUE NOT NULL,
project TEXT NOT NULL,
title TEXT NOT NULL,
body TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL DEFAULT 'open'
CHECK (status IN ('open','claimed','in_progress','done','failed','cancelled')),
priority INTEGER NOT NULL DEFAULT 0,
claimed_by TEXT,
lease_expires_at TEXT,
result TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE task_events (
id TEXT PRIMARY KEY,
task_id TEXT NOT NULL REFERENCES tasks(id),
at TEXT NOT NULL,
actor TEXT NOT NULL,
kind TEXT NOT NULL,
detail TEXT NOT NULL DEFAULT ''
);
CREATE TABLE assertions (
id TEXT PRIMARY KEY,
project TEXT NOT NULL,
content TEXT NOT NULL,
tags TEXT NOT NULL DEFAULT '',
actor TEXT NOT NULL,
task_id TEXT REFERENCES tasks(id),
superseded_by TEXT REFERENCES assertions(id),
created_at TEXT NOT NULL
);
CREATE VIRTUAL TABLE assertions_fts USING fts5(
content, tags, content='assertions', content_rowid='rowid'
);
CREATE TRIGGER assertions_fts_ai AFTER INSERT ON assertions BEGIN
INSERT INTO assertions_fts(rowid, content, tags)
VALUES (new.rowid, new.content, new.tags);
END;
CREATE TRIGGER assertions_fts_ad AFTER DELETE ON assertions BEGIN
INSERT INTO assertions_fts(assertions_fts, rowid, content, tags)
VALUES ('delete', old.rowid, old.content, old.tags);
END;
CREATE TRIGGER assertions_fts_au AFTER UPDATE ON assertions BEGIN
INSERT INTO assertions_fts(assertions_fts, rowid, content, tags)
VALUES ('delete', old.rowid, old.content, old.tags);
INSERT INTO assertions_fts(rowid, content, tags)
VALUES (new.rowid, new.content, new.tags);
END;
CREATE INDEX idx_tasks_project_status ON tasks(project, status);
CREATE INDEX idx_tasks_status_lease ON tasks(status, lease_expires_at);
CREATE INDEX idx_task_events_task_at ON task_events(task_id, at);
CREATE INDEX idx_assertions_project_current ON assertions(project, superseded_by);
INSERT INTO meta(key, value) VALUES ('next_seq', '1');
"#,
r#"
CREATE TABLE task_deps (
task_id TEXT NOT NULL REFERENCES tasks(id),
depends_on_id TEXT NOT NULL REFERENCES tasks(id),
actor TEXT NOT NULL,
created_at TEXT NOT NULL,
PRIMARY KEY (task_id, depends_on_id),
CHECK (task_id <> depends_on_id)
);
CREATE INDEX idx_task_deps_depends_on ON task_deps(depends_on_id);
CREATE TABLE task_paths (
id TEXT PRIMARY KEY,
task_id TEXT NOT NULL REFERENCES tasks(id),
pattern TEXT NOT NULL,
declared_by TEXT NOT NULL,
at TEXT NOT NULL,
UNIQUE (task_id, pattern)
);
CREATE INDEX idx_task_paths_task ON task_paths(task_id);
"#,
r#"
CREATE TABLE task_witness (
task_id TEXT PRIMARY KEY REFERENCES tasks(id),
head TEXT NOT NULL DEFAULT '',
tree TEXT NOT NULL DEFAULT '{}',
at TEXT NOT NULL
);
CREATE TABLE task_changes (
id TEXT PRIMARY KEY,
task_id TEXT NOT NULL REFERENCES tasks(id),
path TEXT NOT NULL,
kind TEXT NOT NULL CHECK (kind IN ('added','modified','deleted')),
hash TEXT NOT NULL DEFAULT '',
first_seen TEXT NOT NULL,
last_seen TEXT NOT NULL,
UNIQUE (task_id, path)
);
CREATE INDEX idx_task_changes_path ON task_changes(path);
CREATE INDEX idx_task_changes_task ON task_changes(task_id);
"#,
r#"
CREATE TABLE task_plan_nodes (
task_id TEXT PRIMARY KEY REFERENCES tasks(id),
project TEXT NOT NULL,
plan TEXT NOT NULL,
node TEXT NOT NULL,
at TEXT NOT NULL,
UNIQUE (project, plan, node)
);
"#,
r#"
CREATE TABLE assertion_footing (
assertion_id TEXT NOT NULL REFERENCES assertions(id),
path TEXT NOT NULL,
hash TEXT NOT NULL DEFAULT '',
-- 1 when the author named this file rather than hird deriving it from the
-- task. A named footing is never overruled by settling.
named INTEGER NOT NULL DEFAULT 0,
at TEXT NOT NULL,
PRIMARY KEY (assertion_id, path)
);
CREATE INDEX idx_assertion_footing_path ON assertion_footing(path);
CREATE TABLE assertion_affirmations (
assertion_id TEXT NOT NULL REFERENCES assertions(id),
actor TEXT NOT NULL,
at TEXT NOT NULL,
PRIMARY KEY (assertion_id, actor)
);
"#,
r#"
CREATE TABLE task_recusals (
task_id TEXT NOT NULL REFERENCES tasks(id),
-- Whoever worked this task is barred from working task_id.
from_task_id TEXT NOT NULL REFERENCES tasks(id),
reason TEXT NOT NULL DEFAULT '',
actor TEXT NOT NULL,
at TEXT NOT NULL,
PRIMARY KEY (task_id, from_task_id),
CHECK (task_id <> from_task_id)
);
CREATE INDEX idx_task_recusals_from ON task_recusals(from_task_id);
-- 1 when finishing this task should put its work in front of somebody else.
ALTER TABLE tasks ADD COLUMN review INTEGER NOT NULL DEFAULT 0;
"#,
r#"
CREATE TABLE task_verdicts (
id TEXT PRIMARY KEY,
-- The review that delivered the verdict.
review_id TEXT NOT NULL REFERENCES tasks(id),
-- The work it judged.
task_id TEXT NOT NULL REFERENCES tasks(id),
verdict TEXT NOT NULL CHECK (verdict IN ('upheld','sent_back')),
-- Whoever's work was judged: the holder of record when the verdict landed.
worker TEXT NOT NULL DEFAULT '',
-- Whoever delivered it.
reviewer TEXT NOT NULL,
at TEXT NOT NULL,
CHECK (review_id <> task_id)
);
CREATE INDEX idx_task_verdicts_task ON task_verdicts(task_id);
CREATE INDEX idx_task_verdicts_review ON task_verdicts(review_id);
"#,
r#"
CREATE TABLE witness_blobs (
-- The same content hash the witness records everywhere else, so a hash in
-- a baseline or a change row is also the key to what the file said.
hash TEXT PRIMARY KEY,
content BLOB NOT NULL,
size INTEGER NOT NULL,
-- When this version was last seen, not first: re-sighting refreshes it,
-- which is what keeps pruning from throwing away versions still in play.
at TEXT NOT NULL
);
"#,
r#"
-- Who the baseline was taken for, so an archived tenure can say whose
-- holding it describes without replaying the event trail.
ALTER TABLE task_witness ADD COLUMN holder TEXT NOT NULL DEFAULT '';
CREATE TABLE task_tenures (
id TEXT PRIMARY KEY,
task_id TEXT NOT NULL REFERENCES tasks(id),
-- 1-based per task, in the order the holdings ended.
n INTEGER NOT NULL,
holder TEXT NOT NULL DEFAULT '',
began_at TEXT NOT NULL,
-- How the holding ended: completed, failed, released, lease_expired or
-- cancelled. Empty when the trail could not say.
ended TEXT NOT NULL DEFAULT '',
ended_at TEXT NOT NULL DEFAULT '',
-- The baseline the holding was measured against, verbatim from
-- task_witness: the commit and the fingerprint of what was dirty.
head TEXT NOT NULL DEFAULT '',
tree TEXT NOT NULL DEFAULT '{}',
archived_at TEXT NOT NULL,
UNIQUE (task_id, n)
);
CREATE INDEX idx_task_tenures_task ON task_tenures(task_id);
CREATE TABLE tenure_changes (
tenure_id TEXT NOT NULL REFERENCES task_tenures(id),
path TEXT NOT NULL,
kind TEXT NOT NULL CHECK (kind IN ('added','modified','deleted')),
hash TEXT NOT NULL DEFAULT '',
first_seen TEXT NOT NULL,
last_seen TEXT NOT NULL,
PRIMARY KEY (tenure_id, path)
);
CREATE INDEX idx_tenure_changes_hash ON tenure_changes(hash);
"#,
r#"
CREATE TABLE task_questions (
id TEXT PRIMARY KEY,
task_id TEXT NOT NULL REFERENCES tasks(id),
n INTEGER NOT NULL,
asked_by TEXT NOT NULL,
question TEXT NOT NULL,
asked_at TEXT NOT NULL,
answer TEXT,
answered_by TEXT,
answered_at TEXT,
UNIQUE (task_id, n)
);
CREATE INDEX idx_task_questions_task ON task_questions(task_id, n);
CREATE UNIQUE INDEX idx_task_questions_one_open
ON task_questions(task_id) WHERE answer IS NULL;
"#,
r#"
CREATE TABLE task_requirements (
task_id TEXT NOT NULL REFERENCES tasks(id),
capability TEXT NOT NULL,
PRIMARY KEY (task_id, capability)
);
CREATE INDEX idx_task_requirements_capability
ON task_requirements(capability, task_id);
"#,
r#"
CREATE TABLE project_recess (
project TEXT PRIMARY KEY,
reason TEXT NOT NULL DEFAULT '',
actor TEXT NOT NULL,
at TEXT NOT NULL
);
"#,
];
pub struct Db {
conn: Connection,
path: PathBuf,
}
impl Db {
pub fn open(path: impl AsRef<Path>) -> Result<Db> {
let path = path.as_ref().to_path_buf();
if let Some(parent) = path.parent() {
if !parent.as_os_str().is_empty() {
std::fs::create_dir_all(parent).map_err(|e| {
crate::error::Error::invalid(format!(
"cannot create database directory {}: {e}",
parent.display()
))
})?;
}
}
let conn = Connection::open(&path)?;
Self::from_connection(conn, path)
}
pub fn open_in_memory() -> Result<Db> {
let conn = Connection::open_in_memory()?;
Self::from_connection(conn, PathBuf::from(":memory:"))
}
fn from_connection(conn: Connection, path: PathBuf) -> Result<Db> {
conn.pragma_update(None, "journal_mode", "WAL")?;
conn.pragma_update(None, "busy_timeout", 5000)?;
conn.pragma_update(None, "synchronous", "NORMAL")?;
conn.pragma_update(None, "foreign_keys", "ON")?;
let db = Db { conn, path };
db.migrate()?;
Ok(db)
}
pub fn path(&self) -> &Path {
&self.path
}
#[cfg(test)]
pub(crate) fn conn(&self) -> &Connection {
&self.conn
}
pub fn tasks(&self) -> Tasks<'_> {
Tasks::new(&self.conn)
}
pub fn questions(&self) -> Questions<'_> {
Questions::new(&self.conn)
}
pub fn requirements(&self) -> Requirements<'_> {
Requirements::new(&self.conn)
}
pub fn events(&self) -> Events<'_> {
Events::new(&self.conn)
}
pub fn memory(&self) -> Memory<'_> {
Memory::new(&self.conn)
}
pub fn deps(&self) -> Deps<'_> {
Deps::new(&self.conn)
}
pub fn scopes(&self) -> Scopes<'_> {
Scopes::new(&self.conn)
}
pub fn plans(&self) -> Plans<'_> {
Plans::new(&self.conn)
}
pub fn witnessed(&self) -> Witnessed<'_> {
Witnessed::new(&self.conn)
}
pub fn footings(&self) -> Footings<'_> {
Footings::new(&self.conn)
}
pub fn recusals(&self) -> Recusals<'_> {
Recusals::new(&self.conn)
}
pub fn recesses(&self) -> Recesses<'_> {
Recesses::new(&self.conn)
}
pub fn verdicts(&self) -> Verdicts<'_> {
Verdicts::new(&self.conn)
}
pub fn recall(&self) -> Recall<'_> {
Recall::new(&self.conn)
}
pub fn schema_version(&self) -> Result<u32> {
let raw: Option<String> = self
.conn
.query_row(
"SELECT value FROM meta WHERE key = 'schema_version'",
[],
|row| row.get(0),
)
.ok();
Ok(raw.and_then(|v| v.parse().ok()).unwrap_or(0))
}
fn migrate(&self) -> Result<()> {
self.conn.execute_batch(
"CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)",
)?;
let applied = self.schema_version()?;
let known = MIGRATIONS.len() as u32;
if applied > known {
return Err(crate::error::Error::invalid(schema_from_the_future(
&self.path, applied, known,
)));
}
for (idx, sql) in MIGRATIONS.iter().enumerate() {
let version = idx as u32 + 1;
if version <= applied {
continue;
}
let tx = self.conn.unchecked_transaction()?;
tx.execute_batch(sql)?;
tx.execute(
"INSERT INTO meta(key, value) VALUES ('schema_version', ?1)
ON CONFLICT(key) DO UPDATE SET value = excluded.value",
[version.to_string()],
)?;
tx.commit()?;
}
Ok(())
}
}
fn schema_from_the_future(path: &Path, found: u32, known: u32) -> String {
let binary = std::env::current_exe()
.ok()
.map(|p| format!(" ({})", p.display()))
.unwrap_or_default();
format!(
"database {} is at schema version {found}, but this hird binary{binary} only \
knows versions up to {known} — a newer hird has migrated it. Upgrade this \
binary (re-run scripts/install.sh) and try again; the database was not changed",
path.display()
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn opening_applies_every_migration() {
let db = Db::open_in_memory().unwrap();
assert_eq!(db.schema_version().unwrap(), MIGRATIONS.len() as u32);
}
#[test]
fn reopening_an_existing_file_is_a_no_op() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("nested").join("hird.db");
let first = Db::open(&path).unwrap();
let seq = first.tasks().create("/p", "t", "", 0, "cli").unwrap().seq;
drop(first);
let second = Db::open(&path).unwrap();
assert_eq!(second.schema_version().unwrap(), MIGRATIONS.len() as u32);
assert_eq!(second.tasks().get(seq).unwrap().title, "t");
}
#[test]
fn a_database_from_a_newer_hird_is_refused_by_name() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("hird.db");
let ahead = (MIGRATIONS.len() as u32 + 5).to_string();
{
let db = Db::open(&path).unwrap();
db.conn()
.execute(
"UPDATE meta SET value = ?1 WHERE key = 'schema_version'",
[&ahead],
)
.unwrap();
}
let err = match Db::open(&path) {
Ok(_) => panic!("a database from the future must be refused"),
Err(e) => e.to_string(),
};
assert!(err.contains(&format!("schema version {ahead}")), "{err}");
assert!(
err.contains(&format!("up to {}", MIGRATIONS.len())),
"{err}"
);
assert!(err.contains("hird.db"), "{err}");
let reread = Connection::open(&path).unwrap();
let stored: String = reread
.query_row(
"SELECT value FROM meta WHERE key = 'schema_version'",
[],
|r| r.get(0),
)
.unwrap();
assert_eq!(stored, ahead);
}
#[test]
fn fts5_is_available_in_the_bundled_sqlite() {
let db = Db::open_in_memory().unwrap();
db.conn()
.execute_batch("CREATE VIRTUAL TABLE probe USING fts5(x)")
.expect("bundled SQLite must be built with FTS5");
}
#[test]
fn wal_and_foreign_keys_are_on_for_file_databases() {
let dir = tempfile::tempdir().unwrap();
let db = Db::open(dir.path().join("hird.db")).unwrap();
let mode: String = db
.conn()
.query_row("PRAGMA journal_mode", [], |r| r.get(0))
.unwrap();
assert_eq!(mode.to_lowercase(), "wal");
let fk: i64 = db
.conn()
.query_row("PRAGMA foreign_keys", [], |r| r.get(0))
.unwrap();
assert_eq!(fk, 1);
}
}