Skip to content

SQL reference

Source: src/SQL/D1.ts

Open an @effect/sql-d1 client over a Cloudflare D1 binding.

Accepts the client returned by Cloudflare.D1.QueryDatabase(db) — or its raw effect directly — and returns a D1Client (which implements the generic SqlClient interface) wrapped in a chainable Proxy, so it can be resolved once at Worker init and used from any handler:

import * as SQL from "alchemy/SQL/D1";
const d1 = yield* Cloudflare.D1.QueryDatabase(Db);
const sql = yield* SQL.D1(d1);
fetch: Effect.gen(function* () {
const users = yield* sql`SELECT * FROM users`;
});

The client build is deferred until the first query and memoized on the current execution’s Scope (via makeExecutionMemo), so the D1Client (and its prepared-statement cache) is built at most once per execution — a Worker fetch/queue/scheduled event, a Durable Object call, or a Workflow run — and torn down when the event settles. Deploy / plan-time invocations never touch D1.

Source: src/SQL/MySQL.ts

Open an @effect/sql-mysql2 client (a connection pool) from a connection URL — a plain Redacted or an Effect of one, e.g. Hyperdrive’s connectionString:

import * as SQL from "alchemy/SQL/MySQL";
const hd = yield* Cloudflare.Hyperdrive.Connect(Hyperdrive);
const sql = yield* SQL.MySQL({ url: hd.connectionString });
fetch: Effect.gen(function* () {
const users = yield* sql`SELECT * FROM users`;
});

The pool opens on the first query of an execution, is reused for every query in it, and closes when the event settles (see makeExecutionMemo); plan/deploy never connect. Workers defaults (resolveMySQLConfig) are overridden in the config:

const sql = yield* SQL.MySQL({
url,
disablePreparedStatements: true,
poolConfig: { ssl: { rejectUnauthorized: true } },
});

Source: src/SQL/Postgres.ts

Open an @effect/sql-pg client (a connection pool) from a connection URL.

Accepts a plain Redacted URL or an Effect of one — e.g. Cloudflare.Hyperdrive.Connect(...) or Fly.ConnectPostgres(...)’s connectionString — and returns a PgClient (which implements the generic SqlClient interface) wrapped in a chainable Proxy, so it can be resolved once at init and used from any handler:

import * as SQL from "alchemy/SQL/Postgres";
const hd = yield* Cloudflare.Hyperdrive.Connect(Hyperdrive);
const sql = yield* SQL.Postgres({ url: hd.connectionString });
fetch: Effect.gen(function* () {
const users = yield* sql`SELECT * FROM users`;
});

The pool is built lazily on the first query and memoized on the current execution’s Scope (via makeExecutionMemo), so it’s created at most once per execution — a Worker fetch/queue/scheduled event, a Durable Object call, a Workflow run, or a Lambda invocation — and its end finalizer fires when the event settles. Yielding the connection URL is likewise deferred, so deploy / plan-time invocations never connect.