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

main
ts 71 lines 2.53 KB
Raw
1 import { inlineSqlParams, MigrationError, type SqlExecutor } from "@alchemy.run/sql/Migrations";
2 import * as Retry from "@distilled.cloud/cloudflare/Retry";
3 import { isTransientError } from "@distilled.cloud/core/category";
4 import * as Effect from "effect/Effect";
5
6 /**
7 * The minimal query surface the migration flow needs: run (possibly
8 * multi-statement) SQL and return the D1 HTTP API's result envelope. Two
9 * implementations exist:
10 *
11 * - the cloud executor (distilled's `d1.queryDatabase`);
12 * - the local executor (`LocalD1Gateway.ts`), which tunnels the same
13 * protocol into the local workerd D1 simulator.
14 */
15 export interface D1QueryResult {
16 result: Array<{
17 results?: unknown;
18 success?: boolean | null;
19 meta?: unknown;
20 }>;
21 }
22
23 export type D1SqlExecutor<E = unknown, R = never> = (
24 sql: string,
25 ) => Effect.Effect<D1QueryResult, E, R>;
26
27 /**
28 * Adapt a raw D1 executor into the registry's {@link SqlExecutor} contract
29 * (see `src/SQL/Migrations/`). Parameters are inlined as SQL literals — the
30 * D1 HTTP protocol path here is raw-SQL-only, and the only parametrized
31 * queries are the migration formats' own bookkeeping. Batches join into a
32 * single multi-statement query: D1 over HTTP has no transactions, so one
33 * batched call is the closest available unit (matching wrangler's own
34 * behavior).
35 */
36 export const makeD1MigrationExecutor = <E>(raw: D1SqlExecutor<E>): SqlExecutor => ({
37 dialect: "sqlite",
38 query: (sql, params) =>
39 raw(params && params.length > 0 ? inlineSqlParams(sql, params, "sqlite") : sql).pipe(
40 Effect.map((result) => (result.result[0]?.results ?? []) as Array<Record<string, unknown>>),
41 Effect.mapError(
42 (cause) =>
43 new MigrationError({
44 message: `D1 query failed: ${String(cause)}`,
45 cause,
46 }),
47 ),
48 ),
49 // D1 may run a batch and still fail its reply; a blind resend would run its
50 // DDL twice (#1889). The migration engine checks `__alchemy_migrations`
51 // before it resends a transient failure.
52 batch: (statements) =>
53 raw(
54 statements
55 .map((statement) => statement.trim())
56 .filter((statement) => statement.length > 0)
57 .map((statement) => (statement.endsWith(";") ? statement : `${statement};`))
58 .join("\n"),
59 ).pipe(
60 Retry.none,
61 Effect.asVoid,
62 Effect.mapError(
63 (cause) =>
64 new MigrationError({
65 message: `D1 migration batch failed: ${String(cause)}`,
66 cause,
67 transient: isTransientError(cause),
68 }),
69 ),
70 ),
71 });