diff --git a/sqlx-postgres/src/migrate.rs b/sqlx-postgres/src/migrate.rs index c37e92f4d6..01f7ee7952 100644 --- a/sqlx-postgres/src/migrate.rs +++ b/sqlx-postgres/src/migrate.rs @@ -276,10 +276,19 @@ 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(); + // note: this would _not_ match the split if the file starts with `-- split-migration` + // because it requires a new line prefix, but that doesn't really make sense anyway so it's fine + let split_migrations = sql.split("\n-- split-migration\n"); + 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( diff --git a/tests/postgres/migrate.rs b/tests/postgres/migrate.rs index 636dffe860..3ca5f3fb06 100644 --- a/tests/postgres/migrate.rs +++ b/tests/postgres/migrate.rs @@ -85,6 +85,26 @@ async fn no_tx(mut conn: PoolConnection) -> anyhow::Result<()> { Ok(()) } + +#[sqlx::test(migrations = false)] +async fn split(mut conn: PoolConnection) -> 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(); diff --git a/tests/postgres/migrations_split/0_create_index.sql b/tests/postgres/migrations_split/0_create_index.sql new file mode 100644 index 0000000000..f8bc50ecdc --- /dev/null +++ b/tests/postgres/migrations_split/0_create_index.sql @@ -0,0 +1,8 @@ +-- no-transaction + +CREATE TABLE test_table (x int); +-- split-migration +CREATE INDEX CONCURRENTLY test_table_x_idx ON test_table (x); +-- split-migration +INSERT INTO test_table (x) VALUES (1); +-- prove that you can have a comment that won't split -- split-migration DROP TABLE does_not_exist;