@steadybrew/postgresjs 4.5.0-rc1 → 4.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/docs/api.md ADDED
@@ -0,0 +1,1609 @@
1
+ # API reference
2
+
3
+ The full API of [@steadybrew/postgresjs](../README.md). Installing, switching from Postgres.js and the fixed upstream issues are in the [README](../README.md).
4
+
5
+ ## Contents
6
+
7
+ * [Connection](#connection)
8
+ * [Queries](#queries)
9
+ * [Building queries](#building-queries)
10
+ * [Advanced query methods](#advanced-query-methods)
11
+ * [Transactions](#transactions)
12
+ * [Data Transformation](#data-transformation)
13
+ * [Listen & notify](#listen--notify)
14
+ * [Realtime subscribe](#realtime-subscribe)
15
+ * [Numbers, bigint, numeric](#numbers-bigint-numeric)
16
+ * [Parameter types](#parameter-types)
17
+ * [Result Array](#result-array)
18
+ * [Connection details](#connection-details)
19
+ * [Custom Types](#custom-types)
20
+ * [Teardown / Cleanup](#teardown--cleanup)
21
+ * [Reserving connections](#reserving-connections)
22
+ * [Error handling](#error-handling)
23
+ * [TypeScript support](#typescript-support)
24
+ * [Migration tools](#migration-tools)
25
+
26
+ ## Connection
27
+
28
+ ### `postgres([url], [options])`
29
+
30
+ You can use either a `postgres://` url connection string or the options to define your database connection properties. Options in the object will override any present in the url. Options will fall back to the same environment variables as psql.
31
+
32
+ ```js
33
+ const sql = postgres('postgres://username:password@host:port/database', {
34
+ host : '', // Postgres ip address[s] or domain name[s]
35
+ port : 5432, // Postgres server port[s]
36
+ database : '', // Name of database to connect to
37
+ username : '', // Username of database user
38
+ password : '', // Password of database user
39
+ ...and more
40
+ })
41
+ ```
42
+
43
+ More options can be found in the [Connection details section](#connection-details).
44
+
45
+ ## Queries
46
+
47
+ ### ```await sql`...` -> Result[]```
48
+
49
+ Postgres.js utilizes [Tagged template functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_templates) to process query parameters **before** interpolation. Using tagged template literals benefits developers by:
50
+
51
+ 1. **Enforcing** safe query generation
52
+ 2. Giving the ` sql`` ` function powerful [utility](#dynamic-inserts) and [query building](#building-queries) features.
53
+
54
+ Any generic value will be serialized as described in [Parameter types](#parameter-types), and replaced by a PostgreSQL protocol placeholder `$1, $2, ...`. The values are then sent separately to PostgreSQL, which handles escaping & casting.
55
+
56
+ All queries will return a `Result` array, with objects mapping column names to each row.
57
+
58
+ ```js
59
+ const xs = await sql`
60
+ insert into users (
61
+ name, age
62
+ ) values (
63
+ 'Murray', 68
64
+ )
65
+
66
+ returning *
67
+ `
68
+
69
+ // xs = [{ user_id: 1, name: 'Murray', age: 68 }]
70
+ ```
71
+
72
+ > Please note that queries are first executed when `awaited` – or instantly by using [`.execute()`](#execute).
73
+
74
+ ### Query parameters
75
+
76
+ Parameters are automatically extracted and handled by the database so that SQL injection isn't possible. No special handling is necessary, simply use tagged template literals as usual.
77
+
78
+ ```js
79
+ const name = 'Mur'
80
+ , age = 60
81
+
82
+ const users = await sql`
83
+ select
84
+ name,
85
+ age
86
+ from users
87
+ where
88
+ name like ${ name + '%' }
89
+ and age > ${ age }
90
+ `
91
+ // users = [{ name: 'Murray', age: 68 }]
92
+ ```
93
+
94
+ > Be careful with quotation marks here. Because Postgres infers column types, you do not need to wrap your interpolated parameters in quotes like `'${name}'`. This will cause an error because the tagged template replaces `${name}` with `$1` in the query string, leaving Postgres to do the interpolation. If you wrap that in a string, Postgres will see `'$1'` and interpret it as a string as opposed to a parameter.
95
+
96
+ ### Dynamic column selection
97
+
98
+ ```js
99
+ const columns = ['name', 'age']
100
+
101
+ await sql`
102
+ select
103
+ ${ sql(columns) }
104
+ from users
105
+ `
106
+
107
+ // Which results in:
108
+ select "name", "age" from users
109
+ ```
110
+
111
+ ### Dynamic inserts
112
+
113
+ ```js
114
+ const user = {
115
+ name: 'Murray',
116
+ age: 68
117
+ }
118
+
119
+ await sql`
120
+ insert into users ${
121
+ sql(user, 'name', 'age')
122
+ }
123
+ `
124
+
125
+ // Which results in:
126
+ insert into users ("name", "age") values ($1, $2)
127
+
128
+ // The columns can also be given with an array
129
+ const columns = ['name', 'age']
130
+
131
+ await sql`
132
+ insert into users ${
133
+ sql(user, columns)
134
+ }
135
+ `
136
+ ```
137
+
138
+ **You can omit column names and simply execute `sql(user)` to get all the fields from the object as columns**. Be careful not to allow users to supply columns that you do not want to be inserted.
139
+
140
+ #### Multiple inserts in one query
141
+ If you need to insert multiple rows at the same time it's also much faster to do it with a single `insert`. Simply pass an array of objects to `sql()`.
142
+
143
+ ```js
144
+ const users = [{
145
+ name: 'Murray',
146
+ age: 68,
147
+ garbage: 'ignore'
148
+ },
149
+ {
150
+ name: 'Walter',
151
+ age: 80
152
+ }]
153
+
154
+ await sql`insert into users ${ sql(users, 'name', 'age') }`
155
+
156
+ // Is translated to:
157
+ insert into users ("name", "age") values ($1, $2), ($3, $4)
158
+
159
+ // Here you can also omit column names which will use object keys as columns
160
+ await sql`insert into users ${ sql(users) }`
161
+
162
+ // Which results in:
163
+ insert into users ("name", "age") values ($1, $2), ($3, $4)
164
+ ```
165
+
166
+ ### Dynamic columns in updates
167
+ This is also useful for update queries
168
+ ```js
169
+ const user = {
170
+ id: 1,
171
+ name: 'Murray',
172
+ age: 68
173
+ }
174
+
175
+ await sql`
176
+ update users set ${
177
+ sql(user, 'name', 'age')
178
+ }
179
+ where user_id = ${ user.id }
180
+ `
181
+
182
+ // Which results in:
183
+ update users set "name" = $1, "age" = $2 where user_id = $3
184
+
185
+ // The columns can also be given with an array
186
+ const columns = ['name', 'age']
187
+
188
+ await sql`
189
+ update users set ${
190
+ sql(user, columns)
191
+ }
192
+ where user_id = ${ user.id }
193
+ `
194
+ ```
195
+
196
+ ### Multiple updates in one query
197
+ To create multiple updates in a single query, it is necessary to use arrays instead of objects to ensure that the order of the items correspond with the column names.
198
+ ```js
199
+ const users = [
200
+ [1, 'John', 34],
201
+ [2, 'Jane', 27],
202
+ ]
203
+
204
+ await sql`
205
+ update users set name = update_data.name, age = (update_data.age)::int
206
+ from (values ${sql(users)}) as update_data (id, name, age)
207
+ where users.id = (update_data.id)::int
208
+ returning users.id, users.name, users.age
209
+ `
210
+ ```
211
+
212
+ ### Dynamic values and `where in`
213
+ Value lists can also be created dynamically, making `where in` queries simple too.
214
+ ```js
215
+ const users = await sql`
216
+ select
217
+ *
218
+ from users
219
+ where age in ${ sql([68, 75, 23]) }
220
+ `
221
+ ```
222
+
223
+ or
224
+ ```js
225
+ const [{ a, b, c }] = await sql`
226
+ select
227
+ *
228
+ from (values ${ sql(['a', 'b', 'c']) }) as x(a, b, c)
229
+ `
230
+ ```
231
+
232
+ ## Building queries
233
+
234
+ Postgres.js features a simple dynamic query builder by conditionally appending/omitting query fragments.
235
+ It works by nesting ` sql`` ` fragments within other ` sql`` ` calls or fragments. This allows you to build dynamic queries safely without risking sql injections through usual string concatenation.
236
+
237
+ ### Partial queries
238
+ ```js
239
+ const olderThan = x => sql`and age > ${ x }`
240
+
241
+ const filterAge = true
242
+
243
+ await sql`
244
+ select
245
+ *
246
+ from users
247
+ where name is not null ${
248
+ filterAge
249
+ ? olderThan(50)
250
+ : sql``
251
+ }
252
+ `
253
+ // Which results in:
254
+ select * from users where name is not null
255
+ // Or
256
+ select * from users where name is not null and age > 50
257
+ ```
258
+
259
+ ### Dynamic filters
260
+ ```js
261
+ await sql`
262
+ select
263
+ *
264
+ from users ${
265
+ id
266
+ ? sql`where user_id = ${ id }`
267
+ : sql``
268
+ }
269
+ `
270
+
271
+ // Which results in:
272
+ select * from users
273
+ // Or
274
+ select * from users where user_id = $1
275
+ ```
276
+
277
+ ### Dynamic ordering
278
+
279
+ ```js
280
+ const id = 1
281
+ const order = {
282
+ username: 'asc'
283
+ created_at: 'desc'
284
+ }
285
+ await sql`
286
+ select
287
+ *
288
+ from ticket
289
+ where account = ${ id }
290
+ order by ${
291
+ Object.entries(order).flatMap(([column, order], i) =>
292
+ [i ? sql`,` : sql``, sql`${ sql(column) } ${ order === 'desc' ? sql`desc` : sql`asc` }`]
293
+ )
294
+ }
295
+ `
296
+ ```
297
+
298
+ ### SQL functions
299
+ Using keywords or calling functions dynamically is also possible by using ``` sql`` ``` fragments.
300
+ ```js
301
+ const date = null
302
+
303
+ await sql`
304
+ update users set updated_at = ${ date || sql`now()` }
305
+ `
306
+
307
+ // Which results in:
308
+ update users set updated_at = now()
309
+ ```
310
+
311
+ ### Table names
312
+ Dynamic identifiers like table names and column names is also supported like so:
313
+ ```js
314
+ const table = 'users'
315
+ , column = 'id'
316
+
317
+ await sql`
318
+ select ${ sql(column) } from ${ sql(table) }
319
+ `
320
+
321
+ // Which results in:
322
+ select "id" from "users"
323
+ ```
324
+
325
+ ### Quick primer on interpolation
326
+
327
+ Here's a quick oversight over all the ways to do interpolation in a query template string:
328
+
329
+ | Interpolation syntax | Usage | Example |
330
+ | ------------- | ------------- | ------------- |
331
+ | `${ sql`` }` | for keywords or sql fragments | ``await sql`SELECT * FROM users ${sql`order by age desc` }` `` |
332
+ | `${ sql(string) }` | for identifiers | ``await sql`SELECT * FROM ${sql('table_name')` `` |
333
+ | `${ sql([] or {}, ...) }` | for helpers | ``await sql`INSERT INTO users ${sql({ name: 'Peter'})}` `` |
334
+ | `${ 'somevalue' }` | for values | ``await sql`SELECT * FROM users WHERE age = ${42}` `` |
335
+
336
+ ## Advanced query methods
337
+
338
+ ### Cursors
339
+
340
+ #### ```await sql``.cursor([rows = 1], [fn])```
341
+
342
+ Use cursors if you need to throttle the amount of rows being returned from a query. You can use a cursor either as an [async iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of) or with a callback function. For a callback function new results won't be requested until the promise / async callback function has resolved.
343
+
344
+ ##### callback function
345
+ ```js
346
+ await sql`
347
+ select
348
+ *
349
+ from generate_series(1,4) as x
350
+ `.cursor(async([row]) => {
351
+ // row = { x: 1 }
352
+ await http.request('https://example.com/wat', { row })
353
+ })
354
+ ```
355
+
356
+ ##### for await...of
357
+ ```js
358
+ // for await...of
359
+ const cursor = sql`select * from generate_series(1,4) as x`.cursor()
360
+
361
+ for await (const [row] of cursor) {
362
+ // row = { x: 1 }
363
+ await http.request('https://example.com/wat', { row })
364
+ }
365
+ ```
366
+
367
+ A single row will be returned by default, but you can also request batches by setting the number of rows desired in each batch as the first argument to `.cursor`:
368
+ ```js
369
+ await sql`
370
+ select
371
+ *
372
+ from generate_series(1,1000) as x
373
+ `.cursor(10, async rows => {
374
+ // rows = [{ x: 1 }, { x: 2 }, ... ]
375
+ await Promise.all(rows.map(row =>
376
+ http.request('https://example.com/wat', { row })
377
+ ))
378
+ })
379
+ ```
380
+
381
+ If an error is thrown inside the callback function no more rows will be requested and the outer promise will reject with the thrown error.
382
+
383
+ You can close the cursor early either by calling `break` in the `for await...of` loop, or by returning the token `sql.CLOSE` from the callback function.
384
+
385
+ ```js
386
+ await sql`
387
+ select * from generate_series(1,1000) as x
388
+ `.cursor(row => {
389
+ return Math.random() > 0.9 && sql.CLOSE // or sql.END
390
+ })
391
+ ```
392
+
393
+ ### Instant iteration
394
+
395
+ #### ```await sql``.forEach(fn)```
396
+
397
+ If you want to handle rows returned by a query one by one, you can use `.forEach` which returns a promise that resolves once there are no more rows.
398
+ ```js
399
+ await sql`
400
+ select created_at, name from events
401
+ `.forEach(row => {
402
+ // row = { created_at: '2019-11-22T14:22:00Z', name: 'connected' }
403
+ })
404
+
405
+ // No more rows
406
+ ```
407
+
408
+ ### Query Descriptions
409
+ #### ```await sql``.describe() -> Result[]```
410
+
411
+ Rather than executing a given query, `.describe` will return information utilized in the query process. This information can include the query identifier, column types, etc.
412
+
413
+ This is useful for debugging and analyzing your Postgres queries. Furthermore, **`.describe` will give you access to the final generated query string that would be executed.**
414
+
415
+ ### Rows as Array of Values
416
+ #### ```sql``.values()```
417
+
418
+ Using `.values` will return rows as an array of values for each column, instead of objects.
419
+
420
+ This can be useful to receive identically named columns, or for specific performance/transformation reasons. The column definitions are still included on the result array, plus access to parsers for each column.
421
+
422
+ ### Rows as Raw Array of Buffers
423
+ #### ```sql``.raw()```
424
+
425
+ Using `.raw` will return rows as an array with `Buffer` values for each column, instead of objects.
426
+
427
+ This can be useful for specific performance/transformation reasons. The column definitions are still included on the result array, plus access to parsers for each column.
428
+
429
+ ### Queries in Files
430
+ #### `await sql.file(path, [args], [options]) -> Result[]`
431
+
432
+ Using a file for a query is also supported with optional parameters to use if the file includes `$1, $2, etc`
433
+
434
+ ```js
435
+ const result = await sql.file('query.sql', ['Murray', 68])
436
+ ```
437
+
438
+ ### Multiple statements in one query
439
+ #### ```await sql``.simple()```
440
+
441
+ The postgres wire protocol supports ["simple"](https://www.postgresql.org/docs/current/protocol-flow.html#id-1.10.6.7.4) and ["extended"](https://www.postgresql.org/docs/current/protocol-flow.html#PROTOCOL-FLOW-EXT-QUERY) queries. "simple" queries supports multiple statements, but does not support any dynamic parameters. "extended" queries support parameters but only one statement. To use "simple" queries you can use
442
+ ```sql``.simple()```. That will create it as a simple query.
443
+
444
+ ```js
445
+ await sql`select 1; select 2;`.simple()
446
+ ```
447
+
448
+ ### Copy to/from as Streams
449
+
450
+ Postgres.js supports [`COPY ...`](https://www.postgresql.org/docs/current/sql-copy.html) queries, which are exposed as [Node.js streams](https://nodejs.org/api/stream.html).
451
+
452
+ #### ```await sql`copy ... from stdin`.writable() -> Writable```
453
+
454
+ ```js
455
+ import { pipeline } from 'node:stream/promises'
456
+
457
+ // Stream of users with the default tab delimitated cells and new-line delimitated rows
458
+ const userStream = Readable.from([
459
+ 'Murray\t68\n',
460
+ 'Walter\t80\n'
461
+ ])
462
+
463
+ const query = await sql`copy users (name, age) from stdin`.writable()
464
+ await pipeline(userStream, query);
465
+ ```
466
+
467
+ #### ```await sql`copy ... to stdout`.readable() -> Readable```
468
+
469
+ ##### Using Stream Pipeline
470
+ ```js
471
+ import { pipeline } from 'node:stream/promises'
472
+ import { createWriteStream } from 'node:fs'
473
+
474
+ const readableStream = await sql`copy users (name, age) to stdout`.readable()
475
+ await pipeline(readableStream, createWriteStream('output.tsv'))
476
+ // output.tsv content: `Murray\t68\nWalter\t80\n`
477
+ ```
478
+
479
+ ##### Using `for await...of`
480
+ ```js
481
+ const readableStream = await sql`
482
+ copy (
483
+ select name, age
484
+ from users
485
+ where age = 68
486
+ ) to stdout
487
+ `.readable()
488
+ for await (const chunk of readableStream) {
489
+ // chunk.toString() === `Murray\t68\n`
490
+ }
491
+ ```
492
+
493
+ > **NOTE** This is a low-level API which does not provide any type safety. To make this work, you must match your [`copy query` parameters](https://www.postgresql.org/docs/current/sql-copy.html) correctly to your [Node.js stream read or write](https://nodejs.org/api/stream.html) code. Ensure [Node.js stream backpressure](https://nodejs.org/en/learn/modules/backpressuring-in-streams) is handled correctly to avoid memory exhaustion.
494
+
495
+ A `COPY` holds its connection until it finishes. Postgres.js cannot tell that a simple-protocol query is a `COPY` until the server answers, so it sends nothing behind a simple query whose text contains the word `copy` (`sql.unsafe()` or `sql.file()` without parameters, `.simple()`, `.readable()`, `.writable()`). Queries sent through `sql` meanwhile run on another connection or wait for one. When every connection is running a `COPY` that has not been ended, for example with `max: 1`, queries, `sql.reserve()` and `sql.begin()` through `sql` reject with `COPY_IN_PROGRESS` instead, because only that `COPY` finishing could free a connection. Statements on a `sql.reserve()` or `sql.begin()` handle reject with `COPY_IN_PROGRESS` while its `COPY` runs.
496
+
497
+ ### Canceling Queries in Progress
498
+
499
+ Postgres.js supports [canceling queries in progress](https://www.postgresql.org/docs/current/protocol-flow.html#PROTOCOL-FLOW-CANCELING-REQUESTS). It works by opening a new connection with a protocol level startup message to cancel the current query running on a specific connection. That means there is no guarantee that the query will be canceled, and due to the possible race conditions it might even result in canceling another query. This is fine for long running queries, but in the case of high load and fast queries it might be better to simply ignore results instead of canceling.
500
+
501
+ ```js
502
+ const query = sql`select pg_sleep(100)`.execute()
503
+ setTimeout(() => query.cancel(), 100)
504
+ const result = await query
505
+ ```
506
+
507
+ A cancelled query rejects with code `57014`. A cancel can arrive too late, in which case the query may still complete, or fail with its own error. `query.cancel()` resolves once the cancel request has been sent. A cancelled query you don't await does not cause an unhandled rejection. A query cancelled before it was sent is removed from the queue and rejects with `57014` without contacting the server.
508
+
509
+ The cancel request opens its own connection with the same `ssl`, `sslnegotiation` and `socket` options, bounded by `connect_timeout`. With [several hosts](#multi-host-connections---high-availability-ha) it always goes to the first one, so a query running on another host is not cancelled.
510
+
511
+ ### Execute
512
+
513
+ #### ```await sql``.execute()```
514
+
515
+ The lazy Promise implementation in Postgres.js is what allows it to distinguish [Nested Fragments](#building-queries) from the main outer query. This also means that queries are always executed at the earliest in the following tick. If you have a specific need to execute the query in the same tick, you can call `.execute()`
516
+
517
+ ### Unsafe raw string queries
518
+
519
+ <details>
520
+ <summary>Advanced unsafe use cases</summary>
521
+
522
+ ### `await sql.unsafe(query, [args], [options]) -> Result[]`
523
+
524
+ If you know what you're doing, you can use `unsafe` to pass any string you'd like to postgres. Please note that this can lead to SQL injection if you're not careful.
525
+
526
+ ```js
527
+ sql.unsafe('select ' + danger + ' from users where id = ' + dragons)
528
+ ```
529
+
530
+ By default, `sql.unsafe` assumes the `query` string is sufficiently dynamic that prepared statements do not make sense, and so defaults them to off. If you'd like to re-enable prepared statements, you can pass `{ prepare: true }`.
531
+
532
+ You can also nest `sql.unsafe` within a safe `sql` expression. This is useful if only part of your fraction has unsafe elements.
533
+
534
+ ```js
535
+ const triggerName = 'friend_created'
536
+ const triggerFnName = 'on_friend_created'
537
+ const eventType = 'insert'
538
+ const schema_name = 'app'
539
+ const table_name = 'friends'
540
+
541
+ await sql`
542
+ create or replace trigger ${sql(triggerName)}
543
+ after ${sql.unsafe(eventType)} on ${sql.unsafe(`${schema_name}.${table_name}`)}
544
+ for each row
545
+ execute function ${sql(triggerFnName)}()
546
+ `
547
+
548
+ await sql`
549
+ create role friend_service with login password ${sql.unsafe(`'${password}'`)}
550
+ `
551
+ ```
552
+
553
+ </details>
554
+
555
+ ## Transactions
556
+
557
+ ### BEGIN / COMMIT `await sql.begin([options = ''], fn) -> fn()`
558
+
559
+ Use `sql.begin` to start a new transaction. Postgres.js will reserve a connection for the transaction and supply a scoped `sql` instance for all transaction uses in the callback function. `sql.begin` will resolve with the returned value from the callback function.
560
+
561
+ `BEGIN` is automatically sent with the optional options, such as `'read write'` or `'isolation level serializable'`; characters other than letters and spaces are removed from them. If the callback throws or a query in it fails, `ROLLBACK` is sent and `sql.begin` rejects with that error. If the server answers the `COMMIT` with `ROLLBACK`, for example after a failed query that was not awaited or a caught savepoint failure, `sql.begin` rejects with [`TRANSACTION_ROLLED_BACK`](#transaction_rolled_back) and nothing is committed.
562
+
563
+ The scoped `sql` only works inside the callback. Statements on it after the transaction has finished, including statements sent while its `COMMIT` or `ROLLBACK` is in flight, reject with `CONNECTION_ENDED`, and statements after its connection closed reject with `CONNECTION_CLOSED`.
564
+
565
+ ```js
566
+ const [user, account] = await sql.begin(async sql => {
567
+ const [user] = await sql`
568
+ insert into users (
569
+ name
570
+ ) values (
571
+ 'Murray'
572
+ )
573
+ returning *
574
+ `
575
+
576
+ const [account] = await sql`
577
+ insert into accounts (
578
+ user_id
579
+ ) values (
580
+ ${ user.user_id }
581
+ )
582
+ returning *
583
+ `
584
+
585
+ return [user, account]
586
+ })
587
+ ```
588
+
589
+ Do note that you can often achieve the same result using [`WITH` queries (Common Table Expressions)](https://www.postgresql.org/docs/current/queries-with.html) instead of using transactions.
590
+
591
+ It's also possible to pipeline the requests in a transaction if needed by returning an array with queries from the callback function like this:
592
+
593
+ ```js
594
+ const result = await sql.begin(sql => [
595
+ sql`update ...`,
596
+ sql`update ...`,
597
+ sql`insert ...`
598
+ ])
599
+ ```
600
+
601
+ ### SAVEPOINT `await sql.savepoint([name], fn) -> fn()`
602
+
603
+ ```js
604
+ sql.begin('read write', async sql => {
605
+ const [user] = await sql`
606
+ insert into users (
607
+ name
608
+ ) values (
609
+ 'Murray'
610
+ )
611
+ `
612
+
613
+ const [account] = (await sql.savepoint(sql =>
614
+ sql`
615
+ insert into accounts (
616
+ user_id
617
+ ) values (
618
+ ${ user.user_id }
619
+ )
620
+ `
621
+ ).catch(err => {
622
+ // Account could not be created. ROLLBACK SAVEPOINT is called because we caught the rejection.
623
+ })) || []
624
+
625
+ return [user, account]
626
+ })
627
+ .then(([user, account]) => {
628
+ // great success - COMMIT succeeded
629
+ })
630
+ .catch(() => {
631
+ // not so good - ROLLBACK was called
632
+ })
633
+ ```
634
+
635
+
636
+ ### PREPARE TRANSACTION `sql.prepare(name)`
637
+
638
+ Indicates that the transactions should be prepared using the [`PREPARE TRANSACTION [NAME]`](https://www.postgresql.org/docs/current/sql-prepare-transaction.html) statement
639
+ instead of being committed.
640
+
641
+ The name must be a non-empty string without NUL characters; invalid names throw `INVALID_TRANSACTION_NAME`. Quotes and backslashes in valid names are preserved.
642
+
643
+ ```js
644
+ sql.begin('read write', async sql => {
645
+ const [user] = await sql`
646
+ insert into users (
647
+ name
648
+ ) values (
649
+ 'Murray'
650
+ )
651
+ `
652
+
653
+ await sql.prepare('tx1')
654
+ })
655
+ ```
656
+
657
+ ## Data Transformation
658
+
659
+ Postgres.js allows for transformation of the data passed to or returned from a query by using the `transform` option.
660
+
661
+ Built in transformation functions are:
662
+
663
+ * For camelCase - `postgres.camel`, `postgres.toCamel`, `postgres.fromCamel`
664
+ * For PascalCase - `postgres.pascal`, `postgres.toPascal`, `postgres.fromPascal`
665
+ * For Kebab-Case - `postgres.kebab`, `postgres.toKebab`, `postgres.fromKebab`
666
+
667
+ These built in transformations will only convert to/from snake_case. For example, using `{ transform: postgres.toCamel }` will convert the column names to camelCase only if the column names are in snake_case to begin with. `{ transform: postgres.fromCamel }` will convert camelCase only to snake_case.
668
+
669
+ By default, using `postgres.camel`, `postgres.pascal` and `postgres.kebab` will perform a two-way transformation - both the data passed to the query and the data returned by the query will be transformed:
670
+
671
+ ```js
672
+ // Transform the column names to and from camel case
673
+ const sql = postgres({ transform: postgres.camel })
674
+
675
+ await sql`CREATE TABLE IF NOT EXISTS camel_case (a_test INTEGER, b_test TEXT)`
676
+ await sql`INSERT INTO camel_case ${ sql([{ aTest: 1, bTest: 1 }]) }`
677
+ const data = await sql`SELECT ${ sql('aTest', 'bTest') } FROM camel_case`
678
+
679
+ console.log(data) // [ { aTest: 1, bTest: '1' } ]
680
+ ```
681
+
682
+ To only perform half of the transformation (eg. only the transformation **to** or **from** camel case), use the other transformation functions:
683
+
684
+ ```js
685
+ // Transform the column names only to camel case
686
+ // (for the results that are returned from the query)
687
+ postgres({ transform: postgres.toCamel })
688
+
689
+ await sql`CREATE TABLE IF NOT EXISTS camel_case (a_test INTEGER)`
690
+ await sql`INSERT INTO camel_case ${ sql([{ a_test: 1 }]) }`
691
+ const data = await sql`SELECT a_test FROM camel_case`
692
+
693
+ console.log(data) // [ { aTest: 1 } ]
694
+ ```
695
+
696
+ ```js
697
+ // Transform the column names only from camel case
698
+ // (for interpolated inserts, updates, and selects)
699
+ const sql = postgres({ transform: postgres.fromCamel })
700
+
701
+ await sql`CREATE TABLE IF NOT EXISTS camel_case (a_test INTEGER)`
702
+ await sql`INSERT INTO camel_case ${ sql([{ aTest: 1 }]) }`
703
+ const data = await sql`SELECT ${ sql('aTest') } FROM camel_case`
704
+
705
+ console.log(data) // [ { a_test: 1 } ]
706
+ ```
707
+
708
+ > Note that Postgres.js does not rewrite the static parts of the tagged template strings. So to transform column names in your queries, the `sql()` helper must be used - eg. `${ sql('columnName') }` as in the examples above.
709
+
710
+ ### Transform `undefined` Values
711
+
712
+ By default, Postgres.js will throw the error `UNDEFINED_VALUE: Undefined values are not allowed` when undefined values are passed
713
+
714
+ ```js
715
+ // Transform the column names to and from camel case
716
+ const sql = postgres({
717
+ transform: {
718
+ undefined: null
719
+ }
720
+ })
721
+
722
+ await sql`CREATE TABLE IF NOT EXISTS transform_undefined (a_test INTEGER)`
723
+ await sql`INSERT INTO transform_undefined ${ sql([{ a_test: undefined }]) }`
724
+ const data = await sql`SELECT a_test FROM transform_undefined`
725
+
726
+ console.log(data) // [ { a_test: null } ]
727
+ ```
728
+
729
+ To combine with the built in transform functions, spread the transform in the `transform` object:
730
+
731
+ ```js
732
+ // Transform the column names to and from camel case
733
+ const sql = postgres({
734
+ transform: {
735
+ ...postgres.camel,
736
+ undefined: null
737
+ }
738
+ })
739
+
740
+ await sql`CREATE TABLE IF NOT EXISTS transform_undefined (a_test INTEGER)`
741
+ await sql`INSERT INTO transform_undefined ${ sql([{ aTest: undefined }]) }`
742
+ const data = await sql`SELECT ${ sql('aTest') } FROM transform_undefined`
743
+
744
+ console.log(data) // [ { aTest: null } ]
745
+ ```
746
+
747
+ ### Custom Transform Functions
748
+
749
+ To specify your own transformation functions, you can use the `column`, `value` and `row` options inside of `transform`, each an object possibly including `to` and `from` keys:
750
+
751
+ * `to`: The function to transform the outgoing query column name to, i.e `SELECT ${ sql('aName') }` to `SELECT a_name` when using `postgres.toCamel`.
752
+ * `from`: The function to transform the incoming query result column name to, see example below.
753
+
754
+ > Both parameters are optional, if not provided, the default transformation function will be used.
755
+
756
+ The built-in transforms in [`src/types.js`](../src/types.js) (`toCamel`, `fromCamel` and the others) show the expected shape.
757
+
758
+ ```js
759
+ function transformColumnToDatabase() { /* ... */ }
760
+ function transformColumnFromDatabase() { /* ... */ }
761
+
762
+ const sql = postgres({
763
+ transform: {
764
+ column: {
765
+ to: transformColumnToDatabase,
766
+ from: transformColumnFromDatabase,
767
+ },
768
+ value: { /* ... */ },
769
+ row: { /* ... */ }
770
+ }
771
+ })
772
+ ```
773
+
774
+ ## Listen & notify
775
+
776
+ When you call `.listen`, a dedicated connection will be created to ensure that you receive notifications instantly. This connection will be used for any further calls to `.listen`. The connection will automatically reconnect according to a backoff reconnection pattern to not overload the database server.
777
+
778
+ ### Listen `await sql.listen(channel, onnotify, [onlisten]) -> { state, unlisten }`
779
+ `.listen` takes the channel name, a function to handle each notify, and an optional function to run every time listen is registered and ready (happens on initial connect and reconnects). It returns a promise which resolves once the `LISTEN` query to Postgres completes, or if there is already a listener active. If either function throws, the error is rethrown as an uncaught exception, and the other listeners and the returned promise are not affected.
780
+
781
+ ```js
782
+ await sql.listen('news', payload => {
783
+ const json = JSON.parse(payload)
784
+ console.log(json.this) // logs 'is'
785
+ })
786
+ ```
787
+
788
+ The optional `onlisten` method is great to use for a very simply queue mechanism:
789
+
790
+ ```js
791
+ await sql.listen(
792
+ 'jobs',
793
+ (x) => run(JSON.parse(x)),
794
+ ( ) => sql`select unfinished_jobs()`.forEach(run)
795
+ )
796
+
797
+ function run(job) {
798
+ // And here you do the work you please
799
+ }
800
+ ```
801
+
802
+ `unlisten()` removes this listener. When it was the channel's last listener, `UNLISTEN` is sent.
803
+
804
+ ```js
805
+ const { unlisten } = await sql.listen('news', payload => console.log(payload))
806
+ await unlisten()
807
+ ```
808
+ ### Notify `await sql.notify(channel, payload) -> Result[]`
809
+ Notify can be done as usual in SQL, or by using the `sql.notify` method.
810
+ ```js
811
+ sql.notify('news', JSON.stringify({ no: 'this', is: 'news' }))
812
+ ```
813
+
814
+ ## Realtime subscribe
815
+
816
+ Postgres.js implements the logical replication protocol of PostgreSQL to support subscription to real-time updates of `insert`, `update` and `delete` operations.
817
+
818
+ > **NOTE** To make this work you must [create the proper publications in your database](https://www.postgresql.org/docs/current/sql-createpublication.html), enable logical replication by setting `wal_level = logical` in `postgresql.conf` and connect using either a replication or superuser.
819
+
820
+ ### Quick start
821
+
822
+ #### Create a publication (eg. in migration)
823
+ ```sql
824
+ CREATE PUBLICATION alltables FOR ALL TABLES
825
+ ```
826
+
827
+ #### Subscribe to updates
828
+ ```js
829
+ const sql = postgres({ publications: 'alltables' }) // 'alltables' is the default
830
+
831
+ const { unsubscribe } = await sql.subscribe(
832
+ 'insert:events',
833
+ (row, { command, relation, key, old }) => {
834
+ // Callback function for each row change
835
+ // tell about new event row over eg. websockets or do something else
836
+ },
837
+ () => {
838
+ // Callback on initial connect and potential reconnects
839
+ },
840
+ (error) => {
841
+ // Callback on connection errors and changes that could not be decoded
842
+ }
843
+ )
844
+ ```
845
+
846
+ `unsubscribe()` removes this subscription. The result also carries `state` and `sql`, the replication connection's backend state and client. While subscribed, the client sends the server a status update every second, so a change reaches you within about a second even when the server misses its wake-up for a commit.
847
+
848
+ If any of these callbacks throws, the error is rethrown as an uncaught exception, and other subscribers and the replication stream are not affected.
849
+
850
+ `onerror` is called in two cases, and stays registered across reconnects until `unsubscribe()`:
851
+
852
+ - **The replication connection fails.** The error is also logged with `console.error`. The subscription reconnects on a new replication slot and calls `onsubscribe` again; changes committed while it was disconnected are not delivered. A failed reconnect is retried with [backoff](#all-postgres-options), logged and passed to `onerror`, and never ends the process.
853
+ - **A change cannot be decoded,** because a [transform](#data-transformation) or a custom type parser threw. That change is skipped and later changes carry on. The error goes only to the subscriptions that would have received the change, matched by operation and table; a subscription filtered by key gets every skipped change of its table, because the key is read from the decoded row. If a column name transform throws, every change of that table is skipped and reported until the server describes the table again, for example after `ALTER TABLE`. If one of the matching subscriptions has no `onerror`, the error is rethrown once as an uncaught exception, which ends the process under Node's default handling.
854
+
855
+ ### Subscribe pattern
856
+
857
+ You can subscribe to specific operations, tables, or even rows with primary keys.
858
+
859
+ #### `operation` `:` `schema` `.` `table` `=` `primary_key`
860
+
861
+ **`operation`** is one of ``` * | insert | update | delete ``` and defaults to `*`
862
+
863
+ **`schema`** defaults to `public`
864
+
865
+ **`table`** is a specific table name and defaults to `*`
866
+
867
+ **`primary_key`** can be used to only subscribe to specific rows
868
+
869
+ ### Examples
870
+
871
+ ```js
872
+ sql.subscribe('*', () => /* everything */ )
873
+ sql.subscribe('insert', () => /* all inserts */ )
874
+ sql.subscribe('*:users', () => /* all operations on the public.users table */ )
875
+ sql.subscribe('delete:users', () => /* all deletes on the public.users table */ )
876
+ sql.subscribe('update:users=1', () => /* all updates on the users row with a primary key = 1 */ )
877
+ ```
878
+
879
+ ## Numbers, bigint, numeric
880
+
881
+ `Number` in javascript is only able to represent 2<sup>53</sup>-1 safely which means that types in PostgreSQLs like `bigint` and `numeric` won't fit into `Number`.
882
+
883
+ JavaScript's [`BigInt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) can match the PostgreSQL type `bigint` which is returned for eg. `count(*)`. Unfortunately, it doesn't work with `JSON.stringify` out of the box, so Postgres.js will return it as a string.
884
+
885
+ If you want to use `BigInt` you can add this custom type:
886
+
887
+ ```js
888
+ const sql = postgres({
889
+ types: {
890
+ bigint: postgres.BigInt
891
+ }
892
+ })
893
+ ```
894
+
895
+ There is currently no guaranteed way to handle `numeric` / `decimal` types in native Javascript. **These [and similar] types will be returned as a `string`**. The best way in this case is to use [custom types](#custom-types).
896
+
897
+ ## Parameter types
898
+
899
+ A `$1` placeholder has a type that PostgreSQL infers from the SQL around it (the column it is compared to or inserted into, a function argument, a cast). Postgres.js has to turn each JavaScript value into text for that type, and `parameter_types` chooses how.
900
+
901
+ Some values carry a type Postgres.js can tell from the JavaScript value: `Date`, `Buffer` / `Uint8Array`, booleans, `bigint`, and anything wrapped in `sql.typed(value, oid)`, `sql.types.*`, `sql.json` or `sql.array` with elements. They are serialized for that type and sent in a single round trip, in every mode. Everything else (strings, numbers, plain objects, `sql.typed(value)` without an OID, an empty `sql.array([])`, arrays) has no such type. `null` is always SQL `NULL`.
902
+
903
+ ### `parameter_types: 'server'` (default)
904
+
905
+ For a value whose type Postgres.js cannot tell, it first asks PostgreSQL for the type of the placeholder, which costs an extra round trip on every query with `prepare: false` and the first time each connection runs that SQL with `prepare: true`, and then serializes the value for that type. This has consequences worth knowing:
906
+
907
+ - a string sent to a `json` or `jsonb` placeholder is sent as JSON, so `'{"a":1}'` is stored as a JSON string, not an object
908
+ - a string or number sent to a `date`, `timestamp` or `timestamptz` placeholder goes through `new Date(x).toISOString()`, where a date-only string such as `'2020-01-02'` is read as UTC and a date-and-time string without an offset such as `'2020-01-02T10:00'` is read in the Node.js process time zone (`TZ`)
909
+ - anything other than `true` sent to a `boolean` placeholder is stored as `false`, including the strings `'true'` and `'t'` and the number `1`
910
+ - a string sent to a `bytea` placeholder is sent as hex of its UTF-8 bytes
911
+ - a custom type registered in `types` with a `from` list runs its `serialize` function
912
+
913
+ ### `parameter_types: 'client'`
914
+
915
+ The JavaScript value decides how it is serialized and PostgreSQL parses the text, so a query with values is one round trip:
916
+
917
+ - a string is sent unchanged as text
918
+ - a number is sent as its JavaScript text (`'' + n`)
919
+ - a plain object (prototype `Object.prototype` or `null`) is sent as `JSON.stringify(x)`
920
+ - any other object (Decimal, Luxon, moment, URL, class instances) is sent as `'' + x`
921
+ - `null` is SQL `NULL`; `undefined` is handled as before
922
+ - a value with a type Postgres.js can tell from the JavaScript value is serialized for that type, as with `'server'`
923
+ - an array whose elements have no such type still makes Postgres.js ask PostgreSQL for the placeholder's type first, because only PostgreSQL knows whether the placeholder is an array, JSON or a custom type; that query takes the extra round trip
924
+
925
+ Measured in production on one app with `prepare: false` behind the Supabase pooler, a day on each mode: against `'warn'`, which takes the same two round trips as `'server'`, the median query went from 5.3 to 3.1 ms and the p95 from 16.8 to 13.5 ms, and the p95 of a request's total query time from 476 to 318 ms. The p99 was unchanged, because the app's slowest statements spend their time in the server, not the round trip.
926
+
927
+ What this changes compared to `'server'`:
928
+
929
+ | Value | Type PostgreSQL infers for the placeholder | `'server'` | `'client'` |
930
+ | --- | --- | --- | --- |
931
+ | string | json, jsonb | sent as JSON: stores a JSON string | parsed as JSON; text that is not JSON is rejected |
932
+ | string | boolean | always `false` | PostgreSQL boolean input (`'t'`, `'yes'`, `'on'`, `'1'` are true); invalid text is rejected |
933
+ | string | date, timestamp, timestamptz | `new Date(s).toISOString()`: date-only strings are read as UTC, date-and-time strings without an offset in the Node.js process time zone (`TZ`) | parsed by PostgreSQL in the PostgreSQL session's `TimeZone` setting; `date` and `timestamp` ignore an explicit offset |
934
+ | string | bytea | hex of the UTF-8 bytes | bytea text input; differs only for strings containing backslashes |
935
+ | string, number | a custom type registered in `types` with a `from` list | the type's `serialize` | sent unchanged as text |
936
+ | number | json, jsonb | `JSON.stringify` (`NaN` and `Infinity` become `null`) | the number's text (`NaN` and `Infinity` are rejected) |
937
+ | number | boolean | `false` | `1` is true, `0` is false, anything else is rejected |
938
+ | number | date, timestamp, timestamptz | `new Date(ms)` | rejected, except `Infinity`; a 6- or 8-digit number is read as a `YYMMDD` or `YYYYMMDD` date |
939
+ | plain object | json, jsonb | `JSON.stringify` or your json `serialize` | `JSON.stringify` |
940
+ | plain object | text | `[object Object]` | JSON text |
941
+ | plain object | a custom type registered in `types` with a `from` list | the type's `serialize` | JSON text, normally rejected |
942
+ | class instance | json, jsonb | `JSON.stringify`, so `toJSON` applies | `'' + x` |
943
+ | class instance | date, timestamp, timestamptz | `new Date(x)` | `'' + x`, normally rejected |
944
+
945
+ `time`, `timetz` and `interval` placeholders have no serializer in either mode: strings and numbers are sent unchanged as text.
946
+
947
+ In practice:
948
+
949
+ - pass `new Date(ms)` for epoch numbers, and set `connection: { timezone }` so date strings are read in the time zone you expect
950
+ - pass `sql.json(s)` for a JSON string value, and `sql.types.name(v)` or `sql.typed(v, oid)` for a custom type; a custom type's `serialize` also runs for a whole array bound to that type, never for a plain value
951
+ - `NaN`, `Infinity` and `-0` are sent as `NaN`, `Infinity` and `0`, and PostgreSQL's input rules for the placeholder's type decide
952
+
953
+ Run `'warn'` first to see which of your queries are affected.
954
+
955
+ **Planned for 5.0:** `'client'` becomes the default. Pass `parameter_types: 'server'` to keep the 4.x behaviour.
956
+
957
+ ### `parameter_types: 'warn'`
958
+
959
+ `'warn'` behaves exactly like `'server'`, and also reports every query in which a value would be sent differently by `'client'`. The report goes to `ontypemismatch`, or to `console.warn` when it is not set:
960
+
961
+ ```js
962
+ const sql = postgres({
963
+ parameter_types: 'warn',
964
+ ontypemismatch: ({ query, parameters }) => {
965
+ // parameters: [{ position: 2, oid: 3802, typeof: 'string' }]
966
+ // position is the $n number, oid the type PostgreSQL inferred for the placeholder
967
+ }
968
+ })
969
+ ```
970
+
971
+ With `debug: true` each entry also carries `serverText` and `clientText`, the two texts that were compared; `clientText` is the error when the `'client'` mode would throw. A query is reported on every execution that has a difference; sample in `ontypemismatch` if that is too much. `'warn'` serializes each untyped value twice and compares the strings. The option can also be set with `?parameter_types=warn` in the connection URL or `PGPARAMETER_TYPES`.
972
+
973
+ `'warn'` compares the serialized text, not the stored value, so a report does not always mean the stored value would change.
974
+
975
+ These reported cases store the same value under both modes:
976
+
977
+ - `0`, `'0'`, `'false'`, `'no'` and `'off'` sent to a `boolean` placeholder (the texts differ, both store `false`)
978
+ - a date string with an explicit offset sent to a `timestamptz` placeholder, as long as it has no more than millisecond precision (`toISOString()` truncates microseconds, so a string with microseconds stores a different value under `'server'`)
979
+ - a string without backslashes sent to a `bytea` placeholder
980
+
981
+ These reported cases store a different value, or are rejected, under `'client'`:
982
+
983
+ - `1`, `'t'`, `'true'`, `'yes'`, `'on'` and `'1'` sent to a `boolean` placeholder (stored `false` today, `true` under `'client'`)
984
+ - a date string with an explicit offset sent to a `timestamp` or `date` placeholder (`'server'` converts to UTC first, `'client'` drops the offset)
985
+ - a string sent to a `json` or `jsonb` placeholder, a plain object sent to a `text` placeholder, and a number sent to a date, timestamp or boolean placeholder
986
+ - a string or number sent to a custom type registered in `types` with a `from` list, which skips its `serialize`
987
+
988
+ Date strings without an explicit offset:
989
+
990
+ | String | Placeholder | Stored the same under both modes when |
991
+ | --- | --- | --- |
992
+ | date and time, such as `'2020-01-02T10:00'` | `timestamptz` | the Node.js process time zone and the PostgreSQL session's `TimeZone` setting match |
993
+ | date only, such as `'2020-01-02'` | `timestamptz` | the PostgreSQL session's `TimeZone` setting is UTC |
994
+ | date and time | `timestamp` or `date` | the Node.js process runs in UTC (`'server'` stores the UTC wall time, `'client'` stores the text as written) |
995
+
996
+ ## Result Array
997
+
998
+ The `Result` Array returned from queries is a custom array allowing for easy destructuring or passing on directly to JSON.stringify or general Array usage. It includes the following properties.
999
+
1000
+ ### .count
1001
+
1002
+ The `count` property is the number of affected rows returned by the database. This is useful for insert, update and delete operations to know the number of rows since .length will be 0 in these cases if not using `RETURNING ...`.
1003
+
1004
+ ### .command
1005
+
1006
+ The `command` run by the query - eg. one of `SELECT`, `UPDATE`, `INSERT`, `DELETE`
1007
+
1008
+ ### .columns
1009
+
1010
+ The `columns` returned by the query useful to determine types, or map to the result values when using `.values()`
1011
+
1012
+ ```js
1013
+ {
1014
+ name : String, // Column name,
1015
+ type : oid, // PostgreSQL oid column type
1016
+ parser: Function // The function used by Postgres.js for parsing
1017
+ }
1018
+ ```
1019
+
1020
+ ### .statement
1021
+
1022
+ The `statement` contains information about the statement implicitly created by Postgres.js.
1023
+
1024
+ ```js
1025
+ {
1026
+ name : String, // The auto generated statement name
1027
+ string : String, // The actual query string executed
1028
+ types : [oid], // An array of oid expected as input parameters
1029
+ columns : [Column] // Array of columns - same as Result.columns
1030
+ }
1031
+ ```
1032
+
1033
+ ### .state
1034
+
1035
+ This is the state `{ pid, secret }` of the connection that executed the query.
1036
+
1037
+ ## Connection details
1038
+
1039
+ ### All Postgres options
1040
+
1041
+ ```js
1042
+ const sql = postgres('postgres://username:password@host:port/database', {
1043
+ host : 'localhost', // Postgres ip address[es] or domain name[s] (alias hostname)
1044
+ port : 5432, // Postgres server port[s]
1045
+ path : '', // unix socket path (usually '/tmp')
1046
+ database : user, // Name of database to connect to (alias db), defaults to the user name
1047
+ username : '', // Username of database user (alias user), defaults to the OS user
1048
+ password : '', // Password of database user (alias pass), or a function, see Dynamic passwords
1049
+ ssl : false, // true, 'require', 'allow', 'prefer', 'verify-full' or tls.connect options
1050
+ sslnegotiation : null, // 'direct' for direct TLS, or 'postgres'
1051
+ max : 10, // Max number of connections, 3 on Cloudflare Workers
1052
+ max_lifetime : random, // Max lifetime in seconds, 30 to 60 minutes by default, see Connection timeout
1053
+ idle_timeout : null, // Idle connection timeout in seconds, off by default
1054
+ connect_timeout : 30, // Connect timeout in seconds, see Connection timeout
1055
+ backoff : fn, // Seconds to wait before a reconnect attempt, see Connection timeout
1056
+ keep_alive : 60, // TCP keepalive delay in seconds, false to disable
1057
+ max_pipeline : 100, // Max queries pipelined on one connection, 0 to disable pipelining
1058
+ prepare : true, // Automatic creation of prepared statements (no_prepare: true disables it)
1059
+ fetch_types : true, // Fetches array types when each connection starts, see Auto fetching of array types
1060
+ parameter_types : 'server', // 'client' or 'warn', see Parameter types
1061
+ types : {}, // Custom types by name, see Custom Types
1062
+ target_session_attrs : null, // Which kind of server to connect to, see Multi-host connections
1063
+ publications : 'alltables', // Publication used by sql.subscribe()
1064
+ socket : fn, // fn returning custom socket to use, see Custom socket
1065
+ debug : false, // true makes query, parameters and types enumerable on errors,
1066
+ // or fn called with (connection, query, parameters, types)
1067
+ onnotice : fn, // (notice), default console.log, false to silence NOTICE
1068
+ onparameter : fn, // (key, value) when a server parameter changes
1069
+ onnotify : fn, // (channel, payload) for every notification on a pool connection
1070
+ onclose : fn, // (connId) when a connection closes
1071
+ onidle : fn, // (connId) when a connection returns to the pool idle
1072
+ ontypemismatch : fn, // Called by parameter_types: 'warn', default console.warn
1073
+ transform : {
1074
+ undefined : undefined, // Transforms undefined values (eg. to null)
1075
+ column : fn, // Transforms incoming column names
1076
+ value : fn, // Transforms incoming row values
1077
+ row : fn // Transforms entire rows
1078
+ },
1079
+ connection : {
1080
+ application_name : 'postgres.js', // Default application_name
1081
+ ... // Other connection parameters, see https://www.postgresql.org/docs/current/runtime-config-client.html
1082
+ }
1083
+ })
1084
+ ```
1085
+
1086
+ The `onnotice`, `onparameter`, `ontypemismatch`, `onnotify`, `onclose`, `onidle`, `backoff` and `debug` callbacks passed in the options are called synchronously from inside the driver. If one throws, the error is rethrown as an uncaught exception and the connection and its queries are not affected; under Node's default handling that ends the process. A `backoff` that throws falls back to the default delay. `onidle` can also be set after creation through `sql.options.onidle`, and is not called for the connections of `sql.listen()` and `sql.subscribe()`.
1087
+
1088
+ ### Dynamic passwords
1089
+
1090
+ When clients need to use alternative authentication schemes such as access tokens or connections to databases with rotating passwords, provide either a synchronous or asynchronous function that will resolve the dynamic password value at connection time.
1091
+
1092
+ ```js
1093
+ const sql = postgres(url, {
1094
+ // Other connection config
1095
+ ...
1096
+ // Password function for the database user
1097
+ password : async () => await signer.getAuthToken(),
1098
+ })
1099
+ ```
1100
+
1101
+ ### SSL
1102
+
1103
+ Although [vulnerable to MITM attacks](https://security.stackexchange.com/a/229297/174913), a common configuration for the `ssl` option for some cloud providers is to set `rejectUnauthorized` to `false` (if `NODE_ENV` is `production`):
1104
+
1105
+ ```js
1106
+ const sql =
1107
+ process.env.NODE_ENV === 'production'
1108
+ ? // "Unless you're using a Private or Shield Heroku Postgres database, Heroku Postgres does not currently support verifiable certificates"
1109
+ // https://help.heroku.com/3DELT3RK/why-can-t-my-third-party-utility-connect-to-heroku-postgres-with-ssl
1110
+ postgres({ ssl: { rejectUnauthorized: false } })
1111
+ : postgres()
1112
+ ```
1113
+
1114
+ `ssl: 'require'`, `'allow'` and `'prefer'` encrypt without verifying the certificate. Only `'prefer'` falls back to an unencrypted connection when the server refuses SSL; the others fail with [`SSL_NOT_SUPPORTED`](#ssl_not_supported). `true`, `'verify-full'` and an options object verify the certificate as `tls.connect` does. `sslnegotiation: 'direct'` starts TLS immediately instead of asking the server first, which PostgreSQL 17 and later accept.
1115
+
1116
+ For more information regarding `ssl`, check out the [Node.js documentation for tls](https://nodejs.org/api/tls.html#tlsconnectoptions-callback).
1117
+
1118
+
1119
+ ### Multi-host connections - High Availability (HA)
1120
+
1121
+ Multiple connection strings can be passed to `postgres()` in the form of `postgres('postgres://localhost:5432,localhost:5433', ...)`. This works the same as the `psql` command. Read more at [multiple host URIs](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-MULTIPLE-HOSTS).
1122
+
1123
+ Connections will be attempted in order of the specified hosts/ports. On a successful connection, all retries will be reset. This ensures that hosts can come up and down seamlessly.
1124
+
1125
+ `target_session_attrs` (or `PGTARGETSESSIONATTRS`) picks which kind of server to connect to. The values and their meaning are libpq's:
1126
+
1127
+ | Value | Connects to |
1128
+ |---|---|
1129
+ | `null` (default) | any server |
1130
+ | `'read-write'` | a server that accepts writes: not a hot standby, and `default_transaction_read_only` off |
1131
+ | `'primary'` | a server that is not a hot standby, even if `default_transaction_read_only` is on |
1132
+ | `'read-only'` | a hot standby, or a server with `default_transaction_read_only` on |
1133
+ | `'standby'` | a hot standby |
1134
+ | `'prefer-standby'` | a hot standby if any host is one, otherwise any server |
1135
+
1136
+ During a failover or an upgrade, `'read-write'` and `'primary'` wait for the promoted server instead of connecting to a standby whose writes would fail. Read traffic that should keep using standbys during the switch belongs on `'prefer-standby'` or no `target_session_attrs` at all.
1137
+
1138
+ With several hosts, a host that answers but is the wrong kind is skipped and the next one is tried at once; if every host answers and none matches, the connection fails immediately with [`TARGET_SESSION_ATTRS`](#target_session_attrs). With a single host, or when some host fails to connect, it keeps retrying, bounded by `connect_timeout` per host, because a failover may be in progress. With `'prefer-standby'`, the search for a standby starts again after each backoff round.
1139
+
1140
+ ### The Connection Pool
1141
+
1142
+ Connections are created lazily once a query is created. This means that simply doing const `sql = postgres(...)` won't have any effect other than instantiating a new `sql` instance.
1143
+
1144
+ > No connection will be made until a query is made.
1145
+
1146
+ For example:
1147
+
1148
+ ```js
1149
+ const sql = postgres() // no connections are opened
1150
+
1151
+ await sql`...` // one connection is now opened
1152
+ await sql`...` // previous opened connection is reused
1153
+
1154
+ // two connections are opened now
1155
+ await Promise.all([
1156
+ sql`...`,
1157
+ sql`...`
1158
+ ])
1159
+ ```
1160
+
1161
+ > When there are high amount of concurrent queries, Postgres.js will open as many connections as needed up until `max` number of connections is reached. By default `max` is 10, and 3 on Cloudflare Workers. This can be changed by setting `max` in the `postgres()` call. Example - `postgres('connectionURL', { max: 20 })`.
1162
+
1163
+ This means that we get a much simpler story for error handling and reconnections. Queries will be sent over the wire immediately on the next available connection in the pool. Connections are automatically taken out of the pool if you start a transaction using `sql.begin()`, and automatically returned to the pool once your transaction is done.
1164
+
1165
+ Any query which was already sent over the wire will be rejected if the connection is lost. It'll automatically defer to the error handling you have for that query, and since connections are lazy it'll automatically try to reconnect the next time a query is made. The benefit of this is no weird generic "onerror" handler that tries to get things back to normal, and also simpler application code since you don't have to handle errors out of context.
1166
+
1167
+ There are no guarantees about queries executing in order unless using a transaction with `sql.begin()` or setting `max: 1`. Of course doing a series of queries, one awaiting the other will work as expected, but that's just due to the nature of js async/promise handling, so it's not necessary for this library to be concerned with ordering.
1168
+
1169
+ Since this library automatically creates prepared statements, connections have a default [`max_lifetime`](#connection-timeout) of 30 to 60 minutes, so that prepared statements do not bloat the server's memory.
1170
+
1171
+ The states a connection and a reserved or transaction handle move through, and what each state guarantees, are described in [lifecycle.md](lifecycle.md).
1172
+
1173
+ ### Pool stats
1174
+
1175
+ `sql.stats()` returns a snapshot of the pool as a plain object, ready to log, serialise from a health endpoint or map to metrics gauges:
1176
+
1177
+ ```js
1178
+ sql.stats()
1179
+ // { max: 10, totalCount: 7, idleCount: 2, waitingCount: 3,
1180
+ // activeCount: 4, availableCount: 5,
1181
+ // busyCount: 3, reservedCount: 1, connectingCount: 1, closingCount: 0,
1182
+ // executingCount: 4, listenCount: 1, subscribeCount: 0 }
1183
+ ```
1184
+
1185
+ | Field | Meaning |
1186
+ |---|---|
1187
+ | `max` | The `max` option |
1188
+ | `totalCount` | Connections that exist: connecting, idle or in use |
1189
+ | `idleCount` | Connections with a live session that are not in use. A connection released while its reserved handle still has queries in flight is idle with `executingCount` above 0 |
1190
+ | `waitingCount` | Issued queries and `reserve()` or `begin()` calls that are not running yet: those in the pool queue, those held by a connection that is still opening, those pipelined behind a connection's running query, and those a reserved handle or transaction has queued behind its own connection |
1191
+ | `activeCount` | `busyCount + reservedCount`, connections in use |
1192
+ | `availableCount` | `idleCount` plus the slots the pool can still open (`max - totalCount - closingCount`): connections a query can get without waiting behind other work |
1193
+ | `busyCount` | Pool connections running queries, including connections at the pipeline limit |
1194
+ | `reservedCount` | Connections held by `reserve()` or `begin()` |
1195
+ | `connectingCount` | Connections opening a session |
1196
+ | `closingCount` | Connections draining or closing. They are not in `totalCount`, but still hold a pool slot until closed |
1197
+ | `executingCount` | Queries the server is running right now, at most one per connection, on pool and reserved connections alike. It includes the queries the driver runs while a connection starts, and a `COPY` for its whole duration |
1198
+ | `listenCount` | Connections held by the internal `sql.listen()` pool (0 or 1) |
1199
+ | `subscribeCount` | Connections held by the internal `sql.subscribe()` pool (0 or 1) |
1200
+
1201
+ `totalCount` and `idleCount` have the same meaning as in node-postgres. `waitingCount` is node-postgres's `waitingCount` extended to queries pipelined on connections and queued in leases, and it includes queries sent with `sql` directly, as `pool.query()` does there. Once the pool is at `max`, Postgres.js pipelines new queries onto busy connections, so waiting work can sit on a connection rather than in the pool queue; `waitingCount` counts it too, so `executingCount + waitingCount` covers all issued work that has not finished. Every snapshot satisfies `totalCount === idleCount + busyCount + reservedCount + connectingCount` and `totalCount + closingCount <= max`, the remainder being slots the pool has not opened.
1202
+
1203
+ `listenCount` and `subscribeCount` are counted outside `max`, and the other fields only describe the `max` pool connections. A reserved connection's `stats()` returns the same snapshot, but `sql` inside `sql.begin()` and savepoints has no `stats()`, so call it on the main `sql`.
1204
+
1205
+ The pool is saturated when `waitingCount > 0 && availableCount === 0`: every connection is in use and more work is waiting. Saturation alone is not a reason to fail a health check, because a single pipelined query on a fully used pool, including a transaction pipelining its own statements, is enough to meet it. A health endpoint should compare `waitingCount` against a limit the application chooses:
1206
+
1207
+ ```js
1208
+ import http from 'node:http'
1209
+
1210
+ const MAX_WAITING = 100
1211
+
1212
+ http.createServer((req, res) => {
1213
+ const stats = sql.stats()
1214
+ const overloaded = stats.availableCount === 0 && stats.waitingCount > MAX_WAITING
1215
+
1216
+ res.writeHead(overloaded ? 503 : 200, { 'content-type': 'application/json' })
1217
+ res.end(JSON.stringify(stats))
1218
+ }).listen(8080)
1219
+ ```
1220
+
1221
+ How much waiting work is acceptable depends on the query durations and the latency the application can tolerate, so the limit has no universal value.
1222
+
1223
+ There are no change events, so take snapshots on a timer or on request.
1224
+
1225
+ ### Connection timeout
1226
+
1227
+ Four options decide when connections close and how fast they reopen.
1228
+
1229
+ - **`idle_timeout`** closes a connection that has been idle for that many seconds. It is off by default. Set it in serverless environments (Lambda, Vercel), when re-instantiating several `sql` instances, and with a database service that closes idle connections itself (see the [`ECONNRESET` issue](https://github.com/porsager/postgres/issues/179)).
1230
+ - **`max_lifetime`** closes a connection that many seconds after its session started; in-flight work finishes first. The default is a random interval between 30 and 60 minutes per connection (`60 * (30 + Math.random() * 30)`), which bounds the memory prepared statements hold on the server, works well with Linux's OOM killer and keeps connections from all closing at once. Pass `null` or `0` to keep connections until `sql.end()`.
1231
+ - **`connect_timeout`** (30 seconds by default) bounds each connection attempt: socket creation, TCP and TLS negotiation, authentication, session checks and type discovery. When an attempt times out the next host is tried, and the acquisition as a whole is bounded by `connect_timeout` multiplied by the number of hosts, measured from the first attempt; time spent waiting on an inherited reconnect delay is not counted. It also bounds a graceful close: if the server does not close the socket within `connect_timeout` seconds after `end()` sends Terminate, the connection is closed anyway. Zero disables all three limits.
1232
+ - **`backoff`** is the delay before a reconnect attempt after failed ones: a number of seconds, or a function of the number of attempts that failed in a row across the pool, returning seconds. The default is `(0.5 + Math.random() / 2) * Math.min(3 ** retries / 100, 20)`: a few milliseconds after the first failure, rising to between 10 and 20 seconds after seven failures. A successful connection resets the count.
1233
+
1234
+ `idle_timeout` and `max_lifetime` are also checked when an idle connection is handed out, so an idle connection that is past either limit, for example after a serverless instance was frozen, is closed instead of being used.
1235
+
1236
+ For example, to close a connection that has either been idle for 20 seconds or existed for more than 30 minutes:
1237
+
1238
+ ```js
1239
+ const sql = postgres({
1240
+ idle_timeout: 20,
1241
+ max_lifetime: 60 * 30
1242
+ })
1243
+ ```
1244
+
1245
+ If the only attempt times out, the error is [`CONNECT_TIMEOUT`](#connect_timeout). Once earlier attempts have failed, exhausting the overall budget reports the earlier error, such as the last server error or `CONNECTION_CLOSED`. With a single host, a socket or socket factory error rejects the query once; with several hosts, errors keep cycling through the hosts with backoff until the budget is spent. Queries already sent to the server are not replayed.
1246
+
1247
+ ### Vercel Fluid Compute
1248
+
1249
+ On Vercel's Fluid Compute an instance can be suspended while a connection sits idle and before `idle_timeout` has closed it, which leaves the connection open on the server. `attachDatabasePool` from `@vercel/functions` keeps the instance alive until idle connections have closed. Pass it the pool through `vercelPool`:
1250
+
1251
+ ```js
1252
+ import postgres from '@steadybrew/postgresjs'
1253
+ import { vercelPool } from '@steadybrew/postgresjs/vercel'
1254
+ import { attachDatabasePool } from '@vercel/functions'
1255
+
1256
+ const sql = postgres({ idle_timeout: 5 })
1257
+ attachDatabasePool(vercelPool(sql))
1258
+ ```
1259
+
1260
+ `vercelPool(sql)` returns the pool object `attachDatabasePool` expects: `options.idleTimeoutMillis` and `on('release', fn)`. It throws unless `idle_timeout` is a positive number of seconds. It hooks into the `onidle` option, which is called with the connection id each time a connection returns to the pool idle and its idle timer starts, and it keeps any `onidle` you set yourself. A connection that was frozen past `idle_timeout` anyway is closed when it is next handed out (see [Connection timeout](#connection-timeout)).
1261
+
1262
+ ### Cloudflare Workers support
1263
+
1264
+ Postgres.js has built-in support for the [TCP socket API](https://developers.cloudflare.com/workers/runtime-apis/tcp-sockets/) in Cloudflare Workers. The package's `workerd` export condition selects that build, so the import is the same as on Node.js.
1265
+
1266
+ You can use Postgres.js directly in a Worker, or to benefit from connection pooling and query caching, via the [Hyperdrive](https://developers.cloudflare.com/hyperdrive/learning/connect-to-postgres/#driver-examples) service available to Workers by passing the Hyperdrive `connectionString` when creating a new `postgres` client as follows:
1267
+
1268
+ ```ts
1269
+ import postgres from '@steadybrew/postgresjs'
1270
+
1271
+ interface Env {
1272
+ HYPERDRIVE: Hyperdrive;
1273
+ }
1274
+
1275
+ export default async fetch(req: Request, env: Env, ctx: ExecutionContext) {
1276
+ // The Postgres.js library accepts a connection string directly
1277
+ const sql = postgres(env.HYPERDRIVE.connectionString)
1278
+ const results = await sql`SELECT * FROM users LIMIT 10`
1279
+ return Response.json(results)
1280
+ }
1281
+ ```
1282
+
1283
+ In `wrangler.toml` you will need to enable the `nodejs_compat` compatibility flag to allow Postgres.js to operate in the Workers environment:
1284
+
1285
+ ```toml
1286
+ compatibility_flags = ["nodejs_compat"]
1287
+ ```
1288
+
1289
+ ### Auto fetching of array types
1290
+
1291
+ Postgres.js automatically fetches array-type information when each connection initializes.
1292
+
1293
+ If you have revoked access to `pg_catalog` this feature will no longer work and will need to be disabled.
1294
+
1295
+ You can disable catalog discovery by setting `fetch_types` to `false`. A fixed set of 22 common built-in array types still supports parsing and serialization, including text, numeric, boolean, JSON, date, UUID, and byte arrays. This changes earlier `fetch_types: false` behavior, which returned built-in arrays as raw strings. Other built-in, user-defined, and extension arrays still require discovery or explicit type handlers.
1296
+
1297
+ SQL `NULL` elements are returned as JavaScript `null`; a quoted text element `"NULL"` remains a string. Explicit array parsers and serializers are preserved independently. Catalog discovery with `fetch_types: true` remains per connection; this change does not cache catalog metadata.
1298
+
1299
+ Column, value, and row transforms apply to application query results; initialization metadata retains its original shape.
1300
+
1301
+ ### Environment variables and URL parameters
1302
+
1303
+ It is also possible to connect to the database without a connection string or any options. Postgres.js falls back to the environment variables used by `psql`:
1304
+
1305
+ ```js
1306
+ const sql = postgres()
1307
+ ```
1308
+
1309
+ | Option | Environment variables |
1310
+ | ---------------------- | ------------------------ |
1311
+ | `host` | `PGHOST` |
1312
+ | `port` | `PGPORT` |
1313
+ | `database` | `PGDATABASE` |
1314
+ | `username` | `PGUSERNAME` or `PGUSER` |
1315
+ | `password` | `PGPASSWORD` |
1316
+ | `application_name` | `PGAPPNAME` |
1317
+ | `target_session_attrs` | `PGTARGETSESSIONATTRS` |
1318
+ | `ssl` | `PGSSL` |
1319
+ | `sslnegotiation` | `PGSSLNEGOTIATION` |
1320
+ | `max` | `PGMAX` |
1321
+ | `idle_timeout` | `PGIDLE_TIMEOUT` |
1322
+ | `connect_timeout` | `PGCONNECT_TIMEOUT` |
1323
+ | `max_lifetime` | `PGMAX_LIFETIME` |
1324
+ | `max_pipeline` | `PGMAX_PIPELINE` |
1325
+ | `backoff` | `PGBACKOFF` |
1326
+ | `keep_alive` | `PGKEEP_ALIVE` |
1327
+ | `prepare` | `PGPREPARE` |
1328
+ | `debug` | `PGDEBUG` |
1329
+ | `fetch_types` | `PGFETCH_TYPES` |
1330
+ | `parameter_types` | `PGPARAMETER_TYPES` |
1331
+ | `publications` | `PGPUBLICATIONS` |
1332
+
1333
+ The options from `ssl` to `publications` are also read from a query parameter of the same name in the URL, such as `?idle_timeout=20`. The values `false` and `disable` turn an option off, so `PGSSL=disable` and `?prepare=false` work as they read. `?sslmode=` sets `ssl`, and `?sslrootcert=system` sets `ssl: 'verify-full'`. Any other query parameter is sent to the server as a connection parameter, as with `connection`.
1334
+
1335
+ An option passed in the object wins over the URL, and the URL wins over the environment. When no user is given, the OS user is used, and the database defaults to the user name. `PGMAX` and `?max=` are read as a string and give a pool of one connection ([#129](https://github.com/steadybrew/postgresjs/issues/129)); pass `max` in the options.
1336
+
1337
+ ### Prepared statements
1338
+
1339
+ Prepared statements will automatically be created for any queries where it can be inferred that the query is static. This can be disabled by using the `prepare: false` option. For instance — this is useful when [using PGBouncer in `transaction mode`](https://github.com/porsager/postgres/issues/93#issuecomment-656290493).
1340
+
1341
+ With `prepare: false`, `parameter_types: 'client'` sends queries with values in one round trip, unless a value is an untyped array; see [Parameter types](#parameter-types) for how it works and what it saved in production.
1342
+
1343
+ **update**: [since 1.21.0](https://www.pgbouncer.org/2023/10/pgbouncer-1-21-0)
1344
+ PGBouncer supports protocol-level named prepared statements when [configured
1345
+ properly](https://www.pgbouncer.org/config.html#max_prepared_statements)
1346
+
1347
+ ## Custom Types
1348
+
1349
+ You can add ergonomic support for custom types, or simply use `sql.typed(value, type)` inline, where type is the PostgreSQL `oid` for the type and the correctly serialized string. _(`oid` values for types can be found in the `pg_catalog.pg_type` table.)_
1350
+
1351
+ Adding Query helpers is the cleanest approach which can be done like this:
1352
+
1353
+ ```js
1354
+ const sql = postgres({
1355
+ types: {
1356
+ rect: {
1357
+ // The pg_types oid to pass to the db along with the serialized value.
1358
+ to : 1337,
1359
+
1360
+ // An array of pg_types oids to handle when parsing values coming from the db.
1361
+ from : [1337],
1362
+
1363
+ //Function that transform values before sending them to the db.
1364
+ serialize : ({ x, y, width, height }) => [x, y, width, height],
1365
+
1366
+ // Function that transforms values coming from the db.
1367
+ parse : ([x, y, width, height]) => { x, y, width, height }
1368
+ }
1369
+ }
1370
+ })
1371
+
1372
+ // Now you can use sql.typed.rect() as specified above
1373
+ const [custom] = await sql`
1374
+ insert into rectangles (
1375
+ name,
1376
+ rect
1377
+ ) values (
1378
+ 'wat',
1379
+ ${ sql.typed.rect({ x: 13, y: 37, width: 42, height: 80 }) }
1380
+ )
1381
+ returning *
1382
+ `
1383
+
1384
+ // custom = { name: 'wat', rect: { x: 13, y: 37, width: 42, height: 80 } }
1385
+
1386
+ ```
1387
+
1388
+ With `parameter_types: 'client'` a type's `serialize` runs for `sql.typed.name(v)` and for a whole array bound to that type, not for a plain value; see [Parameter types](#parameter-types).
1389
+
1390
+ ### Custom socket
1391
+
1392
+ Easily do in-process ssh tunneling to your database by providing a custom socket for Postgres.js to use. The function (optionally async) must return a socket-like duplex stream.
1393
+
1394
+ Here's a sample using [ssh2](https://github.com/mscdex/ssh2)
1395
+
1396
+ ```js
1397
+ import ssh2 from 'ssh2'
1398
+
1399
+ const sql = postgres({
1400
+ ...options,
1401
+ socket: ({ host: [host], port: [port] }) => new Promise((resolve, reject) => {
1402
+ const ssh = new ssh2.Client()
1403
+ ssh
1404
+ .on('error', reject)
1405
+ .on('ready', () =>
1406
+ ssh.forwardOut('127.0.0.1', 12345, host, port,
1407
+ (err, socket) => err ? reject(err) : resolve(socket)
1408
+ )
1409
+ )
1410
+ .connect(sshOptions)
1411
+ })
1412
+ })
1413
+ ```
1414
+
1415
+ ## Teardown / Cleanup
1416
+
1417
+ To ensure proper teardown and cleanup on server restarts use `await sql.end()` before `process.exit()`.
1418
+
1419
+ Calling `sql.end()` will reject new queries and return a Promise which resolves when all queries are finished and the underlying connections are closed. If a `{ timeout }` option is provided any pending queries will be rejected once the timeout (in seconds) is reached and the connections will be destroyed.
1420
+
1421
+ With explicit resource management the pool ends itself at the end of a scope:
1422
+
1423
+ ```js
1424
+ async function main() {
1425
+ await using sql = postgres()
1426
+ await sql`select 1`
1427
+ }
1428
+ ```
1429
+
1430
+ This calls `sql.end()` when the scope exits, so it suits scripts and jobs, not a shared client at a module's top level. The syntax needs Node.js 24+ or TypeScript 5.2+. [Reserved connections](#reserving-connections) release themselves the same way. Transaction handles, cursors, `listen` and `subscribe` are not disposable; `sql.begin()` and `for await` already scope the first two.
1431
+
1432
+ `sql.end()` waits at most `connect_timeout` per connection for the server to close it after Terminate; see [Connection timeout](#connection-timeout).
1433
+
1434
+ ### Sample shutdown using [Prexit](https://github.com/porsager/prexit)
1435
+
1436
+ ```js
1437
+ import prexit from 'prexit'
1438
+
1439
+ prexit(async () => {
1440
+ await sql.end({ timeout: 5 })
1441
+ await new Promise(r => server.close(r))
1442
+ })
1443
+ ```
1444
+
1445
+ ## Reserving connections
1446
+
1447
+ ### `await sql.reserve()`
1448
+
1449
+ The `reserve` method pulls out a connection from the pool, and returns a client that wraps the single connection. This can be used for running queries on an isolated connection.
1450
+
1451
+ ```ts
1452
+ const reserved = await sql.reserve()
1453
+ await reserved`select * from users`
1454
+ await reserved.release()
1455
+ ```
1456
+
1457
+ ### `reserved.release()`
1458
+
1459
+ Once you have finished with the reserved connection, call `release` to add it back to the pool. A `using` or `await using` declaration calls `release()` when the scope exits:
1460
+
1461
+ ```js
1462
+ using reserved = await sql.reserve()
1463
+ await reserved`select * from users`
1464
+ ```
1465
+
1466
+ After release, queries through that reserved handle reject with [`CONNECTION_ENDED`](#connection_ended). Call `sql.reserve()` again to acquire a new handle. A reserved handle whose connection has closed rejects with `CONNECTION_CLOSED` and cannot be reused after reconnect.
1467
+
1468
+ ## Error handling
1469
+
1470
+ Errors are all thrown to related queries and never globally. Errors coming from database itself are always in the [native Postgres format](https://www.postgresql.org/docs/current/errcodes-appendix.html), and the same goes for any [Node.js errors](https://nodejs.org/api/errors.html#errors_common_system_errors) eg. coming from the underlying connection.
1471
+
1472
+ Query errors will contain a stored error with the origin of the query to aid in tracing errors.
1473
+
1474
+ Query errors will also contain the `query` string and the `parameters`. These are not enumerable to avoid accidentally leaking confidential information in logs. To log these it is required to specifically access `error.query` and `error.parameters`, or set `debug: true` in options.
1475
+
1476
+ There are also the following errors specifically for this library. Each has the code below as `err.code`. Errors about the connection have a message such as `write CONNECTION_CLOSED host:port`; the others have the code, a colon and the message, such as `UNDEFINED_VALUE: Undefined values are not allowed`.
1477
+
1478
+ ### UNSAFE_TRANSACTION
1479
+ > Only use sql.begin, sql.reserved or max: 1
1480
+
1481
+ A raw `BEGIN` was sent through the pool. To ensure statements in a transaction run on the same connection (which is required for them to run inside the transaction), use [`sql.begin(...)`](#transactions), a [reserved connection](#reserving-connections) or only allow a single connection in options (`max: 1`).
1482
+
1483
+ ### UNDEFINED_VALUE
1484
+ > Undefined values are not allowed
1485
+
1486
+ Postgres.js won't accept `undefined` as values in tagged template queries since it becomes ambiguous what to do with the value. Use `null` explicitly, or [transform `undefined` values](#transform-undefined-values).
1487
+
1488
+ ### MESSAGE_NOT_SUPPORTED
1489
+ > FunctionCallResponse (B) is not supported
1490
+
1491
+ The server sent a message this library does not handle: `FunctionCallResponse` or `NegotiateProtocolVersion`. Feel free to file an issue if you think something is missing.
1492
+
1493
+ ### MAX_PARAMETERS_EXCEEDED
1494
+ > Max number of parameters (65534) exceeded
1495
+
1496
+ The postgres protocol doesn't allow more than 65534 (16bit) parameters. If you run into this issue there are various workarounds such as using `sql([...])` to escape values instead of passing them as parameters.
1497
+
1498
+ ### SASL_SIGNATURE_MISMATCH
1499
+ > The server did not return the correct signature
1500
+
1501
+ When using SASL authentication the server responds with a signature at the end of the authentication flow which needs to match the one on the client. This is to avoid [man-in-the-middle attacks](https://en.wikipedia.org/wiki/Man-in-the-middle_attack). If you receive this error the connection was canceled because the server did not reply with the expected signature.
1502
+
1503
+ ### NOT_TAGGED_CALL
1504
+ > Query not called as a tagged template literal
1505
+
1506
+ Making queries has to be done using the sql function as a [tagged template](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_templates). This is to ensure parameters are serialized and passed to Postgres as query parameters with correct types and to avoid SQL injection.
1507
+
1508
+ ### SSL_NOT_SUPPORTED
1509
+ > The server does not support SSL connections
1510
+
1511
+ The server answered the SSL request with a refusal while `ssl` is set to a mode other than `'prefer'`. The attempt fails at once for a single host. Use `ssl: 'prefer'` to fall back to an unencrypted connection, or enable SSL on the server. See [SSL](#ssl).
1512
+
1513
+ ### TARGET_SESSION_ATTRS
1514
+ > No host matched target_session_attrs=read-write: localhost:5432 is read-only
1515
+
1516
+ No host satisfied [`target_session_attrs`](#multi-host-connections---high-availability-ha). This error is the `cause` of the `CONNECTION_CLOSED` error the query rejects with, so retry logic keyed on `CONNECTION_CLOSED` keeps working; read `err.cause.code` and `err.cause.message` for the reason. The message names the requested value and each host with the reason it was rejected. When it is raised at once and when the client keeps retrying instead is described under [Multi-host connections](#multi-host-connections---high-availability-ha).
1517
+
1518
+ ### INVALID_TRANSACTION_NAME
1519
+ > sql.prepare requires a non-empty string without null bytes
1520
+
1521
+ Thrown by [`sql.prepare(name)`](#prepare-transaction-sqlpreparename) inside `sql.begin()` for a name that is not a non-empty string, or that contains a NUL character.
1522
+
1523
+ ### 57014
1524
+ > canceling statement due to user request
1525
+
1526
+ The code PostgreSQL uses for a cancelled statement. A query [cancelled](#canceling-queries-in-progress) before it was sent rejects with a plain `Error` carrying this code, so `err.code === '57014'` matches a cancel whether the server or the client settled it.
1527
+
1528
+ ### CONNECTION_CLOSED
1529
+ > write CONNECTION_CLOSED host:port
1530
+
1531
+ This error is thrown if the connection was closed, or could not be opened, without an error of its own. When the server or the network ended the session, or no host matched `target_session_attrs`, the underlying error is available as `err.cause`.
1532
+
1533
+ ### CONNECTION_ENDED
1534
+ > write CONNECTION_ENDED host:port
1535
+
1536
+ This error is thrown if the user has called [`sql.end()`](#teardown--cleanup) and performed a query afterward.
1537
+
1538
+ A reserved `sql` used after `release()`, or a transaction `sql` used after `begin()` has committed, rolled back or prepared, or while its `COMMIT` or `ROLLBACK` is in flight, also rejects with `CONNECTION_ENDED`.
1539
+
1540
+ ### CONNECTION_DESTROYED
1541
+ > write CONNECTION_DESTROYED host:port
1542
+
1543
+ This error is thrown for any queries that were pending when the timeout to [`sql.end({ timeout: X })`](#teardown--cleanup) was reached.
1544
+
1545
+ ### CONNECT_TIMEOUT
1546
+ > write CONNECT_TIMEOUT host:port
1547
+
1548
+ A connection attempt took longer than `connect_timeout` (30 seconds by default, `PGCONNECT_TIMEOUT`). What it covers, how it combines across hosts and which error you get once several attempts failed is described under [Connection timeout](#connection-timeout).
1549
+
1550
+ ### COPY_IN_PROGRESS
1551
+ > You cannot execute queries during copy
1552
+
1553
+ A statement was sent on a `sql.reserve()` or `sql.begin()` handle while its copy operation runs, or through `sql` while every connection is running a copy operation that has not been ended. See [Copy to/from as Streams](#copy-tofrom-as-streams).
1554
+
1555
+ ### TRANSACTION_ROLLED_BACK
1556
+ > The server rolled the transaction back instead of committing it
1557
+
1558
+ This error is thrown by `sql.begin()` when the server answers the final `COMMIT` (or `PREPARE TRANSACTION`) with `ROLLBACK`, because the transaction was aborted by a statement whose error the callback did not surface, such as a failing query that was not awaited. Nothing was committed. When such a query's error was already recorded, it is the error's `cause`.
1559
+
1560
+ ### Other errors
1561
+
1562
+ `postgres()` throws a plain `Error` without a code for an unsupported `target_session_attrs` or `parameter_types` value, `vercelPool()` for a missing `idle_timeout`, and `sql.subscribe()` rejects with one for an empty `publications` option or a malformed pattern.
1563
+
1564
+ ## TypeScript support
1565
+
1566
+ Postgres.js has TypeScript support. You can pass a row list type for your queries in this way:
1567
+ ```ts
1568
+ interface User {
1569
+ id: number
1570
+ name: string
1571
+ }
1572
+
1573
+ const users = await sql<User[]>`SELECT * FROM users`
1574
+ users[0].id // ok => number
1575
+ users[1].name // ok => string
1576
+ users[0].invalid // fails: `invalid` does not exists on `User`
1577
+ ```
1578
+
1579
+ However, be sure to check the array length to avoid accessing properties of `undefined` rows:
1580
+ ```ts
1581
+ const users = await sql<User[]>`SELECT * FROM users WHERE id = ${id}`
1582
+ if (!users.length)
1583
+ throw new Error('Not found')
1584
+ return users[0]
1585
+ ```
1586
+
1587
+ You can also prefer destructuring when you only care about a fixed number of rows.
1588
+ In this case, we recommend you to prefer using tuples to handle `undefined` properly:
1589
+ ```ts
1590
+ const [user]: [User?] = await sql`SELECT * FROM users WHERE id = ${id}`
1591
+ if (!user) // => User | undefined
1592
+ throw new Error('Not found')
1593
+ return user // => User
1594
+
1595
+ // NOTE:
1596
+ const [first, second]: [User?] = await sql`SELECT * FROM users WHERE id = ${id}` // fails: `second` does not exist on `[User?]`
1597
+ const [first, second] = await sql<[User?]>`SELECT * FROM users WHERE id = ${id}` // don't fail : `second: User | undefined`
1598
+ ```
1599
+
1600
+ The declarations need `@types/node` 22 or newer, or `skipLibCheck`. Feel free to open an issue if you have trouble with types.
1601
+
1602
+ ## Migration tools
1603
+
1604
+ Postgres.js doesn't come with a schema migration tool. These third-party modules support Postgres.js; they are not maintained or tested here:
1605
+
1606
+ - https://github.com/porsager/postgres-shift
1607
+ - https://github.com/lukeed/ley
1608
+ - https://github.com/JAForbes/pgmg
1609
+