Skip to main content

agentmux_srv_core/migrations/
schema_probe.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The one "does this table exist" probe. Every migration used to carry its own copy of the
5//! `sqlite_master` query, with its own idea of what to do with an error.
6
7use rusqlite::Connection;
8
9/// Whether `table` exists in `conn`'s main schema. A failed probe is an error, never "absent": a
10/// migration that treats a database it could not read as empty would skip work it owes.
11pub(crate) fn table_exists(conn: &Connection, table: &str) -> rusqlite::Result<bool> {
12    conn.query_row(
13        "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?1)",
14        [table],
15        |row| row.get(0),
16    )
17}
18
19#[cfg(test)]
20mod tests {
21    use super::*;
22
23    #[test]
24    fn a_table_is_found_once_it_exists_and_a_view_or_index_is_not_a_table() {
25        let conn = Connection::open_in_memory().unwrap();
26        assert!(!table_exists(&conn, "t").unwrap());
27        conn.execute_batch("CREATE TABLE t (id INTEGER); CREATE INDEX i ON t(id); CREATE VIEW v AS SELECT id FROM t;").unwrap();
28        assert!(table_exists(&conn, "t").unwrap());
29        assert!(!table_exists(&conn, "i").unwrap());
30        assert!(!table_exists(&conn, "v").unwrap());
31    }
32
33    #[test]
34    fn a_connection_that_cannot_be_read_is_an_error_not_an_absent_table() {
35        let dir = tempfile::tempdir().unwrap();
36        let path = dir.path().join("not-a-database.db");
37        std::fs::write(&path, b"this is not an sqlite file at all, just text padding it past the header size....").unwrap();
38        let conn = Connection::open(&path).unwrap();
39        assert!(table_exists(&conn, "t").is_err());
40    }
41}