The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 2 | import * as Neon from "@alchemy.run/neon"; |
| 3 | import * as SQL from "@alchemy.run/sql/Postgres"; |
| 4 | import type * as Arr from "effect/Array"; |
| 5 | import * as Data from "effect/Data"; |
| 6 | import * as Effect from "effect/Effect"; |
| 7 | import * as HttpServerRequest from "effect/http/HttpServerRequest"; |
| 8 | import * as HttpServerResponse from "effect/http/HttpServerResponse"; |
| 9 | import { makeLayerUsers, makeSqlRoutes, type UserRow } from "./routes.ts"; |
| 10 | |
| 11 | export const Hyperdrive = Effect.gen(function* () { |
| 12 | const project = yield* Neon.Project("SqlPostgresProject"); |
| 13 | return yield* Cloudflare.Hyperdrive.Connection("SqlPostgresEdge", { |
| 14 | origin: project.origin, |
| 15 | // The tests assert read-after-write; Hyperdrive's default SELECT caching |
| 16 | // (~60s TTL) can serve a pre-insert empty result — and keep serving it |
| 17 | // across retries — so caching is disabled for correctness assertions. |
| 18 | caching: { disabled: true }, |
| 19 | }); |
| 20 | }); |
| 21 | |
| 22 | const TABLE = "alchemy_sql_users"; |
| 23 | |
| 24 | const DDL = `CREATE TABLE IF NOT EXISTS ${TABLE} ( |
| 25 | id INT PRIMARY KEY, |
| 26 | name TEXT NOT NULL, |
| 27 | email TEXT NOT NULL |
| 28 | )`; |
| 29 | |
| 30 | class Rollback extends Data.TaggedError("Rollback")<{}> {} |
| 31 | |
| 32 | /** |
| 33 | * Init effect for the whole route surface: binds the Hyperdrive connection, |
| 34 | * builds the `SQL.Postgres` client and the `SQL.PostgresLayer`-backed users |
| 35 | * service, and returns a handler that serves the Postgres-only routes |
| 36 | * (`withTransaction` commit/rollback, multi-row `sql.updateValues`) before |
| 37 | * falling through to the shared dialect-agnostic table. |
| 38 | */ |
| 39 | const PostgresRoutes = Effect.gen(function* () { |
| 40 | const hd = yield* Cloudflare.Hyperdrive.Connect(Hyperdrive); |
| 41 | const sql = yield* SQL.Postgres({ url: hd.connectionString }); |
| 42 | const layerUsers = yield* makeLayerUsers(TABLE).pipe( |
| 43 | Effect.provide(SQL.PostgresLayer({ url: hd.connectionString })), |
| 44 | ); |
| 45 | const shared = makeSqlRoutes({ sql, layerUsers, ddl: DDL, table: TABLE }); |
| 46 | |
| 47 | const handle = Effect.fn(function* (request: HttpServerRequest.HttpServerRequest) { |
| 48 | // POST /tx/commit — statements inside `withTransaction` share one |
| 49 | // transaction and commit together. |
| 50 | if (request.method === "POST" && request.url === "/tx/commit") { |
| 51 | const rows = (yield* request.json) as UserRow[]; |
| 52 | yield* sql.withTransaction( |
| 53 | Effect.gen(function* () { |
| 54 | for (const row of rows) { |
| 55 | yield* sql`INSERT INTO ${sql(TABLE)} ${sql.insert(row)}`; |
| 56 | } |
| 57 | }), |
| 58 | ); |
| 59 | const inserted = yield* sql` |
| 60 | SELECT id, name, email FROM ${sql(TABLE)} |
| 61 | WHERE ${sql.in( |
| 62 | "id", |
| 63 | rows.map((r) => r.id), |
| 64 | )} |
| 65 | ORDER BY id |
| 66 | `; |
| 67 | return yield* HttpServerResponse.json({ rows: inserted }); |
| 68 | } |
| 69 | |
| 70 | // POST /tx/rollback — a failure inside `withTransaction` rolls the |
| 71 | // insert back; the row must not be visible afterwards. |
| 72 | if (request.method === "POST" && request.url === "/tx/rollback") { |
| 73 | const row = (yield* request.json) as UserRow; |
| 74 | const error = yield* sql |
| 75 | .withTransaction( |
| 76 | Effect.gen(function* () { |
| 77 | yield* sql`INSERT INTO ${sql(TABLE)} ${sql.insert(row)}`; |
| 78 | return yield* Effect.fail(new Rollback()); |
| 79 | }), |
| 80 | ) |
| 81 | .pipe(Effect.flip); |
| 82 | const rows = yield* sql`SELECT id FROM ${sql(TABLE)} WHERE id = ${row.id}`; |
| 83 | return yield* HttpServerResponse.json({ |
| 84 | error: (error as { _tag: string })._tag, |
| 85 | rows, |
| 86 | }); |
| 87 | } |
| 88 | |
| 89 | // PUT /users/values — multi-row `sql.updateValues` (not supported on |
| 90 | // sqlite/D1, so it lives here rather than in the shared routes). |
| 91 | if (request.method === "PUT" && request.url === "/users/values") { |
| 92 | const rows = (yield* request.json) as Arr.NonEmptyReadonlyArray<UserRow>; |
| 93 | // `updateValues` binds every value as text — cast the join key back |
| 94 | // to int so `integer = text` doesn't reject the statement. |
| 95 | yield* sql` |
| 96 | UPDATE ${sql(TABLE)} AS t |
| 97 | SET name = data.name, email = data.email |
| 98 | FROM ${sql.updateValues(rows, "data")} |
| 99 | WHERE t.id = data.id::int |
| 100 | `; |
| 101 | const updated = yield* sql` |
| 102 | SELECT id, name, email FROM ${sql(TABLE)} |
| 103 | WHERE ${sql.in( |
| 104 | "id", |
| 105 | rows.map((r) => r.id), |
| 106 | )} |
| 107 | ORDER BY id |
| 108 | `; |
| 109 | return yield* HttpServerResponse.json({ rows: updated }); |
| 110 | } |
| 111 | |
| 112 | return yield* shared.handle(request); |
| 113 | }); |
| 114 | |
| 115 | return { handle }; |
| 116 | }); |
| 117 | |
| 118 | /** |
| 119 | * Effect-native Worker driving `SQL.Postgres` (the raw `@effect/sql-pg` |
| 120 | * client) over a Hyperdrive connection to a Neon Postgres origin. |
| 121 | */ |
| 122 | export default class SqlPostgresWorker extends Cloudflare.Worker<SqlPostgresWorker>()( |
| 123 | "SqlPostgresWorker", |
| 124 | { |
| 125 | main: import.meta.url, |
| 126 | }, |
| 127 | Effect.gen(function* () { |
| 128 | const routes = yield* PostgresRoutes; |
| 129 | |
| 130 | return { |
| 131 | fetch: Effect.gen(function* () { |
| 132 | const request = yield* HttpServerRequest.HttpServerRequest; |
| 133 | const response = yield* routes.handle(request); |
| 134 | if (response !== undefined) { |
| 135 | return response; |
| 136 | } |
| 137 | return yield* HttpServerResponse.json({ error: "not found" }, { status: 404 }); |
| 138 | }).pipe( |
| 139 | Effect.catchCause((cause) => |
| 140 | HttpServerResponse.json({ error: String(cause) }, { status: 500 }), |
| 141 | ), |
| 142 | ), |
| 143 | }; |
| 144 | }).pipe(Effect.provide(Cloudflare.Hyperdrive.ConnectBinding)), |
| 145 | ) {} |