@steadybrew/postgresjs 0.0.0-stage → 3.4.9

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/README.md CHANGED
@@ -1,3 +1,1396 @@
1
- # Temporary Holding Version
1
+ # Postgres.js by Steady Brew
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ This is an independently maintained fork of [Postgres.js](https://github.com/porsager/postgres), the PostgreSQL client for Node.js and Deno created by [Rasmus Porsager](https://github.com/porsager). [Steady Brew](https://github.com/steadybrew) aims to fix bugs and improve the library through community contributions, regression tests, and careful architectural review, while preserving its simple API.
4
+
5
+ ---
6
+
7
+ <img align="left" width="440" height="180" alt="Fastest full PostgreSQL nodejs client" src="https://raw.githubusercontent.com/porsager/postgres/master/postgresjs.svg?sanitize=true">
8
+
9
+ - [🚀 Fastest full-featured node & deno client](https://github.com/porsager/postgres-benchmarks#results)
10
+ - 🏷 ES6 Tagged Template Strings at the core
11
+ - 🏄‍♀️ Simple surface API
12
+ - 🖊️ Dynamic query support
13
+
14
+ <br>
15
+
16
+ ## Getting started
17
+
18
+ <br>
19
+ <img height="220" width="458" alt="Good UX with Postgres.js" src="https://raw.githubusercontent.com/porsager/postgres/master/demo.gif">
20
+ <br>
21
+
22
+ ### Installation
23
+ ```bash
24
+ $ npm install @steadybrew/postgresjs
25
+ ```
26
+
27
+ ### Usage
28
+ Create your `sql` database instance
29
+ ```js
30
+ // db.js
31
+ import postgres from '@steadybrew/postgresjs'
32
+
33
+ const sql = postgres({ /* options */ }) // will use psql environment variables
34
+
35
+ export default sql
36
+ ```
37
+
38
+ Simply import for use elsewhere
39
+ ```js
40
+ // users.js
41
+ import sql from './db.js'
42
+
43
+ async function getUsersOver(age) {
44
+ const users = await sql`
45
+ select
46
+ name,
47
+ age
48
+ from users
49
+ where age > ${ age }
50
+ `
51
+ // users = Result [{ name: "Walter", age: 80 }, { name: 'Murray', age: 68 }, ...]
52
+ return users
53
+ }
54
+
55
+
56
+ async function insertUser({ name, age }) {
57
+ const users = await sql`
58
+ insert into users
59
+ (name, age)
60
+ values
61
+ (${ name }, ${ age })
62
+ returning name, age
63
+ `
64
+ // users = Result [{ name: "Murray", age: 68 }]
65
+ return users
66
+ }
67
+ ```
68
+
69
+ #### ESM dynamic imports
70
+
71
+ The library can be used with ESM dynamic imports as well as shown here.
72
+
73
+ ```js
74
+ const { default: postgres } = await import('@steadybrew/postgresjs')
75
+ ```
76
+
77
+ ## Table of Contents
78
+
79
+ * [Connection](#connection)
80
+ * [Queries](#queries)
81
+ * [Building queries](#building-queries)
82
+ * [Advanced query methods](#advanced-query-methods)
83
+ * [Transactions](#transactions)
84
+ * [Data Transformation](#data-transformation)
85
+ * [Listen & notify](#listen--notify)
86
+ * [Realtime subscribe](#realtime-subscribe)
87
+ * [Numbers, bigint, numeric](#numbers-bigint-numeric)
88
+ * [Result Array](#result-array)
89
+ * [Connection details](#connection-details)
90
+ * [Custom Types](#custom-types)
91
+ * [Teardown / Cleanup](#teardown--cleanup)
92
+ * [Error handling](#error-handling)
93
+ * [TypeScript support](#typescript-support)
94
+ * [Reserving connections](#reserving-connections)
95
+ * [Changelog](./CHANGELOG.md)
96
+
97
+
98
+ ## Connection
99
+
100
+ ### `postgres([url], [options])`
101
+
102
+ 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.
103
+
104
+ ```js
105
+ const sql = postgres('postgres://username:password@host:port/database', {
106
+ host : '', // Postgres ip address[s] or domain name[s]
107
+ port : 5432, // Postgres server port[s]
108
+ database : '', // Name of database to connect to
109
+ username : '', // Username of database user
110
+ password : '', // Password of database user
111
+ ...and more
112
+ })
113
+ ```
114
+
115
+ More options can be found in the [Connection details section](#connection-details).
116
+
117
+ ## Queries
118
+
119
+ ### ```await sql`...` -> Result[]```
120
+
121
+ 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:
122
+
123
+ 1. **Enforcing** safe query generation
124
+ 2. Giving the ` sql`` ` function powerful [utility](#dynamic-inserts) and [query building](#building-queries) features.
125
+
126
+ Any generic value will be serialized according to an inferred type, and replaced by a PostgreSQL protocol placeholder `$1, $2, ...`. The parameters are then sent separately to the database which handles escaping & casting.
127
+
128
+ All queries will return a `Result` array, with objects mapping column names to each row.
129
+
130
+ ```js
131
+ const xs = await sql`
132
+ insert into users (
133
+ name, age
134
+ ) values (
135
+ 'Murray', 68
136
+ )
137
+
138
+ returning *
139
+ `
140
+
141
+ // xs = [{ user_id: 1, name: 'Murray', age: 68 }]
142
+ ```
143
+
144
+ > Please note that queries are first executed when `awaited` – or instantly by using [`.execute()`](#execute).
145
+
146
+ ### Query parameters
147
+
148
+ 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.
149
+
150
+ ```js
151
+ const name = 'Mur'
152
+ , age = 60
153
+
154
+ const users = await sql`
155
+ select
156
+ name,
157
+ age
158
+ from users
159
+ where
160
+ name like ${ name + '%' }
161
+ and age > ${ age }
162
+ `
163
+ // users = [{ name: 'Murray', age: 68 }]
164
+ ```
165
+
166
+ > 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.
167
+
168
+ ### Dynamic column selection
169
+
170
+ ```js
171
+ const columns = ['name', 'age']
172
+
173
+ await sql`
174
+ select
175
+ ${ sql(columns) }
176
+ from users
177
+ `
178
+
179
+ // Which results in:
180
+ select "name", "age" from users
181
+ ```
182
+
183
+ ### Dynamic inserts
184
+
185
+ ```js
186
+ const user = {
187
+ name: 'Murray',
188
+ age: 68
189
+ }
190
+
191
+ await sql`
192
+ insert into users ${
193
+ sql(user, 'name', 'age')
194
+ }
195
+ `
196
+
197
+ // Which results in:
198
+ insert into users ("name", "age") values ($1, $2)
199
+
200
+ // The columns can also be given with an array
201
+ const columns = ['name', 'age']
202
+
203
+ await sql`
204
+ insert into users ${
205
+ sql(user, columns)
206
+ }
207
+ `
208
+ ```
209
+
210
+ **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.
211
+
212
+ #### Multiple inserts in one query
213
+ 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()`.
214
+
215
+ ```js
216
+ const users = [{
217
+ name: 'Murray',
218
+ age: 68,
219
+ garbage: 'ignore'
220
+ },
221
+ {
222
+ name: 'Walter',
223
+ age: 80
224
+ }]
225
+
226
+ await sql`insert into users ${ sql(users, 'name', 'age') }`
227
+
228
+ // Is translated to:
229
+ insert into users ("name", "age") values ($1, $2), ($3, $4)
230
+
231
+ // Here you can also omit column names which will use object keys as columns
232
+ await sql`insert into users ${ sql(users) }`
233
+
234
+ // Which results in:
235
+ insert into users ("name", "age") values ($1, $2), ($3, $4)
236
+ ```
237
+
238
+ ### Dynamic columns in updates
239
+ This is also useful for update queries
240
+ ```js
241
+ const user = {
242
+ id: 1,
243
+ name: 'Murray',
244
+ age: 68
245
+ }
246
+
247
+ await sql`
248
+ update users set ${
249
+ sql(user, 'name', 'age')
250
+ }
251
+ where user_id = ${ user.id }
252
+ `
253
+
254
+ // Which results in:
255
+ update users set "name" = $1, "age" = $2 where user_id = $3
256
+
257
+ // The columns can also be given with an array
258
+ const columns = ['name', 'age']
259
+
260
+ await sql`
261
+ update users set ${
262
+ sql(user, columns)
263
+ }
264
+ where user_id = ${ user.id }
265
+ `
266
+ ```
267
+
268
+ ### Multiple updates in one query
269
+ 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.
270
+ ```js
271
+ const users = [
272
+ [1, 'John', 34],
273
+ [2, 'Jane', 27],
274
+ ]
275
+
276
+ await sql`
277
+ update users set name = update_data.name, age = (update_data.age)::int
278
+ from (values ${sql(users)}) as update_data (id, name, age)
279
+ where users.id = (update_data.id)::int
280
+ returning users.id, users.name, users.age
281
+ `
282
+ ```
283
+
284
+ ### Dynamic values and `where in`
285
+ Value lists can also be created dynamically, making `where in` queries simple too.
286
+ ```js
287
+ const users = await sql`
288
+ select
289
+ *
290
+ from users
291
+ where age in ${ sql([68, 75, 23]) }
292
+ `
293
+ ```
294
+
295
+ or
296
+ ```js
297
+ const [{ a, b, c }] = await sql`
298
+ select
299
+ *
300
+ from (values ${ sql(['a', 'b', 'c']) }) as x(a, b, c)
301
+ `
302
+ ```
303
+
304
+ ## Building queries
305
+
306
+ Postgres.js features a simple dynamic query builder by conditionally appending/omitting query fragments.
307
+ 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.
308
+
309
+ ### Partial queries
310
+ ```js
311
+ const olderThan = x => sql`and age > ${ x }`
312
+
313
+ const filterAge = true
314
+
315
+ await sql`
316
+ select
317
+ *
318
+ from users
319
+ where name is not null ${
320
+ filterAge
321
+ ? olderThan(50)
322
+ : sql``
323
+ }
324
+ `
325
+ // Which results in:
326
+ select * from users where name is not null
327
+ // Or
328
+ select * from users where name is not null and age > 50
329
+ ```
330
+
331
+ ### Dynamic filters
332
+ ```js
333
+ await sql`
334
+ select
335
+ *
336
+ from users ${
337
+ id
338
+ ? sql`where user_id = ${ id }`
339
+ : sql``
340
+ }
341
+ `
342
+
343
+ // Which results in:
344
+ select * from users
345
+ // Or
346
+ select * from users where user_id = $1
347
+ ```
348
+
349
+ ### Dynamic ordering
350
+
351
+ ```js
352
+ const id = 1
353
+ const order = {
354
+ username: 'asc'
355
+ created_at: 'desc'
356
+ }
357
+ await sql`
358
+ select
359
+ *
360
+ from ticket
361
+ where account = ${ id }
362
+ order by ${
363
+ Object.entries(order).flatMap(([column, order], i) =>
364
+ [i ? sql`,` : sql``, sql`${ sql(column) } ${ order === 'desc' ? sql`desc` : sql`asc` }`]
365
+ )
366
+ }
367
+ `
368
+ ```
369
+
370
+ ### SQL functions
371
+ Using keywords or calling functions dynamically is also possible by using ``` sql`` ``` fragments.
372
+ ```js
373
+ const date = null
374
+
375
+ await sql`
376
+ update users set updated_at = ${ date || sql`now()` }
377
+ `
378
+
379
+ // Which results in:
380
+ update users set updated_at = now()
381
+ ```
382
+
383
+ ### Table names
384
+ Dynamic identifiers like table names and column names is also supported like so:
385
+ ```js
386
+ const table = 'users'
387
+ , column = 'id'
388
+
389
+ await sql`
390
+ select ${ sql(column) } from ${ sql(table) }
391
+ `
392
+
393
+ // Which results in:
394
+ select "id" from "users"
395
+ ```
396
+
397
+ ### Quick primer on interpolation
398
+
399
+ Here's a quick oversight over all the ways to do interpolation in a query template string:
400
+
401
+ | Interpolation syntax | Usage | Example |
402
+ | ------------- | ------------- | ------------- |
403
+ | `${ sql`` }` | for keywords or sql fragments | ``await sql`SELECT * FROM users ${sql`order by age desc` }` `` |
404
+ | `${ sql(string) }` | for identifiers | ``await sql`SELECT * FROM ${sql('table_name')` `` |
405
+ | `${ sql([] or {}, ...) }` | for helpers | ``await sql`INSERT INTO users ${sql({ name: 'Peter'})}` `` |
406
+ | `${ 'somevalue' }` | for values | ``await sql`SELECT * FROM users WHERE age = ${42}` `` |
407
+
408
+ ## Advanced query methods
409
+
410
+ ### Cursors
411
+
412
+ #### ```await sql``.cursor([rows = 1], [fn])```
413
+
414
+ 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.
415
+
416
+ ##### callback function
417
+ ```js
418
+ await sql`
419
+ select
420
+ *
421
+ from generate_series(1,4) as x
422
+ `.cursor(async([row]) => {
423
+ // row = { x: 1 }
424
+ await http.request('https://example.com/wat', { row })
425
+ })
426
+ ```
427
+
428
+ ##### for await...of
429
+ ```js
430
+ // for await...of
431
+ const cursor = sql`select * from generate_series(1,4) as x`.cursor()
432
+
433
+ for await (const [row] of cursor) {
434
+ // row = { x: 1 }
435
+ await http.request('https://example.com/wat', { row })
436
+ }
437
+ ```
438
+
439
+ 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`:
440
+ ```js
441
+ await sql`
442
+ select
443
+ *
444
+ from generate_series(1,1000) as x
445
+ `.cursor(10, async rows => {
446
+ // rows = [{ x: 1 }, { x: 2 }, ... ]
447
+ await Promise.all(rows.map(row =>
448
+ http.request('https://example.com/wat', { row })
449
+ ))
450
+ })
451
+ ```
452
+
453
+ 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.
454
+
455
+ 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.
456
+
457
+ ```js
458
+ await sql`
459
+ select * from generate_series(1,1000) as x
460
+ `.cursor(row => {
461
+ return Math.random() > 0.9 && sql.CLOSE // or sql.END
462
+ })
463
+ ```
464
+
465
+ ### Instant iteration
466
+
467
+ #### ```await sql``.forEach(fn)```
468
+
469
+ 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.
470
+ ```js
471
+ await sql`
472
+ select created_at, name from events
473
+ `.forEach(row => {
474
+ // row = { created_at: '2019-11-22T14:22:00Z', name: 'connected' }
475
+ })
476
+
477
+ // No more rows
478
+ ```
479
+
480
+ ### Query Descriptions
481
+ #### ```await sql``.describe() -> Result[]```
482
+
483
+ 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.
484
+
485
+ 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.**
486
+
487
+ ### Rows as Array of Values
488
+ #### ```sql``.values()```
489
+
490
+ Using `.values` will return rows as an array of values for each column, instead of objects.
491
+
492
+ 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.
493
+
494
+ ### Rows as Raw Array of Buffers
495
+ #### ```sql``.raw()```
496
+
497
+ Using `.raw` will return rows as an array with `Buffer` values for each column, instead of objects.
498
+
499
+ 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.
500
+
501
+ ### Queries in Files
502
+ #### `await sql.file(path, [args], [options]) -> Result[]`
503
+
504
+ Using a file for a query is also supported with optional parameters to use if the file includes `$1, $2, etc`
505
+
506
+ ```js
507
+ const result = await sql.file('query.sql', ['Murray', 68])
508
+ ```
509
+
510
+ ### Multiple statements in one query
511
+ #### ```await sql``.simple()```
512
+
513
+ 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
514
+ ```sql``.simple()```. That will create it as a simple query.
515
+
516
+ ```js
517
+ await sql`select 1; select 2;`.simple()
518
+ ```
519
+
520
+ ### Copy to/from as Streams
521
+
522
+ Postgres.js supports [`COPY ...`](https://www.postgresql.org/docs/14/sql-copy.html) queries, which are exposed as [Node.js streams](https://nodejs.org/api/stream.html).
523
+
524
+ #### ```await sql`copy ... from stdin`.writable() -> Writable```
525
+
526
+ ```js
527
+ import { pipeline } from 'node:stream/promises'
528
+
529
+ // Stream of users with the default tab delimitated cells and new-line delimitated rows
530
+ const userStream = Readable.from([
531
+ 'Murray\t68\n',
532
+ 'Walter\t80\n'
533
+ ])
534
+
535
+ const query = await sql`copy users (name, age) from stdin`.writable()
536
+ await pipeline(userStream, query);
537
+ ```
538
+
539
+ #### ```await sql`copy ... to stdout`.readable() -> Readable```
540
+
541
+ ##### Using Stream Pipeline
542
+ ```js
543
+ import { pipeline } from 'node:stream/promises'
544
+ import { createWriteStream } from 'node:fs'
545
+
546
+ const readableStream = await sql`copy users (name, age) to stdout`.readable()
547
+ await pipeline(readableStream, createWriteStream('output.tsv'))
548
+ // output.tsv content: `Murray\t68\nWalter\t80\n`
549
+ ```
550
+
551
+ ##### Using `for await...of`
552
+ ```js
553
+ const readableStream = await sql`
554
+ copy (
555
+ select name, age
556
+ from users
557
+ where age = 68
558
+ ) to stdout
559
+ `.readable()
560
+ for await (const chunk of readableStream) {
561
+ // chunk.toString() === `Murray\t68\n`
562
+ }
563
+ ```
564
+
565
+ > **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/14/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.
566
+
567
+ ### Canceling Queries in Progress
568
+
569
+ Postgres.js supports, [canceling queries in progress](https://www.postgresql.org/docs/7.1/protocol-protocol.html#AEN39000). 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.
570
+
571
+ ```js
572
+ const query = sql`select pg_sleep 100`.execute()
573
+ setTimeout(() => query.cancel(), 100)
574
+ const result = await query
575
+ ```
576
+
577
+ ### Execute
578
+
579
+ #### ```await sql``.execute()```
580
+
581
+ 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()`
582
+
583
+ ### Unsafe raw string queries
584
+
585
+ <details>
586
+ <summary>Advanced unsafe use cases</summary>
587
+
588
+ ### `await sql.unsafe(query, [args], [options]) -> Result[]`
589
+
590
+ 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.
591
+
592
+ ```js
593
+ sql.unsafe('select ' + danger + ' from users where id = ' + dragons)
594
+ ```
595
+
596
+ 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 }`.
597
+
598
+ You can also nest `sql.unsafe` within a safe `sql` expression. This is useful if only part of your fraction has unsafe elements.
599
+
600
+ ```js
601
+ const triggerName = 'friend_created'
602
+ const triggerFnName = 'on_friend_created'
603
+ const eventType = 'insert'
604
+ const schema_name = 'app'
605
+ const table_name = 'friends'
606
+
607
+ await sql`
608
+ create or replace trigger ${sql(triggerName)}
609
+ after ${sql.unsafe(eventType)} on ${sql.unsafe(`${schema_name}.${table_name}`)}
610
+ for each row
611
+ execute function ${sql(triggerFnName)}()
612
+ `
613
+
614
+ await sql`
615
+ create role friend_service with login password ${sql.unsafe(`'${password}'`)}
616
+ `
617
+ ```
618
+
619
+ </details>
620
+
621
+ ## Transactions
622
+
623
+ #### BEGIN / COMMIT `await sql.begin([options = ''], fn) -> fn()`
624
+
625
+ 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.
626
+
627
+ `BEGIN` is automatically sent with the optional options, and if anything fails `ROLLBACK` will be called so the connection can be released and execution can continue.
628
+
629
+ ```js
630
+ const [user, account] = await sql.begin(async sql => {
631
+ const [user] = await sql`
632
+ insert into users (
633
+ name
634
+ ) values (
635
+ 'Murray'
636
+ )
637
+ returning *
638
+ `
639
+
640
+ const [account] = await sql`
641
+ insert into accounts (
642
+ user_id
643
+ ) values (
644
+ ${ user.user_id }
645
+ )
646
+ returning *
647
+ `
648
+
649
+ return [user, account]
650
+ })
651
+ ```
652
+
653
+ 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.
654
+
655
+ 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:
656
+
657
+ ```js
658
+ const result = await sql.begin(sql => [
659
+ sql`update ...`,
660
+ sql`update ...`,
661
+ sql`insert ...`
662
+ ])
663
+ ```
664
+
665
+ #### SAVEPOINT `await sql.savepoint([name], fn) -> fn()`
666
+
667
+ ```js
668
+ sql.begin('read write', async sql => {
669
+ const [user] = await sql`
670
+ insert into users (
671
+ name
672
+ ) values (
673
+ 'Murray'
674
+ )
675
+ `
676
+
677
+ const [account] = (await sql.savepoint(sql =>
678
+ sql`
679
+ insert into accounts (
680
+ user_id
681
+ ) values (
682
+ ${ user.user_id }
683
+ )
684
+ `
685
+ ).catch(err => {
686
+ // Account could not be created. ROLLBACK SAVEPOINT is called because we caught the rejection.
687
+ })) || []
688
+
689
+ return [user, account]
690
+ })
691
+ .then(([user, account]) => {
692
+ // great success - COMMIT succeeded
693
+ })
694
+ .catch(() => {
695
+ // not so good - ROLLBACK was called
696
+ })
697
+ ```
698
+
699
+
700
+ #### PREPARE TRANSACTION `await sql.prepare([name]) -> fn()`
701
+
702
+ Indicates that the transactions should be prepared using the [`PREPARE TRANSACTION [NAME]`](https://www.postgresql.org/docs/current/sql-prepare-transaction.html) statement
703
+ instead of being committed.
704
+
705
+ ```js
706
+ sql.begin('read write', async sql => {
707
+ const [user] = await sql`
708
+ insert into users (
709
+ name
710
+ ) values (
711
+ 'Murray'
712
+ )
713
+ `
714
+
715
+ await sql.prepare('tx1')
716
+ })
717
+ ```
718
+
719
+ ## Data Transformation
720
+
721
+ Postgres.js allows for transformation of the data passed to or returned from a query by using the `transform` option.
722
+
723
+ Built in transformation functions are:
724
+
725
+ * For camelCase - `postgres.camel`, `postgres.toCamel`, `postgres.fromCamel`
726
+ * For PascalCase - `postgres.pascal`, `postgres.toPascal`, `postgres.fromPascal`
727
+ * For Kebab-Case - `postgres.kebab`, `postgres.toKebab`, `postgres.fromKebab`
728
+
729
+ 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.
730
+
731
+ 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:
732
+
733
+ ```js
734
+ // Transform the column names to and from camel case
735
+ const sql = postgres({ transform: postgres.camel })
736
+
737
+ await sql`CREATE TABLE IF NOT EXISTS camel_case (a_test INTEGER, b_test TEXT)`
738
+ await sql`INSERT INTO camel_case ${ sql([{ aTest: 1, bTest: 1 }]) }`
739
+ const data = await sql`SELECT ${ sql('aTest', 'bTest') } FROM camel_case`
740
+
741
+ console.log(data) // [ { aTest: 1, bTest: '1' } ]
742
+ ```
743
+
744
+ To only perform half of the transformation (eg. only the transformation **to** or **from** camel case), use the other transformation functions:
745
+
746
+ ```js
747
+ // Transform the column names only to camel case
748
+ // (for the results that are returned from the query)
749
+ postgres({ transform: postgres.toCamel })
750
+
751
+ await sql`CREATE TABLE IF NOT EXISTS camel_case (a_test INTEGER)`
752
+ await sql`INSERT INTO camel_case ${ sql([{ a_test: 1 }]) }`
753
+ const data = await sql`SELECT a_test FROM camel_case`
754
+
755
+ console.log(data) // [ { aTest: 1 } ]
756
+ ```
757
+
758
+ ```js
759
+ // Transform the column names only from camel case
760
+ // (for interpolated inserts, updates, and selects)
761
+ const sql = postgres({ transform: postgres.fromCamel })
762
+
763
+ await sql`CREATE TABLE IF NOT EXISTS camel_case (a_test INTEGER)`
764
+ await sql`INSERT INTO camel_case ${ sql([{ aTest: 1 }]) }`
765
+ const data = await sql`SELECT ${ sql('aTest') } FROM camel_case`
766
+
767
+ console.log(data) // [ { a_test: 1 } ]
768
+ ```
769
+
770
+ > 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.
771
+
772
+ ### Transform `undefined` Values
773
+
774
+ By default, Postgres.js will throw the error `UNDEFINED_VALUE: Undefined values are not allowed` when undefined values are passed
775
+
776
+ ```js
777
+ // Transform the column names to and from camel case
778
+ const sql = postgres({
779
+ transform: {
780
+ undefined: null
781
+ }
782
+ })
783
+
784
+ await sql`CREATE TABLE IF NOT EXISTS transform_undefined (a_test INTEGER)`
785
+ await sql`INSERT INTO transform_undefined ${ sql([{ a_test: undefined }]) }`
786
+ const data = await sql`SELECT a_test FROM transform_undefined`
787
+
788
+ console.log(data) // [ { a_test: null } ]
789
+ ```
790
+
791
+ To combine with the built in transform functions, spread the transform in the `transform` object:
792
+
793
+ ```js
794
+ // Transform the column names to and from camel case
795
+ const sql = postgres({
796
+ transform: {
797
+ ...postgres.camel,
798
+ undefined: null
799
+ }
800
+ })
801
+
802
+ await sql`CREATE TABLE IF NOT EXISTS transform_undefined (a_test INTEGER)`
803
+ await sql`INSERT INTO transform_undefined ${ sql([{ aTest: undefined }]) }`
804
+ const data = await sql`SELECT ${ sql('aTest') } FROM transform_undefined`
805
+
806
+ console.log(data) // [ { aTest: null } ]
807
+ ```
808
+
809
+ ### Custom Transform Functions
810
+
811
+ 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:
812
+
813
+ * `to`: The function to transform the outgoing query column name to, i.e `SELECT ${ sql('aName') }` to `SELECT a_name` when using `postgres.toCamel`.
814
+ * `from`: The function to transform the incoming query result column name to, see example below.
815
+
816
+ > Both parameters are optional, if not provided, the default transformation function will be used.
817
+
818
+ ```js
819
+ // Implement your own functions, look at postgres.toCamel, etc
820
+ // as a reference:
821
+ // https://github.com/porsager/postgres/blob/4241824ffd7aa94ffb482e54ca9f585d9d0a4eea/src/types.js#L310-L328
822
+ function transformColumnToDatabase() { /* ... */ }
823
+ function transformColumnFromDatabase() { /* ... */ }
824
+
825
+ const sql = postgres({
826
+ transform: {
827
+ column: {
828
+ to: transformColumnToDatabase,
829
+ from: transformColumnFromDatabase,
830
+ },
831
+ value: { /* ... */ },
832
+ row: { /* ... */ }
833
+ }
834
+ })
835
+ ```
836
+
837
+ ## Listen & notify
838
+
839
+ 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.
840
+
841
+ ### Listen `await sql.listen(channel, onnotify, [onlisten]) -> { state }`
842
+ `.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.
843
+
844
+ ```js
845
+ await sql.listen('news', payload => {
846
+ const json = JSON.parse(payload)
847
+ console.log(json.this) // logs 'is'
848
+ })
849
+ ```
850
+
851
+ The optional `onlisten` method is great to use for a very simply queue mechanism:
852
+
853
+ ```js
854
+ await sql.listen(
855
+ 'jobs',
856
+ (x) => run(JSON.parse(x)),
857
+ ( ) => sql`select unfinished_jobs()`.forEach(run)
858
+ )
859
+
860
+ function run(job) {
861
+ // And here you do the work you please
862
+ }
863
+ ```
864
+ ### Notify `await sql.notify(channel, payload) -> Result[]`
865
+ Notify can be done as usual in SQL, or by using the `sql.notify` method.
866
+ ```js
867
+ sql.notify('news', JSON.stringify({ no: 'this', is: 'news' }))
868
+ ```
869
+
870
+ ## Realtime subscribe
871
+
872
+ Postgres.js implements the logical replication protocol of PostgreSQL to support subscription to real-time updates of `insert`, `update` and `delete` operations.
873
+
874
+ > **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.
875
+
876
+ ### Quick start
877
+
878
+ #### Create a publication (eg. in migration)
879
+ ```sql
880
+ CREATE PUBLICATION alltables FOR ALL TABLES
881
+ ```
882
+
883
+ #### Subscribe to updates
884
+ ```js
885
+ const sql = postgres({ publications: 'alltables' })
886
+
887
+ const { unsubscribe } = await sql.subscribe(
888
+ 'insert:events',
889
+ (row, { command, relation, key, old }) => {
890
+ // Callback function for each row change
891
+ // tell about new event row over eg. websockets or do something else
892
+ },
893
+ () => {
894
+ // Callback on initial connect and potential reconnects
895
+ }
896
+ )
897
+ ```
898
+
899
+ ### Subscribe pattern
900
+
901
+ You can subscribe to specific operations, tables, or even rows with primary keys.
902
+
903
+ #### `operation` `:` `schema` `.` `table` `=` `primary_key`
904
+
905
+ **`operation`** is one of ``` * | insert | update | delete ``` and defaults to `*`
906
+
907
+ **`schema`** defaults to `public`
908
+
909
+ **`table`** is a specific table name and defaults to `*`
910
+
911
+ **`primary_key`** can be used to only subscribe to specific rows
912
+
913
+ ### Examples
914
+
915
+ ```js
916
+ sql.subscribe('*', () => /* everything */ )
917
+ sql.subscribe('insert', () => /* all inserts */ )
918
+ sql.subscribe('*:users', () => /* all operations on the public.users table */ )
919
+ sql.subscribe('delete:users', () => /* all deletes on the public.users table */ )
920
+ sql.subscribe('update:users=1', () => /* all updates on the users row with a primary key = 1 */ )
921
+ ```
922
+
923
+ ## Numbers, bigint, numeric
924
+
925
+ `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`.
926
+
927
+ Since Node.js v10.4 we can use [`BigInt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) to 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.
928
+
929
+ If you want to use `BigInt` you can add this custom type:
930
+
931
+ ```js
932
+ const sql = postgres({
933
+ types: {
934
+ bigint: postgres.BigInt
935
+ }
936
+ })
937
+ ```
938
+
939
+ 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).
940
+
941
+ ## Result Array
942
+
943
+ 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.
944
+
945
+ ### .count
946
+
947
+ 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 ...`.
948
+
949
+ ### .command
950
+
951
+ The `command` run by the query - eg. one of `SELECT`, `UPDATE`, `INSERT`, `DELETE`
952
+
953
+ ### .columns
954
+
955
+ The `columns` returned by the query useful to determine types, or map to the result values when using `.values()`
956
+
957
+ ```js
958
+ {
959
+ name : String, // Column name,
960
+ type : oid, // PostgreSQL oid column type
961
+ parser: Function // The function used by Postgres.js for parsing
962
+ }
963
+ ```
964
+
965
+ ### .statement
966
+
967
+ The `statement` contains information about the statement implicitly created by Postgres.js.
968
+
969
+ ```js
970
+ {
971
+ name : String, // The auto generated statement name
972
+ string : String, // The actual query string executed
973
+ types : [oid], // An array of oid expected as input parameters
974
+ columns : [Column] // Array of columns - same as Result.columns
975
+ }
976
+ ```
977
+
978
+ ### .state
979
+
980
+ This is the state `{ pid, secret }` of the connection that executed the query.
981
+
982
+ ## Connection details
983
+
984
+ ### All Postgres options
985
+
986
+ ```js
987
+ const sql = postgres('postgres://username:password@host:port/database', {
988
+ host : '', // Postgres ip address[es] or domain name[s]
989
+ port : 5432, // Postgres server port[s]
990
+ path : '', // unix socket path (usually '/tmp')
991
+ database : '', // Name of database to connect to
992
+ username : '', // Username of database user
993
+ password : '', // Password of database user
994
+ ssl : false, // true, prefer, require, tls.connect options
995
+ sslnegotiation : null, // direct
996
+ max : 10, // Max number of connections
997
+ max_lifetime : null, // Max lifetime in seconds (more info below)
998
+ idle_timeout : 0, // Idle connection timeout in seconds
999
+ connect_timeout : 30, // Connect timeout in seconds
1000
+ prepare : true, // Automatic creation of prepared statements
1001
+ types : [], // Array of custom types, see more below
1002
+ onnotice : fn, // Default console.log, set false to silence NOTICE
1003
+ onparameter : fn, // (key, value) when server param change
1004
+ debug : fn, // Is called with (connection, query, params, types)
1005
+ socket : fn, // fn returning custom socket to use
1006
+ transform : {
1007
+ undefined : undefined, // Transforms undefined values (eg. to null)
1008
+ column : fn, // Transforms incoming column names
1009
+ value : fn, // Transforms incoming row values
1010
+ row : fn // Transforms entire rows
1011
+ },
1012
+ connection : {
1013
+ application_name : 'postgres.js', // Default application_name
1014
+ ... // Other connection parameters, see https://www.postgresql.org/docs/current/runtime-config-client.html
1015
+ },
1016
+ target_session_attrs : null, // Use 'read-write' with multiple hosts to
1017
+ // ensure only connecting to primary
1018
+ fetch_types : true, // Automatically fetches types on connect
1019
+ // on initial connection.
1020
+ })
1021
+ ```
1022
+
1023
+ Note that `max_lifetime = 60 * (30 + Math.random() * 30)` by default. This resolves to an interval between 30 and 60 minutes to optimize for the benefits of prepared statements **and** working nicely with Linux's OOM killer.
1024
+
1025
+ ### Dynamic passwords
1026
+
1027
+ 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.
1028
+
1029
+ ```js
1030
+ const sql = postgres(url, {
1031
+ // Other connection config
1032
+ ...
1033
+ // Password function for the database user
1034
+ password : async () => await signer.getAuthToken(),
1035
+ })
1036
+ ```
1037
+
1038
+ ### SSL
1039
+
1040
+ 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`):
1041
+
1042
+ ```js
1043
+ const sql =
1044
+ process.env.NODE_ENV === 'production'
1045
+ ? // "Unless you're using a Private or Shield Heroku Postgres database, Heroku Postgres does not currently support verifiable certificates"
1046
+ // https://help.heroku.com/3DELT3RK/why-can-t-my-third-party-utility-connect-to-heroku-postgres-with-ssl
1047
+ postgres({ ssl: { rejectUnauthorized: false } })
1048
+ : postgres()
1049
+ ```
1050
+
1051
+ For more information regarding `ssl` with `postgres`, check out the [Node.js documentation for tls](https://nodejs.org/dist/latest-v16.x/docs/api/tls.html#new-tlstlssocketsocket-options).
1052
+
1053
+
1054
+ ### Multi-host connections - High Availability (HA)
1055
+
1056
+ Multiple connection strings can be passed to `postgres()` in the form of `postgres('postgres://localhost:5432,localhost:5433', ...)`. This works the same as native the `psql` command. Read more at [multiple host URIs](https://www.postgresql.org/docs/13/libpq-connect.html#LIBPQ-MULTIPLE-HOSTS).
1057
+
1058
+ 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.
1059
+
1060
+ If you specify `target_session_attrs: 'primary'` or `PGTARGETSESSIONATTRS=primary` Postgres.js will only connect to the primary host, allowing for zero downtime failovers.
1061
+
1062
+ ### The Connection Pool
1063
+
1064
+ 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.
1065
+
1066
+ > No connection will be made until a query is made.
1067
+
1068
+ For example:
1069
+
1070
+ ```js
1071
+ const sql = postgres() // no connections are opened
1072
+
1073
+ await sql`...` // one connection is now opened
1074
+ await sql`...` // previous opened connection is reused
1075
+
1076
+ // two connections are opened now
1077
+ await Promise.all([
1078
+ sql`...`,
1079
+ sql`...`
1080
+ ])
1081
+ ```
1082
+
1083
+ > When there are high amount of concurrent queries, `postgres` will open as many connections as needed up until `max` number of connections is reached. By default `max` is 10. This can be changed by setting `max` in the `postgres()` call. Example - `postgres('connectionURL', { max: 20 })`.
1084
+
1085
+ 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.
1086
+
1087
+ 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.
1088
+
1089
+ 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.
1090
+
1091
+ Since this library automatically creates prepared statements, it also has a default max lifetime for connections to prevent memory bloat on the database itself. This is a random interval for each connection between 45 and 90 minutes. This allows multiple connections to independently come up and down without affecting the service.
1092
+
1093
+ ### Connection timeout
1094
+
1095
+ By default, connections will not close until `.end()` is called. However, it may be useful to have them close automatically when:
1096
+
1097
+ - re-instantiating multiple ` sql`` ` instances
1098
+ - using Postgres.js in a Serverless environment (Lambda, etc.)
1099
+ - using Postgres.js with a database service that automatically closes connections after some time (see [`ECONNRESET` issue](https://github.com/porsager/postgres/issues/179))
1100
+
1101
+ This can be done using the `idle_timeout` or `max_lifetime` options. These configuration options specify the number of seconds to wait before automatically closing an idle connection and the maximum time a connection can exist, respectively.
1102
+
1103
+ For example, to close a connection that has either been idle for 20 seconds or existed for more than 30 minutes:
1104
+
1105
+ ```js
1106
+ const sql = postgres({
1107
+ idle_timeout: 20,
1108
+ max_lifetime: 60 * 30
1109
+ })
1110
+ ```
1111
+
1112
+ ### Cloudflare Workers support
1113
+
1114
+ Postgres.js has built-in support for the [TCP socket API](https://developers.cloudflare.com/workers/runtime-apis/tcp-sockets/) in Cloudflare Workers, which is [on-track](https://github.com/wintercg/proposal-sockets-api) to be standardized and adopted in Node.js and other JavaScript runtimes, such as Deno.
1115
+
1116
+ 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:
1117
+
1118
+ ```ts
1119
+ // Requires Postgres.js 3.4.0 or later
1120
+ import postgres from '@steadybrew/postgresjs'
1121
+
1122
+ interface Env {
1123
+ HYPERDRIVE: Hyperdrive;
1124
+ }
1125
+
1126
+ export default async fetch(req: Request, env: Env, ctx: ExecutionContext) {
1127
+ // The Postgres.js library accepts a connection string directly
1128
+ const sql = postgres(env.HYPERDRIVE.connectionString)
1129
+ const results = await sql`SELECT * FROM users LIMIT 10`
1130
+ return Response.json(results)
1131
+ }
1132
+ ```
1133
+
1134
+ In `wrangler.toml` you will need to enable the `nodejs_compat` compatibility flag to allow Postgres.js to operate in the Workers environment:
1135
+
1136
+ ```toml
1137
+ compatibility_flags = ["nodejs_compat"]
1138
+ ```
1139
+
1140
+ ### Auto fetching of array types
1141
+
1142
+ Postgres.js will automatically fetch table/array-type information when it first connects to a database.
1143
+
1144
+ If you have revoked access to `pg_catalog` this feature will no longer work and will need to be disabled.
1145
+
1146
+ You can disable this feature by setting `fetch_types` to `false`.
1147
+
1148
+ ### Environmental variables
1149
+
1150
+ It is also possible to connect to the database without a connection string or any options. Postgres.js will fall back to the common environment variables used by `psql` as in the table below:
1151
+
1152
+ ```js
1153
+ const sql = postgres()
1154
+ ```
1155
+
1156
+ | Option | Environment Variables |
1157
+ | ------------------ | ------------------------ |
1158
+ | `host` | `PGHOST` |
1159
+ | `port` | `PGPORT` |
1160
+ | `database` | `PGDATABASE` |
1161
+ | `username` | `PGUSERNAME` or `PGUSER` |
1162
+ | `password` | `PGPASSWORD` |
1163
+ | `application_name` | `PGAPPNAME` |
1164
+ | `idle_timeout` | `PGIDLE_TIMEOUT` |
1165
+ | `connect_timeout` | `PGCONNECT_TIMEOUT` |
1166
+
1167
+ ### Prepared statements
1168
+
1169
+ 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).
1170
+
1171
+ **update**: [since 1.21.0](https://www.pgbouncer.org/2023/10/pgbouncer-1-21-0)
1172
+ PGBouncer supports protocol-level named prepared statements when [configured
1173
+ properly](https://www.pgbouncer.org/config.html#max_prepared_statements)
1174
+
1175
+ ## Custom Types
1176
+
1177
+ 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.)_
1178
+
1179
+ Adding Query helpers is the cleanest approach which can be done like this:
1180
+
1181
+ ```js
1182
+ const sql = postgres({
1183
+ types: {
1184
+ rect: {
1185
+ // The pg_types oid to pass to the db along with the serialized value.
1186
+ to : 1337,
1187
+
1188
+ // An array of pg_types oids to handle when parsing values coming from the db.
1189
+ from : [1337],
1190
+
1191
+ //Function that transform values before sending them to the db.
1192
+ serialize : ({ x, y, width, height }) => [x, y, width, height],
1193
+
1194
+ // Function that transforms values coming from the db.
1195
+ parse : ([x, y, width, height]) => { x, y, width, height }
1196
+ }
1197
+ }
1198
+ })
1199
+
1200
+ // Now you can use sql.typed.rect() as specified above
1201
+ const [custom] = await sql`
1202
+ insert into rectangles (
1203
+ name,
1204
+ rect
1205
+ ) values (
1206
+ 'wat',
1207
+ ${ sql.typed.rect({ x: 13, y: 37, width: 42, height: 80 }) }
1208
+ )
1209
+ returning *
1210
+ `
1211
+
1212
+ // custom = { name: 'wat', rect: { x: 13, y: 37, width: 42, height: 80 } }
1213
+
1214
+ ```
1215
+
1216
+ ### Custom socket
1217
+
1218
+ 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.
1219
+
1220
+ Here's a sample using [ssh2](https://github.com/mscdex/ssh2)
1221
+
1222
+ ```js
1223
+ import ssh2 from 'ssh2'
1224
+
1225
+ const sql = postgres({
1226
+ ...options,
1227
+ socket: ({ host: [host], port: [port] }) => new Promise((resolve, reject) => {
1228
+ const ssh = new ssh2.Client()
1229
+ ssh
1230
+ .on('error', reject)
1231
+ .on('ready', () =>
1232
+ ssh.forwardOut('127.0.0.1', 12345, host, port,
1233
+ (err, socket) => err ? reject(err) : resolve(socket)
1234
+ )
1235
+ )
1236
+ .connect(sshOptions)
1237
+ })
1238
+ })
1239
+ ```
1240
+
1241
+ ## Teardown / Cleanup
1242
+
1243
+ To ensure proper teardown and cleanup on server restarts use `await sql.end()` before `process.exit()`.
1244
+
1245
+ 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.
1246
+
1247
+ #### Sample shutdown using [Prexit](https://github.com/porsager/prexit)
1248
+
1249
+ ```js
1250
+ import prexit from 'prexit'
1251
+
1252
+ prexit(async () => {
1253
+ await sql.end({ timeout: 5 })
1254
+ await new Promise(r => server.close(r))
1255
+ })
1256
+ ```
1257
+
1258
+ ## Reserving connections
1259
+
1260
+ ### `await sql.reserve()`
1261
+
1262
+ 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.
1263
+
1264
+ ```ts
1265
+ const reserved = await sql.reserve()
1266
+ await reserved`select * from users`
1267
+ await reserved.release()
1268
+ ```
1269
+
1270
+ ### `reserved.release()`
1271
+
1272
+ Once you have finished with the reserved connection, call `release` to add it back to the pool.
1273
+
1274
+ ## Error handling
1275
+
1276
+ 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.
1277
+
1278
+ Query errors will contain a stored error with the origin of the query to aid in tracing errors.
1279
+
1280
+ 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.
1281
+
1282
+ There are also the following errors specifically for this library.
1283
+
1284
+ ##### UNSAFE_TRANSACTION
1285
+ > Only use sql.begin or max: 1
1286
+
1287
+ To ensure statements in a transaction runs on the same connection (which is required for them to run inside the transaction), you must use [`sql.begin(...)`](#transactions) or only allow a single connection in options (`max: 1`).
1288
+
1289
+ ##### UNDEFINED_VALUE
1290
+ > Undefined values are not allowed
1291
+
1292
+ Postgres.js won't accept `undefined` as values in tagged template queries since it becomes ambiguous what to do with the value. If you want to set something to null, use `null` explicitly.
1293
+
1294
+ ##### MESSAGE_NOT_SUPPORTED
1295
+ > X (X) is not supported
1296
+
1297
+ Whenever a message is received from Postgres which is not supported by this library. Feel free to file an issue if you think something is missing.
1298
+
1299
+ ##### MAX_PARAMETERS_EXCEEDED
1300
+ > Max number of parameters (65534) exceeded
1301
+
1302
+ 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.
1303
+
1304
+ ##### SASL_SIGNATURE_MISMATCH
1305
+ > Message type X not supported
1306
+
1307
+ 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.
1308
+
1309
+ ##### NOT_TAGGED_CALL
1310
+ > Query not called as a tagged template literal
1311
+
1312
+ 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.
1313
+
1314
+ ##### AUTH_TYPE_NOT_IMPLEMENTED
1315
+ > Auth type X not implemented
1316
+
1317
+ Postgres supports many different authentication types. This one is not supported.
1318
+
1319
+ ##### CONNECTION_CLOSED
1320
+ > write CONNECTION_CLOSED host:port
1321
+
1322
+ This error is thrown if the connection was closed without an error. This should not happen during normal operations, so please create an issue if this was unexpected.
1323
+
1324
+ ##### CONNECTION_ENDED
1325
+ > write CONNECTION_ENDED host:port
1326
+
1327
+ This error is thrown if the user has called [`sql.end()`](#teardown--cleanup) and performed a query afterward.
1328
+
1329
+ ##### CONNECTION_DESTROYED
1330
+ > write CONNECTION_DESTROYED host:port
1331
+
1332
+ This error is thrown for any queries that were pending when the timeout to [`sql.end({ timeout: X })`](#teardown--cleanup) was reached.
1333
+
1334
+ ##### CONNECT_TIMEOUT
1335
+ > write CONNECT_TIMEOUT host:port
1336
+
1337
+ This error is thrown if the startup phase of the connection (tcp, protocol negotiation, and auth) took more than the default 30 seconds or what was specified using `connect_timeout` or `PGCONNECT_TIMEOUT`.
1338
+
1339
+ ##### COPY_IN_PROGRESS
1340
+ > You cannot execute queries during copy
1341
+
1342
+ This error is thrown if trying to run a query during a copy operation (writable / readable).
1343
+
1344
+ ## TypeScript support
1345
+
1346
+ `postgres` has TypeScript support. You can pass a row list type for your queries in this way:
1347
+ ```ts
1348
+ interface User {
1349
+ id: number
1350
+ name: string
1351
+ }
1352
+
1353
+ const users = await sql<User[]>`SELECT * FROM users`
1354
+ users[0].id // ok => number
1355
+ users[1].name // ok => string
1356
+ users[0].invalid // fails: `invalid` does not exists on `User`
1357
+ ```
1358
+
1359
+ However, be sure to check the array length to avoid accessing properties of `undefined` rows:
1360
+ ```ts
1361
+ const users = await sql<User[]>`SELECT * FROM users WHERE id = ${id}`
1362
+ if (!users.length)
1363
+ throw new Error('Not found')
1364
+ return users[0]
1365
+ ```
1366
+
1367
+ You can also prefer destructuring when you only care about a fixed number of rows.
1368
+ In this case, we recommend you to prefer using tuples to handle `undefined` properly:
1369
+ ```ts
1370
+ const [user]: [User?] = await sql`SELECT * FROM users WHERE id = ${id}`
1371
+ if (!user) // => User | undefined
1372
+ throw new Error('Not found')
1373
+ return user // => User
1374
+
1375
+ // NOTE:
1376
+ const [first, second]: [User?] = await sql`SELECT * FROM users WHERE id = ${id}` // fails: `second` does not exist on `[User?]`
1377
+ const [first, second] = await sql<[User?]>`SELECT * FROM users WHERE id = ${id}` // don't fail : `second: User | undefined`
1378
+ ```
1379
+
1380
+ We do our best to type all the public API, however types are not always updated when features are added or changed. Feel free to open an issue if you have trouble with types.
1381
+
1382
+ ## Migration tools
1383
+
1384
+ Postgres.js doesn't come with any migration solution since it's way out of scope, but here are some modules that support Postgres.js for migrations:
1385
+
1386
+ - https://github.com/porsager/postgres-shift
1387
+ - https://github.com/lukeed/ley
1388
+ - https://github.com/JAForbes/pgmg
1389
+
1390
+ ## Thank you
1391
+
1392
+ A really big thank you to [@JAForbes](https://twitter.com/jmsfbs) who introduced me to Postgres and still holds my hand navigating all the great opportunities we have.
1393
+
1394
+ Thanks to [@ACXgit](https://twitter.com/andreacoiutti) for initial tests and dogfooding.
1395
+
1396
+ Also thanks to [Ryan Dahl](https://github.com/ry) for letting me have the `postgres` npm package name.