using Microsoft.EntityFrameworkCore; using Npgsql; namespace RegexBot.Data; /// /// Represents a database connection using the settings defined in the bot's global configuration. /// public class BotDatabaseContext : DbContext { private static readonly string _connectionString; static BotDatabaseContext() { // Get our own config loaded just for the SQL stuff var conf = new InstanceConfig(); _connectionString = new NpgsqlConnectionStringBuilder() { Host = conf.SqlHost ?? "localhost", // default to localhost Database = conf.SqlDatabase, Username = conf.SqlUsername, Password = conf.SqlPassword }.ToString(); } /// /// Retrieves the user cache. /// public DbSet UserCache { get; set; } = null!; /// /// Retrieves the guild user cache. /// public DbSet GuildUserCache { get; set; } = null!; /// /// Retrieves the guild message cache. /// public DbSet GuildMessageCache { get; set; } = null!; /// protected sealed override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder .UseNpgsql(_connectionString) .UseSnakeCaseNamingConvention(); /// protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity(entity => entity.Property(e => e.Discriminator).HasMaxLength(4).IsFixedLength()); modelBuilder.Entity(entity => { entity.HasKey(e => new { e.UserId, e.GuildId }); entity.Property(e => e.FirstSeenTime).HasDefaultValueSql("now()"); }); modelBuilder.Entity(entity => entity.Property(e => e.CreatedAt).HasDefaultValueSql("now()")); } }