use migratrom::operations::create_table;
use migratrom::{ApplyOptions, ColumnDef, Migration, MigratromError, PrimaryKey, SqliteDialect};
use migratrom_sqlite::apply_migrations;
use sqlx::sqlite::SqlitePoolOptions;
use sqlx::{Row, SqlitePool};
async fn pool() -> SqlitePool {
SqlitePoolOptions::new()
.max_connections(1)
.connect("sqlite::memory:")
.await
.expect("connect in-memory sqlite")
}
fn users_migration() -> Migration {
let dialect = SqliteDialect;
let op = create_table(
"main",
"users",
&[
ColumnDef::new("id", "INTEGER"),
ColumnDef::new("email", "TEXT"),
],
Some(&PrimaryKey {
columns: vec!["id".into()],
}),
&dialect,
)
.expect("build create_table");
Migration::new(1, None, vec![op])
}
#[tokio::test]
async fn applies_then_skips_on_reapply() {
let pool = pool().await;
let opts = ApplyOptions::default();
let first = apply_migrations(&[users_migration()], &pool, &opts)
.await
.unwrap();
assert_eq!(first.applied, vec![1]);
let count: i64 =
sqlx::query("SELECT COUNT(*) FROM \"main\".sqlite_master WHERE name = 'users'")
.fetch_one(&pool)
.await
.unwrap()
.get(0);
assert_eq!(count, 1);
let second = apply_migrations(&[users_migration()], &pool, &opts)
.await
.unwrap();
assert!(second.applied.is_empty());
}
#[tokio::test]
async fn rejects_edited_applied_migration() {
let pool = pool().await;
let opts = ApplyOptions::default();
apply_migrations(&[users_migration()], &pool, &opts)
.await
.unwrap();
let dialect = SqliteDialect;
let edited_op = create_table(
"main",
"users",
&[ColumnDef::new("id", "INTEGER")],
Some(&PrimaryKey {
columns: vec!["id".into()],
}),
&dialect,
)
.unwrap();
let edited = Migration::new(1, None, vec![edited_op]);
let err = apply_migrations(&[edited], &pool, &opts).await.unwrap_err();
assert!(matches!(
err,
MigratromError::ChecksumMismatch { id: 1, .. }
));
}