summaryrefslogtreecommitdiffstats
path: root/tests/schema_ownership.rs
blob: dac93d697ebe36198a62b78a70a159cb1b763a0b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
//! 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<PathBuf>) {
    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<String> = 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")
    );
}

/// m-18: the version a human reads is `pkgver::full_version`'s to produce —
/// `epoch:pkgver-pkgrel`, with the epoch omitted when it is `0` or empty. That
/// rule used to exist twice, once in Rust and once as a `CASE WHEN epoch='0'`
/// inside `approved_but_unbuilt`, where a change to one would silently make the
/// Attention page disagree with every other page about what a version looks
/// like. SQL selects the parts; Rust formats them.
#[test]
fn only_rust_formats_a_version() {
    let root = Path::new(env!("CARGO_MANIFEST_DIR"));
    let mut files = Vec::new();
    rust_files(&root.join("src"), &mut files);
    let offenders: Vec<String> = files
        .iter()
        .flat_map(|f| {
            let text = std::fs::read_to_string(f).unwrap();
            text.lines()
                .filter(|l| !l.trim_start().starts_with("//"))
                .filter(|l| l.contains("epoch||") || l.contains("||'-'||") || l.contains("pkgver||"))
                .map(|l| format!("  {}: {}", f.strip_path(root), l.trim()))
                .collect::<Vec<_>>()
        })
        .collect();
    assert!(
        offenders.is_empty(),
        "version formatting belongs to `pkgver::full_version`, not to SQL (m-18):\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('\\', "/")
    }
}