refactor(data): squash the 40 migrations into one InitialCreate

The incremental chain was ~31k lines of generated Designer snapshots for a
schema no shipped database steps through anymore. MigrateAndConfigure now
baselines an existing DB onto the squashed id (pre-EF, or history ending at
AddPrimeActionKind) and throws with a reinstall message for a mid-chain DB.
MigrationBaselineTests covers all three paths with a real Migrate().
This commit is contained in:
mika kuns
2026-08-26 13:55:30 +02:00
parent 69fcceb2ed
commit 39d8241360
85 changed files with 628 additions and 30686 deletions
@@ -0,0 +1,123 @@
using ClaudeDo.Data.Models;
using Microsoft.EntityFrameworkCore;
namespace ClaudeDo.Data.Tests;
// The 40 incremental migrations were squashed into one InitialCreate, so every existing database
// carries a history EF no longer recognises. MigrateAndConfigure re-stamps those instead of
// re-creating tables — this is the only test covering that path (every other Data.Tests fixture
// uses EnsureCreated, which skips migrations entirely).
// Replaces TaskNumberMigrationTests, whose subject (the AddTaskNumbers backfill) was squashed away.
public sealed class MigrationBaselineTests : IDisposable
{
private const string LastPreSquashMigrationId = "20260825063230_AddPrimeActionKind";
private const string SquashedMigrationId = "20260826094154_InitialCreate";
private readonly string _dbPath;
private readonly DbContextOptions<ClaudeDoDbContext> _options;
public MigrationBaselineTests()
{
_dbPath = Path.Combine(Path.GetTempPath(), $"claudedo_baseline_{Guid.NewGuid():N}.db");
_options = new DbContextOptionsBuilder<ClaudeDoDbContext>()
.UseSqlite($"Data Source={_dbPath}")
.Options;
}
public void Dispose()
{
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
foreach (var suffix in new[] { "", "-wal", "-shm" })
try { File.Delete(_dbPath + suffix); } catch { }
}
[Fact]
public void Fresh_database_migrates_and_seeds()
{
using var ctx = new ClaudeDoDbContext(_options);
ClaudeDoDbContext.MigrateAndConfigure(ctx);
Assert.Equal(new[] { SquashedMigrationId }, ctx.Database.GetAppliedMigrations());
Assert.NotEmpty(ctx.Lists);
}
[Fact]
public void Fully_migrated_pre_squash_database_is_restamped_and_keeps_its_rows()
{
SeedCurrentSchemaWithHistory(LastPreSquashMigrationId, taskTitle: "survivor");
using var ctx = new ClaudeDoDbContext(_options);
ClaudeDoDbContext.MigrateAndConfigure(ctx);
Assert.Equal(new[] { SquashedMigrationId }, ctx.Database.GetAppliedMigrations());
Assert.Equal("survivor", ctx.Tasks.Single().Title);
}
[Fact]
public void Restamping_is_idempotent()
{
SeedCurrentSchemaWithHistory(LastPreSquashMigrationId, taskTitle: "survivor");
using (var first = new ClaudeDoDbContext(_options))
ClaudeDoDbContext.MigrateAndConfigure(first);
using var second = new ClaudeDoDbContext(_options);
ClaudeDoDbContext.MigrateAndConfigure(second);
Assert.Equal(new[] { SquashedMigrationId }, second.Database.GetAppliedMigrations());
Assert.Equal("survivor", second.Tasks.Single().Title);
}
[Fact]
public void Database_stuck_mid_chain_fails_loudly_instead_of_being_stamped()
{
SeedCurrentSchemaWithHistory("20260810115437_AddFailureReason", taskTitle: "stale");
using var ctx = new ClaudeDoDbContext(_options);
var ex = Assert.Throws<InvalidOperationException>(() => ClaudeDoDbContext.MigrateAndConfigure(ctx));
Assert.Contains("Reinstall ClaudeDo", ex.Message);
}
[Fact]
public void Pre_ef_database_without_history_is_baselined()
{
SeedCurrentSchemaWithHistory(historyId: null, taskTitle: "legacy");
using var ctx = new ClaudeDoDbContext(_options);
ClaudeDoDbContext.MigrateAndConfigure(ctx);
Assert.Equal(new[] { SquashedMigrationId }, ctx.Database.GetAppliedMigrations());
Assert.Equal("legacy", ctx.Tasks.Single().Title);
}
// EnsureCreated builds today's schema without touching __EFMigrationsHistory, which is exactly
// the shape of a database that was fully migrated by the old chain: current tables, old history.
private void SeedCurrentSchemaWithHistory(string? historyId, string taskTitle)
{
using var seed = new ClaudeDoDbContext(_options);
seed.Database.EnsureCreated();
var list = new ListEntity { Id = "l1", Name = "List", CreatedAt = DateTime.UtcNow };
seed.Lists.Add(list);
seed.Tasks.Add(new TaskEntity
{
Id = "t1", ListId = list.Id, Title = taskTitle, Number = 1, CreatedAt = DateTime.UtcNow,
});
seed.SaveChanges();
if (historyId is null) return;
var conn = seed.Database.GetDbConnection();
conn.Open();
using var cmd = conn.CreateCommand();
cmd.CommandText = $"""
CREATE TABLE "__EFMigrationsHistory" (
"MigrationId" TEXT NOT NULL CONSTRAINT "PK___EFMigrationsHistory" PRIMARY KEY,
"ProductVersion" TEXT NOT NULL
);
INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")
VALUES ('{historyId}', '8.0.11');
""";
cmd.ExecuteNonQuery();
conn.Close();
}
}
@@ -1,84 +0,0 @@
using ClaudeDo.Data;
using ClaudeDo.Data.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.Extensions.DependencyInjection;
namespace ClaudeDo.Data.Tests;
// EnsureCreated (used by every other Data.Tests fixture) builds the schema straight from the
// current model and skips migrations entirely, so it can never exercise the AddTaskNumbers
// backfill. This test runs a real Migrate() against a database seeded with pre-migration rows.
public sealed class TaskNumberMigrationTests : IDisposable
{
private const string MigrationBeforeTaskNumbers = "20260810115437_AddFailureReason";
private readonly string _dbPath;
private readonly DbContextOptions<ClaudeDoDbContext> _options;
public TaskNumberMigrationTests()
{
_dbPath = Path.Combine(Path.GetTempPath(), $"claudedo_tasknum_migration_{Guid.NewGuid():N}.db");
_options = new DbContextOptionsBuilder<ClaudeDoDbContext>()
.UseSqlite($"Data Source={_dbPath}")
.Options;
}
public void Dispose()
{
foreach (var suffix in new[] { "", "-wal", "-shm" })
try { File.Delete(_dbPath + suffix); } catch { }
}
[Fact]
public async Task Migrate_backfills_task_numbers_in_creation_order_with_id_tiebreak()
{
await using (var ctx = new ClaudeDoDbContext(_options))
{
var migrator = ctx.Database.GetInfrastructure().GetRequiredService<IMigrator>();
migrator.Migrate(MigrationBeforeTaskNumbers);
var conn = ctx.Database.GetDbConnection();
await conn.OpenAsync();
await ExecAsync(conn, """
INSERT INTO lists (id, name, created_at) VALUES ('l1', 'List', '2026-01-01 00:00:00.0000000');
""");
// Inserted out of creation order, and 'd'/'c' share a timestamp to exercise the id tiebreak.
await ExecAsync(conn, InsertTaskSql("d", "2026-01-03 00:00:00.0000000"));
await ExecAsync(conn, InsertTaskSql("a", "2026-01-01 00:00:00.0000000"));
await ExecAsync(conn, InsertTaskSql("c", "2026-01-03 00:00:00.0000000"));
await ExecAsync(conn, InsertTaskSql("b", "2026-01-02 00:00:00.0000000"));
migrator.Migrate();
}
await using var verify = new ClaudeDoDbContext(_options);
var byId = await verify.Tasks.AsNoTracking().ToDictionaryAsync(t => t.Id, t => t.Number);
Assert.Equal(1, byId["a"]);
Assert.Equal(2, byId["b"]);
Assert.Equal(3, byId["c"]);
Assert.Equal(4, byId["d"]);
var numbers = byId.Values.OrderBy(n => n).ToList();
Assert.Equal(new[] { 1, 2, 3, 4 }, numbers);
var settings = await verify.AppSettings.AsNoTracking().FirstAsync(s => s.Id == AppSettingsEntity.SingletonId);
Assert.Equal(5, settings.NextTaskNumber);
}
private static string InsertTaskSql(string id, string createdAt) => $"""
INSERT INTO tasks (id, list_id, title, status, created_at)
VALUES ('{id}', 'l1', 'Task {id}', 'idle', '{createdAt}');
""";
private static async Task ExecAsync(System.Data.Common.DbConnection conn, string sql)
{
await using var cmd = conn.CreateCommand();
cmd.CommandText = sql;
await cmd.ExecuteNonQueryAsync();
}
}