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

PgClient.ts

423 lines13.4 KB

1/**
2 * PostgreSQL support for Effect SQL, backed by the native wire protocol client.
3 *
4 * @since 4.0.0
5 */
6import type * as Arr from "effect/Array"
7import * as Config from "effect/Config"
8import * as Context from "effect/Context"
9import type * as Duration from "effect/Duration"
10import * as Effect from "effect/Effect"
11import * as Layer from "effect/Layer"
12import type * as Queue from "effect/Queue"
13import type * as Redacted from "effect/Redacted"
14import type * as Scope from "effect/Scope"
15import * as Stream from "effect/Stream"
16import * as Reactivity from "effect/unstable/reactivity/Reactivity"
17import * as Client from "effect/unstable/sql/SqlClient"
18import type { Borrower, Connection } from "effect/unstable/sql/SqlConnection"
19import type { SqlError } from "effect/unstable/sql/SqlError"
20import type { Custom, Fragment } from "effect/unstable/sql/Statement"
21import * as Statement from "effect/unstable/sql/Statement"
22import type { Duplex } from "node:stream"
23import type { ConnectionOptions } from "node:tls"
24import { validateChannelName } from "./internal/sqlError.ts"
25import * as PgConnection from "./PgConnection.ts"
26import * as PgPool from "./PgPool.ts"
27import * as PgTypes from "./PgTypes.ts"
28​
29/**
30 * The runtime type identifier for `PgClient`.
31 *
32 * @category type IDs
33 * @since 4.0.0
34 */
35export const TypeId: TypeId = "~@effect/sql-pg/PgClient"
36​
37/**
38 * The type-level identifier for `PgClient`.
39 *
40 * @category type IDs
41 * @since 4.0.0
42 */
43export type TypeId = "~@effect/sql-pg/PgClient"
44​
45/**
46 * A PostgreSQL `SqlClient` with JSON and `LISTEN`/`NOTIFY` helpers.
47 *
48 * @category services
49 * @since 4.0.0
50 */
51export interface PgClient extends Client.SqlClient {
52 readonly [TypeId]: TypeId
53 readonly config: PgClientConfig
54 readonly json: (_: unknown) => Fragment
55 /**
56 * Registers a channel listener and returns its non-empty payload queue after
57 * PostgreSQL confirms `LISTEN`. The listener holds a connection until the
58 * scope closes.
59 */
60 readonly listen: (
61 channel: string
62 ) => Effect.Effect<Queue.Dequeue<PgConnection.Notification>, SqlError, Scope.Scope>
63 readonly notify: (channel: string, payload: string) => Effect.Effect<void, SqlError>
65​
66/**
67 * The service tag for `PgClient`.
68 *
69 * @category services
70 * @since 4.0.0
71 */
72export const PgClient = Context.Service<PgClient>("@effect/sql-pg/PgClient")
73​
74/**
75 * Connection and query settings for a PostgreSQL client.
76 *
77 * @category models
78 * @since 4.0.0
79 */
80export interface PgClientConfig {
81 readonly url?: Redacted.Redacted | undefined
82​
83 readonly host?: string | undefined
84 readonly port?: number | undefined
85 readonly path?: string | undefined
86 readonly ssl?: boolean | ConnectionOptions | undefined
87 readonly database?: string | undefined
88 readonly username?: string | undefined
89 readonly password?: Redacted.Redacted | undefined
90​
91 readonly connectTimeout?: Duration.Input | undefined
92​
93 readonly stream?: (() => Duplex) | undefined
94​
95 readonly applicationName?: string | undefined
96 readonly spanAttributes?: Record<string, unknown> | undefined
97​
98 readonly transformResultNames?: ((str: string) => string) | undefined
99 readonly transformQueryNames?: ((str: string) => string) | undefined
100 readonly transformJson?: boolean | undefined
101 readonly types?: PgTypes.Registry | undefined
102 /**
103 * Pipelines queries from multiple fibers on each pooled connection.
104 * Transactions, streams, and listeners still reserve a connection.
105 */
106 readonly multiplex?: boolean | undefined
107 /**
108 * How many statements may share one connection when `multiplex` is on.
109 * Defaults to `32`. Higher values trade tail latency for throughput: the
110 * statements sharing a connection are pipelined into one write, and they
111 * also queue behind the slowest of them.
112 */
113 readonly multiplexConcurrency?: number | undefined
114 /**
115 * Caches prepared statements by name. Enabled by default. Disable it for
116 * poolers that cannot preserve named statements between queries.
117 */
118 readonly prepare?: boolean | undefined
119 /** How many statements a connection keeps prepared. Defaults to `100`. */
120 readonly preparedStatementCacheSize?: number | undefined
121 /** Maximum backend message size in bytes. Defaults to 16 MiB. */
122 readonly maxMessageSize?: number | undefined
124​
125/**
126 * PostgreSQL client settings with connection pool limits and timeouts.
127 *
128 * @category models
129 * @since 4.0.0
130 */
131export interface PgPoolConfig extends PgClientConfig {
132 readonly idleTimeout?: Duration.Input | undefined
133​
134 readonly maxConnections?: number | undefined
135 readonly minConnections?: number | undefined
136 readonly connectionTTL?: Duration.Input | undefined
138​
139/**
140 * Creates a scoped PostgreSQL client backed by a connection pool.
141 *
142 * @category constructors
143 * @since 4.0.0
144 */
145export const make = (options: PgPoolConfig): Effect.Effect<PgClient, SqlError, Scope.Scope | Reactivity.Reactivity> =>
146 Effect.flatMap(PgPool.make(options), (pool) =>
147 makeImpl({
148 acquirer: Effect.map(pool.get, makeConnection),
149 borrower: (f) => pool.use((connection) => f(makeConnection(connection))),
150 transactionAcquirer: Effect.map(pool.reserve, makeConnection),
151 listenAcquirer: pool.reserve,
152 config: options
153 }))
154​
155/**
156 * Creates a scoped PostgreSQL client backed by one connection.
157 *
158 * @category constructors
159 * @since 4.0.0
160 */
161export const makeClient = (
162 options: PgClientConfig & {
163 /**
164 * Opens a separate connection for each stream and listener when enabled.
165 */
166 readonly acquireForStream?: boolean | undefined
167 }
168): Effect.Effect<PgClient, SqlError, Scope.Scope | Reactivity.Reactivity> =>
169 Effect.flatMap(PgConnection.make(options), (connection) =>
170 makeImpl({
171 acquirer: Effect.succeed(makeConnection(
172 connection,
173 options.acquireForStream ? PgConnection.make(options) : undefined
174 )),
175 transactionAcquirer: Effect.map(connection.pin, makeConnection),
176 listenAcquirer: options.acquireForStream ? PgConnection.make(options) : connection.pin,
177 config: options
178 }))
179​
180/**
181 * Builds the shared SQL facade around native connection acquirers.
182 */
183const makeImpl = Effect.fnUntraced(function*(
184 options: {
185 readonly acquirer: Effect.Effect<Connection, SqlError, Scope.Scope>
186 readonly borrower?: Borrower | undefined
187 readonly transactionAcquirer: Effect.Effect<Connection, SqlError, Scope.Scope>
188 readonly listenAcquirer: Effect.Effect<PgConnection.PgConnection, SqlError, Scope.Scope>
189 readonly config: PgClientConfig
190 }
191): Effect.fn.Return<PgClient, SqlError, Scope.Scope | Reactivity.Reactivity> {
192 const config = options.config
193 const compiler = makeCompiler(
194 config.transformQueryNames,
195 config.transformJson
196 )
197 const transformRows = config.transformResultNames ?
198 Statement.defaultTransforms(
199 config.transformResultNames,
200 config.transformJson
201 ).array :
202 undefined
203​
204 const listen = (
205 channel: string
206 ): Effect.Effect<Queue.Dequeue<PgConnection.Notification>, SqlError, Scope.Scope> =>
207 Effect.flatMap(options.listenAcquirer, (connection) => connection.listen(channel))
208​
209 return Object.assign(
210 yield* Client.make({
211 acquirer: options.acquirer,
212 borrower: options.borrower,
213 // Postgres prepares transaction control like anything else, and a client
214 // with preparation turned off falls back to the unnamed path anyway.
215 prepareTransactionControls: true,
216 transactionAcquirer: options.transactionAcquirer,
217 compiler,
218 spanAttributes: [
219 ...(config.spanAttributes ? Object.entries(config.spanAttributes) : []),
220 [ATTR_DB_SYSTEM_NAME, "postgresql"],
221 [ATTR_DB_NAMESPACE, config.database ?? config.username ?? "postgres"],
222 [ATTR_SERVER_ADDRESS, config.host ?? "localhost"],
223 [ATTR_SERVER_PORT, config.port ?? 5432]
224 ],
225 transformRows
226 }),
227 {
228 [TypeId]: TypeId as TypeId,
229 config,
230 json: (_: unknown) => Statement.fragment([PgJson(_)]),
231 listen,
232 notify: (channel: string, payload: string) => {
233 const channelError = validateChannelName(channel, "notify")
234 return channelError !== undefined ?
235 Effect.fail(channelError) :
236 Effect.asVoid(Effect.scoped(Effect.flatMap(
237 options.acquirer,
238 (conn) => conn.executeRaw(`SELECT pg_notify($1, $2)`, [channel, payload])
239 )))
240 }
241 }
242 )
243})
244​
245class ConnectionImpl implements Connection {
246 readonly connection: PgConnection.PgConnection
247 readonly streamAcquirer: Effect.Effect<PgConnection.PgConnection, SqlError, Scope.Scope> | undefined
248​
249 constructor(
250 connection: PgConnection.PgConnection,
251 streamAcquirer?: Effect.Effect<PgConnection.PgConnection, SqlError, Scope.Scope> | undefined
252 ) {
253 this.connection = connection
254 this.streamAcquirer = streamAcquirer
255 }
256​
257 private run(query: string, params: ReadonlyArray<unknown>, prepare = true) {
258 return Effect.map(this.connection.query(query, params, prepare), (result) => result.rows)
259 }
260​
261 execute(
262 sql: string,
263 params: ReadonlyArray<unknown>,
264 transformRows: (<A extends object>(row: ReadonlyArray<A>) => ReadonlyArray<A>) | undefined
265 ) {
266 return transformRows
267 ? Effect.map(this.run(sql, params), transformRows)
268 : this.run(sql, params)
269 }
270 executeRaw(sql: string, params: ReadonlyArray<unknown>) {
271 return this.connection.query(sql, params)
272 }
273 executeWithoutTransform(sql: string, params: ReadonlyArray<unknown>) {
274 return this.run(sql, params)
275 }
276 executeValues(sql: string, params: ReadonlyArray<unknown>) {
277 return this.connection.queryValues(sql, params)
278 }
279 executeValuesUnprepared(sql: string, params: ReadonlyArray<unknown>) {
280 return this.connection.queryValues(sql, params, false)
281 }
282 executeUnprepared(
283 sql: string,
284 params: ReadonlyArray<unknown>,
285 transformRows: (<A extends object>(row: ReadonlyArray<A>) => ReadonlyArray<A>) | undefined
286 ) {
287 const operation = this.run(sql, params, false)
288 return transformRows
289 ? Effect.map(operation, transformRows)
290 : operation
291 }
292 executeStream(
293 sql: string,
294 params: ReadonlyArray<unknown>,
295 transformRows: (<A extends object>(row: ReadonlyArray<A>) => ReadonlyArray<A>) | undefined
296 ) {
297 const stream = this.streamAcquirer === undefined
298 ? this.connection.stream(sql, params)
299 : Stream.unwrap(Effect.map(this.streamAcquirer, (connection) => connection.stream(sql, params)))
300 return transformRows
301 ? Stream.mapArray(stream, (rows) => transformRows(rows) as Arr.NonEmptyReadonlyArray<PgConnection.Row>)
302 : stream
303 }
305​
306const makeConnection = (
307 connection: PgConnection.PgConnection,
308 streamAcquirer?: Effect.Effect<PgConnection.PgConnection, SqlError, Scope.Scope> | undefined
309): Connection => new ConnectionImpl(connection, streamAcquirer)
310​
311/**
312 * Provides both `PgClient` and `SqlClient` from an acquisition effect.
313 *
314 * @category layers
315 * @since 4.0.0
316 */
317export const layerFrom = <E, R>(
318 acquire: Effect.Effect<PgClient, E, R>
319): Layer.Layer<PgClient | Client.SqlClient, E, Exclude<R, Scope.Scope | Reactivity.Reactivity>> =>
320 Layer.effectContext(
321 Effect.map(acquire, (client) =>
322 Context.make(PgClient, client).pipe(
323 Context.add(Client.SqlClient, client)
324 ))
325 ).pipe(Layer.provide(Reactivity.layer)) as any
326​
327/**
328 * Creates a client layer from wrapped pool configuration.
329 *
330 * @category layers
331 * @since 4.0.0
332 */
333export const layerConfig = (
334 config: Config.Wrap<PgPoolConfig>
335): Layer.Layer<PgClient | Client.SqlClient, Config.ConfigError | SqlError> =>
336 layerFrom(Effect.flatMap(
337 Config.unwrap(config),
338 make
339 ))
340​
341/**
342 * Creates a client layer from pool configuration.
343 *
344 * @category layers
345 * @since 4.0.0
346 */
347export const layer = (
348 config: PgPoolConfig
349): Layer.Layer<PgClient | Client.SqlClient, SqlError> => layerFrom(make(config))
350​
351/**
352 * Creates the PostgreSQL statement compiler.
353 *
354 * @category constructors
355 * @since 4.0.0
356 */
357export const makeCompiler = (
358 transform?: (_: string) => string,
359 transformJson = true
360): Statement.Compiler => {
361 const transformValue = transformJson && transform
362 ? Statement.defaultTransforms(transform).value
363 : undefined
364​
365 return Statement.makeCompiler<PgCustom>({
366 dialect: "pg",
367 placeholder(_) {
368 return `$${_}`
369 },
370 onIdentifier: transform ?
371 function(value, withoutTransform) {
372 return withoutTransform ? escape(value) : escape(transform(value))
373 } :
374 escape,
375 onRecordUpdate(placeholders, valueAlias, valueColumns, values, returning) {
376 return [
377 `(values ${placeholders}) AS ${valueAlias}${valueColumns}${returning ? ` RETURNING ${returning[0]}` : ""}`,
378 returning ?
379 values.flat().concat(returning[1]) :
380 values.flat()
381 ]
382 },
383 onCustom(type, placeholder, withoutTransform) {
384 switch (type.kind) {
385 case "PgJson": {
386 const value = withoutTransform || transformValue === undefined
387 ? type.paramA
388 : transformValue(type.paramA)
389 return [
390 placeholder(undefined),
391 [PgTypes.jsonb(value)]
392 ]
393 }
394 }
395 }
396 })
398​
399const escape = Statement.defaultEscape("\"")
400​
401/**
402 * PostgreSQL-specific statement fragments.
403 *
404 * @category models
405 * @since 4.0.0
406 */
407export type PgCustom = PgJson
408​
409/**
410 * @category models
411 * @since 4.0.0
412 */
413interface PgJson extends Custom<"PgJson", unknown> {}
414/**
415 * @category constructors
416 * @since 4.0.0
417 */
418const PgJson = Statement.custom<PgJson>("PgJson")
419​
420const ATTR_DB_SYSTEM_NAME = "db.system.name"
421const ATTR_DB_NAMESPACE = "db.namespace"
422const ATTR_SERVER_ADDRESS = "server.address"
423const ATTR_SERVER_PORT = "server.port"