using DysonNetwork.Shared.Models; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; using Microsoft.Extensions.Configuration; using NodaTime; namespace DysonNetwork.Pass.Data; public abstract class ModelBase { public Instant CreatedAt { get; set; } public Instant UpdatedAt { get; set; } public Instant? DeletedAt { get; set; } } public class AppDatabase( DbContextOptions options, IConfiguration configuration ) : DbContext(options) { public DbSet PermissionNodes { get; set; } public DbSet PermissionGroups { get; set; } public DbSet PermissionGroupMembers { get; set; } public DbSet Accounts { get; set; } public DbSet AccountConnections { get; set; } public DbSet AccountProfiles { get; set; } public DbSet AccountContacts { get; set; } public DbSet AccountAuthFactors { get; set; } public DbSet AccountRelationships { get; set; } public DbSet AuthSessions { get; set; } public DbSet AuthChallenges { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseNpgsql( configuration.GetConnectionString("App"), opt => opt .UseNodaTime() ).UseSnakeCaseNamingConvention(); base.OnConfiguring(optionsBuilder); } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity() .HasKey(pg => new { pg.GroupId, pg.Actor }); modelBuilder.Entity() .HasKey(r => new { FromAccountId = r.AccountId, ToAccountId = r.RelatedId }); } public override async Task SaveChangesAsync(CancellationToken cancellationToken = default) { var now = SystemClock.Instance.GetCurrentInstant(); foreach (var entry in ChangeTracker.Entries()) { if (entry.State == EntityState.Added) { entry.Entity.CreatedAt = now; entry.Entity.UpdatedAt = now; } else if (entry.State == EntityState.Modified) { entry.Entity.UpdatedAt = now; } else if (entry.State == EntityState.Deleted) { entry.State = EntityState.Modified; entry.Entity.DeletedAt = now; } } return await base.SaveChangesAsync(cancellationToken); } } public class AppDatabaseFactory : IDesignTimeDbContextFactory { public AppDatabase CreateDbContext(string[] args) { var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json") .Build(); var optionsBuilder = new DbContextOptionsBuilder(); return new AppDatabase(optionsBuilder.Options, configuration); } }