1import * as Effect from "effect/Effect";
2import * as Migrator from "effect/sql/Migrator";
3import * as SqlClient from "effect/sql/SqlClient";
4
5import PullRequestFilesViewed from "./Migrations/053_PullRequestFilesViewed.ts";
6import AutoSettleDisabledAt from "./Migrations/054_ProjectionThreadsAutoSettleDisabledAt.ts";
7
8// Published previews assigned V2 to 53, then 54. Keep their schema and import
9// progress intact while reserving main's migration ids for upgrades from main.
10export const reconcileV2PreviewMigration = Effect.fn("reconcileV2PreviewMigration")(function* () {
11 const sql = yield* SqlClient.SqlClient;
12 return yield* sql.withTransaction(
13 Effect.gen(function* () {
14 const tables = yield* sql`
15 SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'effect_sql_migrations'
16 `;
17 if (tables.length === 0) return [];
18 const history = yield* sql<{ readonly migration_id: number; readonly name: string }>`
19 SELECT migration_id, name FROM effect_sql_migrations WHERE migration_id >= 53
20 `;
21 const legacy = history.find(
22 (row) =>
23 row.name === "OrchestrationV2" && (row.migration_id === 53 || row.migration_id === 54),
24 );
25 if (!legacy) return [];
26 const valid = history.every(
27 (row) =>
28 row === legacy ||
29 (legacy.migration_id === 54 &&
30 ((row.migration_id === 53 && row.name === "PullRequestFilesViewed") ||
31 (row.migration_id === 55 && row.name === "RemoveRedundantProjectionIndexes"))),
32 );
33 if (!valid) {
34 return yield* new Migrator.MigrationError({
35 kind: "BadState",
36 message: "Cannot upgrade V2 preview with unexpected later migrations.",
37 });
38 }
39 const executed: Array<readonly [number, string]> = [];
40 if (legacy.migration_id === 53) {
41 yield* PullRequestFilesViewed;
42 executed.push([53, "PullRequestFilesViewed"]);
43 }
44 yield* AutoSettleDisabledAt;
45 executed.push([54, "ProjectionThreadsAutoSettleDisabledAt"]);
46 // Move the later entry first to avoid a primary-key collision.
47 yield* sql`UPDATE effect_sql_migrations SET migration_id = 56 WHERE migration_id = 55 AND name = 'RemoveRedundantProjectionIndexes'`;
48 yield* sql`UPDATE effect_sql_migrations SET migration_id = 55 WHERE migration_id = ${legacy.migration_id} AND name = 'OrchestrationV2'`;
49 if (legacy.migration_id === 53) {
50 yield* sql`INSERT INTO effect_sql_migrations (migration_id, name) VALUES (53, 'PullRequestFilesViewed')`;
51 }
52 yield* sql`INSERT INTO effect_sql_migrations (migration_id, name) VALUES (54, 'ProjectionThreadsAutoSettleDisabledAt')`;
53 return executed;
54 }),
55 );
56});