use chrono::{DateTime, Utc};
#[derive(Debug, Clone, Copy)]
pub struct MigrationStep {
pub version: i64,
pub description: &'static str,
}
#[derive(Debug, Clone)]
pub struct AppliedMigration {
pub version: i64,
pub description: String,
pub applied_at: DateTime<Utc>,
}
#[derive(Debug)]
pub struct MigrationError {
pub version: i64,
pub description: String,
pub cause: String,
}
impl std::fmt::Display for MigrationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "migration v{} ({}) failed: {}", self.version, self.description, self.cause)
}
}
impl std::error::Error for MigrationError {}
#[cfg(any(feature = "sqlite-memory", feature = "database-memory"))]
fn validate_registry_table(name: &str) -> Result<(), adk_core::AdkError> {
let mut chars = name.chars();
if name.len() > 63
|| !chars.next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
|| !chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
{
return Err(adk_core::AdkError::memory(format!(
"invalid migration registry table `{name}`: use an ASCII identifier of at most 63 bytes \
starting with a letter or underscore, followed by letters, digits or underscores"
)));
}
Ok(())
}
#[cfg(any(feature = "sqlite-memory", feature = "database-memory"))]
macro_rules! sql_migration_body {
(
exec: $exec:expr,
begin: $begin:expr,
detect: $detect:expr,
registry_table: $registry_table:expr,
steps: $steps:expr,
int_type: $int_type:expr $(,)?
) => {{
let registry_table: &str = $registry_table;
super::validate_registry_table(registry_table)?;
let steps: &[(i64, &str, &str)] = $steps;
let create_sql = format!(
"CREATE TABLE IF NOT EXISTS {registry_table} (\
version {} PRIMARY KEY, \
description TEXT NOT NULL, \
applied_at TEXT NOT NULL\
)",
$int_type
);
sqlx::query(sqlx::AssertSqlSafe(create_sql)).execute($exec).await.map_err(|e| {
adk_core::AdkError::memory(format!("migration registry creation failed: {e}"))
})?;
let max_sql = format!("SELECT COALESCE(MAX(version), 0) AS max_v FROM {registry_table}");
let row =
sqlx::query(sqlx::AssertSqlSafe(max_sql)).fetch_one($exec).await.map_err(|e| {
adk_core::AdkError::memory(format!("migration registry read failed: {e}"))
})?;
let mut max_applied: i64 = row.try_get("max_v").map_err(|e| {
adk_core::AdkError::memory(format!("migration registry read failed: {e}"))
})?;
if max_applied == 0 {
let existing = $detect.await?;
if existing {
if let Some(&(v, desc, _)) = steps.first() {
let now = Utc::now().to_rfc3339();
let ins = format!(
"INSERT INTO {registry_table} \
(version, description, applied_at) \
VALUES ($1, $2, $3) ON CONFLICT (version) DO NOTHING"
);
sqlx::query(sqlx::AssertSqlSafe(ins))
.bind(v)
.bind(desc)
.bind(&now)
.execute($exec)
.await
.map_err(|e| {
adk_core::AdkError::memory(format!(
"{}",
MigrationError {
version: v,
description: desc.to_string(),
cause: e.to_string(),
}
))
})?;
max_applied = v;
}
}
}
let max_compiled = steps.last().map(|s| s.0).unwrap_or(0);
if max_applied > max_compiled {
return Err(adk_core::AdkError::memory(format!(
"schema version mismatch: database is at v{max_applied} \
but code only knows up to v{max_compiled}. \
Upgrade your ADK version."
)));
}
for &(version, description, sql) in steps {
if version <= max_applied {
continue;
}
let mut tx = $begin.await.map_err(|e| {
adk_core::AdkError::memory(format!(
"{}",
MigrationError {
version,
description: description.to_string(),
cause: format!("transaction begin failed: {e}"),
}
))
})?;
let applied_sql =
format!("SELECT COUNT(*) AS n FROM {registry_table} WHERE version = $1");
let applied: i64 = sqlx::query(sqlx::AssertSqlSafe(applied_sql))
.bind(version)
.fetch_one(&mut *tx)
.await
.and_then(|row| row.try_get("n"))
.map_err(|e| {
adk_core::AdkError::memory(format!("migration registry read failed: {e}"))
})?;
if applied > 0 {
tx.rollback().await.map_err(|e| {
adk_core::AdkError::memory(format!("transaction rollback failed: {e}"))
})?;
continue;
}
sqlx::Executor::execute(&mut *tx, sqlx::raw_sql(sqlx::AssertSqlSafe(sql)))
.await
.map_err(|e| {
adk_core::AdkError::memory(format!(
"{}",
MigrationError {
version,
description: description.to_string(),
cause: e.to_string(),
}
))
})?;
let now = Utc::now().to_rfc3339();
let rec = format!(
"INSERT INTO {registry_table} \
(version, description, applied_at) \
VALUES ($1, $2, $3)"
);
sqlx::query(sqlx::AssertSqlSafe(rec))
.bind(version)
.bind(description)
.bind(&now)
.execute(&mut *tx)
.await
.map_err(|e| {
adk_core::AdkError::memory(format!(
"{}",
MigrationError {
version,
description: description.to_string(),
cause: format!("registry record failed: {e}"),
}
))
})?;
tx.commit().await.map_err(|e| {
adk_core::AdkError::memory(format!(
"{}",
MigrationError {
version,
description: description.to_string(),
cause: format!("transaction commit failed: {e}"),
}
))
})?;
}
Ok(())
}};
}
#[cfg(any(feature = "sqlite-memory", feature = "database-memory"))]
macro_rules! impl_sql_migration_runner {
(
$mod_name:ident,
$pool_ty:ty,
$conn_ty:ty,
$int_type:expr,
$begin_sql:expr,
$missing_table:expr
) => {
pub mod $mod_name {
use super::MigrationError;
use chrono::Utc;
use sqlx::{Connection, Row};
use std::future::Future;
use std::pin::Pin;
pub async fn run_sql_migrations<F, Fut>(
pool: &$pool_ty,
registry_table: &str,
steps: &[(i64, &str, &str)],
detect_existing: F,
) -> Result<(), adk_core::AdkError>
where
F: FnOnce() -> Fut,
Fut: Future<Output = Result<bool, adk_core::AdkError>>,
{
sql_migration_body!(
exec: pool,
begin: async {
match $begin_sql {
Some(statement) => pool.begin_with(statement).await,
None => pool.begin().await,
}
},
detect: detect_existing(),
registry_table: registry_table,
steps: steps,
int_type: $int_type,
)
}
pub async fn run_sql_migrations_on_connection<F>(
conn: &mut $conn_ty,
registry_table: &str,
steps: &[(i64, &str, &str)],
detect_existing: F,
) -> Result<(), adk_core::AdkError>
where
F: FnOnce(
&mut $conn_ty,
) -> Pin<
Box<dyn Future<Output = Result<bool, adk_core::AdkError>> + Send + '_>,
>,
{
sql_migration_body!(
exec: &mut *conn,
begin: async {
match $begin_sql {
Some(statement) => conn.begin_with(statement).await,
None => conn.begin().await,
}
},
detect: detect_existing(&mut *conn),
registry_table: registry_table,
steps: steps,
int_type: $int_type,
)
}
pub async fn sql_schema_version(
pool: &$pool_ty,
registry_table: &str,
) -> Result<i64, adk_core::AdkError> {
super::validate_registry_table(registry_table)?;
let sql =
format!("SELECT COALESCE(MAX(version), 0) AS max_v FROM {registry_table}");
let missing_table: fn(&dyn sqlx::error::DatabaseError) -> bool = $missing_table;
let row = match sqlx::query(sqlx::AssertSqlSafe(sql)).fetch_one(pool).await {
Ok(row) => row,
Err(sqlx::Error::Database(error)) if missing_table(error.as_ref()) => {
return Ok(0);
}
Err(e) => {
return Err(adk_core::AdkError::memory(format!(
"migration registry read failed: {e}"
)));
}
};
row.try_get("max_v").map_err(|e| {
adk_core::AdkError::memory(format!("migration registry read failed: {e}"))
})
}
}
};
}
#[cfg(feature = "sqlite-memory")]
impl_sql_migration_runner!(
sqlite_runner,
sqlx::SqlitePool,
sqlx::SqliteConnection,
"INTEGER",
Some("BEGIN IMMEDIATE"),
|error| error.message().starts_with("no such table")
);
#[cfg(feature = "database-memory")]
impl_sql_migration_runner!(
pg_runner,
sqlx::PgPool,
sqlx::PgConnection,
"BIGINT",
None::<&str>,
|error| { error.code().as_deref() == Some("42P01") }
);