From 933c637de34095f1ea1ab88b02626bbf22eec7f4 Mon Sep 17 00:00:00 2001 From: aur-build Date: Wed, 18 Nov 2026 15:20:13 +0000 Subject: =?UTF-8?q?db:=20the=20schema=20gets=20an=20owner=20=E2=80=94=20ev?= =?UTF-8?q?ery=20statement=20moves=20into=20db/,=20and=20the=20writer=20st?= =?UTF-8?q?ops=20handing=20out=20connections?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Twelve modules outside `db/` contained hand-rolled SQL — 22 statements in `ops.rs`, 17 in `approve.rs`, 15 in `candidates.rs`, 11 in `publish.rs`, and a dozen more scattered through `watch`, `pipeline`, `http` — which meant the blast radius of a schema change was "any module", and `db/` was a directory rather than a boundary. The audit trail alone was defined in four places with three different detail payloads. Every statement now lives in `db/`. New modules `db::candidates` and `db::approvals` own their tables (including the 21-column candidate select, spelled once as `CANDIDATE_COLS` instead of four times); `db::queries` gains the metrics reads, the retention reads and writes, the publish writes (`insert_release_in`, `cas_accepted_release_in`, `remove_index_packages_in`), the staleness reads and the source-cache lookups; `db::builds` gains `set_release_in`. Where a mutation is a *decision* — the collapse rules, the approval gate, the publish compare-and-swap — the decision stays where it was and the statements are called through the transaction handle, so the atomicity is unchanged and only the SQL moved. `audit_in` is the in-transaction audit append, and `audit` is now a wrapper over it: a decision and its audit row commit together or not at all, which is what I10 actually claims. Enforcement is two-layered, because one layer is a lie. `Writer::call`, `tx` and `send` are `pub(crate)`, which keeps the crate's *users* out — the integration tests and the shim binaries — but `pub(crate)` is crate-wide, so on its own it would not stop `approve.rs` from writing SQL tomorrow. The layer that does is `tests/schema_ownership.rs`: it walks `src/` and fails the build if a statement literal or a rusqlite statement call appears outside `src/db/`. It was checked against a deliberate violation. The test harness still needs to construct states no typed API reaches, so the raw door exists but only under the `test-support` feature, which nothing but this crate's own dev-dependency enables; a production binary cannot see it. --- tests/schema_ownership.rs | 88 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 tests/schema_ownership.rs (limited to 'tests/schema_ownership.rs') diff --git a/tests/schema_ownership.rs b/tests/schema_ownership.rs new file mode 100644 index 0000000..e2904f4 --- /dev/null +++ b/tests/schema_ownership.rs @@ -0,0 +1,88 @@ +//! The schema has one owner (§6 M-1). +//! +//! `db/` is a boundary, not a directory, only if SQL cannot land anywhere else. +//! Part of that is a compile-time fact: `Writer::call`, `tx` and `send` are +//! `pub(crate)`, and the raw door the test harness uses exists only under the +//! `test-support` feature. What the compiler cannot express is the other half — +//! that no module *inside* this crate writes a statement of its own. This does. +//! +//! The rule it enforces: a SQL statement, or a rusqlite statement call, appears +//! in `src/db/` and nowhere else. A module that needs the database asks `db/` +//! for a typed query; if the query does not exist, that is the change to make. + +use std::path::{Path, PathBuf}; + +/// String literals that begin a statement. Matched on the quote so a prose +/// comment that mentions a `SELECT` cannot trip it, and comment lines are +/// skipped anyway. +const SQL_LITERALS: &[&str] = &[ + "\"SELECT", "\"select", "\"INSERT", "\"insert", "\"UPDATE", "\"update", "\"DELETE", "\"delete", + "\"PRAGMA", "\"WITH", +]; + +/// rusqlite entry points. Outside `db/` there is nothing legitimate to hand +/// them, since every statement string is supposed to live in `db/`. +const STATEMENT_CALLS: &[&str] = &[ + ".query_row(", ".query_map(", ".execute(", ".execute_batch(", ".prepare(", ".pragma_query_value(", +]; + +fn rust_files(dir: &Path, out: &mut Vec) { + for entry in std::fs::read_dir(dir).expect("read_dir") { + let path = entry.expect("entry").path(); + if path.is_dir() { + rust_files(&path, out); + } else if path.extension().is_some_and(|e| e == "rs") { + out.push(path); + } + } +} + +#[test] +fn no_sql_statements_outside_the_db_module() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + let mut files = Vec::new(); + rust_files(&root, &mut files); + assert!(files.len() > 20, "found only {} source files — the walk is wrong", files.len()); + + let mut offenders: Vec = Vec::new(); + for file in files { + let rel = file.strip_path(&root); + // The owner of the schema is allowed to contain SQL. + if rel.starts_with("db/") || rel.starts_with("db\\") { + continue; + } + let text = std::fs::read_to_string(&file).expect("read source"); + for (no, line) in text.lines().enumerate() { + let t = line.trim_start(); + if t.starts_with("//") { + continue; + } + for needle in SQL_LITERALS.iter().chain(STATEMENT_CALLS.iter()) { + if line.contains(needle) { + offenders.push(format!("{}:{}: {t}", rel, no + 1)); + break; + } + } + } + } + assert!( + offenders.is_empty(), + "SQL belongs to `db/` (§6 M-1). Move these into a typed query:\n{}", + offenders.join("\n") + ); +} + +/// `src/db/queries.rs` → `db/queries.rs`, so the failure message points at the +/// module rather than an absolute path. +trait StripPath { + fn strip_path(&self, root: &Path) -> String; +} + +impl StripPath for PathBuf { + fn strip_path(&self, root: &Path) -> String { + self.strip_prefix(root) + .unwrap_or(self.as_path()) + .to_string_lossy() + .replace('\\', "/") + } +} -- cgit v1.2.3