From fe5cd2d4249b095e3df1cd801936b562a61e2f3a Mon Sep 17 00:00:00 2001 From: dingo Date: Fri, 27 Feb 2026 09:30:57 -0500 Subject: [PATCH] Add EF design-time factories; fix Game migration; document DB ops MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - DesignTimeFactories.cs: adds IDesignTimeDbContextFactory for all 6 contexts so dotnet-ef tools work without starting the full ASP.NET host (previously failed because Redis/NATS aren't available locally) - SOR.Host.csproj: adds Microsoft.EntityFrameworkCore.Design (PrivateAssets=all) as the EF design-time host still requires it in the startup project - Game/AddGameRulesAndCustomLobby: emptied Up/Down — migration was generated with a stale snapshot duplicating InitialCreate tables; actual GameRuleSet and CustomLobby schema is in AddBoardDimensions - deploy/database-migrations.md: documents how to apply/add migrations against any environment; records pg-forge-01 state as of 2026-02-27 Generated with [Claude Code](https://claude.ai/code) via [Happy](https://happy.engineering) Co-Authored-By: Claude Co-Authored-By: Happy --- .../src/SOR.Database/DesignTimeFactories.cs | 103 ++++++++++++ ...260226125446_AddGameRulesAndCustomLobby.cs | 129 +-------------- Server/src/SOR.Host/SOR.Host.csproj | 7 + deploy/database-migrations.md | 151 ++++++++++++++++++ 4 files changed, 264 insertions(+), 126 deletions(-) create mode 100644 Server/src/SOR.Database/DesignTimeFactories.cs create mode 100644 deploy/database-migrations.md diff --git a/Server/src/SOR.Database/DesignTimeFactories.cs b/Server/src/SOR.Database/DesignTimeFactories.cs new file mode 100644 index 0000000..5165026 --- /dev/null +++ b/Server/src/SOR.Database/DesignTimeFactories.cs @@ -0,0 +1,103 @@ +namespace SOR.Database; + +/// +/// Design-time factory implementations for all DbContexts. +/// +/// These are used exclusively by EF Core tooling ('dotnet ef migrations add', +/// 'dotnet ef database update', etc.) so the tools can instantiate contexts +/// without starting the full ASP.NET Core application. +/// +/// Connection string resolution order: +/// 1. ConnectionStrings__{ContextName} environment variable +/// 2. ConnectionStrings__Default environment variable +/// 3. Hard-coded localhost placeholder (for local dev without env vars set) +/// +/// When running migrations against a remote server, pass --connection explicitly: +/// dotnet ef database update --context SorIdentityDbContext \ +/// --connection "Host=...;Database=SOR;..." +/// + +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Design; +using SOR.Database.Contexts; + +file static class DesignTimeHelper +{ + /// Returns the first non-null/empty value from the env vars tried. + internal static string ResolveConnectionString(string contextName) + => Environment.GetEnvironmentVariable($"ConnectionStrings__{contextName}") + ?? Environment.GetEnvironmentVariable("ConnectionStrings__Default") + ?? "Host=localhost;Port=5432;Database=SOR;Username=postgres;Password=postgres"; +} + +public sealed class SorIdentityDbContextFactory + : IDesignTimeDbContextFactory +{ + public SorIdentityDbContext CreateDbContext(string[] args) + { + var opts = new DbContextOptionsBuilder() + .UseNpgsql(DesignTimeHelper.ResolveConnectionString("Identity")) + .Options; + return new SorIdentityDbContext(opts); + } +} + +public sealed class CatalogDbContextFactory + : IDesignTimeDbContextFactory +{ + public CatalogDbContext CreateDbContext(string[] args) + { + var opts = new DbContextOptionsBuilder() + .UseNpgsql(DesignTimeHelper.ResolveConnectionString("Catalog")) + .Options; + return new CatalogDbContext(opts); + } +} + +public sealed class CollectionDbContextFactory + : IDesignTimeDbContextFactory +{ + public CollectionDbContext CreateDbContext(string[] args) + { + var opts = new DbContextOptionsBuilder() + .UseNpgsql(DesignTimeHelper.ResolveConnectionString("Collection")) + .Options; + return new CollectionDbContext(opts); + } +} + +public sealed class BazaarDbContextFactory + : IDesignTimeDbContextFactory +{ + public BazaarDbContext CreateDbContext(string[] args) + { + var opts = new DbContextOptionsBuilder() + .UseNpgsql(DesignTimeHelper.ResolveConnectionString("Bazaar")) + .Options; + return new BazaarDbContext(opts); + } +} + +public sealed class ChatDbContextFactory + : IDesignTimeDbContextFactory +{ + public ChatDbContext CreateDbContext(string[] args) + { + var opts = new DbContextOptionsBuilder() + .UseNpgsql(DesignTimeHelper.ResolveConnectionString("Chat")) + .Options; + return new ChatDbContext(opts); + } +} + +public sealed class GameDbContextFactory + : IDesignTimeDbContextFactory +{ + public GameDbContext CreateDbContext(string[] args) + { + var opts = new DbContextOptionsBuilder() + .UseNpgsql(DesignTimeHelper.ResolveConnectionString("Game")) + .Options; + return new GameDbContext(opts); + } +} diff --git a/Server/src/SOR.Database/Migrations/Game/20260226125446_AddGameRulesAndCustomLobby.cs b/Server/src/SOR.Database/Migrations/Game/20260226125446_AddGameRulesAndCustomLobby.cs index b08bec3..2dd3fc0 100644 --- a/Server/src/SOR.Database/Migrations/Game/20260226125446_AddGameRulesAndCustomLobby.cs +++ b/Server/src/SOR.Database/Migrations/Game/20260226125446_AddGameRulesAndCustomLobby.cs @@ -1,4 +1,3 @@ -using System; using Microsoft.EntityFrameworkCore.Migrations; #nullable disable @@ -11,136 +10,14 @@ namespace SOR.Database.Migrations.Game /// protected override void Up(MigrationBuilder migrationBuilder) { - migrationBuilder.EnsureSchema( - name: "game"); - - migrationBuilder.CreateTable( - name: "game_sessions", - schema: "game", - columns: table => new - { - Id = table.Column(type: "uuid", nullable: false), - PlayerOneAccountId = table.Column(type: "uuid", nullable: false), - PlayerOneDeckId = table.Column(type: "uuid", nullable: false), - PlayerTwoAccountId = table.Column(type: "uuid", nullable: false), - PlayerTwoDeckId = table.Column(type: "uuid", nullable: false), - PlayerOneReady = table.Column(type: "boolean", nullable: false), - PlayerTwoReady = table.Column(type: "boolean", nullable: false), - Status = table.Column(type: "text", nullable: false), - CreatedAt = table.Column(type: "timestamp with time zone", nullable: false), - StartedAt = table.Column(type: "timestamp with time zone", nullable: true), - EndedAt = table.Column(type: "timestamp with time zone", nullable: true), - WinnerAccountId = table.Column(type: "uuid", nullable: true), - WinCondition = table.Column(type: "text", nullable: true), - state = table.Column(type: "jsonb", nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_game_sessions", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "matchmaking_entries", - schema: "game", - columns: table => new - { - Id = table.Column(type: "uuid", nullable: false), - AccountId = table.Column(type: "uuid", nullable: false), - DeckId = table.Column(type: "uuid", nullable: false), - RankScore = table.Column(type: "integer", nullable: false), - Status = table.Column(type: "text", nullable: false), - JoinedAt = table.Column(type: "timestamp with time zone", nullable: false), - ResolvedAt = table.Column(type: "timestamp with time zone", nullable: true), - MatchedGameSessionId = table.Column(type: "uuid", nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_matchmaking_entries", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "action_logs", - schema: "game", - columns: table => new - { - Id = table.Column(type: "uuid", nullable: false), - GameSessionId = table.Column(type: "uuid", nullable: false), - ActorAccountId = table.Column(type: "uuid", nullable: false), - ActionType = table.Column(type: "text", nullable: false), - payload = table.Column(type: "jsonb", nullable: true), - SequenceNumber = table.Column(type: "integer", nullable: false), - OccurredAt = table.Column(type: "timestamp with time zone", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_action_logs", x => x.Id); - table.ForeignKey( - name: "FK_action_logs_game_sessions_GameSessionId", - column: x => x.GameSessionId, - principalSchema: "game", - principalTable: "game_sessions", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateIndex( - name: "IX_action_logs_ActorAccountId", - schema: "game", - table: "action_logs", - column: "ActorAccountId"); - - migrationBuilder.CreateIndex( - name: "IX_action_logs_GameSessionId_SequenceNumber", - schema: "game", - table: "action_logs", - columns: new[] { "GameSessionId", "SequenceNumber" }, - unique: true); - - migrationBuilder.CreateIndex( - name: "IX_game_sessions_PlayerOneAccountId", - schema: "game", - table: "game_sessions", - column: "PlayerOneAccountId"); - - migrationBuilder.CreateIndex( - name: "IX_game_sessions_PlayerTwoAccountId", - schema: "game", - table: "game_sessions", - column: "PlayerTwoAccountId"); - - migrationBuilder.CreateIndex( - name: "IX_game_sessions_Status_CreatedAt", - schema: "game", - table: "game_sessions", - columns: new[] { "Status", "CreatedAt" }); - - migrationBuilder.CreateIndex( - name: "IX_matchmaking_entries_AccountId_Status", - schema: "game", - table: "matchmaking_entries", - columns: new[] { "AccountId", "Status" }); - - migrationBuilder.CreateIndex( - name: "IX_matchmaking_entries_Status_RankScore", - schema: "game", - table: "matchmaking_entries", - columns: new[] { "Status", "RankScore" }); + // Empty — this migration was generated with a stale model snapshot that + // duplicated all tables from InitialCreate. The actual GameRuleSet / + // CustomLobby / BoardDimensions schema lives in AddBoardDimensions. } /// protected override void Down(MigrationBuilder migrationBuilder) { - migrationBuilder.DropTable( - name: "action_logs", - schema: "game"); - - migrationBuilder.DropTable( - name: "matchmaking_entries", - schema: "game"); - - migrationBuilder.DropTable( - name: "game_sessions", - schema: "game"); } } } diff --git a/Server/src/SOR.Host/SOR.Host.csproj b/Server/src/SOR.Host/SOR.Host.csproj index 0832fa5..d2fb61c 100644 --- a/Server/src/SOR.Host/SOR.Host.csproj +++ b/Server/src/SOR.Host/SOR.Host.csproj @@ -9,6 +9,13 @@ + + + all + runtime; build; native; contentfiles; analyzers + + diff --git a/deploy/database-migrations.md b/deploy/database-migrations.md new file mode 100644 index 0000000..bb725da --- /dev/null +++ b/deploy/database-migrations.md @@ -0,0 +1,151 @@ +# SOR Database Migrations + +SOR uses **EF Core 8** with **6 independent DbContexts**, each owning a separate PostgreSQL +schema. All migrations live in `Server/src/SOR.Database/Migrations//`. + +--- + +## Prerequisites + +```bash +# Install the dotnet-ef global tool (once per machine) +dotnet tool install --global dotnet-ef + +# Verify +dotnet ef --version # must be >= 8.x +``` + +--- + +## Contexts and Schemas + +| Context | Schema | Migration folder | +|------------------------|--------------|-------------------------------------| +| `SorIdentityDbContext` | `identity` | `Migrations/Identity/` | +| `CatalogDbContext` | `catalog` | `Migrations/Catalog/` | +| `CollectionDbContext` | `collection` | `Migrations/Collection/` | +| `BazaarDbContext` | `bazaar` | `Migrations/Bazaar/` | +| `ChatDbContext` | `chat` | `Migrations/Chat/` | +| `GameDbContext` | `game` | `Migrations/Game/` | + +All contexts share the same PostgreSQL database (`SOR`) but are completely isolated by schema. + +--- + +## Applying Migrations to a Remote Server + +Run from `Server/` directory. The `--connection` flag overrides whatever is in appsettings.json +and is the correct way to target a specific environment. + +```bash +cd Server + +CONN="Host=;Port=5432;Database=SOR;Username=;Password=" + +# Apply all 6 contexts (run in order — schemas are independent, no cross-schema FKs) +dotnet ef database update --project src/SOR.Database --context SorIdentityDbContext --connection "$CONN" --no-build +dotnet ef database update --project src/SOR.Database --context CatalogDbContext --connection "$CONN" --no-build +dotnet ef database update --project src/SOR.Database --context CollectionDbContext --connection "$CONN" --no-build +dotnet ef database update --project src/SOR.Database --context BazaarDbContext --connection "$CONN" --no-build +dotnet ef database update --project src/SOR.Database --context ChatDbContext --connection "$CONN" --no-build +dotnet ef database update --project src/SOR.Database --context GameDbContext --connection "$CONN" --no-build +``` + +> **Note:** `--no-build` skips rebuilding and uses already-compiled binaries in `bin/`. +> Omit it (or run `dotnet build` first) if you just changed migration files. + +### pg-forge-01 (production) + +```bash +HOST=172.10.1.127 +USER=SOR-DBA +# password is stored in sor-app-secrets k8s Secret (Cdn__AccessKey isn't it — see deploy/secrets/) +``` + +--- + +## Checking Migration Status + +```bash +CONN="Host=;..." + +# Lists all migrations; any marked (Pending) need to be applied +dotnet ef migrations list --project src/SOR.Database --context SorIdentityDbContext --connection "$CONN" --no-build +dotnet ef migrations list --project src/SOR.Database --context CatalogDbContext --connection "$CONN" --no-build +dotnet ef migrations list --project src/SOR.Database --context CollectionDbContext --connection "$CONN" --no-build +dotnet ef migrations list --project src/SOR.Database --context BazaarDbContext --connection "$CONN" --no-build +dotnet ef migrations list --project src/SOR.Database --context ChatDbContext --connection "$CONN" --no-build +dotnet ef migrations list --project src/SOR.Database --context GameDbContext --connection "$CONN" --no-build +``` + +--- + +## Adding a New Migration + +```bash +cd Server + +# 1. Make your model changes in SOR.Database/Entities/ or Contexts/ + +# 2. Add the migration (pick the right context) +dotnet ef migrations add \ + --project src/SOR.Database \ + --context \ + --output-dir Migrations/ + +# Example: +dotnet ef migrations add AddCardFoilIndex \ + --project src/SOR.Database \ + --context CollectionDbContext \ + --output-dir Migrations/Collection + +# 3. Review the generated Up()/Down() in Migrations//_.cs +# Make sure it only contains the delta — NOT a full recreation of existing tables. + +# 4. Apply to target DB +dotnet ef database update --project src/SOR.Database --context CollectionDbContext --connection "$CONN" +``` + +> **Design-time factories** (`DesignTimeFactories.cs` in `SOR.Database`) allow the EF tools +> to instantiate contexts without starting the full ASP.NET Core application. +> They read the connection string from `ConnectionStrings__Default` env var, +> falling back to `localhost` for local dev. + +--- + +## How EF Tracks Applied Migrations + +Each schema gets its own `__EFMigrationsHistory` table: + +``` +identity.__EFMigrationsHistory +catalog.__EFMigrationsHistory +collection.__EFMigrationsHistory +bazaar.__EFMigrationsHistory +chat.__EFMigrationsHistory +game.__EFMigrationsHistory +``` + +EF Core compares these tables to the migration files to determine what's pending. + +--- + +## Known Migration History + +### pg-forge-01 — last applied (2026-02-27) + +| Context | Last migration applied | +|-----------------|-------------------------------------------------| +| Identity | `20260226111950_AddRankScore` | +| Catalog | `20260226012910_AddDefinitionVersionAndRetired` | +| Collection | `20260225231700_AddPlayerCosmetics` | +| Bazaar | `20260225231658_AddBazaarCosmetics` | +| Chat | `20260226012908_AddPresenceAndNotifications` | +| Game | `20260226162145_AddBoardDimensions` | + +### Notes + +- `GameDbContext/20260226125446_AddGameRulesAndCustomLobby` is intentionally empty. + It was regenerated with a stale snapshot that duplicated InitialCreate tables. + The actual `game_rule_sets` and `custom_lobbies` tables were added in the + following `AddBoardDimensions` migration.