From a01f80bb148a099cf9cd028709140ac9d8e17bde Mon Sep 17 00:00:00 2001 From: MarcWieland Date: Thu, 25 Jun 2026 20:59:10 +0200 Subject: [PATCH] fixed --- timetracker.Server/Program.cs | 61 +++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/timetracker.Server/Program.cs b/timetracker.Server/Program.cs index fedcd48..2eb20e7 100644 --- a/timetracker.Server/Program.cs +++ b/timetracker.Server/Program.cs @@ -133,6 +133,67 @@ using (var scope = app.Services.CreateScope()) { var factory = scope.ServiceProvider.GetRequiredService>(); await using var db = await factory.CreateDbContextAsync(); + + if (dbProvider.Equals("PostgreSQL", StringComparison.OrdinalIgnoreCase)) + { + try + { + var conn = db.Database.GetDbConnection(); + if (conn.State != System.Data.ConnectionState.Open) + { + await conn.OpenAsync(); + } + + // Check if AppSettings table already exists + using (var cmdCheck = conn.CreateCommand()) + { + cmdCheck.CommandText = "SELECT EXISTS (SELECT FROM pg_tables WHERE schemaname = 'public' AND tablename = 'AppSettings');"; + var appSettingsExists = (bool)(await cmdCheck.ExecuteScalarAsync() ?? false); + + if (appSettingsExists) + { + // Ensure __EFMigrationsHistory table exists + using (var cmdCreateHistory = conn.CreateCommand()) + { + cmdCreateHistory.CommandText = @" + CREATE TABLE IF NOT EXISTS ""__EFMigrationsHistory"" ( + ""MigrationId"" character varying(150) NOT NULL, + ""ProductVersion"" character varying(32) NOT NULL, + CONSTRAINT ""PK___EFMigrationsHistory"" PRIMARY KEY (""MigrationId"") + );"; + await cmdCreateHistory.ExecuteNonQueryAsync(); + } + + // Check if the initial migration is already recorded + using (var cmdCheckHistory = conn.CreateCommand()) + { + cmdCheckHistory.CommandText = @"SELECT COUNT(*) FROM ""__EFMigrationsHistory"" WHERE ""MigrationId"" = '20260520133634_Initial';"; + var historyCount = Convert.ToInt32(await cmdCheckHistory.ExecuteScalarAsync() ?? 0); + + if (historyCount == 0) + { + // Seed the history table with the migrations that were already created by EnsureCreated in older versions + using (var cmdInsertHistory = conn.CreateCommand()) + { + cmdInsertHistory.CommandText = @" + INSERT INTO ""__EFMigrationsHistory"" (""MigrationId"", ""ProductVersion"") VALUES + ('20260520133634_Initial', '10.0.9'), + ('20260520200000_AddPublicHolidays', '10.0.9'), + ('20260522081459_AddMultiUser', '10.0.9'), + ('20260607213215_AddFlexTimeAndHolidayState', '10.0.9');"; + await cmdInsertHistory.ExecuteNonQueryAsync(); + } + } + } + } + } + } + catch (Exception ex) + { + Console.WriteLine($"Fehler beim Vorbereiten der PostgreSQL Migrationshistorie: {ex.Message}"); + } + } + await db.Database.MigrateAsync(); }