From 39676fe94ae3fce9964969110a8dd5a9133f1f8f Mon Sep 17 00:00:00 2001 From: 409 <409dev@protonmail.com> Date: Tue, 22 Jul 2025 18:11:41 +0200 Subject: [PATCH] fix postgres `database ... already exists` error --- backend/src/lib/outbound/postgres.rs | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/backend/src/lib/outbound/postgres.rs b/backend/src/lib/outbound/postgres.rs index 1b7ef7b..71cc8dd 100644 --- a/backend/src/lib/outbound/postgres.rs +++ b/backend/src/lib/outbound/postgres.rs @@ -75,11 +75,20 @@ impl Postgres { .await .context("Failed to connect to the PostgreSQL database")?; - // If this fails it's probably because the database already exists, which is exactly what - // we want - let _ = sqlx::query(&format!("CREATE DATABASE {}", config.database_name)) - .execute(&mut connection) - .await; + match sqlx::query("SELECT datname FROM pg_database WHERE datname = $1") + .bind(&config.database_name) + .fetch_one(&mut connection) + .await + { + Ok(_) => (), + Err(sqlx::Error::RowNotFound) => { + sqlx::query(&format!("CREATE DATABASE {}", config.database_name)) + .execute(&mut connection) + .await?; + } + Err(e) => return Err(e.into()), + }; + connection.close().await?; let pool = PgPoolOptions::new()