@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 348 lines 13.9 KB
Raw
1 import type { Contract } from "@prisma/orm-postgres/contract/types";
2 // The Prisma runtime peers are loaded on first use. This module is not
3 // re-exported from `@alchemy.run/prisma`; import `@alchemy.run/prisma/ORM/Postgres`.
4 import type { SqlStorage } from "@prisma/orm-postgres/family-contract/types";
5 import type {
6 Runtime,
7 RuntimeConnection,
8 RuntimeTransaction,
9 } from "@prisma/orm-postgres/family-runtime";
10 import type { SqlExecutionPlan, SqlQueryPlan } from "@prisma/orm-postgres/relational-core/plan";
11 import type { PostgresClient, PostgresOptionsBase } from "@prisma/orm-postgres/runtime";
12 import type { PostgresStaticContext } from "@prisma/orm-postgres/static";
13 import { makeExecutionMemo } from "alchemy/Runtime/ExecutionMemo";
14 import * as Effect from "effect/Effect";
15 import * as Redacted from "effect/Redacted";
16 import * as Stream from "effect/Stream";
17 import { type ClientError, RollbackError, wrapPrismaError } from "./Errors.ts";
18 import { type EffectOrm, makeOrmProxy } from "./OrmClient.ts";
19 import { type Prepare, makePrepare } from "./Prepared.ts";
20 export type { Prepare, Prepared, PreparedQuery, PreparedMutation } from "./Prepared.ts";
21
22 export * from "./Errors.ts";
23 export type { EffectCollection, EffectOrm, WhereFilter } from "./OrmClient.ts";
24
25 /** A Prisma Postgres contract, authored directly or described by emitted types. */
26 export type AnyPostgresContract = Contract<SqlStorage>;
27
28 /** A plan produced by the `sql` builder lane (`db.sql...build()`) or `raw`. */
29 export type Plan<Row> = SqlQueryPlan<Row> | SqlExecutionPlan<Row>;
30
31 export type PostgresConfig<C extends AnyPostgresContract> = PostgresOptionsBase &
32 (
33 | {
34 /** The TypeScript contract returned by Prisma's `defineContract`. */
35 readonly contract: C;
36 readonly contractJson?: never;
37 }
38 | {
39 /** Canonical JSON paired with Prisma's emitted Contract declaration. */
40 readonly contractJson: unknown;
41 readonly contract?: never;
42 }
43 );
44
45 /**
46 * The transaction scope handed to {@link PostgresDatabase.transaction}'s
47 * callback: the same `orm`/`execute` surfaces bound to the open
48 * transaction, plus a typed `rollback`.
49 */
50 export interface PostgresTransaction<C extends AnyPostgresContract> {
51 /** The orm lane, executing on this transaction's connection. */
52 readonly orm: EffectOrm<C>;
53 /** Run a `sql`-lane or `raw` plan on this transaction's connection. */
54 execute<Row>(plan: Plan<Row>): Effect.Effect<Row[], ClientError>;
55 /** Prepare a typed statement whose executions use this transaction. */
56 readonly prepare: Prepare<C>;
57 /**
58 * Abort the transaction: rolls back and fails the `transaction` effect
59 * with {@link RollbackError} (catchable by tag).
60 */
61 rollback(): Effect.Effect<never, RollbackError>;
62 }
63
64 export interface PostgresDatabase<C extends AnyPostgresContract, E = never, R = never> {
65 /**
66 * The native Prisma client for the current execution. Prefer the Effect
67 * methods for typed failures and repeatable execution.
68 */
69 readonly client: Effect.Effect<PostgresClient<C>, E, R>;
70 /**
71 * Run promise-land code against the execution's client:
72 *
73 * ```typescript
74 * const rows = yield* db.use((c) => c.orm.public.User.groupBy(...)...);
75 * ```
76 */
77 readonly use: <A>(
78 f: (client: PostgresClient<C>) => PromiseLike<A>,
79 ) => Effect.Effect<A, ClientError | E, R>;
80 /**
81 * The Effect-native orm lane — chain like Prisma, yield the terminal:
82 *
83 * ```typescript
84 * const user = yield* db.orm.public.User.where({ email }).include("posts").first();
85 * ```
86 */
87 readonly orm: EffectOrm<C, ClientError | E, R>;
88 /**
89 * The pure `sql` builder lane (no connection — plans are data):
90 * `db.sql.public.user.select("id", "email").build()`.
91 */
92 readonly sql: PostgresStaticContext<C>["sql"];
93 /** The raw SQL lane (pure): ``db.raw.sql`SELECT ...` `` builds plans. */
94 readonly raw: PostgresStaticContext<C>["raw"];
95 /** Execute a plan, buffering all rows. */
96 execute<Row>(plan: Plan<Row>): Effect.Effect<Row[], ClientError | E, R>;
97 /** Execute a plan as a row stream (each run re-executes the plan). */
98 stream<Row>(plan: Plan<Row>): Stream.Stream<Row, ClientError | E, R>;
99 /** Prepare a typed statement; each query resolves the current execution's client. */
100 readonly prepare: Prepare<C, E, R>;
101 /**
102 * Run `f` inside a database transaction on a dedicated connection.
103 * Commits on success; rolls back on failure or interruption. Yield
104 * `tx.rollback()` to abort with a typed {@link RollbackError}.
105 */
106 transaction<A, E2, R2>(
107 f: (tx: PostgresTransaction<C>) => Effect.Effect<A, E2, R2>,
108 ): Effect.Effect<A, E2 | ClientError | E, R | R2>;
109 }
110
111 /**
112 * Open a Prisma ORM v8 Postgres client from a connection URL, with
113 * Effect-native query surfaces over Prisma's own builders and engine.
114 *
115 * The client is built at most once per execution — a Worker
116 * `fetch`/`queue`/`scheduled` event, a Durable Object call, a Workflow run,
117 * or a Lambda invocation — and memoized on the execution's `Scope` (via
118 * {@link makeExecutionMemo}), with `close()` registered as a scope finalizer
119 * so the underlying `pg` pool never outlives its event. That per-execution
120 * lifecycle is what makes the client safe on workerd, where sockets are
121 * pinned to the creating request's IoContext. Construction does no I/O
122 * (Prisma connects lazily on the first query), so deploy/plan-time
123 * evaluations never touch the database.
124 *
125 * Model types infer directly from the native TypeScript contract, together
126 * with the connection source's error and requirement channels. No generated
127 * application imports are required. For Prisma rc.11, author contracts with
128 * `defineContract` from `@alchemy.run/prisma/ORM` to retain metadata
129 * lost by the upstream declarations. It uses Prisma's native runtime builders.
130 *
131 *
132 * ```typescript
133 * import * as PrismaPostgres from "@alchemy.run/prisma/ORM/Postgres";
134 * import { contract } from "./prisma/contract.ts";
135 *
136 * const connection = yield* Cloudflare.Hyperdrive.Connect(hyperdrive);
137 * const db = yield* PrismaPostgres.Postgres(
138 * connection.connectionString,
139 * { contract },
140 * );
141 *
142 * fetch: Effect.gen(function* () {
143 * // orm lane — queries ARE Effects, with typed errors
144 * const user = yield* db.orm.public.User.where({ email }).include("posts").first();
145 * const made = yield* db.orm.public.Post.create({ title, authorId: user.id });
146 *
147 * // sql builder lane — pure plans, Effect executor
148 * const rows = yield* db.execute(db.sql.public.user.select("id", "email").build());
149 *
150 * // transactions — commit on success, rollback on failure/interrupt
151 * yield* db.transaction((tx) =>
152 * Effect.gen(function* () {
153 * const u = yield* tx.orm.public.User.create({ email });
154 * if (!u) return yield* tx.rollback();
155 * return u;
156 * }),
157 * );
158 * });
159 * ```
160 *
161 * ### PSL Contracts
162 * **Example:** Use a generated contract-bound factory
163 * ```typescript
164 * import { makeDatabase } from "./prisma/generated/client.ts";
165 * const db = yield* makeDatabase(connection.connectionString);
166 * const users = yield* db.orm.public.User.select("id", "email").all();
167 * ```
168 *
169 * Run `alchemy provider prisma generate` with `withEffect` registered in the ORM
170 * configuration. The factory delegates to this runtime with Prisma's emitted
171 * `Contract` type and `contractJson`; query behavior and cleanup are identical.
172 * Generated `schemas.ts` can be imported independently of this client.
173 *
174 * ### Prepared Queries
175 * **Example:** Reuse a query with typed parameters
176 * ```typescript
177 * const findUser = yield* db.prepare({ email: "pg/text@1" }, (sql, params) =>
178 * sql.public.user
179 * .select("id", "email")
180 * .where((fields, fns) => fns.eq(fields.email, params.email))
181 * .build(),
182 * );
183 * const users = yield* findUser.query({ email: "alice@example.com" });
184 * const rows = findUser.query({ email: "alice@example.com" }).stream;
185 * ```
186 *
187 * Prepared queries resolve the current execution's client for each run. Inside
188 * `db.transaction`, `tx.prepare` binds executions to that transaction instead.
189 * An affected-count plan returns a prepared mutation with `execute(params)`;
190 * a row-returning plan returns a prepared query with `query(params)`.
191 *
192 * The Stream surfaces use Prisma's async iterators. The long-lived Postgres
193 * driver buffers raw results, so these streams do not guarantee bounded memory.
194 *
195 * Queries are lazy and re-runnable: each evaluation replays the chain
196 * against the execution's client, so `Effect.retry` re-issues the query.
197 * Failures surface as granular tagged errors: the SQL-standard integrity
198 * violations each get their own tag (`Prisma.UniqueViolationError`,
199 * `Prisma.ForeignKeyViolationError`, `Prisma.NotNullViolationError`,
200 * `Prisma.CheckViolationError`), other statement failures are
201 * `Prisma.QueryError` (with the normalized `sqlState`), connection
202 * failures are `Prisma.ConnectionError` (with the driver's
203 * `transient` verdict), and Prisma's structured codes split by
204 * category into `Prisma.OrmError` / `Prisma.RuntimeError`
205 * with an autocompleting `code` field.
206 *
207 * @binding
208 * @category ORM
209 */
210 export const Postgres = <C extends AnyPostgresContract, E = never, R = never>(
211 connectionString: Effect.Effect<Redacted.Redacted<string>, E, R>,
212 config: PostgresConfig<C>,
213 ): Effect.Effect<PostgresDatabase<C, E, R>> =>
214 Effect.gen(function* () {
215 const { contract, contractJson, ...options } = config;
216 const [{ default: postgres }, { default: postgresStatic }, { orm }] = yield* Effect.promise(
217 () =>
218 Promise.all([
219 import("@prisma/orm-postgres/runtime"),
220 import("@prisma/orm-postgres/static"),
221 import("@prisma/orm-postgres/orm-client"),
222 ]),
223 );
224
225 // Pure static context: the typed sql/raw builders and the codec
226 // machinery, with no driver and no connection behind them.
227 const statics = postgresStatic<C>({
228 contractJson: contract ?? contractJson,
229 ...(options.extensions === undefined ? {} : { extensions: options.extensions }),
230 });
231
232 const client = yield* makeExecutionMemo(
233 Effect.gen(function* () {
234 const url = Redacted.value(yield* connectionString);
235 const instance =
236 contract === undefined
237 ? postgres<C>({ contractJson, url, ...options })
238 : postgres({ contract, url, ...options });
239 yield* Effect.addFinalizer(() =>
240 Effect.tryPromise(() => instance.close()).pipe(Effect.ignore),
241 );
242 return instance;
243 }),
244 );
245
246 const execute = <Row>(plan: Plan<Row>): Effect.Effect<Row[], ClientError | E, R> =>
247 Effect.flatMap(client, (c) =>
248 Effect.tryPromise({
249 try: (signal) => c.runtime().query(plan, { signal }).toArray(),
250 catch: wrapPrismaError,
251 }),
252 );
253
254 const stream = <Row>(plan: Plan<Row>): Stream.Stream<Row, ClientError | E, R> =>
255 // unwrap re-evaluates per run, so each run gets a fresh
256 // AsyncIterableResult (they are single-consumption).
257 Stream.unwrap(
258 Effect.map(client, (c) =>
259 Stream.fromAsyncIterable(c.runtime().query(plan) as AsyncIterable<Row>, wrapPrismaError),
260 ),
261 );
262
263 const makeTransactionScope = (txn: RuntimeTransaction, runtime: Runtime) => {
264 const txOrm = orm<C>({
265 runtime: txn,
266 context: statics.context,
267 });
268 const tx: PostgresTransaction<C> = {
269 orm: makeOrmProxy<C, never, never>(Effect.succeed(txOrm)),
270 prepare: makePrepare(Effect.succeed(runtime), statics.sql, Effect.succeed(txn)),
271 execute: <Row>(plan: Plan<Row>) =>
272 Effect.tryPromise({
273 try: (signal) => txn.query(plan, { signal }).toArray(),
274 catch: wrapPrismaError,
275 }),
276 rollback: () => Effect.fail(new RollbackError()),
277 };
278 return tx;
279 };
280
281 const transaction = <A, E2, R2>(
282 f: (tx: PostgresTransaction<C>) => Effect.Effect<A, E2, R2>,
283 ): Effect.Effect<A, E2 | ClientError | E, R | R2> =>
284 Effect.flatMap(client, (c) =>
285 Effect.acquireUseRelease(
286 Effect.tryPromise({
287 try: async () => {
288 const connection: RuntimeConnection = await c.runtime().connection();
289 try {
290 const txn = await connection.transaction();
291 return { connection, txn, committed: false };
292 } catch (error) {
293 await connection.destroy(error).catch(() => {});
294 throw error;
295 }
296 },
297 catch: wrapPrismaError,
298 }),
299 (scope) =>
300 f(makeTransactionScope(scope.txn, c.runtime())).pipe(
301 Effect.flatMap((value) =>
302 Effect.tryPromise({
303 try: async () => {
304 await scope.txn.commit();
305 scope.committed = true;
306 return value;
307 },
308 catch: wrapPrismaError,
309 }),
310 ),
311 ),
312 (scope) =>
313 // Rollback on any non-committed exit (failure, interrupt, or
314 // commit failure), then return the connection to the pool —
315 // destroying it if cleanup itself failed.
316 Effect.promise(async () => {
317 try {
318 if (!scope.committed) await scope.txn.rollback();
319 await scope.connection.release();
320 } catch (error) {
321 await scope.connection.destroy(error).catch(() => {});
322 }
323 }),
324 ),
325 );
326
327 const db: PostgresDatabase<C, E, R> = {
328 client,
329 use: (f) =>
330 Effect.flatMap(client, (c) =>
331 Effect.tryPromise({
332 try: () => Promise.resolve(f(c)),
333 catch: wrapPrismaError,
334 }),
335 ),
336 orm: makeOrmProxy<C, ClientError | E, R>(Effect.map(client, (c) => c.orm)),
337 sql: statics.sql,
338 raw: statics.raw,
339 prepare: makePrepare(
340 Effect.map(client, (c) => c.runtime()),
341 statics.sql,
342 ),
343 execute,
344 stream,
345 transaction,
346 };
347 return db;
348 });