Added db migrations

This commit is contained in:
2026-01-05 21:54:15 +01:00
commit 0a57915447
20 changed files with 439 additions and 0 deletions

View File

@@ -0,0 +1,26 @@
using dc_bot.db.Model;
using dc_bot.db.Model.administration;
using dc_bot.db.Model.system;
using Microsoft.EntityFrameworkCore;
namespace dc_bot.db;
public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
public required DbSet<ExecutedMigration> ExecutedMigrations { get; set; }
public required DbSet<User> Users { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ExecutedMigration>(e =>
{
e.ToTable("_executed_migrations", "system");
e.HasKey(e => e.MigrationId);
});
modelBuilder.Entity<User>(e =>
{
e.ToTable("users", "administration");
});
}
}

View File

@@ -0,0 +1,74 @@
using System.Runtime.CompilerServices;
using dc_bot.db.Model.system;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace dc_bot.db;
public class MigrationService
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly string MigrationDirectory = Environment.GetEnvironmentVariable("DB_MIGRATION_DIR") ??
Path.Combine(AppContext.BaseDirectory, "Scripts");
public MigrationService(IServiceScopeFactory scopeFactory)
{
_scopeFactory = scopeFactory;
}
private List<string> GetMigrations()
{
if (!Directory.Exists(MigrationDirectory))
return new List<string>();
var files = Directory.GetFiles(MigrationDirectory, "*.sql")
.Select(Path.GetFileName)
.OrderBy(f => f)
.ToList();
return files;
}
public async Task Migrate()
{
using var scope = _scopeFactory.CreateScope();
var context = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var appliedMigrations = await context.ExecutedMigrations
.Select(m => m.MigrationId)
.ToListAsync();
var appliedMigrationNames = appliedMigrations
.Select(m => m.Replace(".sql", string.Empty))
.ToHashSet(StringComparer.OrdinalIgnoreCase);
var migrations = GetMigrations()
.Where(m => !appliedMigrationNames.Contains(m))
.ToList();
foreach (var migration in migrations)
{
try
{
var migrationPath = Path.Combine(MigrationDirectory, migration);
var sql = await File.ReadAllTextAsync(migrationPath);
await context.Database.ExecuteSqlRawAsync(sql);
var executedMigration = new ExecutedMigration
{
MigrationId = migration,
Created = DateTime.UtcNow,
Updated = DateTime.UtcNow
};
context.ExecutedMigrations.Add(executedMigration);
await context.SaveChangesAsync();
}
catch (Exception ex)
{
Console.WriteLine($"Error applying migration {migration}: {ex.Message}");
throw;
}
}
}
}

View File

@@ -0,0 +1,9 @@
namespace dc_bot.db.Model;
public interface IDbModel
{
public bool Deleted { get; set; }
public Double EditorId { get; set; }
public DateTimeOffset Created { get; set; }
public DateTimeOffset Updated { get; set; }
}

View File

@@ -0,0 +1,12 @@
namespace dc_bot.db.Model.administration;
public class User : IDbModel
{
public Double Id { get; set; }
public required string KeycloakId { get; init; }
public bool Deleted { get; set; }
public double EditorId { get; set; }
public DateTimeOffset Created { get; set; }
public DateTimeOffset Updated { get; set; }
}

View File

@@ -0,0 +1,10 @@
using Microsoft.EntityFrameworkCore;
namespace dc_bot.db.Model.system;
public class ExecutedMigration
{
public required string MigrationId { get; set; }
public DateTimeOffset Created { get; set; }
public DateTimeOffset Updated { get; set; }
}

View File

@@ -0,0 +1,9 @@
CREATE SCHEMA IF NOT EXISTS public;
CREATE SCHEMA IF NOT EXISTS system;
CREATE TABLE IF NOT EXISTS system._executed_migrations
(
MigrationId VARCHAR(255) PRIMARY KEY,
Created timestamptz NOT NULL DEFAULT NOW(),
Updated timestamptz NOT NULL DEFAULT NOW()
);

View File

@@ -0,0 +1,37 @@
CREATE OR REPLACE FUNCTION public.history_trigger_function()
RETURNS TRIGGER AS
$$
DECLARE
schema_name TEXT;
history_table_name TEXT;
BEGIN
-- Construct the name of the history table based on the current table
schema_name := TG_TABLE_SCHEMA;
history_table_name := TG_TABLE_NAME || '_history';
IF (TG_OP = 'INSERT') THEN
RETURN NEW;
END IF;
-- Insert the old row into the history table on UPDATE or DELETE
IF (TG_OP = 'UPDATE' OR TG_OP = 'DELETE') THEN
EXECUTE format(
'INSERT INTO %I.%I SELECT ($1).*',
schema_name,
history_table_name
)
USING OLD;
END IF;
-- For UPDATE, update the UpdatedUtc column and return the new row
IF (TG_OP = 'UPDATE') THEN
NEW.updated := NOW(); -- Update the UpdatedUtc column
RETURN NEW;
END IF;
-- For DELETE, return OLD to allow the deletion
IF (TG_OP = 'DELETE') THEN
RETURN OLD;
END IF;
END;
$$ LANGUAGE plpgsql;

View File

@@ -0,0 +1,26 @@
CREATE SCHEMA IF NOT EXISTS administration;
CREATE TABLE IF NOT EXISTS administration.users
(
Id SERIAL PRIMARY KEY,
KeycloakId UUID NOT NULL,
-- for history
Deleted BOOLEAN NOT NULL DEFAULT FALSE,
EditorId INT NULL REFERENCES administration.users (Id),
Created timestamptz NOT NULL DEFAULT NOW(),
Updated timestamptz NOT NULL DEFAULT NOW(),
CONSTRAINT UC_KeycloakId UNIQUE (KeycloakId)
);
CREATE TABLE IF NOT EXISTS administration.users_history
(
LIKE administration.users
);
CREATE TRIGGER users_history_trigger
BEFORE INSERT OR UPDATE OR DELETE
ON administration.users
FOR EACH ROW
EXECUTE FUNCTION public.history_trigger_function();

View File

@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<None Update="Scripts\**">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="10.0.1" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.0" />
</ItemGroup>
</Project>