Foxnouns.NET/Foxnouns.Backend/Database/DatabaseContext.cs

112 lines
4.8 KiB
C#
Raw Normal View History

using System.Diagnostics.CodeAnalysis;
using EntityFramework.Exceptions.PostgreSQL;
2024-05-27 15:53:54 +02:00
using Foxnouns.Backend.Database.Models;
using Foxnouns.Backend.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore.Diagnostics;
2024-05-27 15:53:54 +02:00
using Npgsql;
namespace Foxnouns.Backend.Database;
public class DatabaseContext : DbContext
{
private readonly NpgsqlDataSource _dataSource;
private readonly ILoggerFactory? _loggerFactory;
2024-05-27 15:53:54 +02:00
public DbSet<User> Users { get; set; }
public DbSet<Member> Members { get; set; }
public DbSet<AuthMethod> AuthMethods { get; set; }
public DbSet<FediverseApplication> FediverseApplications { get; set; }
public DbSet<Token> Tokens { get; set; }
public DbSet<Application> Applications { get; set; }
public DbSet<TemporaryKey> TemporaryKeys { get; set; }
2024-05-27 15:53:54 +02:00
public DatabaseContext(Config config, ILoggerFactory? loggerFactory)
2024-05-27 15:53:54 +02:00
{
var connString = new NpgsqlConnectionStringBuilder(config.Database.Url)
{
Pooling = config.Database.EnablePooling ?? true,
2024-05-27 15:53:54 +02:00
Timeout = config.Database.Timeout ?? 5,
MaxPoolSize = config.Database.MaxPoolSize ?? 50,
2024-09-10 16:53:43 +02:00
MinPoolSize = 0,
ConnectionPruningInterval = 10,
ConnectionIdleLifetime = 10,
2024-05-27 15:53:54 +02:00
}.ConnectionString;
var dataSourceBuilder = new NpgsqlDataSourceBuilder(connString);
dataSourceBuilder.UseNodaTime();
dataSourceBuilder.UseJsonNet();
2024-05-27 15:53:54 +02:00
_dataSource = dataSourceBuilder.Build();
_loggerFactory = loggerFactory;
2024-05-27 15:53:54 +02:00
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.ConfigureWarnings(c =>
c.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning)
.Ignore(CoreEventId.SaveChangesFailed))
2024-05-27 15:53:54 +02:00
.UseNpgsql(_dataSource, o => o.UseNodaTime())
.UseSnakeCaseNamingConvention()
.UseLoggerFactory(_loggerFactory)
.UseExceptionProcessor();
2024-05-27 15:53:54 +02:00
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
{
// Snowflakes are stored as longs
configurationBuilder.Properties<Snowflake>().HaveConversion<Snowflake.ValueConverter>();
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().HasIndex(u => u.Username).IsUnique();
2024-09-26 15:08:08 +02:00
modelBuilder.Entity<User>().HasIndex(u => u.Sid).IsUnique();
2024-05-27 15:53:54 +02:00
modelBuilder.Entity<Member>().HasIndex(m => new { m.UserId, m.Name }).IsUnique();
2024-09-26 15:08:08 +02:00
modelBuilder.Entity<Member>().HasIndex(m => m.Sid).IsUnique();
modelBuilder.Entity<TemporaryKey>().HasIndex(k => k.Key).IsUnique();
2024-05-27 15:53:54 +02:00
2024-09-26 15:08:08 +02:00
modelBuilder.Entity<User>().Property(u => u.Sid).HasDefaultValueSql("find_free_user_sid()");
modelBuilder.Entity<User>().Property(u => u.Fields).HasColumnType("jsonb");
modelBuilder.Entity<User>().Property(u => u.Names).HasColumnType("jsonb");
modelBuilder.Entity<User>().Property(u => u.Pronouns).HasColumnType("jsonb");
modelBuilder.Entity<User>().Property(u => u.CustomPreferences).HasColumnType("jsonb");
2024-09-05 22:17:10 +02:00
modelBuilder.Entity<User>().Property(u => u.Settings).HasColumnType("jsonb");
2024-05-27 15:53:54 +02:00
2024-09-26 15:08:08 +02:00
modelBuilder.Entity<Member>().Property(m => m.Sid).HasDefaultValueSql("find_free_member_sid()");
modelBuilder.Entity<Member>().Property(m => m.Fields).HasColumnType("jsonb");
modelBuilder.Entity<Member>().Property(m => m.Names).HasColumnType("jsonb");
modelBuilder.Entity<Member>().Property(m => m.Pronouns).HasColumnType("jsonb");
modelBuilder.HasDbFunction(typeof(DatabaseContext).GetMethod(nameof(FindFreeUserSid))!)
.HasName("find_free_user_sid");
modelBuilder.HasDbFunction(typeof(DatabaseContext).GetMethod(nameof(FindFreeMemberSid))!)
.HasName("find_free_member_sid");
2024-05-27 15:53:54 +02:00
}
/// <summary>
/// Dummy method that calls <c>find_free_user_sid()</c> when used in an EF Core query.
/// </summary>
public string FindFreeUserSid() => throw new NotSupportedException();
/// <summary>
/// Dummy method that calls <c>find_free_member_sid()</c> when used in an EF Core query.
/// </summary>
public string FindFreeMemberSid() => throw new NotSupportedException();
2024-05-27 15:53:54 +02:00
}
[SuppressMessage("ReSharper", "UnusedType.Global", Justification = "Used by EF Core's migration generator")]
2024-05-27 15:53:54 +02:00
public class DesignTimeDatabaseContextFactory : IDesignTimeDbContextFactory<DatabaseContext>
{
public DatabaseContext CreateDbContext(string[] args)
{
// Read the configuration file
var config = new ConfigurationBuilder()
.AddConfiguration()
.Build()
// Get the configuration as our config class
.Get<Config>() ?? new();
return new DatabaseContext(config, null);
2024-05-27 15:53:54 +02:00
}
}