From d63e6a7ba6e6cdc5f754a222af71efc5cd97e6a1 Mon Sep 17 00:00:00 2001 From: Frolov-Nikita Date: Sun, 22 Oct 2023 19:37:23 +0500 Subject: [PATCH] Restore database initialization script --- AsbCloudDb/EFExtentionsInnitialization.cs | 50 +++++++++++++++++++++++ AsbCloudInfrastructure/Startup.cs | 6 ++- 2 files changed, 54 insertions(+), 2 deletions(-) create mode 100644 AsbCloudDb/EFExtentionsInnitialization.cs diff --git a/AsbCloudDb/EFExtentionsInnitialization.cs b/AsbCloudDb/EFExtentionsInnitialization.cs new file mode 100644 index 00000000..110a75ae --- /dev/null +++ b/AsbCloudDb/EFExtentionsInnitialization.cs @@ -0,0 +1,50 @@ +using Microsoft.EntityFrameworkCore; +using System; +using System.Linq; +using Microsoft.EntityFrameworkCore.Infrastructure; + +namespace AsbCloudDb +{ + public static class EFExtentionsInnitialization + { + public static void EnshureCreatedAndMigrated(this DatabaseFacade db) + { + db.SetCommandTimeout(TimeSpan.FromMinutes(5)); + if (db.EnsureCreated()) + { + db.CreateMigrationTable(); + db.WriteMigrationsInfo(); + } + else + { + db.SetCommandTimeout(TimeSpan.FromMinutes(20)); + db.Migrate(); + } + } + + private static void CreateMigrationTable(this DatabaseFacade db) + { + var sqlCreateMigrationTable = + $"CREATE TABLE public.\"__EFMigrationsHistory\" " + + $"(\"MigrationId\" varchar(150) NOT NULL, " + + $" \"ProductVersion\" varchar(32) NOT NULL, " + + $" CONSTRAINT \"PK___EFMigrationsHistory\" PRIMARY KEY (\"MigrationId\"));"; + db.ExecuteSqlRaw(sqlCreateMigrationTable); + } + + private static void WriteMigrationsInfo(this DatabaseFacade db) + { + var efVersion = db.GetType().Assembly.GetName().Version!; + var efVersionString = $"{efVersion.Major}.{efVersion.Minor}.{efVersion.Build}"; + + var migrations = db.GetPendingMigrations() + .Select(migration => $" ('{migration}', '{efVersionString}')"); + + var sqlAddLastMigration = + $"INSERT INTO public.\"__EFMigrationsHistory\" " + + $"(\"MigrationId\", \"ProductVersion\") " + + $"VALUES {string.Join(',', migrations)};"; + db.ExecuteSqlRaw(sqlAddLastMigration); + } + } +} diff --git a/AsbCloudInfrastructure/Startup.cs b/AsbCloudInfrastructure/Startup.cs index 9aff9ca9..240c8892 100644 --- a/AsbCloudInfrastructure/Startup.cs +++ b/AsbCloudInfrastructure/Startup.cs @@ -12,6 +12,9 @@ using AsbCloudInfrastructure.Background; using AsbCloudApp.Data.SAUB; using AsbCloudInfrastructure.Services.SAUB; using AsbCloudInfrastructure.Services.Subsystems; +using System.Linq; +using DocumentFormat.OpenXml.InkML; +using AsbCloudDb; namespace AsbCloudInfrastructure { @@ -23,8 +26,7 @@ namespace AsbCloudInfrastructure var provider = scope.ServiceProvider; var context = provider.GetRequiredService(); - context.Database.SetCommandTimeout(TimeSpan.FromMinutes(5)); - context.Database.Migrate(); + context.Database.EnshureCreatedAndMigrated(); // TODO: Сделать инициализацию кеша телеметрии более явной. _ = provider.GetRequiredService>();