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

Use a transaction when applying migrations #1822

Merged
merged 1 commit into from
Jul 2, 2024
Merged
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
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
Loading