175 lines
6.5 KiB
C#
175 lines
6.5 KiB
C#
using System.Linq.Expressions;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.EntityFrameworkCore.Design;
|
|
using NodaTime;
|
|
using Npgsql;
|
|
using Quartz;
|
|
|
|
namespace DysonNetwork.Sphere;
|
|
|
|
public abstract class ModelBase
|
|
{
|
|
public Instant CreatedAt { get; set; }
|
|
public Instant UpdatedAt { get; set; }
|
|
public Instant? DeletedAt { get; set; }
|
|
}
|
|
|
|
public class AppDatabase(
|
|
DbContextOptions<AppDatabase> options,
|
|
IConfiguration configuration
|
|
) : DbContext(options)
|
|
{
|
|
public DbSet<Account.Account> Accounts { get; set; }
|
|
public DbSet<Account.Profile> AccountProfiles { get; set; }
|
|
public DbSet<Account.AccountContact> AccountContacts { get; set; }
|
|
public DbSet<Account.AccountAuthFactor> AccountAuthFactors { get; set; }
|
|
public DbSet<Account.Relationship> AccountRelationships { get; set; }
|
|
public DbSet<Auth.Session> AuthSessions { get; set; }
|
|
public DbSet<Auth.Challenge> AuthChallenges { get; set; }
|
|
public DbSet<Storage.CloudFile> Files { get; set; }
|
|
|
|
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
|
|
{
|
|
var dataSourceBuilder = new NpgsqlDataSourceBuilder(configuration.GetConnectionString("App"));
|
|
dataSourceBuilder.EnableDynamicJson();
|
|
dataSourceBuilder.UseNodaTime();
|
|
var dataSource = dataSourceBuilder.Build();
|
|
|
|
optionsBuilder.UseNpgsql(
|
|
dataSource,
|
|
opt => opt.UseNodaTime()
|
|
).UseSnakeCaseNamingConvention();
|
|
|
|
base.OnConfiguring(optionsBuilder);
|
|
}
|
|
|
|
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
|
{
|
|
base.OnModelCreating(modelBuilder);
|
|
|
|
modelBuilder.Entity<Account.Account>()
|
|
.HasOne(a => a.Profile)
|
|
.WithOne(p => p.Account)
|
|
.HasForeignKey<Account.Profile>(p => p.Id);
|
|
|
|
modelBuilder.Entity<Account.Relationship>()
|
|
.HasKey(r => new { FromAccountId = r.AccountId, ToAccountId = r.RelatedId });
|
|
modelBuilder.Entity<Account.Relationship>()
|
|
.HasOne(r => r.Account)
|
|
.WithMany(a => a.OutgoingRelationships)
|
|
.HasForeignKey(r => r.AccountId);
|
|
modelBuilder.Entity<Account.Relationship>()
|
|
.HasOne(r => r.Related)
|
|
.WithMany(a => a.IncomingRelationships)
|
|
.HasForeignKey(r => r.RelatedId);
|
|
|
|
// Automatically apply soft-delete filter to all entities inheriting BaseModel
|
|
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
|
|
{
|
|
if (typeof(ModelBase).IsAssignableFrom(entityType.ClrType))
|
|
{
|
|
var method = typeof(AppDatabase)
|
|
.GetMethod(nameof(SetSoftDeleteFilter),
|
|
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static)!
|
|
.MakeGenericMethod(entityType.ClrType);
|
|
|
|
method.Invoke(null, [modelBuilder]);
|
|
}
|
|
}
|
|
}
|
|
|
|
private static void SetSoftDeleteFilter<TEntity>(ModelBuilder modelBuilder)
|
|
where TEntity : ModelBase
|
|
{
|
|
modelBuilder.Entity<TEntity>().HasQueryFilter(e => e.DeletedAt == null);
|
|
}
|
|
|
|
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
|
|
{
|
|
var now = SystemClock.Instance.GetCurrentInstant();
|
|
|
|
foreach (var entry in ChangeTracker.Entries<ModelBase>())
|
|
{
|
|
switch (entry.State)
|
|
{
|
|
case EntityState.Added:
|
|
entry.Entity.CreatedAt = now;
|
|
entry.Entity.UpdatedAt = now;
|
|
break;
|
|
case EntityState.Modified:
|
|
entry.Entity.UpdatedAt = now;
|
|
break;
|
|
case EntityState.Deleted:
|
|
entry.State = EntityState.Modified;
|
|
entry.Entity.DeletedAt = now;
|
|
break;
|
|
case EntityState.Detached:
|
|
case EntityState.Unchanged:
|
|
default:
|
|
break;
|
|
}
|
|
}
|
|
|
|
return await base.SaveChangesAsync(cancellationToken);
|
|
}
|
|
}
|
|
|
|
public class AppDatabaseRecyclingJob(AppDatabase db, ILogger<AppDatabaseRecyclingJob> logger) : IJob
|
|
{
|
|
public async Task Execute(IJobExecutionContext context)
|
|
{
|
|
logger.LogInformation("Deleting soft-deleted records...");
|
|
|
|
var now = SystemClock.Instance.GetCurrentInstant();
|
|
var threshold = now - Duration.FromDays(7);
|
|
|
|
var entityTypes = db.Model.GetEntityTypes()
|
|
.Where(t => typeof(ModelBase).IsAssignableFrom(t.ClrType) && t.ClrType != typeof(ModelBase))
|
|
.Select(t => t.ClrType);
|
|
|
|
foreach (var entityType in entityTypes)
|
|
{
|
|
var set = (IQueryable)db.GetType().GetMethod(nameof(DbContext.Set), Type.EmptyTypes)!
|
|
.MakeGenericMethod(entityType).Invoke(db, null)!;
|
|
var parameter = Expression.Parameter(entityType, "e");
|
|
var property = Expression.Property(parameter, nameof(ModelBase.DeletedAt));
|
|
var condition = Expression.LessThan(property, Expression.Constant(threshold, typeof(Instant?)));
|
|
var notNull = Expression.NotEqual(property, Expression.Constant(null, typeof(Instant?)));
|
|
var finalCondition = Expression.AndAlso(notNull, condition);
|
|
var lambda = Expression.Lambda(finalCondition, parameter);
|
|
|
|
var queryable = set.Provider.CreateQuery(
|
|
Expression.Call(
|
|
typeof(Queryable),
|
|
"Where",
|
|
[entityType],
|
|
set.Expression,
|
|
Expression.Quote(lambda)
|
|
)
|
|
);
|
|
|
|
var toListAsync = typeof(EntityFrameworkQueryableExtensions)
|
|
.GetMethod(nameof(EntityFrameworkQueryableExtensions.ToListAsync))!
|
|
.MakeGenericMethod(entityType);
|
|
|
|
var items = await (dynamic)toListAsync.Invoke(null, [queryable, CancellationToken.None])!;
|
|
db.RemoveRange(items);
|
|
}
|
|
|
|
await db.SaveChangesAsync();
|
|
}
|
|
}
|
|
|
|
public class AppDatabaseFactory : IDesignTimeDbContextFactory<AppDatabase>
|
|
{
|
|
public AppDatabase CreateDbContext(string[] args)
|
|
{
|
|
var configuration = new ConfigurationBuilder()
|
|
.SetBasePath(Directory.GetCurrentDirectory())
|
|
.AddJsonFile("appsettings.json")
|
|
.Build();
|
|
|
|
var optionsBuilder = new DbContextOptionsBuilder<AppDatabase>();
|
|
return new AppDatabase(optionsBuilder.Options, configuration);
|
|
}
|
|
} |