|
| 1 | +"""SQLite repository adapter (ADR 0001: SQLite first, behind the backend-agnostic port). |
| 2 | +
|
| 3 | +Schema is versioned via ``PRAGMA user_version`` and migrated forward on open. SQLite- |
| 4 | +specific concerns stay encapsulated here; callers see only the :class:`Repository` port. |
| 5 | +""" |
| 6 | + |
| 7 | +from __future__ import annotations |
| 8 | + |
| 9 | +import sqlite3 |
| 10 | +from collections.abc import Iterable |
| 11 | +from pathlib import Path |
| 12 | +from typing import cast |
| 13 | + |
| 14 | +from panopticon.core.models import Ball, HistoryEntry, Repo, Task |
| 15 | +from panopticon.core.repository import ( |
| 16 | + AlreadyExists, |
| 17 | + NotFound, |
| 18 | + Repository, |
| 19 | + validate_append_only, |
| 20 | + validate_task_invariants, |
| 21 | +) |
| 22 | + |
| 23 | +# Forward-only schema migrations. Index i in this list corresponds to user_version i+1. |
| 24 | +MIGRATIONS: tuple[str, ...] = ( |
| 25 | + # v1 — initial schema |
| 26 | + """ |
| 27 | + CREATE TABLE repo ( |
| 28 | + id TEXT PRIMARY KEY, |
| 29 | + name TEXT NOT NULL, |
| 30 | + default_base TEXT NOT NULL |
| 31 | + ); |
| 32 | + CREATE TABLE task ( |
| 33 | + id TEXT PRIMARY KEY, |
| 34 | + repo_id TEXT NOT NULL REFERENCES repo(id), |
| 35 | + workflow TEXT NOT NULL, |
| 36 | + state TEXT NOT NULL, |
| 37 | + ball TEXT NOT NULL, |
| 38 | + slug TEXT |
| 39 | + ); |
| 40 | + CREATE TABLE history ( |
| 41 | + task_id TEXT NOT NULL REFERENCES task(id), |
| 42 | + seq INTEGER NOT NULL, |
| 43 | + at TEXT NOT NULL, |
| 44 | + from_state TEXT, |
| 45 | + to_state TEXT NOT NULL, |
| 46 | + via TEXT, |
| 47 | + note TEXT, |
| 48 | + PRIMARY KEY (task_id, seq) |
| 49 | + ); |
| 50 | + """, |
| 51 | +) |
| 52 | + |
| 53 | + |
| 54 | +class SqliteRepository(Repository): |
| 55 | + """A SQLite-backed :class:`~panopticon.core.repository.Repository`.""" |
| 56 | + |
| 57 | + def __init__(self, path: str | Path = ":memory:") -> None: |
| 58 | + self._conn = sqlite3.connect(str(path)) |
| 59 | + self._conn.row_factory = sqlite3.Row |
| 60 | + self._conn.execute("PRAGMA foreign_keys = ON") |
| 61 | + self._migrate() |
| 62 | + |
| 63 | + def close(self) -> None: |
| 64 | + self._conn.close() |
| 65 | + |
| 66 | + def _migrate(self) -> None: |
| 67 | + version = cast(int, self._conn.execute("PRAGMA user_version").fetchone()[0]) |
| 68 | + for i in range(version, len(MIGRATIONS)): |
| 69 | + self._conn.executescript(MIGRATIONS[i]) |
| 70 | + self._conn.execute(f"PRAGMA user_version = {i + 1}") |
| 71 | + self._conn.commit() |
| 72 | + |
| 73 | + # -- repos -------------------------------------------------------------------- |
| 74 | + |
| 75 | + def create_repo(self, repo: Repo) -> None: |
| 76 | + try: |
| 77 | + self._conn.execute( |
| 78 | + "INSERT INTO repo (id, name, default_base) VALUES (?, ?, ?)", |
| 79 | + (repo.id, repo.name, repo.default_base), |
| 80 | + ) |
| 81 | + except sqlite3.IntegrityError as exc: |
| 82 | + raise AlreadyExists(f"repo {repo.id!r} already exists") from exc |
| 83 | + self._conn.commit() |
| 84 | + |
| 85 | + def get_repo(self, repo_id: str) -> Repo | None: |
| 86 | + row = self._conn.execute( |
| 87 | + "SELECT id, name, default_base FROM repo WHERE id = ?", (repo_id,) |
| 88 | + ).fetchone() |
| 89 | + return _row_to_repo(row) if row is not None else None |
| 90 | + |
| 91 | + def list_repos(self) -> list[Repo]: |
| 92 | + rows = self._conn.execute("SELECT id, name, default_base FROM repo ORDER BY id") |
| 93 | + return [_row_to_repo(r) for r in rows] |
| 94 | + |
| 95 | + # -- tasks -------------------------------------------------------------------- |
| 96 | + |
| 97 | + def create_task(self, task: Task) -> None: |
| 98 | + validate_task_invariants(task) |
| 99 | + if self._task_exists(task.id): |
| 100 | + raise AlreadyExists(f"task {task.id!r} already exists") |
| 101 | + if self.get_repo(task.repo_id) is None: |
| 102 | + raise NotFound(f"repo {task.repo_id!r} does not exist") |
| 103 | + with self._conn: # transaction |
| 104 | + self._conn.execute( |
| 105 | + "INSERT INTO task (id, repo_id, workflow, state, ball, slug) " |
| 106 | + "VALUES (?, ?, ?, ?, ?, ?)", |
| 107 | + (task.id, task.repo_id, task.workflow, task.state, task.ball.value, task.slug), |
| 108 | + ) |
| 109 | + self._insert_history(task.id, 0, task.history) |
| 110 | + |
| 111 | + def get_task(self, task_id: str) -> Task | None: |
| 112 | + row = self._conn.execute( |
| 113 | + "SELECT id, repo_id, workflow, state, ball, slug FROM task WHERE id = ?", |
| 114 | + (task_id,), |
| 115 | + ).fetchone() |
| 116 | + if row is None: |
| 117 | + return None |
| 118 | + return _row_to_task(row, self._load_history(task_id)) |
| 119 | + |
| 120 | + def list_tasks(self) -> list[Task]: |
| 121 | + rows = self._conn.execute( |
| 122 | + "SELECT id, repo_id, workflow, state, ball, slug FROM task ORDER BY id" |
| 123 | + ).fetchall() |
| 124 | + return [_row_to_task(r, self._load_history(cast(str, r["id"]))) for r in rows] |
| 125 | + |
| 126 | + def save_task(self, task: Task) -> None: |
| 127 | + validate_task_invariants(task) |
| 128 | + stored = self._load_history(task.id) |
| 129 | + if not self._task_exists(task.id): |
| 130 | + raise NotFound(f"task {task.id!r} does not exist") |
| 131 | + validate_append_only(stored, task.history) |
| 132 | + with self._conn: # transaction |
| 133 | + self._conn.execute( |
| 134 | + "UPDATE task SET state = ?, ball = ?, slug = ? WHERE id = ?", |
| 135 | + (task.state, task.ball.value, task.slug, task.id), |
| 136 | + ) |
| 137 | + self._insert_history(task.id, len(stored), task.history[len(stored) :]) |
| 138 | + |
| 139 | + # -- helpers ------------------------------------------------------------------ |
| 140 | + |
| 141 | + def _task_exists(self, task_id: str) -> bool: |
| 142 | + return ( |
| 143 | + self._conn.execute("SELECT 1 FROM task WHERE id = ?", (task_id,)).fetchone() |
| 144 | + is not None |
| 145 | + ) |
| 146 | + |
| 147 | + def _insert_history( |
| 148 | + self, task_id: str, start_seq: int, entries: Iterable[HistoryEntry] |
| 149 | + ) -> None: |
| 150 | + self._conn.executemany( |
| 151 | + "INSERT INTO history (task_id, seq, at, from_state, to_state, via, note) " |
| 152 | + "VALUES (?, ?, ?, ?, ?, ?, ?)", |
| 153 | + [ |
| 154 | + (task_id, start_seq + i, e.at, e.from_state, e.to_state, e.via, e.note) |
| 155 | + for i, e in enumerate(entries) |
| 156 | + ], |
| 157 | + ) |
| 158 | + |
| 159 | + def _load_history(self, task_id: str) -> list[HistoryEntry]: |
| 160 | + rows = self._conn.execute( |
| 161 | + "SELECT at, from_state, to_state, via, note FROM history " |
| 162 | + "WHERE task_id = ? ORDER BY seq", |
| 163 | + (task_id,), |
| 164 | + ).fetchall() |
| 165 | + return [ |
| 166 | + HistoryEntry( |
| 167 | + at=cast(str, r["at"]), |
| 168 | + from_state=cast("str | None", r["from_state"]), |
| 169 | + to_state=cast(str, r["to_state"]), |
| 170 | + via=cast("str | None", r["via"]), |
| 171 | + note=cast("str | None", r["note"]), |
| 172 | + ) |
| 173 | + for r in rows |
| 174 | + ] |
| 175 | + |
| 176 | + |
| 177 | +def _row_to_repo(row: sqlite3.Row) -> Repo: |
| 178 | + return Repo( |
| 179 | + id=cast(str, row["id"]), |
| 180 | + name=cast(str, row["name"]), |
| 181 | + default_base=cast(str, row["default_base"]), |
| 182 | + ) |
| 183 | + |
| 184 | + |
| 185 | +def _row_to_task(row: sqlite3.Row, history: list[HistoryEntry]) -> Task: |
| 186 | + return Task( |
| 187 | + id=cast(str, row["id"]), |
| 188 | + repo_id=cast(str, row["repo_id"]), |
| 189 | + workflow=cast(str, row["workflow"]), |
| 190 | + state=cast(str, row["state"]), |
| 191 | + ball=Ball(cast(str, row["ball"])), |
| 192 | + slug=cast("str | None", row["slug"]), |
| 193 | + history=history, |
| 194 | + ) |
0 commit comments