2024-08-18 20:16:38 -05:00
|
|
|
namespace SanctionsSearch.Worker.Persistence;
|
|
|
|
|
|
2024-08-20 23:42:20 -05:00
|
|
|
class AppDbContext(DbOptions options) : DbContext
|
2024-08-18 20:16:38 -05:00
|
|
|
{
|
2024-08-20 23:42:20 -05:00
|
|
|
private readonly DbOptions _options = options;
|
2024-08-18 20:16:38 -05:00
|
|
|
private SqliteConnection? _connection;
|
2024-08-20 23:42:20 -05:00
|
|
|
internal string DatabasePath { get; private set; } = string.Empty;
|
2024-08-18 20:16:38 -05:00
|
|
|
public DbSet<Sdn> Sdns { get; set; } = default!;
|
|
|
|
|
public DbSet<Address> Addresses { get; set; } = default!;
|
|
|
|
|
public DbSet<Alias> Aliases { get; set; } = default!;
|
|
|
|
|
public DbSet<Comment> Comments { get; set; } = default!;
|
|
|
|
|
|
|
|
|
|
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
|
|
|
|
|
{
|
2024-08-18 20:34:07 -05:00
|
|
|
var folder = Assembly.GetExecutingAssembly().Location;
|
|
|
|
|
var path = Path.GetDirectoryName(folder);
|
|
|
|
|
var dataDir = Path.Combine(path!, "Data");
|
2024-08-18 20:16:38 -05:00
|
|
|
|
|
|
|
|
if (Directory.Exists(dataDir) == false)
|
|
|
|
|
{
|
|
|
|
|
Directory.CreateDirectory(dataDir);
|
|
|
|
|
}
|
|
|
|
|
|
2024-08-20 23:42:20 -05:00
|
|
|
var dbPath = Path.Combine(dataDir, _options.DatabaseName);
|
|
|
|
|
DatabasePath = dbPath;
|
2024-08-18 20:16:38 -05:00
|
|
|
|
|
|
|
|
_connection = new SqliteConnection($"Data Source={dbPath}");
|
|
|
|
|
_connection.Open();
|
|
|
|
|
|
|
|
|
|
optionsBuilder.UseSqlite(_connection);
|
|
|
|
|
}
|
|
|
|
|
|
2024-08-20 23:42:20 -05:00
|
|
|
public async override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
|
2024-08-18 20:16:38 -05:00
|
|
|
{
|
2024-08-20 23:42:20 -05:00
|
|
|
// TODO: Use TimeProvider instead of DateTime.UtcNow
|
|
|
|
|
var now = DateTime.UtcNow;
|
|
|
|
|
|
|
|
|
|
foreach (var changedEntity in ChangeTracker.Entries())
|
|
|
|
|
{
|
|
|
|
|
if (changedEntity.Entity is Entity entity)
|
|
|
|
|
{
|
|
|
|
|
switch (changedEntity.State)
|
|
|
|
|
{
|
|
|
|
|
case EntityState.Added:
|
|
|
|
|
entity.CreatedAt = now;
|
|
|
|
|
entity.UpdatedAt = now;
|
|
|
|
|
break;
|
|
|
|
|
|
|
|
|
|
case EntityState.Modified:
|
|
|
|
|
Entry(entity).Property(x => x.CreatedAt).IsModified = false;
|
|
|
|
|
entity.UpdatedAt = now;
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return await base.SaveChangesAsync(cancellationToken);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async override ValueTask DisposeAsync()
|
|
|
|
|
{
|
|
|
|
|
if (_connection is not null)
|
|
|
|
|
{
|
|
|
|
|
await _connection.DisposeAsync();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
await base.DisposeAsync();
|
2024-08-18 20:16:38 -05:00
|
|
|
}
|
|
|
|
|
}
|