Skip to main content

atomr_persistence_sql/
schema.rs

1//! Idempotent schema bootstrap.
2//!
3//! `ensure_schema` is safe to call on startup in dev / test; in prod it is
4//! guarded by the `auto_migrate` config flag (no-op when disabled).
5
6use atomr_persistence::JournalError;
7use sqlx::AnyPool;
8
9use crate::config::{SqlConfig, SqlDialect};
10
11/// Install sqlx runtime drivers for every enabled feature. Idempotent.
12pub(crate) fn init_drivers() {
13    sqlx::any::install_default_drivers();
14}
15
16/// Apply the migration DDL for the configured dialect. Statements are split
17/// on `;` so a single embedded SQL file can bootstrap every required table.
18pub async fn ensure_schema(pool: &AnyPool, cfg: &SqlConfig) -> Result<(), JournalError> {
19    if !cfg.auto_migrate {
20        return Ok(());
21    }
22    let ddl = crate::dialect::migration_for(cfg.dialect);
23    for stmt in split_statements(ddl) {
24        sqlx::query(&stmt).execute(pool).await.map_err(JournalError::backend)?;
25    }
26    Ok(())
27}
28
29fn split_statements(ddl: &str) -> Vec<String> {
30    let stripped: String =
31        ddl.lines().map(|l| l.split("--").next().unwrap_or("")).collect::<Vec<_>>().join("\n");
32    stripped.split(';').map(str::trim).filter(|s| !s.is_empty()).map(|s| s.to_string()).collect()
33}
34
35/// Drop every journal/snapshot row for tests that want a clean slate.
36/// Requires the schema to already exist.
37#[allow(dead_code)]
38pub async fn truncate(pool: &AnyPool, _dialect: SqlDialect) -> Result<(), JournalError> {
39    for table in ["event_tags", "event_journal", "snapshot_store"] {
40        sqlx::query(&format!("DELETE FROM {table}")).execute(pool).await.map_err(JournalError::backend)?;
41    }
42    Ok(())
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48
49    #[test]
50    fn splitter_skips_blank_and_comments() {
51        let sql = "-- hello\nCREATE TABLE a (id INT);\n\nCREATE TABLE b (id INT);";
52        let out = split_statements(sql);
53        assert_eq!(out.len(), 2);
54        assert!(out[0].starts_with("CREATE TABLE a"));
55    }
56}