| 1 | /** |
| 2 | * Runs database migrations for Durable Object SQLite storage that uses Effect |
| 3 | * SQL. |
| 4 | * |
| 5 | * This module re-exports the shared `Migrator` loaders and error types, then |
| 6 | * provides `run` and `layer` helpers that execute ordered migrations through the |
| 7 | * current Durable Object SQLite `SqlClient`. Use it when a Durable |
| 8 | * Object needs to create or upgrade its local schema during construction, before |
| 9 | * repositories or request handlers use the object storage, or in tests that |
| 10 | * exercise Durable Object persistence. |
| 11 | * |
| 12 | * Migrations are recorded in `effect_sql_migrations` by default and are loaded |
| 13 | * using the shared `<id>_<name>` file or record-key convention. The underlying |
| 14 | * storage is scoped to a Durable Object id, so running migrations for one object |
| 15 | * does not update any other object instance; run the migrator against the same |
| 16 | * `DurableObjectStorage`-backed client that the object uses for normal queries |
| 17 | * so migrations can run in Cloudflare-managed transactions. These SQL |
| 18 | * migrations are separate from Cloudflare's Durable Object class migrations, and |
| 19 | * the Durable Object must already be configured with SQLite storage before this |
| 20 | * module can apply schema changes. Repeated startup runs are expected and are |
| 21 | * guarded by the migrations table, but request handling should wait until the |
| 22 | * migration layer has finished. This adapter does not currently write SQLite |
| 23 | * schema dumps for `schemaDirectory`. |
| 24 | * |
| 25 | * @since 4.0.0 |
| 26 | */ |
| 27 | import type * as Effect from "effect/Effect" |
| 28 | import * as Layer from "effect/Layer" |
| 29 | import * as Migrator from "effect/sql/Migrator" |
| 30 | import type * as Client from "effect/sql/SqlClient" |
| 31 | import type { SqlError } from "effect/sql/SqlError" |
| 32 | |
| 33 | /** |
| 34 | * @since 4.0.0 |
| 35 | */ |
| 36 | export * from "effect/sql/Migrator" |
| 37 | |
| 38 | /** |
| 39 | * Runs SQL migrations using the configured `SqlClient`, returning the migrations that were applied. |
| 40 | * |
| 41 | * @category running |
| 42 | * @since 4.0.0 |
| 43 | */ |
| 44 | export const run: <R2 = never>( |
| 45 | { loader, schemaDirectory, table }: Migrator.MigratorOptions<R2> |
| 46 | ) => Effect.Effect< |
| 47 | ReadonlyArray<readonly [id: number, name: string]>, |
| 48 | Migrator.MigrationError | SqlError, |
| 49 | Client.SqlClient | R2 |
| 50 | > = Migrator.make({}) |
| 51 | |
| 52 | /** |
| 53 | * Creates a layer that runs the configured SQL migrations during layer construction. |
| 54 | * |
| 55 | * @category layers |
| 56 | * @since 4.0.0 |
| 57 | */ |
| 58 | export const layer = <R>( |
| 59 | options: Migrator.MigratorOptions<R> |
| 60 | ): Layer.Layer<never, Migrator.MigrationError | SqlError, Client.SqlClient | R> => Layer.effectDiscard(run(options)) |