use diesel::SqliteConnection;
use diesel_migrations::{EmbeddedMigrations, MigrationHarness, embed_migrations};
use tracing::instrument;
use crate::COMPONENT;
use crate::db::schema_hash::verify_schema;
pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!("src/db/migrations");
#[instrument(level = "debug", target = COMPONENT, skip_all, err)]
pub fn apply_migrations(
conn: &mut SqliteConnection,
) -> std::result::Result<(), miden_node_db::DatabaseError> {
let migrations = conn.pending_migrations(MIGRATIONS).expect("In memory migrations never fail");
tracing::info!(target = COMPONENT, migrations = migrations.len(), "Applying migrations");
let Err(e) = conn.run_pending_migrations(MIGRATIONS) else {
verify_schema(conn)?;
return Ok(());
};
tracing::warn!(target = COMPONENT, error = ?e, "Failed to apply migration");
conn.revert_last_migration(MIGRATIONS)
.expect("Duality is maintained by the developer");
Ok(())
}