Open History to see the last commit
1import { assert, describe, it } from "@effect/vitest";
2import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import * as Effect from "effect/Effect";
5import * as Exit from "effect/Exit";
6import * as FileSystem from "effect/FileSystem";
7import * as Path from "effect/Path";
8import * as SqlClient from "effect/sql/SqlClient";
9import * as Ref from "effect/Ref";
10import * as Logger from "effect/Logger";
11import * as Console from "effect/Console";
12import * as NodeUtil from "node:util";
13import type { DatabaseMigrationProgress as Progress } from "@t3tools/contracts";
14import {
15 databaseMigrationProgress,
16 DATABASE_MIGRATION_PROGRESS_MESSAGE,
17} from "@t3tools/shared/databaseMigrationLog";
18import * as DatabaseMigrationProgress from "./DatabaseMigrationProgress.ts";
19
20import { migrationManifest, runMigrations } from "./Migrations.ts";
21
22const v2Migrations = migrationManifest.filter(([id]) => id >= 55);
23const newerMigrationId = Math.max(...migrationManifest.map(([id]) => id)) + 1;
24
25const history = Effect.gen(function* () {
26 const sql = yield* SqlClient.SqlClient;
27 const rows = yield* sql<{ readonly migration_id: number; readonly name: string }>`
28 SELECT migration_id, name FROM effect_sql_migrations ORDER BY migration_id
29 `;
30 return rows.map((row) => [row.migration_id, row.name] as const);
31});
32
33const v2TableCount = Effect.gen(function* () {
34 const sql = yield* SqlClient.SqlClient;
35 const rows = yield* sql`
36 SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE 'orchestration_v2_%'
37 `;
38 return rows.length;
39});
40
41describe("runMigrations", () => {
42 it.effect("refuses to start when another migration took a V2 id", () =>
43 Effect.gen(function* () {
44 const sql = yield* SqlClient.SqlClient;
45 yield* runMigrations({ toMigrationInclusive: 54 });
46 yield* sql`
47 INSERT INTO effect_sql_migrations (migration_id, name) VALUES (55, 'FutureMainMigration')
48 `;
49 const before = yield* history;
50
51 assert.deepStrictEqual(yield* runMigrations({ toMigrationInclusive: 54 }), []);
52 const exit = yield* Effect.exit(runMigrations());
53
54 assert.isTrue(Exit.isFailure(exit));
55 assert.include(String(exit), "55_OrchestrationV2 (recorded: FutureMainMigration)");
56 assert.deepStrictEqual(yield* history, before);
57 assert.strictEqual(yield* v2TableCount, 0);
58 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
59 );
60
61 it.effect("refuses to start when a later id would skip V2 migrations", () =>
62 Effect.gen(function* () {
63 const sql = yield* SqlClient.SqlClient;
64 yield* runMigrations({ toMigrationInclusive: 54 });
65 yield* sql`
66 INSERT INTO effect_sql_migrations (migration_id, name)
67 VALUES (${newerMigrationId}, 'FutureMainMigration')
68 `;
69 const before = yield* history;
70
71 const exit = yield* Effect.exit(runMigrations());
72
73 assert.isTrue(Exit.isFailure(exit));
74 for (const [id, name] of v2Migrations) {
75 assert.include(String(exit), `${id}_${name} (recorded: nothing)`);
76 }
77 assert.deepStrictEqual(yield* history, before);
78 assert.strictEqual(yield* v2TableCount, 0);
79 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
80 );
81
82 it.effect("upgrades a database at exactly 54, then rechecks it without a write lock", () =>
83 Effect.gen(function* () {
84 const sql = yield* SqlClient.SqlClient;
85 yield* runMigrations({ toMigrationInclusive: 54 });
86 const current = yield* Ref.make<Progress | null>(null);
87 const steps: Array<Progress | null> = [];
88 const loggedSteps: Array<Progress | null> = [];
89 let output = "";
90 const pretty = Logger.consolePretty({ mode: "tty", colors: false });
91 const logger = Logger.make((options) => {
92 pretty.log(options);
93 if (String(options.message).startsWith(DATABASE_MIGRATION_PROGRESS_MESSAGE)) {
94 steps.push(Ref.getUnsafe(current));
95 loggedSteps.push(databaseMigrationProgress(output.slice(-4_000)));
96 }
97 });
98 assert.deepStrictEqual(
99 yield* runMigrations().pipe(
100 Effect.provideService(DatabaseMigrationProgress.DatabaseMigrationProgress, { current }),
101 Effect.provide(Logger.layer([logger], { mergeWithExisting: false })),
102 Effect.provideService(Console.Console, {
103 ...globalThis.console,
104 log: (...args) => {
105 output += `${NodeUtil.format(...args)}\n`;
106 },
107 }),
108 ),
109 v2Migrations,
110 );
111 assert.deepStrictEqual(
112 steps,
113 v2Migrations.map((_, index) => ({ current: index + 1, total: v2Migrations.length })),
114 );
115 assert.deepStrictEqual(loggedSteps, steps);
116 assert.isNull(yield* Ref.get(current));
117 assert.deepStrictEqual(
118 yield* runMigrations().pipe(
119 Effect.provideService(DatabaseMigrationProgress.DatabaseMigrationProgress, { current }),
120 ),
121 [],
122 );
123 assert.isNull(yield* Ref.get(current));
124 assert.deepStrictEqual(yield* history, migrationManifest);
125 assert.isAbove(yield* v2TableCount, 0);
126
127 // query_only rejects BEGIN IMMEDIATE, which CLI startup would otherwise take on the live database.
128 yield* sql`PRAGMA query_only = ON`;
129 assert.deepStrictEqual(yield* runMigrations(), []);
130 assert.deepStrictEqual(yield* history, migrationManifest);
131 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
132 );
133
134 it.effect("drops the unused correlation index and keeps correlation values", () =>
135 Effect.gen(function* () {
136 const sql = yield* SqlClient.SqlClient;
137 yield* runMigrations({ toMigrationInclusive: 54 });
138 yield* sql`
139 INSERT INTO orchestration_events (
140 event_id, aggregate_kind, stream_id, stream_version, event_type, occurred_at,
141 command_id, causation_event_id, correlation_id, actor_kind, payload_json, metadata_json
142 )
143 VALUES (
144 'event-1', 'thread', 'thread-1', 0, 'thread.created', '2026-01-01T00:00:00.000Z',
145 'command-1', NULL, 'correlation-1', 'client', '{}', '{}'
146 )
147 `;
148
149 yield* runMigrations();
150
151 const indexes = yield* sql<{ readonly name: string }>`
152 SELECT name FROM sqlite_master
153 WHERE type = 'index' AND tbl_name = 'orchestration_events' AND sql IS NOT NULL
154 `;
155 const indexNames = indexes.map((row) => row.name);
156 assert.notInclude(indexNames, "idx_orch_events_correlation_id");
157 for (const kept of [
158 "idx_orch_events_stream_version",
159 "idx_orch_events_stream_sequence",
160 "idx_orch_events_command_id",
161 "idx_orchestration_events_agent_stream_sequence",
162 ]) {
163 assert.include(indexNames, kept);
164 }
165 const events = yield* sql<{ readonly correlation_id: string | null }>`
166 SELECT correlation_id FROM orchestration_events WHERE event_id = 'event-1'
167 `;
168 assert.deepStrictEqual(events, [{ correlation_id: "correlation-1" }]);
169 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
170 );
171
172 it.effect.each([30, 54])("still starts with a site-local migration at id %s", (id) =>
173 Effect.gen(function* () {
174 const sql = yield* SqlClient.SqlClient;
175 yield* runMigrations({ toMigrationInclusive: 54 });
176 yield* sql`
177 UPDATE effect_sql_migrations SET name = 'SiteLocalMigration' WHERE migration_id = ${id}
178 `;
179
180 assert.deepStrictEqual(yield* runMigrations(), v2Migrations);
181 assert.isAbove(yield* v2TableCount, 0);
182 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
183 );
184
185 it.effect("only checks V2 migrations within the requested limit", () =>
186 Effect.gen(function* () {
187 const sql = yield* SqlClient.SqlClient;
188 yield* runMigrations({ toMigrationInclusive: 55 });
189 yield* sql`
190 INSERT INTO effect_sql_migrations (migration_id, name)
191 VALUES (56, 'SiteLocalMigration'), (${newerMigrationId}, 'NewerV2Migration')
192 `;
193 const before = yield* history;
194
195 assert.deepStrictEqual(yield* runMigrations({ toMigrationInclusive: 55 }), []);
196 const exit = yield* Effect.exit(runMigrations({ toMigrationInclusive: 56 }));
197 assert.isTrue(Exit.isFailure(exit));
198 assert.include(
199 String(exit),
200 "56_RemoveRedundantProjectionIndexes (recorded: SiteLocalMigration)",
201 );
202 assert.notInclude(String(exit), "57_ScheduledTaskWebhooks");
203 assert.deepStrictEqual(yield* history, before);
204 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
205 );
206
207 it.effect("keeps the migrations that finished before a later one failed", () =>
208 Effect.gen(function* () {
209 const sql = yield* SqlClient.SqlClient;
210 yield* runMigrations({ toMigrationInclusive: 81 });
211 yield* sql`CREATE TABLE orchestration_v2_projection_turn_item_counts (thread_id TEXT)`;
212
213 const current = yield* Ref.make<Progress | null>(null);
214 const exit = yield* Effect.exit(
215 runMigrations().pipe(
216 Effect.provideService(DatabaseMigrationProgress.DatabaseMigrationProgress, { current }),
217 ),
218 );
219
220 assert.isTrue(Exit.isFailure(exit));
221 assert.isNull(yield* Ref.get(current));
222 assert.deepStrictEqual(
223 yield* history,
224 migrationManifest.filter(([id]) => id <= 84),
225 );
226 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
227 );
228
229 it.effect("reapplies peer link migrations whose ledger rows are missing", () =>
230 Effect.gen(function* () {
231 const sql = yield* SqlClient.SqlClient;
232 yield* runMigrations({ toMigrationInclusive: 72 });
233 yield* sql`DELETE FROM effect_sql_migrations WHERE migration_id BETWEEN 70 AND 72`;
234
235 assert.deepStrictEqual(
236 yield* runMigrations(),
237 migrationManifest.filter(([id]) => id >= 70),
238 );
239 assert.deepStrictEqual(yield* history, migrationManifest);
240 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
241 );
242
243 it.effect("still starts after a newer build recorded a later V2 migration", () =>
244 Effect.gen(function* () {
245 const sql = yield* SqlClient.SqlClient;
246 yield* runMigrations();
247 yield* sql`
248 INSERT INTO effect_sql_migrations (migration_id, name)
249 VALUES (${newerMigrationId}, 'NewerV2Migration')
250 `;
251
252 assert.deepStrictEqual(yield* runMigrations(), []);
253 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
254 );
255});
256
257// The npm launcher reads the highest migration id from these file names.
258it.effect("registers every migration file", () =>
259 Effect.gen(function* () {
260 const fs = yield* FileSystem.FileSystem;
261 const path = yield* Path.Path;
262 const dir = path.join(import.meta.dirname, "Migrations");
263 const files = (yield* fs.readDirectory(dir)).flatMap((name) => {
264 const match = /^(\d+)_(\w+)\.ts$/.exec(name);
265 return match ? [[Number(match[1]), match[2]] as const] : [];
266 });
267 assert.deepStrictEqual(
268 files.toSorted(([a], [b]) => a - b),
269 migrationManifest,
270 );
271 }).pipe(Effect.provide(NodeServices.layer)),
272);