Open History to see the last commit
1/**
2 * Connects Effect SQL to PostgreSQL using the `pg` package.
3 *
4 * This module provides constructors and layers for building a PostgreSQL
5 * client from pool settings, a managed `pg.Client`, an existing `pg.Pool`, or
6 * custom connection code. The client runs Effect SQL queries against
7 * PostgreSQL, including transactions and streamed results, and adds helpers for
8 * JSON values and LISTEN/NOTIFY messages. It also maps common PostgreSQL
9 * failures, such as connection, authentication, constraint, timeout, and
10 * deadlock errors, into Effect SQL errors.
11 *
12 * @since 4.0.0
13 */
14import * as Arr from "effect/Array"
15import * as Cause from "effect/Cause"
16import * as Channel from "effect/Channel"
17import * as Config from "effect/Config"
18import * as Context from "effect/Context"
19import * as Duration from "effect/Duration"
20import * as Effect from "effect/Effect"
21import * as Fiber from "effect/Fiber"
22import * as Layer from "effect/Layer"
23import * as Number from "effect/Number"
24import * as Option from "effect/Option"
25import * as Queue from "effect/Queue"
26import * as RcRef from "effect/RcRef"
27import * as Redacted from "effect/Redacted"
28import * as Scope from "effect/Scope"
29import * as Semaphore from "effect/Semaphore"
30import * as Stream from "effect/Stream"
31import * as Reactivity from "effect/unstable/reactivity/Reactivity"
32import * as Client from "effect/unstable/sql/SqlClient"
33import type { Connection } from "effect/unstable/sql/SqlConnection"
34import type * as SqlConnection from "effect/unstable/sql/SqlConnection"
35import {
36 AuthenticationError,
37 AuthorizationError,
38 ConnectionError,
39 ConstraintError,
40 DeadlockError,
41 LockTimeoutError,
42 SerializationError,
43 SqlError,
44 SqlSyntaxError,
45 StatementTimeoutError,
46 UniqueViolation,
47 UnknownError
48} from "effect/unstable/sql/SqlError"
49import type { Custom, Fragment } from "effect/unstable/sql/Statement"
50import * as Statement from "effect/unstable/sql/Statement"
51import type { Duplex } from "node:stream"
52import type { ConnectionOptions } from "node:tls"
53import * as Pg from "pg"
54import * as PgConnString from "pg-connection-string"
55import Cursor from "pg-cursor"
56
57/**
58 * Runtime type identifier used to mark `PgClient` values.
59 *
60 * @category type IDs
61 * @since 4.0.0
62 */
63export const TypeId: TypeId = "~@effect/sql-pg/PgClient"
64
65/**
66 * Type-level identifier used to mark `PgClient` values.
67 *
68 * @category type IDs
69 * @since 4.0.0
70 */
71export type TypeId = "~@effect/sql-pg/PgClient"
72
73/**
74 * PostgreSQL client service, extending `SqlClient` with JSON parameter fragments and LISTEN/NOTIFY helpers.
75 *
76 * @category models
77 * @since 4.0.0
78 */
79export interface PgClient extends Client.SqlClient {
80 readonly [TypeId]: TypeId
81 readonly config: PgClientConfig
82 readonly json: (_: unknown) => Fragment
83 readonly listen: (channel: string) => Stream.Stream<string, SqlError>
84 readonly notify: (channel: string, payload: string) => Effect.Effect<void, SqlError>
85}
86
87/**
88 * Service tag for the PostgreSQL client service.
89 *
90 * **When to use**
91 *
92 * Use to access or provide a PostgreSQL client through the Effect context.
93 *
94 * @category services
95 * @since 4.0.0
96 */
97export const PgClient = Context.Service<PgClient>("@effect/sql-pg/PgClient")
98
99/**
100 * Configuration for a PostgreSQL client, including connection, TLS, custom stream, application name, type parser, JSON transform, and query/result name transform options.
101 *
102 * @category constructors
103 * @since 4.0.0
104 */
105export interface PgClientConfig {
106 readonly url?: Redacted.Redacted | undefined
107
108 readonly host?: string | undefined
109 readonly port?: number | undefined
110 readonly path?: string | undefined
111 readonly ssl?: boolean | ConnectionOptions | undefined
112 readonly database?: string | undefined
113 readonly username?: string | undefined
114 readonly password?: Redacted.Redacted | undefined
115
116 readonly connectTimeout?: Duration.Input | undefined
117
118 readonly stream?: (() => Duplex) | undefined
119
120 readonly applicationName?: string | undefined
121 readonly spanAttributes?: Record<string, unknown> | undefined
122
123 readonly transformResultNames?: ((str: string) => string) | undefined
124 readonly transformQueryNames?: ((str: string) => string) | undefined
125 readonly transformJson?: boolean | undefined
126 readonly types?: Pg.CustomTypesConfig | undefined
127}
128
129/**
130 * PostgreSQL pool configuration, extending `PgClientConfig` with idle timeout, pool size, and connection lifetime settings.
131 *
132 * @category constructors
133 * @since 4.0.0
134 */
135export interface PgPoolConfig extends PgClientConfig {
136 readonly idleTimeout?: Duration.Input | undefined
137
138 readonly maxConnections?: number | undefined
139 readonly minConnections?: number | undefined
140 readonly connectionTTL?: Duration.Input | undefined
141}
142
143/**
144 * Creates a scoped PostgreSQL client backed by a managed `pg` connection pool.
145 *
146 * @category constructors
147 * @since 4.0.0
148 */
149export const make = (options: PgPoolConfig): Effect.Effect<PgClient, SqlError, Scope.Scope | Reactivity.Reactivity> =>
150 fromPool({
151 ...options,
152 acquire: Effect.gen(function*() {
153 const pool = new Pg.Pool({
154 connectionString: options.url ? Redacted.value(options.url) : undefined,
155 user: options.username,
156 host: options.host,
157 database: options.database,
158 password: options.password ? Redacted.value(options.password) : undefined,
159 ssl: options.ssl,
160 port: options.port,
161 ...(options.stream ? { stream: options.stream } : {}),
162 connectionTimeoutMillis: options.connectTimeout
163 ? Duration.toMillis(Duration.fromInputUnsafe(options.connectTimeout))
164 : undefined,
165 idleTimeoutMillis: options.idleTimeout
166 ? Duration.toMillis(Duration.fromInputUnsafe(options.idleTimeout))
167 : undefined,
168 max: options.maxConnections,
169 min: options.minConnections,
170 maxLifetimeSeconds: options.connectionTTL
171 ? Duration.toSeconds(Duration.fromInputUnsafe(options.connectionTTL))
172 : undefined,
173 application_name: options.applicationName ?? "@effect/sql-pg",
174 types: options.types
175 })
176
177 pool.on("error", (_err) => {})
178
179 yield* Effect.acquireRelease(
180 Effect.tryPromise({
181 try: () => pool.query("SELECT 1"),
182 catch: (cause) => new SqlError({ reason: classifyError(cause, "PgClient: Failed to connect", "connect") })
183 }),
184 () =>
185 Effect.promise(() => pool.end()).pipe(
186 Effect.timeoutOption(1000)
187 ),
188 { interruptible: true }
189 ).pipe(
190 Effect.timeoutOrElse({
191 duration: options.connectTimeout ?? Duration.seconds(5),
192 orElse: () =>
193 Effect.fail(
194 new SqlError({
195 reason: new ConnectionError({
196 cause: new Error("Connection timed out"),
197 message: "PgClient: Connection timed out",
198 operation: "connect"
199 })
200 })
201 )
202 })
203 )
204
205 return pool
206 })
207 })
208
209/**
210 * Creates a scoped PostgreSQL client backed by a managed single `pg` client, optionally acquiring a separate client for streaming and LISTEN operations.
211 *
212 * @category constructors
213 * @since 4.0.0
214 */
215export const makeClient = (
216 options: PgClientConfig & {
217 /**
218 * Whether to acquire a separate client for each sql.stream / sql.listen
219 */
220 readonly acquireForStream?: boolean | undefined
221 }
222): Effect.Effect<PgClient, SqlError, Scope.Scope | Reactivity.Reactivity> =>
223 fromClient({
224 ...options,
225 acquire: Effect.acquireRelease(
226 Effect.tryPromise({
227 try: async () => {
228 const client = new Pg.Client({
229 connectionString: options.url ? Redacted.value(options.url) : undefined,
230 user: options.username,
231 host: options.host,
232 database: options.database,
233 password: options.password ? Redacted.value(options.password) : undefined,
234 ssl: options.ssl,
235 port: options.port,
236 ...(options.stream ? { stream: options.stream } : {}),
237 application_name: options.applicationName ?? "@effect/sql-pg",
238 types: options.types
239 })
240 await client.connect()
241 return client
242 },
243 catch: (cause) => new SqlError({ reason: classifyError(cause, "PgClient: Failed to connect", "connect") })
244 }),
245 (client) =>
246 Effect.promise(() => client.end()).pipe(
247 Effect.timeoutOption(1000)
248 ),
249 { interruptible: true }
250 ).pipe(
251 Effect.timeoutOrElse({
252 duration: options.connectTimeout ?? Duration.seconds(5),
253 orElse: () =>
254 Effect.fail(
255 new SqlError({
256 reason: new ConnectionError({
257 cause: new Error("Connection timed out"),
258 message: "PgClient: Connection timed out",
259 operation: "connect"
260 })
261 })
262 )
263 })
264 ),
265 acquireForStream: options.acquireForStream ?? false
266 })
267
268/**
269 * Builds a PostgreSQL client from a scoped `pg` pool acquisition effect, deriving transaction, streaming, and LISTEN/NOTIFY support from that pool.
270 *
271 * @category constructors
272 * @since 4.0.0
273 */
274export const fromPool = Effect.fnUntraced(function*(
275 options: {
276 readonly acquire: Effect.Effect<Pg.Pool, SqlError, Scope.Scope>
277
278 readonly applicationName?: string | undefined
279 readonly spanAttributes?: Record<string, unknown> | undefined
280
281 readonly transformResultNames?: ((str: string) => string) | undefined
282 readonly transformQueryNames?: ((str: string) => string) | undefined
283 readonly transformJson?: boolean | undefined
284 readonly types?: Pg.CustomTypesConfig | undefined
285 }
286): Effect.fn.Return<PgClient, SqlError, Scope.Scope | Reactivity.Reactivity> {
287 const pool = yield* options.acquire
288
289 const makeConection = (client?: Pg.PoolClient) =>
290 new ConnectionImpl(
291 function runWithClient<A>(f: (client: Pg.ClientBase, resume: (_: Effect.Effect<A, SqlError>) => void) => void) {
292 if (client !== undefined) {
293 return Effect.callback<A, SqlError>((resume) => {
294 f(client!, resume)
295 return makeCancel(pool, client!)
296 })
297 }
298 return Effect.callback<A, SqlError>((resume) => {
299 let done = false
300 let cancel: Effect.Effect<void> | undefined = undefined
301 let client: Pg.PoolClient | undefined = undefined
302 function onError(cause: Error) {
303 cleanup(cause)
304 resume(Effect.fail(new SqlError({ reason: classifyError(cause, "Connection error", "acquireConnection") })))
305 }
306 function cleanup(cause?: Error) {
307 if (!done) client?.release(cause)
308 done = true
309 client?.off("error", onError)
310 }
311 pool.connect((cause, client_) => {
312 if (cause) {
313 return resume(
314 Effect.fail(
315 new SqlError({
316 reason: classifyError(cause, "Failed to acquire connection", "acquireConnection")
317 })
318 )
319 )
320 } else if (!client_) {
321 return resume(
322 Effect.fail(
323 new SqlError({
324 reason: new ConnectionError({
325 message: "Failed to acquire connection",
326 cause: new Error("No client returned"),
327 operation: "acquireConnection"
328 })
329 })
330 )
331 )
332 } else if (done) {
333 client_.release()
334 return
335 }
336 client = client_
337 client.once("error", onError)
338 cancel = makeCancel(pool, client)
339 f(client, (eff) => {
340 cleanup()
341 resume(eff)
342 })
343 })
344 return Effect.suspend(() => {
345 if (!cancel) {
346 cleanup()
347 return Effect.void
348 }
349 return Effect.ensuring(cancel, Effect.sync(cleanup))
350 })
351 })
352 },
353 client ? Effect.succeed(client) : reserveRaw
354 )
355
356 const reserveRaw = Effect.callback<Pg.PoolClient, SqlError, Scope.Scope>((resume) => {
357 const fiber = Fiber.getCurrent()!
358 const scope = Context.getUnsafe(fiber.context, Scope.Scope)
359 let cause: Error | undefined = undefined
360 function onError(cause_: Error) {
361 cause = cause_
362 }
363 pool.connect((err, client, release) => {
364 if (err) {
365 return resume(
366 Effect.fail(
367 new SqlError({
368 reason: classifyError(
369 err,
370 "Failed to acquire connection for transaction",
371 "acquireConnection"
372 )
373 })
374 )
375 )
376 } else if (!client) {
377 return resume(
378 Effect.fail(
379 new SqlError({
380 reason: new ConnectionError({
381 message: "Failed to acquire connection for transaction",
382 cause: new Error("No client returned"),
383 operation: "acquireConnection"
384 })
385 })
386 )
387 )
388 }
389 client.on("error", onError)
390 resume(Effect.as(
391 Scope.addFinalizer(
392 scope,
393 Effect.sync(() => {
394 client.off("error", onError)
395 release(cause)
396 })
397 ),
398 client
399 ))
400 })
401 })
402 const reserve = Effect.map(reserveRaw, makeConection)
403
404 const onListenClientError = (_: Error) => {
405 }
406
407 const listenAcquirer = yield* RcRef.make({
408 acquire: Effect.acquireRelease(
409 Effect.tryPromise({
410 try: async () => {
411 const client = new Pg.Client(pool.options)
412 await client.connect()
413 client.on("error", onListenClientError)
414 return client
415 },
416 catch: (cause) =>
417 new SqlError({
418 reason: classifyError(cause, "Failed to acquire connection for listen", "acquireConnection")
419 })
420 }),
421 (client) =>
422 Effect.promise(() => {
423 client.off("error", onListenClientError)
424 return client.end()
425 }).pipe(
426 Effect.timeoutOption(1000)
427 ),
428 { interruptible: true }
429 )
430 })
431
432 let config: PgClientConfig = {
433 url: pool.options.connectionString ? Redacted.make(pool.options.connectionString) : undefined,
434 host: pool.options.host,
435 port: pool.options.port,
436 database: pool.options.database,
437 username: pool.options.user,
438 password: typeof pool.options.password === "string" ? Redacted.make(pool.options.password) : undefined,
439 ssl: pool.options.ssl,
440 applicationName: pool.options.application_name,
441 types: pool.options.types
442 }
443 if (pool.options.connectionString) {
444 // @effect-diagnostics-next-line tryCatchInEffectGen:off
445 try {
446 const parsed = PgConnString.parse(pool.options.connectionString)
447 config = {
448 ...config,
449 host: config.host ?? parsed.host ?? undefined,
450 port: config.port ?? (parsed.port ? Option.getOrUndefined(Number.parse(parsed.port)) : undefined),
451 username: config.username ?? parsed.user ?? undefined,
452 password: config.password ?? (parsed.password ? Redacted.make(parsed.password) : undefined),
453 database: config.database ?? parsed.database ?? undefined
454 }
455 } catch {
456 //
457 }
458 }
459
460 return yield* makeWith({
461 acquirer: Effect.succeed(makeConection()),
462 transactionAcquirer: reserve,
463 listenAcquirer: RcRef.get(listenAcquirer),
464 config,
465 spanAttributes: options.spanAttributes,
466 transformResultNames: options.transformResultNames,
467 transformQueryNames: options.transformQueryNames,
468 transformJson: options.transformJson
469 })
470})
471
472/**
473 * Builds a PostgreSQL client from a scoped `pg` client acquisition effect, serializing access when sharing the client and optionally using separate clients for streams and LISTEN.
474 *
475 * @category constructors
476 * @since 4.0.0
477 */
478export const fromClient = Effect.fnUntraced(function*(
479 options: {
480 readonly acquire: Effect.Effect<Pg.Client, SqlError, Scope.Scope>
481
482 /**
483 * Whether to acquire a separate client for each sql.stream / sql.listen.
484 */
485 readonly acquireForStream: boolean
486
487 readonly applicationName?: string | undefined
488 readonly spanAttributes?: Record<string, unknown> | undefined
489
490 readonly transformResultNames?: ((str: string) => string) | undefined
491 readonly transformQueryNames?: ((str: string) => string) | undefined
492 readonly transformJson?: boolean | undefined
493 readonly types?: Pg.CustomTypesConfig | undefined
494 }
495): Effect.fn.Return<PgClient, SqlError, Scope.Scope | Reactivity.Reactivity> {
496 function onError() {}
497 const acquireWithErrorHandler = options.acquire.pipe(
498 Effect.tap((client) => {
499 client.on("error", onError)
500 return Effect.addFinalizer(() => {
501 client.off("error", onError)
502 return Effect.void
503 })
504 })
505 )
506 const client = yield* acquireWithErrorHandler
507
508 const semaphore = Semaphore.makeUnsafe(1)
509 let streamClient = options.acquireForStream ? acquireWithErrorHandler : Effect.acquireRelease(
510 Effect.as(semaphore.take(1), client),
511 () => semaphore.release(1)
512 )
513
514 const makeConection = (client: Pg.Client) =>
515 new ConnectionImpl(
516 function runWithClient<A>(f: (client: Pg.ClientBase, resume: (_: Effect.Effect<A, SqlError>) => void) => void) {
517 return Effect.callback<A, SqlError>((resume) => {
518 f(client, resume)
519 })
520 },
521 streamClient
522 )
523 const connection = makeConection(client)
524 const acquirer = semaphore.withPermit(Effect.succeed(connection))
525
526 const config: PgClientConfig = {
527 ...options,
528 host: client.host,
529 port: client.port,
530 database: client.database,
531 username: client.user,
532 password: typeof client.password === "string" ? Redacted.make(client.password) : undefined,
533 ssl: client.ssl
534 }
535
536 return yield* makeWith({
537 acquirer,
538 transactionAcquirer: acquirer,
539 listenAcquirer: streamClient,
540 config,
541 spanAttributes: options.spanAttributes,
542 transformResultNames: options.transformResultNames,
543 transformQueryNames: options.transformQueryNames,
544 transformJson: options.transformJson
545 })
546})
547
548/**
549 * Creates a `PgClient` from SQL connection acquirers, a LISTEN acquirer, client configuration, and transformation options.
550 *
551 * **When to use**
552 *
553 * Use to build a PostgreSQL client from custom connection acquisition logic
554 * instead of the built-in pool or single-client constructors.
555 *
556 * @category constructors
557 * @since 4.0.0
558 */
559export const makeWith = Effect.fnUntraced(function*(
560 options: {
561 readonly acquirer: SqlConnection.Acquirer
562 readonly transactionAcquirer: SqlConnection.Acquirer
563 readonly listenAcquirer: Effect.Effect<Pg.ClientBase, SqlError, Scope.Scope>
564
565 readonly config: PgClientConfig
566 readonly spanAttributes?: Record<string, unknown> | undefined
567
568 readonly transformResultNames?: ((str: string) => string) | undefined
569 readonly transformQueryNames?: ((str: string) => string) | undefined
570 readonly transformJson?: boolean | undefined
571 }
572): Effect.fn.Return<PgClient, SqlError, Scope.Scope | Reactivity.Reactivity> {
573 const compiler = makeCompiler(
574 options.transformQueryNames,
575 options.transformJson
576 )
577 const transformRows = options.transformResultNames ?
578 Statement.defaultTransforms(
579 options.transformResultNames,
580 options.transformJson
581 ).array :
582 undefined
583
584 const config = options.config
585
586 return Object.assign(
587 yield* Client.make({
588 acquirer: options.acquirer,
589 transactionAcquirer: options.transactionAcquirer,
590 compiler,
591 spanAttributes: [
592 ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
593 [ATTR_DB_SYSTEM_NAME, "postgresql"],
594 [ATTR_DB_NAMESPACE, config.database ?? config.username ?? "postgres"],
595 [ATTR_SERVER_ADDRESS, config.host ?? "localhost"],
596 [ATTR_SERVER_PORT, config.port ?? 5432]
597 ],
598 transformRows
599 }),
600 {
601 [TypeId]: TypeId as TypeId,
602 config: options.config,
603 json: (_: unknown) => Statement.fragment([PgJson(_)]),
604 listen: (channel: string) =>
605 Stream.callback<string, SqlError>(Effect.fnUntraced(function*(queue) {
606 const client = yield* options.listenAcquirer
607 function onNotification(msg: Pg.Notification) {
608 if (msg.channel === channel && msg.payload) {
609 Queue.offerUnsafe(queue, msg.payload)
610 }
611 }
612 yield* Effect.addFinalizer(() =>
613 Effect.promise(() => {
614 client.off("notification", onNotification)
615 return client.query(`UNLISTEN ${Pg.escapeIdentifier(channel)}`)
616 })
617 )
618 yield* Effect.tryPromise({
619 try: () => client.query(`LISTEN ${Pg.escapeIdentifier(channel)}`),
620 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to listen", "listen") })
621 })
622 client.on("notification", onNotification)
623 })),
624 notify: (channel: string, payload: string) =>
625 Effect.asVoid(Effect.scoped(Effect.flatMap(
626 options.acquirer,
627 (conn) => conn.executeRaw(`SELECT pg_notify($1, $2)`, [channel, payload])
628 )))
629 }
630 )
631})
632
633class ConnectionImpl implements Connection {
634 constructor(
635 runWithClient: <A>(
636 f: (client: Pg.ClientBase, resume: (_: Effect.Effect<A, SqlError>) => void) => void
637 ) => Effect.Effect<A, SqlError>,
638 reserve: Effect.Effect<Pg.ClientBase, SqlError, Scope.Scope>
639 ) {
640 this.runWithClient = runWithClient
641 this.reserve = reserve
642 }
643
644 private readonly runWithClient: <A>(
645 f: (client: Pg.ClientBase, resume: (_: Effect.Effect<A, SqlError>) => void) => void
646 ) => Effect.Effect<A, SqlError>
647 private readonly reserve: Effect.Effect<Pg.ClientBase, SqlError, Scope.Scope>
648
649 private run(query: string, params: ReadonlyArray<unknown>) {
650 return this.runWithClient<ReadonlyArray<any>>((client, resume) => {
651 client.query(query, params as any, (err, result) => {
652 if (err) {
653 resume(
654 Effect.fail(new SqlError({ reason: classifyError(err, "Failed to execute statement", "execute") }))
655 )
656 } else {
657 // Multi-statement queries return an array of results
658 resume(Effect.succeed(
659 Array.isArray(result)
660 ? result.map((r) => r.rows ?? [])
661 : result.rows ?? []
662 ))
663 }
664 })
665 })
666 }
667
668 execute(
669 sql: string,
670 params: ReadonlyArray<unknown>,
671 transformRows: (<A extends object>(row: ReadonlyArray<A>) => ReadonlyArray<A>) | undefined
672 ) {
673 return transformRows
674 ? Effect.map(this.run(sql, params), transformRows)
675 : this.run(sql, params)
676 }
677 executeRaw(sql: string, params: ReadonlyArray<unknown>) {
678 return this.runWithClient<Pg.Result>((client, resume) => {
679 client.query(sql, params as any, (err, result) => {
680 if (err) {
681 resume(
682 Effect.fail(new SqlError({ reason: classifyError(err, "Failed to execute statement", "execute") }))
683 )
684 } else {
685 resume(Effect.succeed(result))
686 }
687 })
688 })
689 }
690 executeWithoutTransform(sql: string, params: ReadonlyArray<unknown>) {
691 return this.run(sql, params)
692 }
693 executeValues(sql: string, params: ReadonlyArray<unknown>) {
694 return this.runWithClient<ReadonlyArray<any>>((client, resume) => {
695 client.query(
696 {
697 text: sql,
698 rowMode: "array",
699 values: params as Array<string>
700 },
701 (err, result) => {
702 if (err) {
703 resume(
704 Effect.fail(new SqlError({ reason: classifyError(err, "Failed to execute statement", "execute") }))
705 )
706 } else {
707 resume(Effect.succeed(result.rows))
708 }
709 }
710 )
711 })
712 }
713 executeValuesUnprepared(sql: string, params: ReadonlyArray<unknown>) {
714 return this.executeValues(sql, params)
715 }
716 executeUnprepared(
717 sql: string,
718 params: ReadonlyArray<unknown>,
719 transformRows: (<A extends object>(row: ReadonlyArray<A>) => ReadonlyArray<A>) | undefined
720 ) {
721 return this.execute(sql, params, transformRows)
722 }
723 executeStream(
724 sql: string,
725 params: ReadonlyArray<unknown>,
726 transformRows: (<A extends object>(row: ReadonlyArray<A>) => ReadonlyArray<A>) | undefined
727 ) {
728 // oxlint-disable-next-line @typescript-eslint/no-this-alias
729 const self = this
730 return Stream.fromChannel(Channel.fromTransform(Effect.fnUntraced(function*(_, scope) {
731 const client = yield* Scope.provide(self.reserve, scope)
732 yield* Scope.addFinalizer(scope, Effect.promise(() => cursor.close()))
733 const cursor = client.query(new Cursor(sql, params as any))
734 // @effect-diagnostics-next-line returnEffectInGen:off
735 return Effect.callback<Arr.NonEmptyReadonlyArray<any>, SqlError | Cause.Done>((resume) => {
736 cursor.read(128, (err, rows) => {
737 if (err) {
738 resume(Effect.fail(new SqlError({ reason: classifyError(err, "Failed to execute statement", "stream") })))
739 } else if (Arr.isArrayNonEmpty(rows)) {
740 resume(Effect.succeed(transformRows ? transformRows(rows) as any : rows))
741 } else {
742 resume(Cause.done())
743 }
744 })
745 })
746 })))
747 }
748}
749
750const cancelEffects = new WeakMap<Pg.PoolClient, Effect.Effect<void> | undefined>()
751const makeCancel = (pool: Pg.Pool, client: Pg.PoolClient) => {
752 if (cancelEffects.has(client)) {
753 return cancelEffects.get(client)!
754 }
755 const processId = (client as any).processID
756 const eff = processId !== undefined
757 // query cancelation is best-effort, so we don't fail if it doesn't work
758 ? Effect.callback<void>((resume) => {
759 if (pool.ending) return resume(Effect.void)
760 pool.query(`SELECT pg_cancel_backend(${processId})`, () => {
761 resume(Effect.void)
762 })
763 }).pipe(
764 Effect.interruptible,
765 Effect.timeoutOption(5000)
766 )
767 : undefined
768 cancelEffects.set(client, eff)
769 return eff
770}
771
772/**
773 * Creates a layer from an effect that acquires a `PgClient`, providing both `PgClient` and `SqlClient`.
774 *
775 * @category layers
776 * @since 4.0.0
777 */
778export const layerFrom = <E, R>(
779 acquire: Effect.Effect<PgClient, E, R>
780): Layer.Layer<PgClient | Client.SqlClient, E, Exclude<R, Scope.Scope | Reactivity.Reactivity>> =>
781 Layer.effectContext(
782 Effect.map(acquire, (client) =>
783 Context.make(PgClient, client).pipe(
784 Context.add(Client.SqlClient, client)
785 ))
786 ).pipe(Layer.provide(Reactivity.layer)) as any
787
788/**
789 * Creates a layer from a `Config`-wrapped PostgreSQL pool configuration, providing both `PgClient` and `SqlClient`.
790 *
791 * @category layers
792 * @since 4.0.0
793 */
794export const layerConfig: (
795 config: Config.Wrap<PgPoolConfig>
796) => Layer.Layer<PgClient | Client.SqlClient, Config.ConfigError | SqlError> = (
797 config: Config.Wrap<PgPoolConfig>
798): Layer.Layer<PgClient | Client.SqlClient, Config.ConfigError | SqlError> =>
799 layerFrom(Effect.flatMap(
800 Config.unwrap(config),
801 make
802 ))
803
804/**
805 * Creates a layer from a concrete PostgreSQL pool configuration, providing both `PgClient` and `SqlClient`.
806 *
807 * @category layers
808 * @since 4.0.0
809 */
810export const layer = (
811 config: PgPoolConfig
812): Layer.Layer<PgClient | Client.SqlClient, SqlError> => layerFrom(make(config))
813
814/**
815 * Creates the PostgreSQL statement compiler, using `$1` placeholders, double-quoted identifiers, PostgreSQL returning clauses, and optional JSON value transformation.
816 *
817 * @category constructors
818 * @since 4.0.0
819 */
820export const makeCompiler = (
821 transform?: (_: string) => string,
822 transformJson = true
823): Statement.Compiler => {
824 const transformValue = transformJson && transform
825 ? Statement.defaultTransforms(transform).value
826 : undefined
827
828 return Statement.makeCompiler<PgCustom>({
829 dialect: "pg",
830 placeholder(_) {
831 return `$${_}`
832 },
833 onIdentifier: transform ?
834 function(value, withoutTransform) {
835 return withoutTransform ? escape(value) : escape(transform(value))
836 } :
837 escape,
838 onRecordUpdate(placeholders, valueAlias, valueColumns, values, returning) {
839 return [
840 `(values ${placeholders}) AS ${valueAlias}${valueColumns}${returning ? ` RETURNING ${returning[0]}` : ""}`,
841 returning ?
842 values.flat().concat(returning[1]) :
843 values.flat()
844 ]
845 },
846 onCustom(type, placeholder, withoutTransform) {
847 switch (type.kind) {
848 case "PgJson": {
849 return [
850 placeholder(undefined),
851 [
852 withoutTransform || transformValue === undefined
853 ? type.paramA
854 : transformValue(type.paramA)
855 ]
856 ]
857 }
858 }
859 }
860 })
861}
862
863const escape = Statement.defaultEscape("\"")
864
865/**
866 * PostgreSQL-specific custom statement fragments supported by the compiler, currently JSON parameter fragments.
867 *
868 * @category custom types
869 * @since 4.0.0
870 */
871export type PgCustom = PgJson
872
873/**
874 * @category custom types
875 * @since 4.0.0
876 */
877interface PgJson extends Custom<"PgJson", unknown> {}
878/**
879 * @category custom types
880 * @since 4.0.0
881 */
882const PgJson = Statement.custom<PgJson>("PgJson")
883
884const ATTR_DB_SYSTEM_NAME = "db.system.name"
885const ATTR_DB_NAMESPACE = "db.namespace"
886const ATTR_SERVER_ADDRESS = "server.address"
887const ATTR_SERVER_PORT = "server.port"
888
889const pgCodeFromCause = (cause: unknown): string | undefined => {
890 if (typeof cause !== "object" || cause === null || !("code" in cause)) {
891 return undefined
892 }
893 const code = cause.code
894 return typeof code === "string" ? code : undefined
895}
896
897const pgConstraintFromCause = (cause: unknown): string => {
898 if (typeof cause !== "object" || cause === null || !("constraint" in cause)) {
899 return "unknown"
900 }
901 const constraint = cause.constraint
902 if (typeof constraint !== "string") {
903 return "unknown"
904 }
905 const normalized = constraint.trim()
906 return normalized.length === 0 ? "unknown" : normalized
907}
908
909const classifyError = (
910 cause: unknown,
911 message: string,
912 operation: string
913) => {
914 const props = { cause, message, operation }
915 const code = pgCodeFromCause(cause)
916 if (code !== undefined) {
917 if (code.startsWith("08")) {
918 return new ConnectionError(props)
919 }
920 if (code.startsWith("28")) {
921 return new AuthenticationError(props)
922 }
923 if (code === "42501") {
924 return new AuthorizationError(props)
925 }
926 if (code.startsWith("42")) {
927 return new SqlSyntaxError(props)
928 }
929 if (code === "23505") {
930 return new UniqueViolation({ ...props, constraint: pgConstraintFromCause(cause) })
931 }
932 if (code.startsWith("23")) {
933 return new ConstraintError(props)
934 }
935 if (code === "40P01") {
936 return new DeadlockError(props)
937 }
938 if (code === "40001") {
939 return new SerializationError(props)
940 }
941 if (code === "55P03") {
942 return new LockTimeoutError(props)
943 }
944 if (code === "57014") {
945 return new StatementTimeoutError(props)
946 }
947 }
948 return new UnknownError(props)
949}