Skip to content

Commit

Permalink
Run migration sql commands in a single database statement
Browse files Browse the repository at this point in the history
The stateful way of doing the transaction could potentially use a different database connection from the pool. This change avoids that issue.
  • Loading branch information
mpscholten committed May 24, 2022
1 parent c9794f2 commit 1ff977d
Showing 1 changed file with 7 additions and 10 deletions.
17 changes: 7 additions & 10 deletions IHP/SchemaMigration.hs
Original file line number Diff line number Diff line change
Expand Up @@ -43,19 +43,16 @@ runMigration :: (?modelContext :: ModelContext) => Migration -> IO ()
runMigration migration@Migration { revision, migrationFile } = do
migrationSql <- Text.readFile (cs $ migrationPath migration)

withTransaction do
sqlExec (fromString . cs $ migrationSql) ()
sqlExec "INSERT INTO schema_migrations (revision) VALUES (?)" [revision]
let fullSql = [trimming|
BEGIN;
${migrationSql}
INSERT INTO schema_migrations (revision) VALUES (?);
COMMIT;
|]
sqlExec (fromString . cs $ fullSql) [revision]

pure ()

withTransaction :: (?modelContext :: ModelContext) => IO a -> IO a
withTransaction block = do
_ <- sqlExec "BEGIN" ()
result <- block
_ <- sqlExec "COMMIT" ()
pure result

-- | Creates the @schema_migrations@ table if it doesn't exist yet
createSchemaMigrationsTable :: (?modelContext :: ModelContext) => IO ()
createSchemaMigrationsTable = do
Expand Down

0 comments on commit 1ff977d

Please sign in to comment.