Add schema version constant and checks

This commit is contained in:
thePR0M3TH3AN
2025-05-22 08:17:51 -04:00
parent 32de11efdc
commit af35c90c50
2 changed files with 27 additions and 0 deletions

View File

@@ -18,6 +18,11 @@ use rusqlite::{
use std::result::Result as StdResult;
use tracing::{debug, info, warn};
/* ─── schema version ───────────────────────────────────────────────── */
/// Current library schema version.
pub const SCHEMA_VERSION: i32 = 1_1;
/* ─── embedded migrations ─────────────────────────────────────────── */
const MIGRATIONS: &[(&str, &str)] = &[
@@ -47,6 +52,18 @@ const MIGRATIONS: &[(&str, &str)] = &[
),
];
/* ─── schema helpers ─────────────────────────────────────────────── */
/// Fetch the highest version recorded in the `schema_version` table.
pub fn current_schema_version(conn: &Connection) -> Result<i32> {
let version: i32 = conn.query_row(
"SELECT IFNULL(MAX(version), 0) FROM schema_version",
[],
|r| r.get(0),
)?;
Ok(version)
}
/* ─── connection bootstrap ────────────────────────────────────────── */
pub fn open<P: AsRef<Path>>(db_path: P) -> Result<Connection> {
@@ -133,6 +150,15 @@ pub(crate) fn apply_migrations(conn: &mut Connection) -> Result<()> {
warn!("migrations not applied: {:?}", missing);
}
let current = current_schema_version(conn)?;
if current != SCHEMA_VERSION {
anyhow::bail!(
"database schema version {} does not match library version {}",
current,
SCHEMA_VERSION
);
}
Ok(())
}