From d782d8469cde085f9144bf0405725bc703e246b7 Mon Sep 17 00:00:00 2001 From: George Wu Date: Wed, 18 Feb 2026 17:56:06 -0800 Subject: [PATCH] fix: always apply database schema on startup Previously, the application only applied the schema if auth.users table didn't exist. This caused issues when upgrading - new schema elements (like storage.trash_items view) weren't created on existing databases. Now the schema is applied on every startup. Since schema.sql uses 'IF NOT EXISTS' and 'CREATE OR REPLACE', it's safe to run repeatedly. --- src/infrastructure/db.rs | 40 ++++++++++------------------------------ 1 file changed, 10 insertions(+), 30 deletions(-) diff --git a/src/infrastructure/db.rs b/src/infrastructure/db.rs index 4c2b3bfb..8c4d6f41 100644 --- a/src/infrastructure/db.rs +++ b/src/infrastructure/db.rs @@ -1,6 +1,6 @@ use crate::common::config::AppConfig; use anyhow::Result; -use sqlx::{PgPool, Row, postgres::PgPoolOptions}; +use sqlx::{PgPool, postgres::PgPoolOptions}; use std::time::Duration; pub async fn create_database_pool(config: &AppConfig) -> Result { @@ -37,25 +37,16 @@ pub async fn create_database_pool(config: &AppConfig) -> Result { Ok(_) => { tracing::info!("PostgreSQL connection established successfully"); - if !tables_exist(&pool).await { - tracing::warn!("Database tables do not exist. Auto-applying schema..."); - if let Err(e) = apply_schema(&pool).await { - return Err(anyhow::anyhow!( - "Database schema could not be applied: {}. \ - Run manually: psql -f db/schema.sql", - e - )); - } - - // Verify tables were actually created - if !tables_exist(&pool).await { - return Err(anyhow::anyhow!( - "Database schema was applied but tables still missing. \ - Check db/schema.sql for errors." - )); - } - tracing::info!("Database schema applied and verified successfully"); + // Always apply schema - it's idempotent (uses IF NOT EXISTS and CREATE OR REPLACE) + tracing::info!("Applying database schema..."); + if let Err(e) = apply_schema(&pool).await { + return Err(anyhow::anyhow!( + "Database schema could not be applied: {}. \ + Run manually: psql -f db/schema.sql", + e + )); } + tracing::info!("Database schema applied successfully"); return Ok(pool); } @@ -91,17 +82,6 @@ pub async fn create_database_pool(config: &AppConfig) -> Result { )) } -/// Check whether the core auth tables exist in the database. -async fn tables_exist(pool: &PgPool) -> bool { - sqlx::query( - "SELECT EXISTS (SELECT 1 FROM pg_tables WHERE schemaname = 'auth' AND tablename = 'users')", - ) - .fetch_one(pool) - .await - .map(|row| row.get::(0)) - .unwrap_or(false) -} - /// Apply the embedded schema.sql to the database. /// First tries `raw_sql` (simple query protocol). If that fails, falls back /// to splitting the SQL into individual statements and executing them one by one.