Open History to see the last commit
1/**
2 * PostgreSQL support for Effect SQL, backed by the native wire protocol client.
3 *
4 * @stability unstable
5 * @since 4.0.0
6 */
7import type * as Arr from "effect/Array"
8import * as Config from "effect/Config"
9import * as Context from "effect/Context"
10import type * as Duration from "effect/Duration"
11import * as Effect from "effect/Effect"
12import * as Layer from "effect/Layer"
13import type * as Pool from "effect/Pool"
14import type * as Queue from "effect/Queue"
15import * as Reactivity from "effect/reactivity/Reactivity"
16import type * as Redacted from "effect/Redacted"
17import type * as Scope from "effect/Scope"
18import * as Client from "effect/sql/SqlClient"
19import type { Borrower, Connection } from "effect/sql/SqlConnection"
20import { SqlError, UnknownError } from "effect/sql/SqlError"
21import type { Custom, Fragment } from "effect/sql/Statement"
22import * as Statement from "effect/sql/Statement"
23import * as Stream from "effect/Stream"
24import type { Duplex } from "node:stream"
25import type { ConnectionOptions } from "node:tls"
26import { resolveConfig } from "./internal/config.ts"
27import { connectionInternals } from "./internal/connection.ts"
28import { validateChannelName } from "./internal/sqlError.ts"
29import * as PgConnection from "./PgConnection.ts"
30import * as PgPool from "./PgPool.ts"
31import * as PgTypes from "./PgTypes.ts"
32
33/**
34 * The runtime type identifier for `PgClient`.
35 *
36 * @stability unstable
37 * @category type IDs
38 * @since 4.0.0
39 */
40export const TypeId: TypeId = "~@effect/sql-pg/PgClient"
41
42/**
43 * The type-level identifier for `PgClient`.
44 *
45 * @stability unstable
46 * @category type IDs
47 * @since 4.0.0
48 */
49export type TypeId = "~@effect/sql-pg/PgClient"
50
51/**
52 * A PostgreSQL `SqlClient` with JSON and `LISTEN`/`NOTIFY` helpers.
53 *
54 * @stability unstable
55 * @category services
56 * @since 4.0.0
57 */
58export interface PgClient extends Client.Base {
59 readonly [TypeId]: TypeId
60 readonly config: PgClientConfig
61 readonly json: (_: unknown) => Fragment
62 /**
63 * Registers a channel listener and returns its notification queue after
64 * PostgreSQL confirms `LISTEN`. The listener holds a connection until the
65 * scope closes.
66 * Connection failures after registration fail the queue with the original
67 * `SqlError`. Intentional scope closure interrupts consumers.
68 */
69 readonly listen: (
70 channel: string
71 ) => Effect.Effect<Queue.Dequeue<PgConnection.Notification, SqlError>, SqlError, Scope.Scope>
72 readonly notify: (channel: string, payload: string) => Effect.Effect<void, SqlError>
73 /**
74 * Returns a snapshot of connection pool occupancy. A client from `makeClient`
75 * has one session that stays leased for its lifetime, so it always reports
76 * `{ idle: 0, used: 1, pending: 0, min: 1, max: 1 }` whatever statements run
77 * on it.
78 */
79 readonly poolStats: Effect.Effect<Pool.Stats>
80}
81
82/**
83 * The service tag for `PgClient`.
84 *
85 * @stability unstable
86 * @category services
87 * @since 4.0.0
88 */
89export const PgClient = Context.Service<PgClient, PgClient & Client.SqlClient>("@effect/sql-pg/PgClient")
90
91/**
92 * Connection and query settings for a PostgreSQL client.
93 *
94 * @stability unstable
95 * @category models
96 * @since 4.0.0
97 */
98export interface PgClientConfig<R = never> {
99 readonly url?: Redacted.Redacted | undefined
100
101 readonly host?: string | undefined
102 readonly port?: number | undefined
103 readonly path?: string | undefined
104 readonly ssl?: boolean | ConnectionOptions | undefined
105 readonly database?: string | undefined
106 readonly username?: string | undefined
107 /**
108 * A static password or an Effect evaluated for each connection attempt.
109 * Providers must handle typed errors and require no services.
110 * {@link Effect.orDie} converts typed errors to defects, not retryable SQL errors.
111 */
112 readonly password?: Redacted.Redacted | Effect.Effect<Redacted.Redacted> | undefined
113
114 readonly connectTimeout?: Duration.Input | undefined
115 /** Idle time before TCP keepalive probes start. See `PgConnection.Config.keepAlive`. */
116 readonly keepAlive?: Duration.Input | undefined
117
118 readonly stream?: (() => Duplex) | undefined
119
120 /**
121 * Overrides `startupParameters.application_name`, the URL's `application_name`,
122 * and the default `"@effect/sql-pg"`, in that order.
123 */
124 readonly applicationName?: string | undefined
125 /**
126 * Session defaults sent in every physical connection's startup packet.
127 * Names are lowercased; `user`, `database`, `replication`, and `options` are
128 * reserved. `client_encoding` only accepts UTF8 / UTF-8 (case-insensitive).
129 * Empty names and NUL bytes fail before connecting; PostgreSQL validates
130 * other settings. Do not set the same GUC here and in `startupOptions`.
131 */
132 readonly startupParameters?: Readonly<Record<string, string>> | undefined
133 /**
134 * Opaque PostgreSQL startup options, overriding the URL's `options` parameter.
135 * Forwarded without parsing `-c` flags or checking for duplicate GUCs.
136 */
137 readonly startupOptions?: string | undefined
138 readonly spanAttributes?: Record<string, unknown> | undefined
139
140 readonly transformResultNames?: ((str: string) => string) | undefined
141 readonly transformQueryNames?: ((str: string) => string) | undefined
142 readonly transformJson?: boolean | undefined
143 readonly types?: PgTypes.Registry | undefined
144 /**
145 * Pipelines queries from multiple fibers on each pooled connection.
146 * Transactions, streams, and listeners still reserve a connection.
147 */
148 readonly multiplex?: boolean | undefined
149 /**
150 * How many statements may share one connection when `multiplex` is on.
151 * Defaults to `32`. Higher values trade tail latency for throughput: the
152 * statements sharing a connection are pipelined into one write, and they
153 * also queue behind the slowest of them.
154 */
155 readonly multiplexConcurrency?: number | undefined
156 /**
157 * Caches prepared statements by name. Enabled by default. Disable it for
158 * poolers that cannot preserve named statements between queries, such as
159 * PgBouncer in transaction mode with `max_prepared_statements = 0`.
160 */
161 readonly prepare?: boolean | undefined
162 /** How many statements a connection keeps prepared. Defaults to `100`. */
163 readonly preparedStatementCacheSize?: number | undefined
164 /** Maximum backend message size in bytes. Defaults to 16 MiB. */
165 readonly maxMessageSize?: number | undefined
166 /**
167 * Runs after each connection checkout, in the fiber that uses the connection.
168 *
169 * **Details**
170 *
171 * Runs once per statement or stream outside a transaction, including
172 * multiplexed statements, and once per `withTransaction`, `reserve`, `listen`
173 * and `notify`. Finalizers it adds run when that acquisition ends. Services it
174 * requires are captured when the client is built, and the consuming fiber's
175 * services take precedence.
176 *
177 * **Gotchas**
178 *
179 * Keep it cheap: it runs while holding the connection. With `makeClient` and
180 * `acquireForStream`, it runs before a stream opens its own connection.
181 *
182 * **Example** (Reading request context on each checkout)
183 *
184 * ```ts
185 * import { PgClient } from "@effect/sql-pg"
186 * import { Context, Effect } from "effect"
187 *
188 * // Set by each request handler with `Effect.provideService`.
189 * const KeepAlive = Context.Reference<(() => void) | undefined>("app/KeepAlive", {
190 * defaultValue: () => undefined
191 * })
192 *
193 * const layer = PgClient.layer({
194 * onAcquire: Effect.gen(function*() {
195 * const keepAlive = yield* KeepAlive
196 * keepAlive?.()
197 * })
198 * })
199 * ```
200 */
201 readonly onAcquire?: Effect.Effect<void, never, R> | undefined
202}
203
204/**
205 * PostgreSQL client settings with connection pool limits and timeouts.
206 *
207 * @stability unstable
208 * @category models
209 * @since 4.0.0
210 */
211export interface PgPoolConfig<R = never> extends PgClientConfig<R> {
212 readonly idleTimeout?: Duration.Input | undefined
213
214 readonly maxConnections?: number | undefined
215 readonly minConnections?: number | undefined
216 readonly connectionTTL?: Duration.Input | undefined
217 /** Bounds how long acquiring a pooled connection takes. See `PgPool.Config.acquireTimeout`. */
218 readonly acquireTimeout?: Duration.Input | undefined
219}
220
221/**
222 * Creates a scoped PostgreSQL client backed by a connection pool.
223 *
224 * @stability unstable
225 * @category constructors
226 * @since 4.0.0
227 */
228export const make = <R = never>(
229 options: PgPoolConfig<R>
230): Effect.Effect<PgClient & Client.SqlClient, SqlError, Scope.Scope | Reactivity.Reactivity | R> =>
231 Effect.flatMap(PgPool.make(options), (pool) =>
232 makeImpl({
233 acquirer: Effect.map(pool.get, makeConnection),
234 borrower: (f) => pool.use((connection) => f(makeConnection(connection))),
235 transactionAcquirer: Effect.map(pool.reserve, makeConnection),
236 listenAcquirer: pool.reserve,
237 config: options,
238 poolStats: pool.stats
239 }))
240
241/**
242 * Creates a scoped PostgreSQL client backed by one connection.
243 *
244 * @stability unstable
245 * @category constructors
246 * @since 4.0.0
247 */
248export const makeClient = <R = never>(
249 options: PgClientConfig<R> & {
250 /**
251 * Opens a separate connection for each stream and listener when enabled.
252 */
253 readonly acquireForStream?: boolean | undefined
254 }
255): Effect.Effect<PgClient & Client.SqlClient, SqlError, Scope.Scope | Reactivity.Reactivity | R> =>
256 Effect.flatMap(PgConnection.make(options), (connection) =>
257 makeImpl({
258 acquirer: Effect.succeed(makeConnection(
259 connection,
260 options.acquireForStream ? PgConnection.make(options) : undefined
261 )),
262 transactionAcquirer: Effect.map(connection.pin, makeConnection),
263 listenAcquirer: options.acquireForStream ? PgConnection.make(options) : connection.pin,
264 config: options,
265 // The one session is leased for the client's lifetime.
266 poolStats: Effect.succeed({ idle: 0, used: 1, pending: 0, min: 1, max: 1 })
267 }))
268
269/**
270 * Builds the shared SQL facade around native connection acquirers.
271 */
272const makeImpl = Effect.fnUntraced(function*<R>(
273 options: {
274 readonly acquirer: Effect.Effect<Connection, SqlError, Scope.Scope>
275 readonly borrower?: Borrower | undefined
276 readonly transactionAcquirer: Effect.Effect<Connection, SqlError, Scope.Scope>
277 readonly listenAcquirer: Effect.Effect<PgConnection.PgConnection, SqlError, Scope.Scope>
278 readonly config: PgClientConfig<R>
279 readonly poolStats: Effect.Effect<Pool.Stats>
280 }
281): Effect.fn.Return<PgClient & Client.SqlClient, SqlError, Scope.Scope | Reactivity.Reactivity | R> {
282 // The consuming fiber's services take precedence over the captured ones.
283 const hook = options.config.onAcquire
284 const context = yield* Effect.context<R>()
285 const onAcquire = hook &&
286 Effect.updateContext(hook, (current: Context.Context<never>) => Context.merge(context, current))
287 const config: PgClientConfig = { ...options.config, onAcquire }
288 const resolved = yield* resolveConfig(config)
289 let { acquirer, borrower, listenAcquirer, transactionAcquirer } = options
290 if (onAcquire !== undefined) {
291 acquirer = Effect.tap(acquirer, onAcquire)
292 transactionAcquirer = Effect.tap(transactionAcquirer, onAcquire)
293 listenAcquirer = Effect.tap(listenAcquirer, onAcquire)
294 if (borrower !== undefined) {
295 const borrow = borrower
296 // Scope each statement so hook finalizers run when it ends.
297 borrower = (f) => borrow((connection) => Effect.scoped(Effect.andThen(onAcquire, f(connection))))
298 }
299 }
300 const compiler = makeCompiler(
301 config.transformQueryNames,
302 config.transformJson
303 )
304 const transformRows = config.transformResultNames ?
305 Statement.defaultTransforms(
306 config.transformResultNames,
307 config.transformJson
308 ).array :
309 undefined
310
311 const listen = (
312 channel: string
313 ): Effect.Effect<Queue.Dequeue<PgConnection.Notification, SqlError>, SqlError, Scope.Scope> =>
314 Effect.flatMap(listenAcquirer, (connection) => connection.listen(channel))
315
316 return Object.assign(
317 yield* Client.make({
318 driver: "pg",
319 acquirer,
320 borrower,
321 // Postgres prepares transaction control like anything else, and a client
322 // with preparation turned off falls back to the unnamed path anyway.
323 prepareTransactionControls: true,
324 commit,
325 onCommitFailure,
326 // A session the server ended has nothing left to roll back.
327 isTransaction: (conn) => connectionInternals((conn as ConnectionImpl).connection).deadError() === undefined,
328 releaseSavepoint: (name) => `RELEASE SAVEPOINT ${name}`,
329 transactionAcquirer,
330 compiler,
331 spanAttributes: [
332 ...(config.spanAttributes ? Object.entries(config.spanAttributes) : []),
333 [ATTR_DB_SYSTEM_NAME, "postgresql"],
334 // PostgreSQL connects to the database named after the user when none is given.
335 [ATTR_DB_NAMESPACE, resolved.startupParameters.database ?? resolved.username],
336 [ATTR_SERVER_ADDRESS, resolved.host],
337 [ATTR_SERVER_PORT, resolved.port]
338 ],
339 transformRows
340 }),
341 {
342 [TypeId]: TypeId as TypeId,
343 config,
344 poolStats: options.poolStats,
345 json: (_: unknown) => Statement.fragment([PgJson(_)]),
346 listen,
347 notify: (channel: string, payload: string) => {
348 const channelError = validateChannelName(channel, "notify")
349 return channelError !== undefined ?
350 Effect.fail(channelError) :
351 Effect.asVoid(Effect.scoped(Effect.flatMap(
352 acquirer,
353 (conn) => conn.executeRaw(`SELECT pg_notify($1, $2)`, [channel, payload])
354 )))
355 }
356 }
357 )
358})
359
360class ConnectionImpl implements Connection {
361 readonly connection: PgConnection.PgConnection
362 readonly streamAcquirer: Effect.Effect<PgConnection.PgConnection, SqlError, Scope.Scope> | undefined
363
364 constructor(
365 connection: PgConnection.PgConnection,
366 streamAcquirer?: Effect.Effect<PgConnection.PgConnection, SqlError, Scope.Scope> | undefined
367 ) {
368 this.connection = connection
369 this.streamAcquirer = streamAcquirer
370 }
371
372 private run(query: string, params: ReadonlyArray<unknown>, prepare = true) {
373 return Effect.map(this.connection.query(query, params, prepare), (result) => result.rows)
374 }
375
376 execute(
377 sql: string,
378 params: ReadonlyArray<unknown>,
379 transformRows: (<A extends object>(row: ReadonlyArray<A>) => ReadonlyArray<A>) | undefined
380 ) {
381 return transformRows
382 ? Effect.map(this.run(sql, params), transformRows)
383 : this.run(sql, params)
384 }
385 executeRaw(sql: string, params: ReadonlyArray<unknown>) {
386 return this.connection.query(sql, params)
387 }
388 executeWithoutTransform(sql: string, params: ReadonlyArray<unknown>) {
389 return this.run(sql, params)
390 }
391 executeValues(sql: string, params: ReadonlyArray<unknown>) {
392 return this.connection.queryValues(sql, params)
393 }
394 executeValuesUnprepared(sql: string, params: ReadonlyArray<unknown>) {
395 return this.connection.queryValues(sql, params, false)
396 }
397 executeUnprepared(
398 sql: string,
399 params: ReadonlyArray<unknown>,
400 transformRows: (<A extends object>(row: ReadonlyArray<A>) => ReadonlyArray<A>) | undefined
401 ) {
402 const operation = this.run(sql, params, false)
403 return transformRows
404 ? Effect.map(operation, transformRows)
405 : operation
406 }
407 executeStream(
408 sql: string,
409 params: ReadonlyArray<unknown>,
410 transformRows: (<A extends object>(row: ReadonlyArray<A>) => ReadonlyArray<A>) | undefined
411 ) {
412 const stream = this.streamAcquirer === undefined
413 ? this.connection.stream(sql, params)
414 : Stream.unwrap(Effect.map(this.streamAcquirer, (connection) => connection.stream(sql, params)))
415 return transformRows
416 ? Stream.mapArray(stream, (rows) => transformRows(rows) as Arr.NonEmptyReadonlyArray<PgConnection.Row>)
417 : stream
418 }
419}
420
421/** PostgreSQL returns `ROLLBACK` for `COMMIT` when a transaction is aborted. */
422const commit = (conn: Connection): Effect.Effect<void, SqlError> =>
423 Effect.flatMap(
424 conn.executeRaw("COMMIT", []) as Effect.Effect<PgConnection.Result, SqlError>,
425 (result) =>
426 result.command === "ROLLBACK"
427 ? Effect.fail(
428 new SqlError({
429 reason: new UnknownError({
430 cause: new Error("COMMIT rolled back an aborted transaction"),
431 message: "PgClient: COMMIT rolled back an aborted transaction",
432 operation: "commit"
433 })
434 })
435 )
436 : Effect.void
437 )
438
439/**
440 * Rolls back a transaction left open by a `COMMIT` the backend rejected before
441 * running it. Outside a transaction `ROLLBACK` only warns. Its own failure is
442 * ignored so the `COMMIT` error is the one reported; a session it leaves
443 * aborted is closed on pin release.
444 */
445const onCommitFailure = (conn: Connection): Effect.Effect<void> =>
446 Effect.ignore(conn.executeUnprepared("ROLLBACK", [], undefined))
447
448const makeConnection = (
449 connection: PgConnection.PgConnection,
450 streamAcquirer?: Effect.Effect<PgConnection.PgConnection, SqlError, Scope.Scope> | undefined
451): Connection => new ConnectionImpl(connection, streamAcquirer)
452
453/**
454 * Provides both `PgClient` and `SqlClient` from an acquisition effect.
455 *
456 * @stability unstable
457 * @category layers
458 * @since 4.0.0
459 */
460export const layerFrom = <E, R>(
461 acquire: Effect.Effect<PgClient & Client.SqlClient, E, R>
462): Layer.Layer<PgClient | Client.SqlClient, E, Exclude<R, Scope.Scope | Reactivity.Reactivity>> =>
463 Layer.effectContext(
464 Effect.map(acquire, (client) =>
465 Context.make(PgClient, client).pipe(
466 Context.add(Client.SqlClient, client)
467 ))
468 ).pipe(Layer.provide(Reactivity.layer)) as any
469
470/**
471 * Creates a client layer from wrapped pool configuration.
472 *
473 * @stability unstable
474 * @category layers
475 * @since 4.0.0
476 */
477export const layerConfig = <R = never>(
478 config: Config.Wrap<PgPoolConfig<R>>
479): Layer.Layer<
480 PgClient | Client.SqlClient,
481 Config.ConfigError | SqlError,
482 Exclude<R, Scope.Scope | Reactivity.Reactivity>
483> =>
484 layerFrom(Effect.flatMap(
485 Config.unwrap(config),
486 make
487 ))
488
489/**
490 * Creates a client layer from pool configuration.
491 *
492 * @stability unstable
493 * @category layers
494 * @since 4.0.0
495 */
496export const layer = <R = never>(
497 config: PgPoolConfig<R>
498): Layer.Layer<PgClient | Client.SqlClient, SqlError, Exclude<R, Scope.Scope | Reactivity.Reactivity>> =>
499 layerFrom(make(config))
500
501/**
502 * Creates the PostgreSQL statement compiler.
503 *
504 * @stability unstable
505 * @category constructors
506 * @since 4.0.0
507 */
508export const makeCompiler = (
509 transform?: (_: string) => string,
510 transformJson = true
511): Statement.Compiler => {
512 const transformValue = transformJson && transform
513 ? Statement.defaultTransforms(transform).value
514 : undefined
515
516 return Statement.makeCompiler<PgCustom>({
517 dialect: "pg",
518 placeholder(_) {
519 return `$${_}`
520 },
521 onIdentifier: transform ?
522 function(value, withoutTransform) {
523 return withoutTransform ? escape(value) : escape(transform(value))
524 } :
525 escape,
526 onRecordUpdate(placeholders, valueAlias, valueColumns, values, returning) {
527 return [
528 `(values ${placeholders}) AS ${valueAlias}${valueColumns}${returning ? ` RETURNING ${returning[0]}` : ""}`,
529 returning ?
530 values.flat().concat(returning[1]) :
531 values.flat()
532 ]
533 },
534 onCustom(type, placeholder, withoutTransform) {
535 switch (type.kind) {
536 case "PgJson": {
537 const value = withoutTransform || transformValue === undefined
538 ? type.paramA
539 : transformValue(type.paramA)
540 return [
541 placeholder(undefined),
542 [PgTypes.jsonb(value)]
543 ]
544 }
545 }
546 }
547 })
548}
549
550const escape = Statement.defaultEscape("\"")
551
552/**
553 * PostgreSQL-specific statement fragments.
554 *
555 * @stability unstable
556 * @category models
557 * @since 4.0.0
558 */
559export type PgCustom = PgJson
560
561/**
562 * @category models
563 * @since 4.0.0
564 */
565interface PgJson extends Custom<"PgJson", unknown> {}
566/**
567 * @category constructors
568 * @since 4.0.0
569 */
570const PgJson = Statement.custom<PgJson>("PgJson")
571
572const ATTR_DB_SYSTEM_NAME = "db.system.name"
573const ATTR_DB_NAMESPACE = "db.namespace"
574const ATTR_SERVER_ADDRESS = "server.address"
575const ATTR_SERVER_PORT = "server.port"