cat_gateway/db/event/schema_check/
mod.rs

1//! Check if the schema is up-to-date.
2
3use crate::db::event::{DATABASE_SCHEMA_VERSION, EventDB};
4
5/// Schema in database does not match schema supported by the Crate.
6#[derive(thiserror::Error, Debug, PartialEq, Eq)]
7#[error(
8    " Schema in database does not match schema supported by the Crate. The current schema version: {was}, the schema version we expected: {expected}"
9)]
10pub(crate) struct MismatchedSchemaError {
11    /// The current DB schema version.
12    was: i32,
13    /// The expected DB schema version.
14    expected: i32,
15}
16
17/// `select_max_version.sql`
18const SELECT_MAX_VERSION_SQL: &str = include_str!("select_max_version.sql");
19
20impl EventDB {
21    /// Check the schema version.
22    /// return the current schema version if its current.
23    /// Otherwise return an error.
24    pub(crate) async fn schema_version_check() -> anyhow::Result<i32> {
25        let schema_check = Self::query_one(SELECT_MAX_VERSION_SQL, &[]).await?;
26
27        let current_ver = schema_check.try_get("max")?;
28
29        if current_ver == DATABASE_SCHEMA_VERSION {
30            Ok(current_ver)
31        } else {
32            Err(MismatchedSchemaError {
33                was: current_ver,
34                expected: DATABASE_SCHEMA_VERSION,
35            }
36            .into())
37        }
38    }
39}