use sqlx::PgPool;
use sqlx::Row;
use tracing::warn;
use ff_core::engine_error::EngineError;
use crate::error::map_sqlx_error;
pub async fn check_schema_version(pool: &PgPool, required: u32) -> Result<(), EngineError> {
let ledger: i64 = match sqlx::query(
"SELECT MAX(version) FROM _sqlx_migrations WHERE success = TRUE",
)
.fetch_optional(pool)
.await
{
Ok(Some(row)) => row.try_get::<Option<i64>, _>(0).ok().flatten().unwrap_or(0),
Ok(None) => 0,
Err(sqlx::Error::Database(ref db)) if db.code().as_deref() == Some("42P01") => 0,
Err(other) => return Err(map_sqlx_error(other)),
};
let required_i = required as i64;
if ledger < required_i {
return Err(EngineError::Unavailable {
op: "schema_version",
});
}
if ledger > required_i {
warn!(
ledger,
required = required_i,
"postgres schema ledger is ahead of binary — Wave 3 will gate this on the backward_compatible annotation"
);
}
Ok(())
}