The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { NodeServices } from "@effect/platform-node" |
| 2 | import { PgMigrator } from "@effect/sql-pg" |
| 3 | import { assert, it } from "@effect/vitest" |
| 4 | import { Deferred, Effect, Fiber } from "effect" |
| 5 | import { SqlClient } from "effect/sql" |
| 6 | import { TestClock } from "effect/testing" |
| 7 | import { PgContainer } from "./utils.ts" |
| 8 | |
| 9 | it.layer(PgContainer.layerClient, { timeout: "30 seconds" })("PgMigrator", (it) => { |
| 10 | it.effect("accepts a history table committed by a concurrent migrator", () => |
| 11 | Effect.gen(function*() { |
| 12 | const sql = yield* SqlClient.SqlClient |
| 13 | const created = yield* Deferred.make<number>() |
| 14 | const commit = yield* Deferred.make<void>() |
| 15 | let migrationRuns = 0 |
| 16 | const creator = yield* sql.withTransaction(Effect.gen(function*() { |
| 17 | const [session] = yield* sql<{ pid: number }>`SELECT pg_backend_pid() AS pid` |
| 18 | yield* sql`CREATE TABLE race_migrations ( |
| 19 | migration_id INTEGER PRIMARY KEY, |
| 20 | created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), |
| 21 | name TEXT NOT NULL |
| 22 | )` |
| 23 | yield* sql`INSERT INTO race_migrations (migration_id, name) VALUES (1, 'init')` |
| 24 | yield* Deferred.succeed(created, session.pid) |
| 25 | yield* Deferred.await(commit) |
| 26 | })).pipe(Effect.forkScoped) |
| 27 | |
| 28 | yield* Effect.gen(function*() { |
| 29 | const creatorPid = yield* Deferred.await(created) |
| 30 | const migrator = yield* PgMigrator.run({ |
| 31 | table: "race_migrations", |
| 32 | loader: PgMigrator.fromRecord({ |
| 33 | "1_init": Effect.sync(() => { |
| 34 | migrationRuns++ |
| 35 | }) |
| 36 | }) |
| 37 | }).pipe(Effect.forkScoped) |
| 38 | |
| 39 | // Release the creator only once CREATE has reached PostgreSQL and is blocked on it. |
| 40 | yield* Effect.gen(function*() { |
| 41 | while (true) { |
| 42 | const blocked = yield* sql`SELECT pid FROM pg_stat_activity |
| 43 | WHERE wait_event_type = 'Lock' |
| 44 | AND query LIKE 'CREATE TABLE "race_migrations"%' |
| 45 | AND ${creatorPid} = ANY(pg_blocking_pids(pid))` |
| 46 | if (blocked.length > 0) return |
| 47 | yield* Effect.sleep(10) |
| 48 | } |
| 49 | }).pipe(Effect.timeout("10 seconds")) |
| 50 | |
| 51 | yield* Deferred.succeed(commit, undefined) |
| 52 | yield* Fiber.join(creator) |
| 53 | assert.deepStrictEqual(yield* Fiber.join(migrator), []) |
| 54 | assert.strictEqual(migrationRuns, 0) |
| 55 | assert.deepStrictEqual( |
| 56 | yield* sql`SELECT migration_id, name FROM race_migrations`, |
| 57 | [{ migration_id: 1, name: "init" }] |
| 58 | ) |
| 59 | }).pipe(Effect.ensuring(Deferred.succeed(commit, undefined))) |
| 60 | }).pipe(Effect.scoped, Effect.provide(NodeServices.layer), TestClock.withLive), 30_000) |
| 61 | }) |