Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ConnectPostgres.ts

68 lines2.2 KB

1import * as Binding from "alchemy/Binding";
2import type { RuntimeContext } from "alchemy/RuntimeContext";
3import * as Data from "effect/Data";
4import type * as Effect from "effect/Effect";
5import type * as Redacted from "effect/Redacted";
6import type { Postgres } from "./Postgres.ts";
7​
8/**
9 * Bind a {@link Postgres} cluster to a Fly {@link Service} and obtain
10 * the Effect-native connection strings for `Drizzle.Postgres` /
11 * `SQL.Postgres`. Alchemy transports the cluster's connection URIs
12 * automatically; callers do not configure connection-string env vars.
13 *
14 * `ConnectPostgres` is the Context tag, the type, and the callable —
15 * `yield* Fly.ConnectPostgres(Db)`. Provide {@link ConnectPostgresHttp}.
16 *
17 * **Example:** Bind Postgres in a Service
18 * ```typescript
19 * import * as Drizzle from "@alchemy.run/drizzle/Postgres";
20 *
21 * const conn = yield* Fly.ConnectPostgres(Db);
22 * const db = yield* Drizzle.Postgres(conn.connectionString);
23 *
24 * fetch: Effect.gen(function* () {
25 * const rows = yield* db.select().from(users);
26 * });
27 * ```
28 *
29 * @binding
30 * @product Postgres
31 */
32export interface ConnectPostgres extends Binding.Service<
33 ConnectPostgres,
34 "Fly.ConnectPostgres",
35 (postgres: Postgres) => Effect.Effect<ConnectPostgresClient>
36> {}
37​
38export const ConnectPostgres = Binding.Service<ConnectPostgres>("Fly.ConnectPostgres");
39​
40export const connectEnvKeys = (postgres: Pick<Postgres, "LogicalId">) => {
41 const id = postgres.LogicalId.replaceAll(/[^a-zA-Z0-9]/g, "_").toUpperCase();
42 return {
43 pooled: `FLY_POSTGRES_${id}_POOLED`,
44 direct: `FLY_POSTGRES_${id}_DIRECT`,
45 };
46};
47​
48export class PostgresUrlMissing extends Data.TaggedError("Fly.PostgresUrlMissing")<{
49 resourceName: string;
50}> {}
51​
52export interface ConnectPostgresClient {
53 /**
54 * Pooled PgBouncer connection string. Pass this to
55 * {@link Drizzle.Postgres} or `SQL.Postgres`.
56 */
57 connectionString: Effect.Effect<Redacted.Redacted<string>, PostgresUrlMissing, RuntimeContext>;
58 /**
59 * Direct (non-PgBouncer) connection string. Use this for session-scoped
60 * features (advisory locks, `LISTEN/NOTIFY`) when you are not going
61 * through the pooled URL.
62 */
63 directConnectionString: Effect.Effect<
64 Redacted.Redacted<string>,
65 PostgresUrlMissing,
66 RuntimeContext
67 >;