Migration tool for SQLx that allows for arbitrary SQL/Rust execution within a transaction on the write connection.
```rust
use std::borrow::Cow; use asynctrait::asynctrait; use promad::{file_basename, Migration, Migrator, error::{Error, Result}}; use sqlx::{postgres::PgPoolOptions, PgPool, Postgres, Executor, Row}; use testcontainers::{clients, Container};
pub struct FirstMigration;
impl Migration
async fn up(
&self,
_read: &mut sqlx::PgConnection,
write: &mut sqlx::PgConnection,
) -> Result<()> {
sqlx::query("CREATE TABLE test (id INT PRIMARY KEY)")
.execute(write)
.await?;
Ok(())
}
async fn down(
&self,
_read: &mut sqlx::PgConnection,
write: &mut sqlx::PgConnection,
) -> Result<()> {
sqlx::query("DROP TABLE test")
.execute(write)
.await?;
Ok(())
}
}
let docker = clients::Cli::default(); let pgsql = docker.run(testcontainers::images::postgres::Postgres::default()); let port = pgsql.gethostport_ipv4(5432); let pool = PgPoolOptions::new() .connect(&format!( "postgres://postgres:postgres@localhost:{}/postgres", port )) .await.unwrap();
let mut migrator = Migrator::create(pool.clone()); migrator.addmigration(Box::new(FirstMigration)); migrator.applyall().await.unwrap();
// Check that the table exists. let mut conn = pool.acquire().await.unwrap();
let row = sqlx::query("SELECT EXISTS (SELECT FROM informationschema.tables WHERE tableschema = 'public' AND tablename = 'test')") .fetchone(&mut conn) .await.unwrap();
assert!(row.get::
migrator.revert_all().await.unwrap();
let row = sqlx::query("SELECT EXISTS (SELECT FROM informationschema.tables WHERE tableschema = 'public' AND tablename = 'test')") .fetchone(&mut conn) .await.unwrap();
assert!(!row.get::
```