Foxchat.NET/Foxchat.Identity/Database/IdentityContext.cs
2024-05-14 03:51:31 +02:00

63 lines
2.2 KiB
C#

using Foxchat.Core;
using Foxchat.Core.Database;
using Foxchat.Identity.Database.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
namespace Foxchat.Identity.Database;
public class IdentityContext : IDatabaseContext
{
private readonly string _connString;
public DbSet<Account> Accounts { get; set; }
public DbSet<ChatInstance> ChatInstances { get; set; }
public override DbSet<Instance> Instance { get; set; }
public DbSet<Token> Tokens { get; set; }
public DbSet<GuildAccount> GuildAccounts { get; set; }
public IdentityContext(InstanceConfig config)
{
_connString = new Npgsql.NpgsqlConnectionStringBuilder(config.Database.Url)
{
Timeout = config.Database.Timeout ?? 5,
MaxPoolSize = config.Database.MaxPoolSize ?? 50,
}.ConnectionString;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseNpgsql(_connString)
.UseSnakeCaseNamingConvention();
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
{
// ULIDs are stored as UUIDs in the database
configurationBuilder.Properties<Ulid>().HaveConversion<UlidConverter>();
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Account>().HasIndex(a => a.Username).IsUnique();
modelBuilder.Entity<Account>().HasIndex(a => a.Email).IsUnique();
modelBuilder.Entity<ChatInstance>().HasIndex(i => i.Domain).IsUnique();
modelBuilder.Entity<GuildAccount>().HasKey(g => new { g.ChatInstanceId, g.GuildId, g.AccountId });
}
}
public class DesignTimeIdentityContextFactory : IDesignTimeDbContextFactory<IdentityContext>
{
public IdentityContext CreateDbContext(string[] args)
{
// Read the configuration file
var config = new ConfigurationBuilder()
.AddConfiguration("identity.ini")
.Build()
// Get the configuration as our config class
.Get<InstanceConfig>() ?? new();
return new IdentityContext(config);
}
}