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