Update docs - add ESM info

* Update docs - start

* Add logo & discord

* Start updating docs for esm style imports

* Update docs with logo & info on pooling

* Update more import statements

---------

Co-authored-by: Brian Carlson <brian.carlson@getcruise.com>
This commit is contained in:
Brian C 2025-04-23 16:46:21 -05:00 committed by GitHub
parent 56e2862577
commit 0c1629bea2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
15 changed files with 194 additions and 67 deletions

20
docs/README.md Normal file
View File

@ -0,0 +1,20 @@
# node-postgres docs website
This is the documentation for node-postgres which is currently hosted at [https://node-postgres.com](https://node-postgres.com).
## Development
To run the documentation locally, you need to have [Node.js](https://nodejs.org) installed. Then, you can clone the repository and install the dependencies:
```bash
cd docs
yarn
```
Once you've installed the deps, you can run the development server:
```bash
yarn dev
```
This will start a local server at [http://localhost:3000](http://localhost:3000) where you can view the documentation and see your changes.

11
docs/components/logo.tsx Normal file
View File

@ -0,0 +1,11 @@
import React from 'react'
type Props = {
src: string
alt?: string
}
export function Logo(props: Props) {
const alt = props.alt || 'Logo'
return <img src={props.src} alt={alt} width={100} height={100} style={{ width: 400, height: 'auto' }} />
}

View File

@ -33,8 +33,7 @@ type Config = {
example to create a client with specific connection information:
```js
import pg from 'pg'
const { Client } = pg
import { Client } from 'pg'
const client = new Client({
user: 'database-user',
@ -48,8 +47,7 @@ const client = new Client({
## client.connect
```js
import pg from 'pg'
const { Client } = pg
import { Client } from 'pg'
const client = new Client()
await client.connect()
@ -91,8 +89,7 @@ client.query(text: string, values?: any[]) => Promise<Result>
**Plain text query**
```js
import pg from 'pg'
const { Client } = pg
import { Client } from 'pg'
const client = new Client()
await client.connect()
@ -106,8 +103,7 @@ await client.end()
**Parameterized query**
```js
import pg from 'pg'
const { Client } = pg
import { Client } from 'pg'
const client = new Client()
await client.connect()
@ -145,8 +141,7 @@ await client.end()
If you pass an object to `client.query` and the object has a `.submit` function on it, the client will pass it's PostgreSQL server connection to the object and delegate query dispatching to the supplied object. This is an advanced feature mostly intended for library authors. It is incidentally also currently how the callback and promise based queries above are handled internally, but this is subject to change. It is also how [pg-cursor](https://github.com/brianc/node-pg-cursor) and [pg-query-stream](https://github.com/brianc/node-pg-query-stream) work.
```js
import pg from 'pg'
const { Query } = pg
import { Query } from 'pg'
const query = new Query('select $1::text as name', ['brianc'])
const result = client.query(query)

View File

@ -18,8 +18,7 @@ $ npm install pg pg-cursor
Instantiates a new Cursor. A cursor is an instance of `Submittable` and should be passed directly to the `client.query` method.
```js
import pg from 'pg'
const { Pool } = pg
import { Pool } from 'pg'
import Cursor from 'pg-cursor'
const pool = new Pool()
@ -29,11 +28,9 @@ const values = [10]
const cursor = client.query(new Cursor(text, values))
cursor.read(100, (err, rows) => {
cursor.close(() => {
client.release()
})
})
const { rows } = await cursor.read(100)
console.log(rows.length) // 100 (unless the table has fewer than 100 rows)
client.release()
```
```ts
@ -58,8 +55,7 @@ If the cursor has read to the end of the result sets all subsequent calls to cur
Here is an example of reading to the end of a cursor:
```js
import pg from 'pg'
const { Pool } = pg
import { Pool } from 'pg'
import Cursor from 'pg-cursor'
const pool = new Pool()

View File

@ -48,8 +48,7 @@ type Config = {
example to create a new pool with configuration:
```js
import pg from 'pg'
const { Pool } = pg
import { Pool } from 'pg'
const pool = new Pool({
host: 'localhost',
@ -69,8 +68,7 @@ pool.query(text: string, values?: any[]) => Promise<pg.Result>
```
```js
import pg from 'pg'
const { Pool } = pg
import { Pool } from 'pg'
const pool = new Pool()
@ -102,8 +100,7 @@ Acquires a client from the pool.
- If the pool is 'full' and all clients are currently checked out will wait in a FIFO queue until a client becomes available by it being released back to the pool.
```js
import pg from 'pg'
const { Pool } = pg
import { Pool } from 'pg'
const pool = new Pool()
@ -121,8 +118,7 @@ Client instances returned from `pool.connect` will have a `release` method which
The `release` method on an acquired client returns it back to the pool. If you pass a truthy value in the `destroy` parameter, instead of releasing the client to the pool, the pool will be instructed to disconnect and destroy this client, leaving a space within itself for a new client.
```js
import pg from 'pg'
const { Pool } = pg
import { Pool } from 'pg'
const pool = new Pool()
@ -134,8 +130,7 @@ client.release()
```
```js
import pg from 'pg'
const { Pool } = pg
import { Pool } from 'pg'
const pool = new Pool()
assert(pool.totalCount === 0)
@ -168,8 +163,7 @@ Calling `pool.end` will drain the pool of all active clients, disconnect them, a
```js
// again both promises and callbacks are supported:
import pg from 'pg'
const { Pool } = pg
import { Pool } from 'pg'
const pool = new Pool()

View File

@ -5,5 +5,7 @@
"transactions": "Transactions",
"types": "Data Types",
"ssl": "SSL",
"native": "Native"
"native": "Native",
"esm": "ESM",
"callbacks": "Callbacks"
}

View File

@ -0,0 +1,39 @@
---
title: Callbacks
---
## Callback Support
`async` / `await` is the preferred way to write async code these days with node, but callbacks are supported in the `pg` module and the `pg-pool` module. To use them, pass a callback function as the last argument to the following methods & it will be called and a promise will not be returned:
```js
const { Pool, Client } = require('pg')
// pool
const pool = new Pool()
// run a query on an available client
pool.query('SELECT NOW()', (err, res) => {
console.log(err, res)
})
// check out a client to do something more complex like a transaction
pool.connect((err, client, release) => {
client.query('SELECT NOW()', (err, res) => {
release()
console.log(err, res)
pool.end()
})
})
// single client
const client = new Client()
client.connect((err) => {
if (err) throw err
client.query('SELECT NOW()', (err, res) => {
console.log(err, res)
client.end()
})
})
```

View File

@ -0,0 +1,37 @@
---
title: ESM
---
## ESM Support
As of v8.15.x node-postgres supporters the __ECMAScript Module__ (ESM) format. This means you can use `import` statements instead of `require` or `import pg from 'pg'`.
CommonJS modules are still supported. The ESM format is an opt-in feature and will not affect existing codebases that use CommonJS.
The docs have been changed to show ESM usage, but in a CommonJS context you can still use the same code, you just need to change the import format.
If you're using CommonJS, you can use the following code to import the `pg` module:
```js
const pg = require('pg')
const { Client } = pg
// etc...
```
### ESM Usage
If you're using ESM, you can use the following code to import the `pg` module:
```js
import { Client } from 'pg'
// etc...
```
Previously if you were using ESM you would have to use the following code:
```js
import pg from 'pg'
const { Client } = pg
// etc...
```

View File

@ -22,8 +22,7 @@ const config = {
},
}
import pg from 'pg'
const { Client, Pool } = pg
import { Client, Pool } from 'pg'
const client = new Client(config)
await client.connect()

View File

@ -16,8 +16,7 @@ To execute a transaction with node-postgres you simply execute `BEGIN / COMMIT /
## Examples
```js
import pg from 'pg'
const { Pool } = pg
import { Pool } from 'pg'
const pool = new Pool()
const client = await pool.connect()

View File

@ -22,8 +22,7 @@ That's the same structure I used in the [project structure](/guides/project-stru
My `db/index.js` file usually starts out like this:
```js
import pg from 'pg'
const { Pool } = pg
import { Pool } from 'pg'
const pool = new Pool()

View File

@ -27,13 +27,12 @@ The location doesn't really matter - I've found it usually ends up being somewha
Typically I'll start out my `db/index.js` file like so:
```js
import pg from 'pg'
const { Pool } = pg
import { Pool } from 'pg'
const pool = new Pool()
export const query = (text, params, callback) => {
return pool.query(text, params, callback)
export const query = (text, params) => {
return pool.query(text, params)
}
```
@ -55,8 +54,7 @@ app.get('/:id', async (req, res, next) => {
Imagine we have lots of routes scattered throughout many files under our `routes/` directory. We now want to go back and log every single query that's executed, how long it took, and the number of rows it returned. If we had required node-postgres directly in every route file we'd have to go edit every single route - that would take forever & be really error prone! But thankfully we put our data access into `db/index.js`. Let's go add some logging:
```js
import pg from 'pg'
const { Pool } = pg
import { Pool } from 'pg'
const pool = new Pool()
@ -76,8 +74,7 @@ _note: I didn't log the query parameters. Depending on your application you migh
Now what if we need to check out a client from the pool to run several queries in a row in a transaction? We can add another method to our `db/index.js` file when we need to do this:
```js
import pg from 'pg'
const { Pool } = pg
import { Pool } from 'pg'
const pool = new Pool()

View File

@ -3,6 +3,8 @@ title: Welcome
slug: /
---
import { Logo } from '/components/logo.tsx'
node-postgres is a collection of node.js modules for interfacing with your PostgreSQL database. It has support for callbacks, promises, async/await, connection pooling, prepared statements, cursors, streaming results, C/C++ bindings, rich type parsing, and more! Just like PostgreSQL itself there are a lot of features: this documentation aims to get you up and running quickly and in the right direction. It also tries to provide guides for more advanced & edge-case topics allowing you to tap into the full power of PostgreSQL from node.js.
## Install
@ -15,19 +17,33 @@ $ npm install pg
node-postgres continued development and support is made possible by the many [supporters](https://github.com/brianc/node-postgres/blob/master/SPONSORS.md).
Special thanks to [Medplum](https://www.medplum.com/) for sponsoring node-postgres for a whole year!
<a href="https://www.medplum.com/">
<img
alt="Medplum"
src="https://raw.githubusercontent.com/medplum/medplum-logo/refs/heads/main/medplum-logo.png"
style={{
width: '300px',
height: 'auto',
margin: '0 auto',
display: 'block',
}}
/>
</a>
If you or your company would like to sponsor node-postgres stop by [GitHub Sponsors](https://github.com/sponsors/brianc) and sign up or feel free to [email me](mailto:brian@pecanware.com) if you want to add your logo to the documentation or discuss higher tiers of sponsorship!
# Version compatibility
node-postgres strives to be compatible with all recent LTS versions of node & the most recent "stable" version. At the time of this writing node-postgres is compatible with node 8.x, 10.x, 12.x and 14.x To use node >= 14.x you will need to install `pg@8.2.x` or later due to some internal stream changes on the node 14 branch. Dropping support for an old node lts version will always be considered a breaking change in node-postgres and will be done on _major_ version number changes only, and we will try to keep support for 8.x for as long as reasonably possible.
node-postgres strives to be compatible with all recent LTS versions of node & the most recent "stable" version. At the time of this writing node-postgres is compatible with node 18.x, 20.x, 22.x, and 24.x.
## Getting started
The simplest possible way to connect, query, and disconnect is with async/await:
```js
import pg from 'pg'
const { Client } = pg
import { Client } from 'pg'
const client = new Client()
await client.connect()
@ -41,8 +57,7 @@ await client.end()
For the sake of simplicity, these docs will assume that the methods are successful. In real life use, make sure to properly handle errors thrown in the methods. A `try/catch` block is a great way to do so:
```ts
import pg from 'pg'
const { Client } = pg
import { Client } from 'pg'
const client = new Client()
await client.connect()
@ -56,22 +71,17 @@ try {
}
```
### Callbacks
### Pooling
If you prefer a callback-style approach to asynchronous programming, all async methods support an optional callback parameter as well:
In most applications you'll wannt to use a [connection pool](/features/pooling) to manage your connections. This is a more advanced topic, but here's a simple example of how to use it:
```js
import pg from 'pg'
const { Client } = pg
const client = new Client()
client.connect((err) => {
client.query('SELECT $1::text as message', ['Hello world!'], (err, res) => {
console.log(err ? err.stack : res.rows[0].message) // Hello World!
client.end()
})
})
import { Pool } from 'pg'
const pool = new Pool()
const res = await pool.query('SELECT $1::text as message', ['Hello world!'])
console.log(res.rows[0].message) // Hello world!
```
Our real-world apps are almost always more complicated than that, and I urge you to read on!

BIN
docs/public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@ -10,7 +10,6 @@ export default {
docsRepositoryBase: 'https://github.com/brianc/node-postgres/blob/master/docs', // base URL for the docs repository
titleSuffix: ' node-postgres',
darkMode: true,
footer: true,
navigation: {
prev: true,
next: true,
@ -23,13 +22,43 @@ export default {
},
logo: (
<>
<svg>...</svg>
<span>node-postgres</span>
<svg
version="1.0"
xmlns="http://www.w3.org/2000/svg"
height={48}
width={48}
viewBox="0 0 1024.000000 1024.000000"
preserveAspectRatio="xMidYMid meet"
>
<g transform="translate(0.000000,1024.000000) scale(0.100000,-0.100000)" fill="#3c873a" stroke="none">
<path
d="M4990 7316 c-391 -87 -703 -397 -1003 -996 -285 -568 -477 -1260
-503 -1811 l-7 -142 -112 7 c-103 5 -207 27 -382 78 -37 11 -44 10 -63 -7 -61
-55 17 -180 177 -285 91 -60 194 -103 327 -137 l104 -26 17 -71 c44 -183 152
-441 256 -613 125 -207 322 -424 493 -541 331 -229 774 -291 1113 -156 112 45
182 94 209 147 13 24 13 35 -1 90 -22 87 -88 219 -134 267 -46 49 -79 52 -153
14 -168 -85 -360 -54 -508 83 -170 157 -244 440 -195 743 50 304 231 601 430
706 168 89 332 60 463 -81 66 -71 110 -140 197 -315 83 -166 116 -194 203
-170 88 23 370 258 637 531 411 420 685 806 808 1139 54 145 71 243 71 410 1
128 -3 157 -27 243 -86 310 -243 543 -467 690 -207 137 -440 157 -966 85
l-161 -22 -94 41 c-201 87 -327 113 -533 112 -77 -1 -166 -7 -196 -13z m-89
-1357 c15 -10 34 -38 43 -61 23 -56 13 -111 -28 -156 -59 -64 -171 -54 -216
21 -35 57 -22 145 28 190 44 40 122 43 173 6z m-234 -1361 c-46 -74 -156 -188
-249 -258 -211 -159 -459 -219 -734 -179 l-76 12 89 28 c187 60 485 229 683
388 l75 60 122 0 122 1 -32 -52z"
/>
</g>
</svg>
<span style={{ fontWeight: 800 }}>node-postgres</span>
</>
),
chat: {
link: 'https://discord.gg/4nbb6zJa',
},
head: (
<>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="shortcut icon" href="/favicon.ico" />
<meta
name="description"
content="node-postgres is a collection of node.js modules for interfacing with your PostgreSQL database."