2022-03-19 07:00:15 +00:00
|
|
|
|
using Microsoft.EntityFrameworkCore;
|
2022-08-10 00:37:29 +00:00
|
|
|
|
using Npgsql;
|
2022-03-19 07:00:15 +00:00
|
|
|
|
|
|
|
|
|
namespace BirthdayBot.Data;
|
|
|
|
|
public class BotDatabaseContext : DbContext {
|
2022-08-10 00:37:29 +00:00
|
|
|
|
private static readonly string _connectionString;
|
|
|
|
|
|
|
|
|
|
static BotDatabaseContext() {
|
|
|
|
|
// Get our own config loaded just for the SQL stuff
|
|
|
|
|
var conf = new Configuration();
|
|
|
|
|
_connectionString = new NpgsqlConnectionStringBuilder() {
|
|
|
|
|
Host = conf.SqlHost ?? "localhost", // default to localhost
|
|
|
|
|
Database = conf.SqlDatabase,
|
|
|
|
|
Username = conf.SqlUsername,
|
|
|
|
|
Password = conf.SqlPassword,
|
2022-11-22 04:38:06 +00:00
|
|
|
|
ApplicationName = conf.SqlApplicationName
|
2022-08-10 00:37:29 +00:00
|
|
|
|
}.ToString();
|
2022-03-19 21:53:53 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public DbSet<GuildConfig> GuildConfigurations { get; set; } = null!;
|
|
|
|
|
public DbSet<UserEntry> UserEntries { get; set; } = null!;
|
2022-03-19 07:00:15 +00:00
|
|
|
|
|
|
|
|
|
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
|
2022-08-10 00:37:29 +00:00
|
|
|
|
=> optionsBuilder
|
|
|
|
|
.UseNpgsql(_connectionString)
|
2022-03-19 07:00:15 +00:00
|
|
|
|
.UseSnakeCaseNamingConvention();
|
|
|
|
|
|
|
|
|
|
protected override void OnModelCreating(ModelBuilder modelBuilder) {
|
|
|
|
|
modelBuilder.Entity<GuildConfig>(entity => {
|
|
|
|
|
entity.HasKey(e => e.GuildId)
|
|
|
|
|
.HasName("settings_pkey");
|
|
|
|
|
|
|
|
|
|
entity.Property(e => e.GuildId).ValueGeneratedNever();
|
|
|
|
|
|
|
|
|
|
entity.Property(e => e.LastSeen).HasDefaultValueSql("now()");
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
modelBuilder.Entity<UserEntry>(entity => {
|
|
|
|
|
entity.HasKey(e => new { e.GuildId, e.UserId })
|
|
|
|
|
.HasName("user_birthdays_pkey");
|
|
|
|
|
|
|
|
|
|
entity.Property(e => e.LastSeen).HasDefaultValueSql("now()");
|
|
|
|
|
|
|
|
|
|
entity.HasOne(d => d.Guild)
|
|
|
|
|
.WithMany(p => p.UserEntries)
|
|
|
|
|
.HasForeignKey(d => d.GuildId)
|
2022-03-21 19:11:30 +00:00
|
|
|
|
.HasConstraintName("user_birthdays_guild_id_fkey")
|
|
|
|
|
.OnDelete(DeleteBehavior.Cascade);
|
2022-03-19 07:00:15 +00:00
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
}
|