Skip to content

Commit

Permalink
Merge pull request #1822 from Kobzol/db-migrations-tx
Browse files Browse the repository at this point in the history
Use a transaction when applying migrations
  • Loading branch information
ehuss committed Jul 2, 2024
2 parents 0ddb063 + 6ca524e commit 989e03c
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 10 deletions.
23 changes: 14 additions & 9 deletions src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ fn cert() {
make_certificates();
}

pub async fn run_migrations(client: &DbClient) -> anyhow::Result<()> {
pub async fn run_migrations(client: &mut DbClient) -> anyhow::Result<()> {
client
.execute(
"CREATE TABLE IF NOT EXISTS database_versions (
Expand Down Expand Up @@ -182,17 +182,22 @@ pub async fn run_migrations(client: &DbClient) -> anyhow::Result<()> {

for (idx, migration) in MIGRATIONS.iter().enumerate() {
if idx >= migration_idx {
client
.execute(*migration, &[])
let tx = client
.transaction()
.await
.context("Cannot create migration transactin")?;
tx.execute(*migration, &[])
.await
.with_context(|| format!("executing {}th migration", idx))?;
client
.execute(
"UPDATE database_versions SET migration_counter = $1",
&[&(idx as i32 + 1)],
)
tx.execute(
"UPDATE database_versions SET migration_counter = $1",
&[&(idx as i32 + 1)],
)
.await
.with_context(|| format!("updating migration counter to {}", idx))?;
tx.commit()
.await
.with_context(|| format!("updating migration counter to {}", idx))?;
.context("Cannot commit migration transaction")?;
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ async fn serve_req(

async fn run_server(addr: SocketAddr) -> anyhow::Result<()> {
let pool = db::ClientPool::new();
db::run_migrations(&*pool.get().await)
db::run_migrations(&mut *pool.get().await)
.await
.context("database migrations")?;

Expand Down

0 comments on commit 989e03c

Please sign in to comment.