# @fastify/postgres 中文文档

规范地址：https://npmcn.com/package/%40fastify/postgres/

版本：6\.1\.2
npm 元数据更新时间：2026-11-04T14:09:57.167Z
中文译文更新时间：2026-11-14T11:22:54.315Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40fastify/postgres
原文对照：https://npmcn.com/package/%40fastify/postgres/?lang=original
项目主页：https://github.com/fastify/fastify-postgres#readme
源码仓库：https://github.com/fastify/fastify-postgres

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：70.3 kB，26 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：1 个
- peer 依赖：pg \>=6\.0\.0
- 首次发布：2022-04-27T15:00:13.711Z
- 最新版本发布：2026-11-04T14:09:56.768Z
- 近 30 天下载量：205264（2026-10-15 至 2026-11-13，npm 官方下载统计）
- 已发布版本数：15（近 12 个月 3 个）

## 中文简介

快捷 PostgreSQL 连接插件

## 安装

```sh
npm install @fastify/postgres
```

也可以使用：`pnpm add @fastify/postgres`、`yarn add @fastify/postgres`、`bun add @fastify/postgres`

## README

# @ fastify/ postgres (帮助)

[![CI](https://github.com/fastify/fastify-postgres/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/fastify-postgres/actions/workflows/ci.yml) [![NPM version](https://img.shields.io/npm/v/@fastify/postgres.svg?style=flat)](https://www.npmjs.com/package/@fastify/postgres) [![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard)

快捷 PostgreSQL 连接插件; 通过此功能, 您可以在服务器的每个部分共享相同的 PostgreSQL 连接池 . 在车盖下 [节点后置](https://github.com/brianc/node-postgres) 选项 `register` 将传递给 PostgreSQL 游泳池建造者.

## 安装

```
npm i pg @fastify/postgres
```

### 兼容性

| 插件版本 | 快速化版本 |
| --- | --- |
| `>=6.x` | `^5.x` |
| `^5.x` | `^4.x` |
| `>=3.x <5.x` | `^3.x` |
| `>=1.x <3.x` | `^2.x` |
| `>=1.x <3.x` | `^1.x` |

请注意,如果一个快取版本没有支持,那么该插件的相应版本也一样 上表列出. 见 [快速化 LTS 政策](https://github.com/fastify/fastify/blob/main/docs/Reference/LTS.md) 更多细节.

## 使用量

添加到您的项目中 `register` 你们就完了! 此插件将添加 `pg` 命名空间到您的快捷实例,其属性如下:

```
connect: the function to get a connection from the pool
pool: the pool instance
Client: a client constructor for a single query
query: a utility to perform a query _without_ a transaction
transact: a utility to perform multiple queries _with_ a transaction
```

示例

```js
const fastify = require('fastify')()

fastify.register(require('@fastify/postgres'), {
  connectionString: 'postgres://postgres@localhost/postgres'
})

fastify.get('/user/:id', (req, reply) => {
  fastify.pg.connect(onConnect)

  function onConnect (err, client, release) {
    if (err) return reply.send(err)

    client.query(
      'SELECT id, username, hash, salt FROM users WHERE id=$1', [req.params.id],
      function onResult (err, result) {
        release()
        reply.send(err || result)
      }
    )
  }
})

fastify.listen({ port: 3000 }, err => {
  if (err) throw err
  console.log(`server listening on ${fastify.server.address().port}`)
})
```

Async 等待也得到了支持! (英语)!

```js
const fastify = require('fastify')()

fastify.register(require('@fastify/postgres'), {
  connectionString: 'postgres://postgres@localhost/postgres'
})

fastify.get('/user/:id', async (req, reply) => {
  const client = await fastify.pg.connect()
  try {
    const { rows } = await client.query(
      'SELECT id, username, hash, salt FROM users WHERE id=$1', [req.params.id],
    )
    // Note: avoid doing expensive computation here, this will block releasing the client
    return rows
  } finally {
    // Release the client immediately after query resolves, or upon error
    client.release()
  }
})

fastify.listen({ port: 3000 }, err => {
  if (err) throw err
  console.log(`server listening on ${fastify.server.address().port}`)
})
```

使用 `pg.query`

```js
const fastify = require('fastify')()

fastify.register(require('@fastify/postgres'), {
  connectionString: 'postgres://postgres@localhost/postgres'
})

fastify.get('/user/:id', (req, reply) => {
  fastify.pg.query(
    'SELECT id, username, hash, salt FROM users WHERE id=$1', [req.params.id],
    function onResult (err, result) {
      reply.send(err || result)
    }
  )
})

fastify.listen({ port: 3000 }, err => {
  if (err) throw err
  console.log(`server listening on ${fastify.server.address().port}`)
})
```

使用 `pg.transact`

```js
const fastify = require('fastify')()

fastify.register(require('@fastify/postgres'), {
  connectionString: 'postgres://postgres@localhost/postgres'
})

fastify.post('/user/:username', (req, reply) => {
  // will return a promise, fastify will send the result automatically
  return fastify.pg.transact(async client => {
    // will resolve to an id, or reject with an error
    const id = await client.query('INSERT INTO users(username) VALUES($1) RETURNING id', [req.params.username])

    // potentially do something with id

    return id
  })
})

/* or with a transaction callback

fastify.pg.transact(client => {
    return client.query('INSERT INTO users(username) VALUES($1) RETURNING id', [req.params.username])
  },
  function onResult (err, result) {
    reply.send(err || result)
  }
})

*/

/* or with a commit callback

fastify.pg.transact((client, commit) => {
  client.query('INSERT INTO users(username) VALUES($1) RETURNING id', [req.params.username], (err, id) => {
    commit(err, id)
  });
})

*/

fastify.listen({ port: 3000 }, err => {
  if (err) throw err
  console.log(`server listening on ${fastify.server.address().port}`)
})
```

如你所见,由于客户是内部完成的,所以没有必要关闭客户端. 承诺和等待也受到支持.

### 名称选项

如果需要设置多个数据库,您可以通过路过来命名每个数据库 `name: 'foo'`。然后,它将作为 `fastify.pg.foo`。 。 。 . 您可以同时使用未命名和命名的邮递连接 。 只能有一个无名连接,它会作为 `fastify.pg`。 。 。 .

```js
const fastify = require('fastify')()

fastify.register(require('@fastify/postgres'), {
  connectionString: 'postgres://postgres@localhost/postgres',
  name: 'foo'
})

fastify.get('/user/:id', (req, reply) => {
  fastify.pg.foo.query(
    'SELECT id, username, hash, salt FROM users WHERE id=$1', [req.params.id],
    function onResult (err, result) {
      reply.send(err || result)
    }
  )
})

fastify.listen({ port: 3000 }, err => {
  if (err) throw err
  console.log(`server listening on ${fastify.server.address().port}`)
})
```

### 本地选项

如果您想要最大性能, 您可以安装 [pg-内在](https://github.com/brianc/node-pg-native),然后通过 `native: true` 到插件选项. _注:它需要安装 PostgreSQL 客户端库和工具,参见 [指令](https://github.com/brianc/node-pg-native#install)。 。 。 ._ 注:尝试使用本地选项而不成功安装 `pg-native` 将返回警告,并将归依定期 `pg` 模块.

```js
const fastify = require('fastify')()

fastify.register(require('@fastify/postgres'), {
  connectionString: 'postgres://postgres@localhost/postgres',
  native: true
})

fastify.get('/user/:id', (req, reply) => {
  fastify.pg.query(
    'SELECT id, username, hash, salt FROM users WHERE id=$1', [req.params.id],
    function onResult (err, result) {
      reply.send(err || result)
    }
  )
})

fastify.listen({ port: 3000 }, err => {
  if (err) throw err
  console.log(`server listening on ${fastify.server.address().port}`)
})
```

### `pg` 选项

如果你想提供自己的 `pg` 例如,用于支持软件包的模块 [`pg-range`](https://www.npmjs.com/package/pg-range),您可以提供可选 `pg` 要使用补丁库的选项 :

```js
const fastify = require('fastify')()
const pg = require("pg");
require("pg-range").install(pg)

fastify.register(require('@fastify/postgres'), {
  connectionString: 'postgres://postgres@localhost/postgres',
  pg: pg
})

fastify.get('/user/:id', (req, reply) => {
  fastify.pg.query(
    'SELECT id, username, hash, salt FROM users WHERE id=$1', [req.params.id],
    function onResult (err, result) {
      reply.send(err || result)
    }
  )
})

fastify.listen({ port: 3000 }, err => {
  if (err) throw err
  console.log(`server listening on ${fastify.server.address().port}`)
})
```

### SSL/TLS 用户

此插件不执行 SSL 本身: 您通过的任何选项 `register` (包括 `ssl`)作为正文转发给 `pg`是因为 `Pool`编号 :`Client` 构造器,所以由 [节点后置](https://node-postgres.com/features/ssl) 这儿也有工作.

启用 SSL 有两种方法:

**1\. 通过 `ssl` 选项对象**

当您需要禁用证书验证时有用(例如连接到一个带有自签名证书的数据库,比如在Heroku上),或者直接提供证书/密钥.

```js
const fastify = require('fastify')()

fastify.register(require('@fastify/postgres'), {
  connectionString: process.env.DATABASE_URL,
  ssl: {
    rejectUnauthorized: false
  }
})
```

**2\. 连接字符串中的 SSL 参数**

您也可以通过添加参数来启用SSL,例如 `sslmode`, (中文(简体) ), `sslrootcert`, (中文(简体) ), `sslcert` 财务报告和审定财务报表 `sslkey` 直接连接字符串 :

```js
const fastify = require('fastify')()

fastify.register(require('@fastify/postgres'), {
  connectionString: 'postgres://username:password@host:port/databasename?sslmode=verify-full&sslrootcert=yourrootcert&sslcert=yourclientcertificate&sslkey=yourclientkey'
})
```

> QQ 警告 : 不混合两种方法。 如果连接字符串包含任何 `sslmode`, (中文(简体) ), `sslcert`, (中文(简体) ), `sslkey` 或者说 `sslrootcert`中,这些值优先于 `ssl` 选项对象,和 `ssl` 选项将被有效忽略。 选择一种方法(两种方法中的一种) `ssl` 对象,或连接字符串中的 SSL 参数)并粘接它.

### 切换路由选项

通过使用 `transact` 选项。 请注意,这一备选办法必须在以下范围内加以界定: `pg` 选项可以生效.

`query` 然后可以在 `request.pg` 或者说 `request.pg[name]` 财务报告和审定财务报表 `transact` 可以为有值的根 pg 客户端设置 `true` 或对于 pg 客户端在有值的特定命名空间 `name`。请注意,注册插件时需要设置命名空间,以便在请求对象上可用.

```js
// transact set for the route pg client
fastify.get('/user/:id', { pg: { transact: true } }, (req, reply) => {
  // transaction wrapped queries, NO error handling
  req.pg.query('SELECT username FROM users WHERE id=1')
  req.pg.query('SELECT username FROM users WHERE id=2')
  req.pg.query('SELECT username FROM users WHERE id=3')
})

// transact set for a pg client at name
fastify.get('/user/:id', { pg: { transact: 'foo' } }, (req, reply) => {
  // transaction wrapped queries, NO error handling
  req.pg.foo.query('SELECT username FROM users WHERE id=1')
  req.pg.foo.query('SELECT username FROM users WHERE id=2')
  req.pg.foo.query('SELECT username FROM users WHERE id=3')
})
```

重要: 交易的回滚依赖于处理器失败被一个 `onError` 钩. 这意味着包裹的路由处理器不得在内部发现任何出错.

在插件中,使用 `preHandler` 钩入打开交易,然后是 `onError` 财务报告和审定财务报表 `onSend` 钩来承诺或回滚并释放客户端回池.

## 类型脚本使用

安装 pg 模块的编译器和打字 :

```shell
npm i -D typescript @types/pg
```

更多实例 [实例/类型说明](https://npmcn.com/package/%40fastify/postgres/examples/typescript) 目录.

## 开发和测试

### Docker 办法

首先,开始邮递:

```sh
npm run postgres
```

然后,你可以在另一个终端中找到运行的插头,输入DB,然后运行测试:

```sh
$ docker ps
CONTAINER ID        IMAGE                 COMMAND                  CREATED             STATUS              PORTS                    NAMES
28341f85c4cd        postgres:9.6-alpine   "docker-entrypoint.s…"   3 minutes ago       Up 3 minutes        0.0.0.0:5432->5432/tcp   jovial_shockley

$ docker exec -ti jovial_shockley /usr/local/bin/psql -d postgres -U postgres  -c 'CREATE TABLE users(id serial PRIMARY KEY, username VARCHAR (50) NOT NULL);'
CREATE TABLE

$ npm test
```

### 自定义 Postgres 方法

1.  在您选择的 Postgres 服务器中建立您选择的数据库
    
2.  使用
    
    ```sql
    CREATE TABLE users(id serial PRIMARY KEY, username VARCHAR (50) NOT NULL);
    ```
    
3.  在 a 中指定连接字符串 `DATABASE_TEST_URL` 运行测试时的环境变量
    
    ```bash
    DATABASE_TEST_URL="postgres://username:password@localhost/something_thats_a_test_database" npm test
    ```
    

## 承认

这个项目由下列各方慷慨赞助:

-   [临近格式](https://nearform.com/)

过去提案国:

-   莱兹

## 许可证

许可证根据 [麻省理工学院](https://npmcn.com/package/%40fastify/postgres/LICENSE)。 。 。 .

## 常见问题

### @fastify/postgres 是什么？

快捷 PostgreSQL 连接插件

### 如何安装 @fastify/postgres？

在项目目录运行 npm install @fastify/postgres，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：pg（\>=6\.0\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @fastify/postgres 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @fastify/postgres 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @fastify/postgres 可以商用吗？

@fastify/postgres 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @fastify/postgres 的下载量有多少？

根据 npm 官方下载统计，@fastify/postgres 在 2026/10/15 – 2026/11/13 这 30 天内被下载 205,264 次，日均约 6,842 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @fastify/postgres 还在维护吗？

最新版本 6\.1\.2 发布于 2026/11/04（9 天前）；至今共发布 15 个版本，其中过去 12 个月发布了 3 个；首次发布于 2022/04/27。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

