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

main
ts 87 lines 2.75 KB
Raw
1 import {
2 makeStatementExecutor,
3 MigrationError,
4 migrationError,
5 probeExecutor,
6 rowsFromCells,
7 runMigrations,
8 type NormalizedMigrationsInput,
9 type StampedMigrationsState,
10 } from "@alchemy.run/sql/Migrations";
11 import * as alloydb from "@distilled.cloud/gcp/alloydb_v1";
12 import * as Effect from "effect/Effect";
13 import * as Redacted from "effect/Redacted";
14
15 /**
16 * AlloyDB `instances.executeSql` as a {@link SqlExecutor}. AlloyDB rolls
17 * back every statement of a call when one fails, so each migration batch
18 * is one atomic request.
19 */
20 const makeDataApiExecutor = Effect.fn(function* (options: {
21 instance: string;
22 database: string;
23 user: string;
24 password: string;
25 }) {
26 const executeSql = yield* alloydb.executeSqlProjectsLocationsClustersInstances;
27 return makeStatementExecutor({
28 dialect: "postgres",
29 batch: "atomic",
30 execute: (sqlStatement) =>
31 executeSql({
32 instance: options.instance,
33 body: {
34 database: options.database,
35 user: options.user,
36 password: options.password,
37 sqlStatement,
38 },
39 }).pipe(
40 Effect.mapError(migrationError(`executeSql on '${options.instance}'`)),
41 // SQL errors come back inside a 200 response.
42 Effect.flatMap((response) => {
43 if (response.metadata?.status === "ERROR") {
44 return Effect.fail(
45 new MigrationError({
46 message: `executeSql on '${options.instance}' failed: ${response.metadata.message ?? "unknown error"}`,
47 }),
48 );
49 }
50 const last = response.sqlResults?.at(-1);
51 return Effect.succeed(rowsFromCells(last?.columns, last?.rows));
52 }),
53 ),
54 });
55 });
56
57 /**
58 * Apply migrations to a database on an AlloyDB primary instance through
59 * the Data API. Call once the instance is ready.
60 */
61 export const runInstanceMigrations = Effect.fn(function* (options: {
62 instance: string;
63 database: string;
64 input: NormalizedMigrationsInput;
65 stamped: StampedMigrationsState;
66 user: string | undefined;
67 password: string | Redacted.Redacted<string> | undefined;
68 }) {
69 if (options.user === undefined || options.password === undefined) {
70 return yield* new MigrationError({
71 message: `Migrations on '${options.instance}' need credentials; set migrationsUser and migrationsPassword`,
72 });
73 }
74 const executor = yield* makeDataApiExecutor({
75 instance: options.instance,
76 database: options.database,
77 user: options.user,
78 password: Redacted.isRedacted(options.password)
79 ? Redacted.value(options.password)
80 : options.password,
81 });
82 return yield* runMigrations({
83 input: options.input,
84 stamped: options.stamped,
85 withExecutor: (apply) => probeExecutor(executor).pipe(Effect.flatMap(apply)),
86 });
87 });