Add EF design-time factories; fix Game migration; document DB ops
- DesignTimeFactories.cs: adds IDesignTimeDbContextFactory<T> 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 <noreply@anthropic.com> Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
@@ -0,0 +1,103 @@
|
||||
namespace SOR.Database;
|
||||
|
||||
/// <summary>
|
||||
/// 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;..."
|
||||
/// </summary>
|
||||
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Design;
|
||||
using SOR.Database.Contexts;
|
||||
|
||||
file static class DesignTimeHelper
|
||||
{
|
||||
/// <summary>Returns the first non-null/empty value from the env vars tried.</summary>
|
||||
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<SorIdentityDbContext>
|
||||
{
|
||||
public SorIdentityDbContext CreateDbContext(string[] args)
|
||||
{
|
||||
var opts = new DbContextOptionsBuilder<SorIdentityDbContext>()
|
||||
.UseNpgsql(DesignTimeHelper.ResolveConnectionString("Identity"))
|
||||
.Options;
|
||||
return new SorIdentityDbContext(opts);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class CatalogDbContextFactory
|
||||
: IDesignTimeDbContextFactory<CatalogDbContext>
|
||||
{
|
||||
public CatalogDbContext CreateDbContext(string[] args)
|
||||
{
|
||||
var opts = new DbContextOptionsBuilder<CatalogDbContext>()
|
||||
.UseNpgsql(DesignTimeHelper.ResolveConnectionString("Catalog"))
|
||||
.Options;
|
||||
return new CatalogDbContext(opts);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class CollectionDbContextFactory
|
||||
: IDesignTimeDbContextFactory<CollectionDbContext>
|
||||
{
|
||||
public CollectionDbContext CreateDbContext(string[] args)
|
||||
{
|
||||
var opts = new DbContextOptionsBuilder<CollectionDbContext>()
|
||||
.UseNpgsql(DesignTimeHelper.ResolveConnectionString("Collection"))
|
||||
.Options;
|
||||
return new CollectionDbContext(opts);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class BazaarDbContextFactory
|
||||
: IDesignTimeDbContextFactory<BazaarDbContext>
|
||||
{
|
||||
public BazaarDbContext CreateDbContext(string[] args)
|
||||
{
|
||||
var opts = new DbContextOptionsBuilder<BazaarDbContext>()
|
||||
.UseNpgsql(DesignTimeHelper.ResolveConnectionString("Bazaar"))
|
||||
.Options;
|
||||
return new BazaarDbContext(opts);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class ChatDbContextFactory
|
||||
: IDesignTimeDbContextFactory<ChatDbContext>
|
||||
{
|
||||
public ChatDbContext CreateDbContext(string[] args)
|
||||
{
|
||||
var opts = new DbContextOptionsBuilder<ChatDbContext>()
|
||||
.UseNpgsql(DesignTimeHelper.ResolveConnectionString("Chat"))
|
||||
.Options;
|
||||
return new ChatDbContext(opts);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class GameDbContextFactory
|
||||
: IDesignTimeDbContextFactory<GameDbContext>
|
||||
{
|
||||
public GameDbContext CreateDbContext(string[] args)
|
||||
{
|
||||
var opts = new DbContextOptionsBuilder<GameDbContext>()
|
||||
.UseNpgsql(DesignTimeHelper.ResolveConnectionString("Game"))
|
||||
.Options;
|
||||
return new GameDbContext(opts);
|
||||
}
|
||||
}
|
||||
+3
-126
@@ -1,4 +1,3 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
@@ -11,136 +10,14 @@ namespace SOR.Database.Migrations.Game
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.EnsureSchema(
|
||||
name: "game");
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "game_sessions",
|
||||
schema: "game",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
PlayerOneAccountId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
PlayerOneDeckId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
PlayerTwoAccountId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
PlayerTwoDeckId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
PlayerOneReady = table.Column<bool>(type: "boolean", nullable: false),
|
||||
PlayerTwoReady = table.Column<bool>(type: "boolean", nullable: false),
|
||||
Status = table.Column<string>(type: "text", nullable: false),
|
||||
CreatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
StartedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
|
||||
EndedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
|
||||
WinnerAccountId = table.Column<Guid>(type: "uuid", nullable: true),
|
||||
WinCondition = table.Column<string>(type: "text", nullable: true),
|
||||
state = table.Column<string>(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<Guid>(type: "uuid", nullable: false),
|
||||
AccountId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
DeckId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
RankScore = table.Column<int>(type: "integer", nullable: false),
|
||||
Status = table.Column<string>(type: "text", nullable: false),
|
||||
JoinedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
ResolvedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
|
||||
MatchedGameSessionId = table.Column<Guid>(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<Guid>(type: "uuid", nullable: false),
|
||||
GameSessionId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
ActorAccountId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
ActionType = table.Column<string>(type: "text", nullable: false),
|
||||
payload = table.Column<string>(type: "jsonb", nullable: true),
|
||||
SequenceNumber = table.Column<int>(type: "integer", nullable: false),
|
||||
OccurredAt = table.Column<DateTimeOffset>(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.
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,13 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- EF Core design-time tools — required for 'dotnet ef database update' to work
|
||||
when SOR.Host is the startup project. PrivateAssets=all = dev-only, not in output. -->
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
|
||||
</PackageReference>
|
||||
|
||||
<!-- Infrastructure clients — registered once in Host, shared by all services -->
|
||||
<PackageReference Include="StackExchange.Redis" />
|
||||
<PackageReference Include="NATS.Net" />
|
||||
|
||||
@@ -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/<Schema>/`.
|
||||
|
||||
---
|
||||
|
||||
## 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=<HOST>;Port=5432;Database=SOR;Username=<USER>;Password=<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=<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 <MigrationName> \
|
||||
--project src/SOR.Database \
|
||||
--context <ContextName> \
|
||||
--output-dir Migrations/<Schema>
|
||||
|
||||
# Example:
|
||||
dotnet ef migrations add AddCardFoilIndex \
|
||||
--project src/SOR.Database \
|
||||
--context CollectionDbContext \
|
||||
--output-dir Migrations/Collection
|
||||
|
||||
# 3. Review the generated Up()/Down() in Migrations/<Schema>/<timestamp>_<Name>.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.
|
||||
Reference in New Issue
Block a user