Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(postgres): allow running multiple statements in no tx migrations #3694

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions sqlx-postgres/src/migrate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -276,10 +276,17 @@ async fn execute_migration(
conn: &mut PgConnection,
migration: &Migration,
) -> Result<(), MigrateError> {
let _ = conn
.execute(&*migration.sql)
.await
.map_err(|e| MigrateError::ExecuteMigration(e, migration.version))?;
let sql = migration.sql.trim();
let split_migrations = sql.split("/* sqlx: split */");
for part in split_migrations {
if part.trim().is_empty() {
continue;
}
let _ = conn
.execute(&*part.trim())
.await
.map_err(|e| MigrateError::ExecuteMigration(e, migration.version))?;
}

// language=SQL
let _ = query(
Expand Down
20 changes: 20 additions & 0 deletions tests/postgres/migrate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,26 @@ async fn no_tx(mut conn: PoolConnection<Postgres>) -> anyhow::Result<()> {
Ok(())
}


#[sqlx::test(migrations = false)]
async fn split(mut conn: PoolConnection<Postgres>) -> anyhow::Result<()> {
clean_up(&mut conn).await?;
let migrator = Migrator::new(Path::new("tests/postgres/migrations_split")).await?;

// run migration
migrator.run(&mut conn).await?;

// check outcome
let res: i32 = conn
.fetch_one("SELECT * FROM test_table")
.await?
.get(0);

assert_eq!(res, 1);

Ok(())
}

/// Ensure that we have a clean initial state.
async fn clean_up(conn: &mut PgConnection) -> anyhow::Result<()> {
conn.execute("DROP DATABASE IF EXISTS test_db").await.ok();
Expand Down
7 changes: 7 additions & 0 deletions tests/postgres/migrations_split/0_create_table.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
-- no-transaction

CREATE TABLE test_table (x int);
/* sqlx: split */
CREATE INDEX CONCURRENTLY test_table_x_idx ON test_table (x);
/* sqlx: split */
INSERT INTO test_table (x) VALUES (1);