Restore database initialization script

This commit is contained in:
Frolov-Nikita 2023-10-22 19:37:23 +05:00
parent c0c94cf423
commit d63e6a7ba6
No known key found for this signature in database
GPG Key ID: 719E3386D12B0760
2 changed files with 54 additions and 2 deletions

View File

@ -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);
}
}
}

View File

@ -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<IAsbCloudDbContext>();
context.Database.SetCommandTimeout(TimeSpan.FromMinutes(5));
context.Database.Migrate();
context.Database.EnshureCreatedAndMigrated();
// TODO: Сделать инициализацию кеша телеметрии более явной.
_ = provider.GetRequiredService<TelemetryDataCache<TelemetryDataSaubDto>>();