DD.WellWorkover.Cloud/AsbCloudDb/EFExtensionsInitialization.cs

58 lines
2.1 KiB
C#
Raw Normal View History

using Microsoft.EntityFrameworkCore;
2023-10-22 19:37:23 +05:00
using System;
using System.Linq;
using Microsoft.EntityFrameworkCore.Infrastructure;
2023-12-07 09:08:25 +05:00
using System.Diagnostics;
2023-10-22 19:37:23 +05:00
namespace AsbCloudDb
{
public static class EFExtensionsInitialization
2023-10-22 19:37:23 +05:00
{
public static void EnsureCreatedAndMigrated(this DatabaseFacade db)
2023-10-22 19:37:23 +05:00
{
2024-02-05 10:38:57 +05:00
var connectionString = db.GetConnectionString();
Trace.TraceInformation($"connectionString: {connectionString}");
2023-10-22 19:37:23 +05:00
db.SetCommandTimeout(TimeSpan.FromMinutes(5));
if (db.EnsureCreated())
{
2023-12-07 09:08:25 +05:00
Trace.TraceInformation("Creating DB");
Console.WriteLine("Creating DB");
2023-10-22 19:37:23 +05:00
db.CreateMigrationTable();
db.WriteMigrationsInfo();
}
else
{
2023-12-07 09:08:25 +05:00
Trace.TraceInformation("Migrating DB");
2023-10-22 19:37:23 +05:00
db.SetCommandTimeout(TimeSpan.FromMinutes(20));
2023-12-07 09:08:25 +05:00
Console.WriteLine("db.Migrate()");
2023-10-22 19:37:23 +05:00
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);
}
}
}