Skip to main content

azoth_sqlite/
schema.rs

1use azoth_core::error::{AzothError, Result};
2use rusqlite::Connection;
3
4/// Update schema version
5///
6/// This is called by the MigrationManager after a migration has been applied.
7/// It simply updates the schema_version in the projection_meta table.
8///
9/// Note: This function does NOT apply any migrations itself. All migration
10/// logic should be defined using the Migration trait and applied via MigrationManager.
11pub fn migrate(conn: &Connection, target_version: u32) -> Result<()> {
12    let current_version: u32 = conn
13        .query_row(
14            "SELECT schema_version FROM projection_meta WHERE id = 0",
15            [],
16            |row| {
17                let v: i64 = row.get(0)?;
18                Ok(v as u32)
19            },
20        )
21        .map_err(|e| AzothError::Projection(e.to_string()))?;
22
23    if target_version < current_version {
24        return Err(AzothError::InvalidState(format!(
25            "Cannot downgrade schema version from {} to {}. Use MigrationManager::rollback_last() instead.",
26            current_version, target_version
27        )));
28    }
29
30    if current_version == target_version {
31        // Already at target version
32        return Ok(());
33    }
34
35    // Update to target version
36    update_schema_version(conn, target_version)?;
37    Ok(())
38}
39
40/// Update the schema version in metadata
41fn update_schema_version(conn: &Connection, version: u32) -> Result<()> {
42    conn.execute(
43        "UPDATE projection_meta SET schema_version = ?1, updated_at = datetime('now') WHERE id = 0",
44        [version as i64],
45    )
46    .map_err(|e| AzothError::Projection(e.to_string()))?;
47
48    Ok(())
49}