@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 697 lines 26.4 KB
Raw
1 import { Database } from "bun:sqlite";
2 import {
3 applyAlchemyFormat,
4 applyMigrations,
5 MigrationError,
6 readDrizzleDirRecords,
7 readFlatRecords,
8 type SqlExecutor,
9 } from "@alchemy.run/sql/Migrations";
10 import { expect, layer } from "@alchemy.run/test";
11 import * as NodeServices from "@effect/platform-node/NodeServices";
12 import * as Effect from "effect/Effect";
13 import * as Result from "effect/Result";
14 import { makeSqliteExecutor, tableNames } from "./sqlite-executor.ts";
15
16 const fixture = (name: string) => new URL(`./fixtures/${name}`, import.meta.url).pathname;
17
18 const describe = layer(NodeServices.layer);
19
20 const ALCHEMY_COLUMNS = ["id", "hash", "created_at", "name", "applied_at"];
21
22 const migrationRows = (db: Database, table = "__alchemy_migrations") =>
23 db.query(`SELECT hash, created_at, name, applied_at FROM ${table} ORDER BY id;`).all() as Array<{
24 hash: string;
25 created_at: number | null;
26 name: string;
27 applied_at: string | null;
28 }>;
29
30 // Fails `0001_users.sql` batches the way a data API can (#1889): `"lost"` runs
31 // the batch and then fails the reply, `"dropped"` fails before running it.
32 // `transient` is the flag the transport sets on the failure, `failures` is how
33 // many sends fail, and `failLedgerRead` fails the ledger read that follows a
34 // failed send.
35 const flakyBatches = (
36 executor: SqlExecutor,
37 options: {
38 fault: "lost" | "dropped";
39 transient: boolean;
40 failures?: number;
41 failLedgerRead?: boolean;
42 },
43 ): SqlExecutor & { sends: () => number } => {
44 const { fault, transient, failures = 1, failLedgerRead = false } = options;
45 let sends = 0;
46 let failed = false;
47 return {
48 ...executor,
49 sends: () => sends,
50 query: (sql, params) =>
51 failed && failLedgerRead
52 ? Effect.fail(new MigrationError({ message: "ledger read failed", transient: true }))
53 : executor.query(sql, params),
54 batch: (statements) =>
55 Effect.gen(function* () {
56 // Only the migration's own batch, not the bookkeeping table's setup.
57 if (!statements.some((statement) => statement.includes("CREATE TABLE users"))) {
58 return yield* executor.batch(statements);
59 }
60 sends++;
61 if (sends > failures) return yield* executor.batch(statements);
62 if (fault === "lost") yield* executor.batch(statements);
63 failed = true;
64 return yield* new MigrationError({ message: "503 Service Unavailable", transient });
65 }),
66 };
67 };
68
69 describe("alchemy format", (it) => {
70 it.effect(
71 "does not resend a batch that landed before its reply was lost",
72 () =>
73 Effect.gen(function* () {
74 const db = new Database(":memory:");
75 const executor = flakyBatches(makeSqliteExecutor(db), { fault: "lost", transient: true });
76 const records = yield* readFlatRecords(fixture("flat"));
77 yield* applyAlchemyFormat({
78 executor,
79 table: "__alchemy_migrations",
80 records: records.slice(0, 1),
81 });
82 // A resend would fail on the bare CREATE TABLE.
83 expect(executor.sends()).toBe(1);
84 expect(migrationRows(db).map((r) => r.name)).toEqual(["0001_users.sql"]);
85 }),
86 { tags: ["unit", "local"] },
87 );
88
89 it.effect(
90 "resends a transient batch failure that did not land",
91 () =>
92 Effect.gen(function* () {
93 const db = new Database(":memory:");
94 const executor = flakyBatches(makeSqliteExecutor(db), {
95 fault: "dropped",
96 transient: true,
97 });
98 const records = yield* readFlatRecords(fixture("flat"));
99 yield* applyAlchemyFormat({
100 executor,
101 table: "__alchemy_migrations",
102 records: records.slice(0, 1),
103 });
104 expect(executor.sends()).toBe(2);
105 expect(migrationRows(db).map((r) => r.name)).toEqual(["0001_users.sql"]);
106 }),
107 { tags: ["unit", "local"] },
108 );
109
110 it.effect(
111 "fails when the resend fails too, without sending a third time",
112 () =>
113 Effect.gen(function* () {
114 const db = new Database(":memory:");
115 const executor = flakyBatches(makeSqliteExecutor(db), {
116 fault: "dropped",
117 transient: true,
118 failures: 2,
119 });
120 const records = yield* readFlatRecords(fixture("flat"));
121 const result = yield* Effect.result(
122 applyAlchemyFormat({
123 executor,
124 table: "__alchemy_migrations",
125 records: records.slice(0, 1),
126 }),
127 );
128 expect(Result.isFailure(result)).toBe(true);
129 if (Result.isFailure(result)) {
130 expect(result.failure._tag).toBe("MigrationError");
131 expect(result.failure.message).toContain("503");
132 }
133 expect(executor.sends()).toBe(2);
134 expect(migrationRows(db)).toEqual([]);
135 }),
136 { tags: ["unit", "local"] },
137 );
138
139 it.effect(
140 "fails without resending when the ledger cannot be read after a failure",
141 () =>
142 Effect.gen(function* () {
143 const db = new Database(":memory:");
144 const executor = flakyBatches(makeSqliteExecutor(db), {
145 fault: "dropped",
146 transient: true,
147 failLedgerRead: true,
148 });
149 const records = yield* readFlatRecords(fixture("flat"));
150 const result = yield* Effect.result(
151 applyAlchemyFormat({
152 executor,
153 table: "__alchemy_migrations",
154 records: records.slice(0, 1),
155 }),
156 );
157 expect(Result.isFailure(result)).toBe(true);
158 if (Result.isFailure(result)) {
159 expect(result.failure._tag).toBe("MigrationError");
160 expect(result.failure.message).toContain("ledger read failed");
161 }
162 expect(executor.sends()).toBe(1);
163 expect(migrationRows(db)).toEqual([]);
164 }),
165 { tags: ["unit", "local"] },
166 );
167
168 it.effect(
169 "fails a non-transient batch failure without resending it",
170 () =>
171 Effect.gen(function* () {
172 const db = new Database(":memory:");
173 const executor = flakyBatches(makeSqliteExecutor(db), {
174 fault: "dropped",
175 transient: false,
176 });
177 const records = yield* readFlatRecords(fixture("flat"));
178 const result = yield* Effect.result(
179 applyAlchemyFormat({
180 executor,
181 table: "__alchemy_migrations",
182 records: records.slice(0, 1),
183 }),
184 );
185 expect(Result.isFailure(result)).toBe(true);
186 if (Result.isFailure(result)) expect(result.failure._tag).toBe("MigrationError");
187 expect(executor.sends()).toBe(1);
188 expect(migrationRows(db)).toEqual([]);
189 }),
190 { tags: ["unit", "local"] },
191 );
192
193 it.effect(
194 "creates the table and applies flat migrations in order",
195 () =>
196 Effect.gen(function* () {
197 const db = new Database(":memory:");
198 const executor = makeSqliteExecutor(db);
199 const records = yield* readFlatRecords(fixture("flat"));
200 yield* applyAlchemyFormat({ executor, table: "__alchemy_migrations", records });
201
202 expect(tableNames(db)).toEqual(
203 expect.arrayContaining(["__alchemy_migrations", "posts", "users"]),
204 );
205 const columns = db.query("PRAGMA table_info(__alchemy_migrations);").all() as Array<{
206 name: string;
207 }>;
208 expect(columns.map((c) => c.name)).toEqual(ALCHEMY_COLUMNS);
209
210 const rows = migrationRows(db);
211 expect(rows.map((r) => r.name)).toEqual(["0001_users.sql", "0002_posts.sql"]);
212 expect(rows[0].hash).toMatch(/^[0-9a-f]{64}$/);
213 expect(rows[0].applied_at).toBeTruthy();
214
215 // Idempotent — a replay would throw on the bare CREATE TABLEs.
216 yield* applyAlchemyFormat({ executor, table: "__alchemy_migrations", records });
217 expect(migrationRows(db).length).toBe(2);
218 }),
219 { tags: ["unit", "local"] },
220 );
221
222 it.effect(
223 "applies only pending migrations on subsequent runs",
224 () =>
225 Effect.gen(function* () {
226 const db = new Database(":memory:");
227 const executor = makeSqliteExecutor(db);
228 const records = yield* readFlatRecords(fixture("flat"));
229 yield* applyAlchemyFormat({
230 executor,
231 table: "__alchemy_migrations",
232 records: records.slice(0, 1),
233 });
234 yield* applyAlchemyFormat({ executor, table: "__alchemy_migrations", records });
235 expect(migrationRows(db).map((r) => r.name)).toEqual(["0001_users.sql", "0002_posts.sql"]);
236 }),
237 { tags: ["unit", "local"] },
238 );
239
240 // #1389: name-keyed skip used to ignore content hashes, then the
241 // resource persisted the new hashes as if the rewrite had applied.
242 it.effect(
243 "fails when an already-applied migration's contents changed",
244 () =>
245 Effect.gen(function* () {
246 const db = new Database(":memory:");
247 const executor = makeSqliteExecutor(db);
248 const records = yield* readFlatRecords(fixture("flat"));
249 yield* applyAlchemyFormat({
250 executor,
251 table: "__alchemy_migrations",
252 records,
253 });
254 const rewritten = [
255 {
256 ...records[0],
257 hash: "a".repeat(64),
258 sql: "SELECT 1;",
259 statements: ["SELECT 1;"],
260 },
261 records[1],
262 ];
263 const result = yield* Effect.result(
264 applyAlchemyFormat({
265 executor,
266 table: "__alchemy_migrations",
267 records: rewritten,
268 }),
269 );
270 expect(Result.isFailure(result)).toBe(true);
271 if (Result.isFailure(result)) {
272 expect(result.failure._tag).toBe("RewrittenMigrationHistoryError");
273 expect(result.failure.message).toContain("0001_users.sql");
274 }
275 expect(migrationRows(db).map((r) => r.hash)).toEqual(records.map((r) => r.hash));
276 }),
277 { tags: ["unit", "local"] },
278 );
279
280 it.effect(
281 "fails when an already-applied migration file is removed",
282 () =>
283 Effect.gen(function* () {
284 const db = new Database(":memory:");
285 const executor = makeSqliteExecutor(db);
286 const records = yield* readFlatRecords(fixture("flat"));
287 yield* applyAlchemyFormat({
288 executor,
289 table: "__alchemy_migrations",
290 records,
291 });
292 const result = yield* Effect.result(
293 applyAlchemyFormat({
294 executor,
295 table: "__alchemy_migrations",
296 records: records.slice(1),
297 }),
298 );
299 expect(Result.isFailure(result)).toBe(true);
300 if (Result.isFailure(result)) {
301 expect(result.failure._tag).toBe("RewrittenMigrationHistoryError");
302 expect(result.failure.message).toContain("0001_users.sql");
303 }
304 }),
305 { tags: ["unit", "local"] },
306 );
307
308 it.effect(
309 "upgrades the legacy Alchemy 3-column table in place without replaying",
310 () =>
311 Effect.gen(function* () {
312 const db = new Database(":memory:");
313 // A pre-registry deploy: the invented shape, TEXT id.
314 db.run(
315 "CREATE TABLE d1_migrations (id TEXT PRIMARY KEY, name TEXT NOT NULL, applied_at TEXT NOT NULL);",
316 );
317 db.run(
318 "INSERT INTO d1_migrations (id, name, applied_at) VALUES ('00001', '0001_users.sql', '2024-01-01 00:00:00');",
319 );
320 // ...and migration 0001 really ran:
321 db.run("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL);");
322
323 const executor = makeSqliteExecutor(db);
324 const records = yield* readFlatRecords(fixture("flat"));
325 // Legacy deploys keep converging against their persisted table.
326 yield* applyAlchemyFormat({ executor, table: "d1_migrations", records });
327
328 const columns = db.query("PRAGMA table_info(d1_migrations);").all() as Array<{
329 name: string;
330 type: string;
331 }>;
332 expect(columns.map((c) => c.name)).toEqual(ALCHEMY_COLUMNS);
333 const rows = migrationRows(db, "d1_migrations");
334 expect(rows.map((r) => r.name)).toEqual(["0001_users.sql", "0002_posts.sql"]);
335 // Backfilled from the matching local record, not a placeholder.
336 expect(rows[0].hash).toBe(records[0].hash);
337 // The original applied_at survives the rebuild.
338 expect(rows[0].applied_at).toBe("2024-01-01 00:00:00");
339 expect(tableNames(db)).toContain("posts");
340 }),
341 { tags: ["unit", "local"] },
342 );
343
344 it.effect(
345 "upgrades the oldest 2-column shape, reading names from the primary column",
346 () =>
347 Effect.gen(function* () {
348 const db = new Database(":memory:");
349 db.run(
350 "CREATE TABLE __alchemy_migrations (id TEXT PRIMARY KEY, applied_at TEXT NOT NULL);",
351 );
352 db.run(
353 "INSERT INTO __alchemy_migrations (id, applied_at) VALUES ('0001_users.sql', '2024-01-01 00:00:00');",
354 );
355 db.run("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL);");
356
357 const executor = makeSqliteExecutor(db);
358 const records = yield* readFlatRecords(fixture("flat"));
359 yield* applyAlchemyFormat({ executor, table: "__alchemy_migrations", records });
360 expect(migrationRows(db).map((r) => r.name)).toEqual(["0001_users.sql", "0002_posts.sql"]);
361 }),
362 { tags: ["unit", "local"] },
363 );
364
365 it.effect(
366 "converts a wrangler-shaped table in place when it IS the resolved table",
367 () =>
368 Effect.gen(function* () {
369 const db = new Database(":memory:");
370 db.run(
371 "CREATE TABLE d1_migrations (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE, applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL);",
372 );
373 db.run(
374 "INSERT INTO d1_migrations (name, applied_at) VALUES ('0001_users.sql', '2024-01-01 00:00:00');",
375 );
376 db.run("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL);");
377
378 const executor = makeSqliteExecutor(db);
379 const records = yield* readFlatRecords(fixture("flat"));
380 yield* applyAlchemyFormat({ executor, table: "d1_migrations", records });
381 const columns = db.query("PRAGMA table_info(d1_migrations);").all() as Array<{
382 name: string;
383 }>;
384 expect(columns.map((c) => c.name)).toEqual(ALCHEMY_COLUMNS);
385 expect(migrationRows(db, "d1_migrations").map((r) => r.name)).toEqual([
386 "0001_users.sql",
387 "0002_posts.sql",
388 ]);
389 }),
390 { tags: ["unit", "local"] },
391 );
392
393 it.effect(
394 "legacy rows recorded as dir/migration.sql keep matching directory records",
395 () =>
396 // Pre-registry Alchemy applied drizzle-layout dirs under the flat
397 // key (`<dir>/migration.sql`); current records key them by `<dir>`.
398 Effect.gen(function* () {
399 const db = new Database(":memory:");
400 db.run(
401 "CREATE TABLE d1_migrations (id TEXT PRIMARY KEY, name TEXT NOT NULL, applied_at TEXT NOT NULL);",
402 );
403 db.run(
404 "INSERT INTO d1_migrations (id, name, applied_at) VALUES ('00001', '20240101000000_init/migration.sql', '2024-01-01 00:00:00');",
405 );
406 db.run("CREATE TABLE users (id integer PRIMARY KEY NOT NULL, name text NOT NULL);");
407 db.run("CREATE UNIQUE INDEX users_name_unique ON users (name);");
408
409 const executor = makeSqliteExecutor(db);
410 const records = yield* readDrizzleDirRecords(fixture("drizzle-v1"));
411 yield* applyAlchemyFormat({ executor, table: "d1_migrations", records });
412 expect(migrationRows(db, "d1_migrations").map((r) => r.name)).toEqual([
413 "20240101000000_init/migration.sql",
414 "20240102000000_add_posts",
415 ]);
416 expect(tableNames(db)).toContain("posts");
417 }),
418 { tags: ["unit", "local"] },
419 );
420
421 it.effect(
422 "fails the upgrade when a recorded migration matches no local file",
423 () =>
424 Effect.gen(function* () {
425 const db = new Database(":memory:");
426 db.run(
427 "CREATE TABLE __alchemy_migrations (id TEXT PRIMARY KEY, name TEXT NOT NULL, applied_at TEXT NOT NULL);",
428 );
429 db.run(
430 "INSERT INTO __alchemy_migrations (id, name, applied_at) VALUES ('00001', 'zzz_deleted.sql', '2024-01-01 00:00:00');",
431 );
432 const executor = makeSqliteExecutor(db);
433 const records = yield* readFlatRecords(fixture("flat"));
434 const result = yield* Effect.result(
435 applyAlchemyFormat({ executor, table: "__alchemy_migrations", records }),
436 );
437 expect(Result.isFailure(result)).toBe(true);
438 if (Result.isFailure(result)) {
439 expect(result.failure._tag).toBe("MigrationHistoryConflictError");
440 expect(result.failure.message).toContain("zzz_deleted.sql");
441 }
442 }),
443 { tags: ["unit", "local"] },
444 );
445 });
446
447 describe("one-way conversion from foreign tables", (it) => {
448 it.effect(
449 "adopts a wrangler-migrated database: history copied, table frozen",
450 () =>
451 Effect.gen(function* () {
452 const db = new Database(":memory:");
453 // What `wrangler d1 migrations apply` left behind.
454 db.run(
455 "CREATE TABLE d1_migrations (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE, applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL);",
456 );
457 db.run(
458 "INSERT INTO d1_migrations (name, applied_at) VALUES ('0001_users.sql', '2024-01-01 00:00:00');",
459 );
460 db.run("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL);");
461
462 const executor = makeSqliteExecutor(db);
463 const records = yield* readFlatRecords(fixture("flat"));
464 yield* applyAlchemyFormat({ executor, table: "__alchemy_migrations", records });
465
466 // History converted, only the pending migration ran.
467 const rows = migrationRows(db);
468 expect(rows.map((r) => r.name)).toEqual(["0001_users.sql", "0002_posts.sql"]);
469 expect(rows[0].hash).toBe(records[0].hash);
470 expect(rows[0].applied_at).toBe("2024-01-01 00:00:00");
471
472 // The wrangler table is frozen — never written, never dropped.
473 const wrangler = db.query("SELECT name FROM d1_migrations ORDER BY id;").all() as Array<{
474 name: string;
475 }>;
476 expect(wrangler.map((r) => r.name)).toEqual(["0001_users.sql"]);
477 }),
478 { tags: ["unit", "local"] },
479 );
480
481 it.effect(
482 "conversion fails when foreign history references a missing local file",
483 () =>
484 Effect.gen(function* () {
485 const db = new Database(":memory:");
486 db.run(
487 "CREATE TABLE d1_migrations (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE, applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL);",
488 );
489 db.run("INSERT INTO d1_migrations (name) VALUES ('zzz_gone.sql');");
490 const executor = makeSqliteExecutor(db);
491 const records = yield* readFlatRecords(fixture("flat"));
492 const result = yield* Effect.result(
493 applyAlchemyFormat({ executor, table: "__alchemy_migrations", records }),
494 );
495 expect(Result.isFailure(result)).toBe(true);
496 if (Result.isFailure(result)) {
497 expect(result.failure._tag).toBe("MigrationHistoryConflictError");
498 }
499 }),
500 { tags: ["unit", "local"] },
501 );
502
503 it.effect(
504 "adopts a state-lost legacy 3-column d1_migrations as a conversion source",
505 () =>
506 // Old Alchemy deploys wrote a 3-column d1_migrations; if state was
507 // lost (adoption), the resolved table is __alchemy_migrations and
508 // the legacy table must be picked up as a source, not replayed.
509 Effect.gen(function* () {
510 const db = new Database(":memory:");
511 db.run(
512 "CREATE TABLE d1_migrations (id TEXT PRIMARY KEY, name TEXT NOT NULL, applied_at TEXT NOT NULL);",
513 );
514 db.run(
515 "INSERT INTO d1_migrations (id, name, applied_at) VALUES ('00001', '0001_users.sql', '2024-01-01 00:00:00');",
516 );
517 db.run("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL);");
518
519 const executor = makeSqliteExecutor(db);
520 const records = yield* readFlatRecords(fixture("flat"));
521 yield* applyAlchemyFormat({ executor, table: "__alchemy_migrations", records });
522
523 const rows = migrationRows(db);
524 expect(rows.map((r) => r.name)).toEqual(["0001_users.sql", "0002_posts.sql"]);
525 expect(rows[0].hash).toBe(records[0].hash);
526 // The legacy table is frozen as a source, still 3 columns.
527 const legacyColumns = db.query("PRAGMA table_info(d1_migrations);").all() as Array<{
528 name: string;
529 }>;
530 expect(legacyColumns.map((c) => c.name)).toEqual(["id", "name", "applied_at"]);
531 }),
532 { tags: ["unit", "local"] },
533 );
534
535 it.effect(
536 "prefers drizzle history when multiple foreign sources exist",
537 () =>
538 Effect.gen(function* () {
539 const db = new Database(":memory:");
540 const records = yield* readDrizzleDirRecords(fixture("drizzle-v1"));
541 // Both a drizzle table and a wrangler table exist; drizzle's is
542 // probed first and carries hashes, so it wins.
543 db.run(
544 "CREATE TABLE __drizzle_migrations (id INTEGER PRIMARY KEY, hash text NOT NULL, created_at numeric, name text, applied_at TEXT);",
545 );
546 db.run(
547 `INSERT INTO __drizzle_migrations (hash, created_at, name) VALUES ('${records[0].hash}', 1704067200000, '20240101000000_init');`,
548 );
549 db.run(
550 "CREATE TABLE d1_migrations (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE, applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL);",
551 );
552 db.run("INSERT INTO d1_migrations (name) VALUES ('20240101000000_init');");
553 db.run("CREATE TABLE users (id integer PRIMARY KEY NOT NULL, name text NOT NULL);");
554 db.run("CREATE UNIQUE INDEX users_name_unique ON users (name);");
555
556 const executor = makeSqliteExecutor(db);
557 yield* applyAlchemyFormat({ executor, table: "__alchemy_migrations", records });
558 const rows = migrationRows(db);
559 expect(rows.map((r) => r.name)).toEqual([
560 "20240101000000_init",
561 "20240102000000_add_posts",
562 ]);
563 // Hash came from drizzle's table (wrangler has none).
564 expect(rows[0].hash).toBe(records[0].hash);
565 }),
566 { tags: ["unit", "local"] },
567 );
568
569 it.effect(
570 "adopts a prisma-migrated database via _prisma_migrations",
571 () =>
572 Effect.gen(function* () {
573 const db = new Database(":memory:");
574 // Prisma's table shape (sqlite rendition), one applied + one
575 // rolled-back migration.
576 db.run(
577 `CREATE TABLE _prisma_migrations (
578 id TEXT PRIMARY KEY,
579 checksum TEXT NOT NULL,
580 finished_at TEXT,
581 migration_name TEXT NOT NULL,
582 logs TEXT,
583 rolled_back_at TEXT,
584 started_at TEXT NOT NULL,
585 applied_steps_count INTEGER NOT NULL DEFAULT 0
586 );`,
587 );
588 const records = yield* readDrizzleDirRecords(fixture("prisma"));
589 db.run(
590 `INSERT INTO _prisma_migrations (id, checksum, finished_at, migration_name, started_at, applied_steps_count)
591 VALUES ('a', '${records[0].hash}', '2024-01-01 00:00:01', '20240101000000_init', '2024-01-01 00:00:00', 1);`,
592 );
593 db.run(
594 `INSERT INTO _prisma_migrations (id, checksum, rolled_back_at, migration_name, started_at)
595 VALUES ('b', 'dead', '2024-01-02 00:00:00', '20240102000000_rolled_back', '2024-01-02 00:00:00');`,
596 );
597 // The applied migration's tables exist (Prisma-dialect SQL in the
598 // fixture is postgres-flavored, so create a stand-in):
599 db.run("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT);");
600
601 const executor = makeSqliteExecutor(db);
602 yield* applyAlchemyFormat({
603 executor,
604 // Only the applied row must convert; the rolled-back row is
605 // skipped even though it has no local file.
606 table: "__alchemy_migrations",
607 records: records.slice(0, 1),
608 });
609 const rows = migrationRows(db);
610 expect(rows.map((r) => r.name)).toEqual(["20240101000000_init"]);
611 // Prisma's checksum is sha256 of migration.sql — carried verbatim.
612 expect(rows[0].hash).toBe(records[0].hash);
613 // Frozen source.
614 expect(
615 (
616 db.query("SELECT COUNT(*) AS n FROM _prisma_migrations;").all() as Array<{ n: number }>
617 )[0].n,
618 ).toBe(2);
619 }),
620 { tags: ["unit", "local"] },
621 );
622
623 it.effect(
624 "a failed prisma migration blocks conversion with guidance",
625 () =>
626 Effect.gen(function* () {
627 const db = new Database(":memory:");
628 db.run(
629 `CREATE TABLE _prisma_migrations (
630 id TEXT PRIMARY KEY,
631 checksum TEXT NOT NULL,
632 finished_at TEXT,
633 migration_name TEXT NOT NULL,
634 logs TEXT,
635 rolled_back_at TEXT,
636 started_at TEXT NOT NULL,
637 applied_steps_count INTEGER NOT NULL DEFAULT 0
638 );`,
639 );
640 db.run(
641 `INSERT INTO _prisma_migrations (id, checksum, migration_name, started_at)
642 VALUES ('a', 'abc', '20240101000000_broken', '2024-01-01 00:00:00');`,
643 );
644 const executor = makeSqliteExecutor(db);
645 const records = yield* readFlatRecords(fixture("flat"));
646 const result = yield* Effect.result(
647 applyAlchemyFormat({ executor, table: "__alchemy_migrations", records }),
648 );
649 expect(Result.isFailure(result)).toBe(true);
650 if (Result.isFailure(result)) {
651 expect(result.failure._tag).toBe("MigrationError");
652 expect(result.failure.message).toContain("prisma migrate resolve");
653 }
654 }),
655 { tags: ["unit", "local"] },
656 );
657 });
658
659 describe("registry apply", (it) => {
660 it.effect(
661 "keys directory-layout dirs by directory name",
662 () =>
663 Effect.gen(function* () {
664 const db = new Database(":memory:");
665 const executor = makeSqliteExecutor(db);
666 yield* applyMigrations({
667 resolved: { dir: fixture("drizzle-v1"), table: "__alchemy_migrations" },
668 executor,
669 });
670 expect(migrationRows(db).map((r) => r.name)).toEqual([
671 "20240101000000_init",
672 "20240102000000_add_posts",
673 ]);
674 }),
675 { tags: ["unit", "local"] },
676 );
677
678 it.effect(
679 "rejects drizzle-v0 layouts",
680 () =>
681 Effect.gen(function* () {
682 const db = new Database(":memory:");
683 const executor = makeSqliteExecutor(db);
684 const result = yield* Effect.result(
685 applyMigrations({
686 resolved: { dir: fixture("drizzle-v0"), table: "__alchemy_migrations" },
687 executor,
688 }),
689 );
690 expect(Result.isFailure(result)).toBe(true);
691 if (Result.isFailure(result)) {
692 expect(result.failure._tag).toBe("DrizzleV0LayoutError");
693 }
694 }),
695 { tags: ["unit", "local"] },
696 );
697 });