# postgrejs

> Professional PostgreSQL client NodeJS

Latest version **3.15.2** (published 2026-11-15) · BSD-3-Clause license · 0 weekly downloads

## Install

```sh
npm install postgrejs
pnpm add postgrejs
yarn add postgrejs
bun add postgrejs
```

## Health

**Score 70/100 (B)** — status: active.

Positive: has types; esm support; no vulnerabilities; has provenance; recently updated; high maintenance score.

Warnings: low downloads.

## Facts

| | |
|---|---|
| Version | 3.15.2 |
| Published | 2026-11-15 |
| First published | 2024-05-01 |
| Weekly downloads | 0 |
| License | BSD-3-Clause |
| TypeScript types | bundled |
| Module format | ESM |
| Node | >=22.0 |
| Dependencies | 8 |
| Unpacked size | 1 MB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Provenance | attested (GitHub Actions) |
| GitHub stars | 84 |
| Author | Panates |
| Maintainers | erayhanoglu, ilkergurelli, bircanyuruk |
| Keywords | postgresql, postgres, postgre, pg, database, db, driver, client, backend, rdbms, sql, typescript, wire-protocol, no-native-bindings, cursor, server-side-cursor, logical-replication, copy, connection-pool, prepared-statements, bun, bunjs |

## Links

- npm: https://www.npmjs.com/package/postgrejs
- Repository: https://github.com/panates/postgrejs
- Homepage: https://www.postgrejs.com/
- npm.io page: https://npm.io/package/postgrejs

## Dependencies (8)

- [tslib](https://npm.io/package/tslib.md) ^2.9.1
- [power-tasks](https://npm.io/package/power-tasks.md) ^1.14.2
- [doublylinked](https://npm.io/package/doublylinked.md) ^2.5.6
- [flexy-buffer](https://npm.io/package/flexy-buffer.md) ^1.1.2
- [lightning-pool](https://npm.io/package/lightning-pool.md) ^4.14.2
- [@jsopen/objects](https://npm.io/package/@jsopen/objects.md) ^2.3.4
- [putil-promisify](https://npm.io/package/putil-promisify.md) ^1.10.1
- [putil-varhelpers](https://npm.io/package/putil-varhelpers.md) ^1.7.0

## Alternatives

- [angular-pipes](https://npm.io/package/angular-pipes.md) — 5.6K weekly downloads
- [@ng-web-apis/midi](https://npm.io/package/@ng-web-apis/midi.md) — 2.6K weekly downloads
- [happn-3](https://npm.io/package/happn-3.md) — 1.6K weekly downloads
- [@opensip-cli/lang-go](https://npm.io/package/@opensip-cli/lang-go.md) — 1.2K weekly downloads
- [@temporal-architect/claude-plugin](https://npm.io/package/@temporal-architect/claude-plugin.md) — 335 weekly downloads

## Recent versions

- 3.15.2 (latest) — 2026-11-15
- 3.15.1 — 2026-11-10
- 3.15.0 — 2026-11-09
- 3.14.2 — 2026-11-07
- 3.14.1 — 2026-10-28
- 3.14.0 — 2026-10-09
- 3.13.0 — 2026-10-06
- 3.12.2 — 2026-10-05
- 3.12.1 — 2026-09-29
- 3.12.0 — 2026-09-27
- 3.11.1 — 2026-09-24
- 3.11.0 — 2026-09-23
- 3.10.1 — 2026-09-22
- 3.10.0 — 2026-09-22
- 3.9.0 — 2026-09-22
- … 39 more at https://npm.io/package/postgrejs/versions

## README

<!--suppress HtmlDeprecatedAttribute -->
<p align="center">
  <a href="https://www.postgrejs.com/" target="_blank" rel="noopener noreferrer">
    <img src="https://www.postgrejs.com/img/postgrejs-header-block.webp" width="1280" alt="PostgreJS Logo" />
  </a>
</p>

[![NPM Version][npm-image]][npm-url]
[![NPM Downloads][downloads-image]][downloads-url]
[![CI Tests][ci-test-image]][ci-test-url]
[![Test Coverage][coveralls-image]][coveralls-url]

## Why PostgreJS?

**PostgreJS** is a PostgreSQL driver for Node.js and Bun built from the wire protocol up - no `libpq`, no native bindings,
just TypeScript talking directly to PostgreSQL. That from-scratch design is also what makes it fast and light: every
byte on the wire is handled by code written for exactly that purpose, with a binary-first protocol, shared buffers,
and row/column decoding pipelines built to avoid unnecessary allocation, instead of generic string plumbing bolted
onto a client meant for text.

### Blazing Fast

The numbers back it up. In PostgreJS's own benchmark suite - run head-to-head against
[`pg`](https://github.com/brianc/node-postgres) (node-postgres) and [`postgres`](https://github.com/porsager/postgres)
(postgres.js) on identical workloads - PostgreJS opens a connection up to **3x faster** than postgres.js, pushes
pooled queries through up to **6.5x faster** than pg, and fetches large result sets nearly **5x faster** than pg
too. It's also the only one of the three Node drivers with a complete binary wire protocol across every data
type, rather than falling back to text for most of them. See [`docs/BENCHMARKS.md`](docs/BENCHMARKS.md) for the full
methodology and every scenario.

The same suite runs under Bun, where Bun's own built-in `Bun.sql` joins the comparison as a fourth client - see
[`docs/BENCHMARKS-bun.md`](docs/BENCHMARKS-bun.md).

### Small Footprint

The same benchmarks show it using a fraction of the memory: peak heap usage typically runs **3-7x lower** than both
pg and postgres.js - as much as **7x lower** when streaming cursors or fetching large arrays - and it spends a
fraction of the time either of them does in garbage collection. Shared buffers and decode paths that read values
straight out of the wire buffer leave far less garbage behind per row, so there's less for the GC to clean up in
the first place.

### Batteries Included

Speed and memory aside, PostgreJS is also the most complete driver of the three: a dynamic `sql` tag for
composable, parameterized SQL, per-query type mapping, and TC39 Explicit Resource Management (`using`) support are
unique to it, alongside a feature set most drivers spread across several add-on packages - connection pooling,
prepared statements, server-side cursors, LISTEN/NOTIFY, bulk `COPY` streams, logical replication, large objects,
two-phase commit, multi-host failover, and SCRAM channel binding - all in the one package, written in
strictly-typed TypeScript from the ground up.

### Bring Your Own ORM

PostgreJS is a driver, not a framework, so what you build on top of it stays your choice:

<!-- The same cards as the integrations section on postgrejs.com: each
     project's full logo, which carries its name, over the one-line
     description, linking to its integration page. HTML because GitHub and npm
     strip CSS.

     Each logo is two links, one per theme. GitHub hides a link whose href ends
     in #gh-dark-mode-only or #gh-light-mode-only according to its own theme
     setting; a <picture> would follow the OS theme instead, and npm moves its
     <img> out of the link. npm has no such rule and a light page, so the build
     drops the dark links from the README it publishes (support/npm-readme.mjs).

     Each row has a <tbody> of its own, so GitHub's tr:nth-child(2n) striping,
     which counts within the parent, never greys the second row. -->
<table>
  <tbody><tr>
    <td align="center" width="280" valign="top"><br>
      <a href="https://www.postgrejs.com/docs/integrations/sqb"><img src="https://www.postgrejs.com/img/sqb-full-light.svg" alt="SQB" height="40"></a><br><br>
      Panates' own multi-dialect ORM and query builder. Its PostgreSQL adapter is built directly on postgrejs.<br><br>
    </td>
    <td align="center" width="280" valign="top"><br>
      <a href="https://www.postgrejs.com/docs/integrations/joist"><img src="https://www.postgrejs.com/img/joist-full-light.svg" alt="Joist" height="40"></a><br><br>
      Joist 2.5 ships a postgrejs driver of its own, which keeps each row undecoded until an entity reads it.<br><br>
    </td>
    <td align="center" width="280" valign="top"><br>
      <h3><a href="https://www.postgrejs.com/docs/integrations/kysely"><img src="https://www.postgrejs.com/img/kysely-logo.svg" alt="" height="40" align="absmiddle"></a>&nbsp;Kysely</h3>
      A type-safe SQL query builder. Run it on postgrejs instead of pg with a drop-in dialect.<br><br>
    </td>
  </tr></tbody>
  <tbody><tr>
    <td align="center" width="280" valign="top"><br>
      <a href="https://www.postgrejs.com/docs/integrations/drizzle"><img src="https://www.postgrejs.com/img/drizzle-logo-light.svg" alt="Drizzle ORM" height="34"></a><br><br>
      A lightweight TypeScript ORM: schema, relational queries and migrations on postgrejs.<br><br>
    </td>
    <td align="center" width="280" valign="top"><br>
      <a href="https://www.postgrejs.com/docs/integrations/typeorm"><img src="https://www.postgrejs.com/img/typeorm-full-light.svg" alt="TypeORM" height="40"></a><br><br>
      A pg-compatible facade. Bring postgrejs to TypeORM by changing one line.<br><br>
    </td>
    <td align="center" width="280" valign="top"><br>
      <a href="https://www.postgrejs.com/docs/integrations/prisma"><img src="https://www.postgrejs.com/img/prisma-full-light.svg" alt="Prisma" height="40"></a><br><br>
      A driver adapter. Run a Prisma schema on postgrejs instead of pg.<br><br>
    </td>
  </tr></tbody>
</table>

Each adapter hands the compiled SQL straight to this client, with no `pg` left anywhere in the chain, and each is
compared query by query against the driver it replaces - and, where the project ships a suite of its own, run
against that too. So adopting one is a change to how the connection is created and nothing else.

Joist's is the Joist project's own, and uses `RowDecoder` to leave each cell undecoded until an entity reads it.
Codegen and migrations there still run on `pg`, though the runtime does not.

### OpenTelemetry Instrumentation

Every query, prepared statement, pipeline, cursor fetch, `COPY`, transaction command, connection attempt and pool
checkout is published on Node's `diagnostics_channel`, and nothing is published while nobody listens.
[`postgrejs-otel`](https://github.com/panates/postgrejs/tree/main/packages/otel) turns those events into OpenTelemetry
spans that follow the stable database semantic conventions, and records the database client metrics: operation
duration, returned rows, and the pool's connections, waiting callers, wait time and timeouts. It patches nothing, so
import order and bundling make no difference, and it runs on Node.js and Bun.

```ts
import { NodeSDK } from '@opentelemetry/sdk-node';
import { PostgrejsInstrumentation } from 'postgrejs-otel';

new NodeSDK({ instrumentations: [new PostgrejsInstrumentation()] }).start();
```

A cursor's `FETCH` spans link back to the query that opened the cursor, and an optional SQL comment carries the trace
context to the server, where it shows up in `pg_stat_activity` and the server logs.

### Runs Where You Run

<!-- Same card shape as the adapters above, for the same reason: GitHub strips CSS, and a table
     is the one layout that survives everywhere the README is read. -->
<table>
  <tr>
    <td align="center" width="230" valign="top">
      <a href="https://www.postgrejs.com/docs/getting-started/benchmarks"><img src="https://www.postgrejs.com/img/nodejs-logo.svg" alt="Node.js" height="46"></a><br><br>
      <b><a href="https://www.postgrejs.com/docs/getting-started/benchmarks">Node.js</a></b><br>
    </td>
    <td align="center" width="230" valign="top">
      <a href="https://www.postgrejs.com/docs/getting-started/benchmarks-bun"><img src="https://www.postgrejs.com/img/bun-logo.svg" alt="Bun" height="46"></a><br><br>
      <b><a href="https://www.postgrejs.com/docs/getting-started/benchmarks-bun">Bun</a></b><br>
    </td>
    <td align="center" width="230" valign="top">
      <a href="https://www.postgrejs.com/docs/guides/cloudflare-workers"><img src="https://www.postgrejs.com/img/cloudflare-logo.svg" alt="Cloudflare Workers" height="46"></a><br><br>
      <b><a href="https://www.postgrejs.com/docs/guides/cloudflare-workers">Cloudflare Workers</a></b><br>
    </td>
  </tr>
</table>

Node and Bun run **the same test suite** in CI on every push - Node across 22, 24 and 26 against PostgreSQL 12, 16
and 18, Bun against 18 - so neither is a target that merely ought to work. Workers is not in that matrix yet: it
was measured by hand against PostgreSQL 18, a plain connection and a TLS one, and what the runtime does and does not
allow is written down in [docs/CLOUDFLARE-WORKERS.md](docs/CLOUDFLARE-WORKERS.md).

## Installation

```bash
$ npm install postgrejs --save
```

## Documentation

### Please read the [documentation](https://www.postgrejs.com/) for detailed usage

Upgrading from 3.5? See [docs/MIGRATION-v3.5-to-v3.6.md](docs/MIGRATION-v3.5-to-v3.6.md) - `query()` no longer stops at
100 rows, and `fetchAsString` now returns the server's own text.

## Library Overview

- **Language:** Pure JavaScript, with no native/binary dependencies to compile or ship.
- **Strictly typed:** Written entirely in TypeScript, with types shipped alongside the package.
- **Modern module format:** Ships as ESM; Node 22.12+ can `require()` it from CommonJS code as well.
- **Promise-based API:** Every asynchronous operation returns a promise - no callbacks to wrangle.
- **Rigorously tested:** A test suite covering the wire protocol, every data type, and connection-handling edge case,
  run on every push against PostgreSQL 12 through 18.

## Feature Comparison

How PostgreJS compares to [`pg`](https://github.com/brianc/node-postgres) (node-postgres) and
[`postgres`](https://github.com/porsager/postgres) (postgres.js). Every row was checked against the libraries' own
source rather than their documentation — versions compared: **PostgreJS 3.4.0, pg 8.23.0, postgres.js 3.4.9**. ✅ built
in · 🟡 partial or needs a separate package · ❌ not supported.

| Feature                           |       PostgreJS        |          pg           |   postgres.js    |
|:---------------------------------|:----------------------:|:-------------------:|:----------------:|
| ***Packaging***                   |                        |                       |                  |
| Packages to install               |           1            |    4 <sup>1</sup>     |        1         |
| Module system                     |          ESM           |        ESM/CJS        |     ESM/CJS      |
| Language                          |           TS           |    JS <sup>2</sup>    | JS <sup>3</sup>  |
| Cloudflare Workers                |    ✅ <sup>28</sup>    |   🟡 <sup>29</sup>    | ✅ <sup>30</sup> |
| ***Wire protocol***               |                        |                       |                  |
| Protocol version                  |          3.2           |          3.0          |       3.0        |
| Simple Query protocol             |           ✅           |          ✅           |        ✅        |
| Extended Query protocol           |           ✅           |          ✅           |        ✅        |
| Text wire format                  |           ✅           |          ✅           |        ✅        |
| Binary wire format                |           ✅           |    🟡 <sup>4</sup>    | ❌ <sup>5</sup>  |
| Per-column format selection       |           ✅           |          ❌           |        ❌        |
| Long cancel key (opt-in)          |           ✅           |          ❌           |        ❌        |
| Legacy Function Call protocol     |           ✅           |          ❌           |        ❌        |
| Graceful protocol renegotiation   |           ✅           |          ❌           |        ❌        |
| ***High-level API***              |                        |                       |                  |
| Object and array row modes        |           ✅           |          ✅           |        ✅        |
| Dynamic SQL helpers               |      ✅ `sql` tag      |          ❌           |        ✅        |
| Per-query type mapping            |           ✅           |    ❌ <sup>6</sup>    | ❌ <sup>6</sup>  |
| Query cancellation                |     ✅ AbortSignal     |          ✅           |        ✅        |
| Per-query timeout                 |     ✅ AbortSignal     |          ✅           | ❌ <sup>7</sup>  |
| Reference counters                | Connection / Statement |          ❌           |        ❌        |
| Caller kept in async error stacks |           ✅           |    🟡 <sup>8</sup>    | 🟡 <sup>9</sup>  |
| Error located in the SQL text     |    ✅ line and mark    |       🟡 offset       |    🟡 offset     |
| TC39 Explicit Resource Management |           ✅           |          ❌           |        ❌        |
| ***Querying***                    |                        |                       |                  |
| Query parameters                  |           ✅           |          ✅           |        ✅        |
| Parameter type casting            |           ✅           |   🟡 <sup>10</sup>    |        ✅        |
| Prepared statements <sup>24</sup> |     ✅ automatic      |      ✅ manual       |   ✅ automatic   |
| Statement-level rollback <sup>25</sup> |     ✅ automatic      |          ❌           |    🟡 manual     |
| Scoped transaction helper <sup>26</sup> |     ✅ nests      |          ❌           |        ✅        |
| Batch execution <sup>21</sup>     |           ✅           |          ❌           |        ❌        |
| Multi-statement round trip <sup>23</sup> |     ✅     |          ❌           |        ❌        |
| Multi-statement scripts           |           ✅           |          ✅           |        ✅        |
| Server-side cursors               |           ✅           |   🟡 <sup>11</sup>    |        ✅        |
| `COPY TO` / `COPY FROM`           |           ✅           |   🟡 <sup>12</sup>    |        ✅        |
| Binary COPY encoding <sup>22</sup> |           ✅           |          ❌           |        ❌        |
| Row count after a COPY            |           ✅           |          ✅           |        ❌        |
| ***Transaction management***      |                        |                       |                  |
| Transaction API                   |           ✅           |          ❌           |        ✅        |
| Savepoints                        |           ✅           |          ❌           |        ✅        |
| Two-phase commit API              |           ✅           |          ❌           | 🟡 <sup>13</sup> |
| ***Session management***          |                        |                       |                  |
| Built-in connection pool          |           ✅           |          ✅           |   ✅ implicit    |
| Pipelining on one connection      |     ✅ opt-in/call     |   ✅ opt-in/client    |   ✅ automatic   |
| Graceful shutdown                 |           ✅           |   ❌ <sup>14</sup>    |        ✅        |
| Multiple hosts                    |           ✅           |          ❌           |        ✅        |
| LISTEN/NOTIFY                     |           ✅           |   🟡 <sup>15</sup>    |        ✅        |
| ***Data types***                  |                        |                       |                  |
| Text encoders                     |          125           | generic <sup>16</sup> |        14        |
| Text decoders                     |          125           |          44           | 12 <sup>17</sup> |
| Binary encoders                   |   121 <sup>27</sup>    |          ❌           |        ❌        |
| Binary decoders                   |          125           |          16           |        ❌        |
| Multidimensional arrays           |       ✅ binary        | 🟡 text <sup>18</sup> |     🟡 text      |
| ***Security***                    |                        |                       |                  |
| SSL/TLS                           |           ✅           |          ✅           |        ✅        |
| Direct TLS negotiation (PG17)     |           ✅           |          ✅           |        ✅        |
| Cleartext, MD5, SCRAM-SHA-256     |           ✅           |          ✅           |        ✅        |
| SCRAM channel binding (`-PLUS`)   |       ✅ default       |       ✅ opt-in       |        ❌        |
| ***Beyond querying***             |                        |                       |                  |
| Logical replication               |           ✅           |   🟡 <sup>19</sup>    |        ✅        |
| Large object API                  |           ✅           |          ❌           |        ✅        |
| Native libpq bindings             |           ❌           |   🟡 <sup>20</sup>    |        ❌        |
| ***Observability***               |                        |                       |                  |
| `diagnostics_channel` events      |    ✅ <sup>31</sup>    |          ❌           | ✅ <sup>32</sup> |
| OpenTelemetry instrumentation     |   ✅ `postgrejs-otel`   |   🟡 <sup>33</sup>    | ❌ <sup>34</sup> |
| Spans beyond queries and connects |  ✅ <sup>35</sup>  |          ❌           |        ❌        |
| Database client metrics           |  ✅ operation and pool  |   🟡 <sup>36</sup>    |        ❌        |
| Trace context in the SQL comment  |           ✅           |          🟡           |        ❌        |

- <sup>1</sup> What it takes to reach the feature set above. PostgreJS and postgres.js ship everything in the one
  package you import; `pg` needs `pg-cursor` for cursors, `pg-query-stream`
  for row streams and `pg-copy-streams` for COPY, each installed and versioned separately.
- <sup>2</sup> Types come from the separate `@types/pg`; only the `pg-protocol` and
  `pg-connection-string` sub-packages are written in TypeScript.
- <sup>3</sup> Ships a hand-maintained `.d.ts`.
- <sup>4</sup> Results only - parameters are always stringified. Opt-in per query or per client, and all columns at
  once. No binary parser is registered for `bytea`, and binary arrays decode only `int4`, `int8` and `text` elements.
- <sup>5</sup> Both format-code counts are hardcoded to zero and parameters are stringified, so everything on the wire
  is text.
- <sup>6</sup> Global or per-client (pg) and per-instance (postgres.js), but not per query.
- <sup>7</sup> Connection-level timeouts only.
- <sup>8</sup> Restored by calling `Error.captureStackTrace` from the promise's own rejection handler, where the
  synchronous stack is already gone - the caller's frames come from Node's async stack traces, so they survive an
  awaited chain but not a `.then()`/`.catch()` one, and the callback API gets none at all.
- <sup>9</sup> Captured at the tagged template, four frames deep; `sql.unsafe()` gets none.
- <sup>10</sup> A `types` array on the query config does reach the Parse message, but the same field doubles as the
  result parser override, so any row-returning query throws inside pg's own handler. Verified usable only for statements
  that return no rows (pg 8.23.0).
- <sup>11</sup> Core has the row-limit primitive; the cursor and stream APIs are separate packages.
- <sup>12</sup> The core `Query` refuses COPY IN; `pg-copy-streams` is required.
- <sup>13</sup> `sql.prepare(name)` runs `PREPARE TRANSACTION` inside `begin`, but there is no helper for the other
  half - `COMMIT PREPARED` / `ROLLBACK PREPARED` have to be written as raw SQL.
- <sup>14</sup> `end()` destroys the socket when a query is still in flight, so the query is aborted rather than
  awaited; only a client in pipeline mode waits for drain first.
- <sup>15</sup> On the client only - the pool does not forward notifications.
- <sup>16</sup> pg has no per-OID text encoders: a parameter is converted by its
  JavaScript type rather than by the type it is going into, so there is no
  count to give.
- <sup>17</sup> Plus every array type, whose OIDs are read from the catalog when a
  connection opens rather than registered ahead of time.
- <sup>18</sup> Its binary array decoder covers only `int4`, `int8` and `text` elements, so everything else falls back to
  text anyway.
- <sup>19</sup> A connection flag exists, but nothing decodes the stream.
- <sup>20</sup> `pg-native` swaps the pure JavaScript protocol for libpq, and its own
  documentation lists what stops working with it: `pg-cursor`, `pg-query-stream` and
  `pg-copy-streams` all "operate directly on the binary stream and therefore are
  incompatible" - so server-side cursors, row streaming and COPY are what it costs.
- <sup>21</sup> One statement executed over many parameter sets behind a single `Sync`, each set's row count reported
  separately. pg and postgres.js both emit a `Sync` per execution (`syncBuffer` in pg's `connection.js`, the
  concatenated `ExecuteUnnamed` in postgres.js's), so a burst of executions costs a server round of implicit-transaction
  bookkeeping each, pipelined or not. Writing one multi-row statement by hand is a separate approach that all three
  support, and both PostgreJS and postgres.js ship value builders for it - it is faster still where it applies, but it
  is one statement rather than many, and PostgreSQL's 65535-parameter ceiling bounds it.
- <sup>22</sup> Turning JavaScript rows into the binary `COPY` format, rather than carrying a payload the caller
  formatted first. All three can carry a `COPY` stream, but only as bytes: postgres.js hands back a `Writable` that
  wraps raw chunks in `CopyData`, and pg reaches the same point through `pg-copy-streams`. Producing the format needs a
  binary encoder per type, which neither driver has - see Binary encoders above, where the same gap shows up for query
  parameters. The capability is still reachable with pg through a third package, `pg-copy-streams-binary`, which brings
  its own encoders; postgres.js has no equivalent.
- <sup>23</sup> Several different statements sent under one `Sync`, so they cost a single round of the server's
  transaction bookkeeping rather than one each, arrive as one implicit transaction, and come back as per-statement
  results. Distinct from the Pipelining row above, which is about not waiting between queries: all three do that, and
  all three still close every statement with its own `Sync` - pg sends one immediately after each Execute
  (`query.js`), and postgres.js concatenates Execute and Sync into a single constant (`ExecuteUnnamed`). Atomicity on
  its own is reachable anywhere with an explicit `BEGIN`/`COMMIT`; what that cannot recover is the round trip, since
  the per-statement Syncs and two extra statements remain.
- <sup>24</sup> Whether a repeated query is parsed again every time. PostgreJS and postgres.js both keep a per-connection
  cache keyed on the SQL and reuse a server-side statement, so a repeat costs `Bind`/`Execute` rather than
  `Parse`/`Bind`/`Describe`/`Execute`; pg prepares only the statements you name yourself (`query.js`: "named queries
  must always be prepared"), with nothing caching by SQL text. The two automatic ones differ in when they start:
  postgres.js on first sight, PostgreJS on the second use, which leaves a genuinely one-shot query at its unprepared
  cost. Both default to on and both take `prepare: false`, which matters for PgBouncer in transaction pooling mode
  before 1.21, where a named statement does not survive to the next call.
- <sup>25</sup> Whether one failed statement inside a transaction leaves the rest of the block runnable. PostgreJS puts
  every statement under a savepoint of its own by default (`rollbackOnError`), rolling back to it when the statement
  fails, and carries the `SAVEPOINT`/`RELEASE` pair inside the statement's own round trip rather than paying a round
  trip for each. postgres.js has savepoints, but as a scope the caller opens around a callback (`savepoint(name, fn)`
  in `src/index.js`), so a statement is protected only where someone wrapped it; pg has no savepoint handling in
  `lib/` at all, so a failed statement leaves the block aborted until the caller rolls back themselves.
- <sup>26</sup> Whether the library runs a callback inside a transaction for you, committing or rolling back on the way
  out. PostgreJS has `transaction(fn)` on both a connection and the pool, and a call made inside one already open takes
  a savepoint, so nesting needs nothing from the caller. postgres.js has `sql.begin(fn)` (`src/index.js`), where a
  nested scope is opened explicitly with `sql.savepoint(fn)` instead. pg has no such helper in `lib/` - `BEGIN` and
  `COMMIT` are statements the caller sends, and getting a transaction onto one connection is the caller's problem too.
- <sup>27</sup> Every registered type but `tsvector` and `tsquery`, which have none deliberately: the server's own
  input parser is what sorts and deduplicates a vector and what defines a query's grammar, so encoding either here
  would make the same text mean one thing written as a literal and another bound as a parameter. They are sent as
  text instead, which is exact.
- <sup>28</sup> PostgreJS runs on workerd under `nodejs_compat` with nothing installed and no build of its own.
  Measured end to end: a plain connection against PostgreSQL 18, and a TLS one against a managed PostgreSQL 18 whose
  certificate comes from Let's Encrypt - the same server refusing the connection outright (`28000 connection is
  insecure`) when `sslmode` is dropped, which is what makes the encrypted one mean something. TLS opens a socket of
  the runtime's own and upgrades it with `startTls()`, since `tls.connect({ socket })` is not something workerd can
  carry out. Three limits are the runtime's, and all three libraries have them: `ca`, `cert` and `rejectUnauthorized`
  have nowhere to go (workerd's TLS options are `{ expectedServerHostname?: string }`, so a self-signed certificate
  cannot be trusted and a local server cannot be reached over TLS at all); `sslnegotiation=direct` cannot announce the
  `postgresql` ALPN protocol, and is refused by name here; and SCRAM channel binding has no server certificate to bind
  to, so `channelBinding: 'require'` is refused and the default `prefer` authenticates without it. Hyperdrive is the
  other way in, terminating TLS in Cloudflare's own network - checked here against its binding. See
  [docs/CLOUDFLARE-WORKERS.md](docs/CLOUDFLARE-WORKERS.md).
- <sup>29</sup> pg reaches workerd through `pg-cloudflare`, a separate package it carries as an optional dependency
  and selects at runtime (`lib/stream.js`, on `navigator.userAgent`). That package wraps `cloudflare:sockets` and
  upgrades with its own `startTls()`, so TLS is available where PostgreJS's is not - at the cost of a second package
  and of nothing happening at all if it was not installed.
- <sup>30</sup> postgres.js ships a build for the runtime: a `workerd` condition in `exports` pointing at `cf/`, whose
  polyfills shim `net`/`tls` onto `cloudflare:sockets` including `startTls({ servername })`. One package, the right
  code chosen by the resolver, TLS included.
- <sup>31</sup> Nine tracing channels (query, execute, prepare, prepared statement execute, pipeline, cursor
  fetch, COPY, connect, pool acquire) and five plain ones for pool activity, all under `postgrejs:`. Nothing is
  published while nobody subscribes.
- <sup>32</sup> Added in postgres.js 4.1.0, newer than the 3.4.9 the rest of the table compares: tracing channels
  for queries, connects and `sql.begin` transactions, and plain ones for pool events and notices.
- <sup>33</sup> `@opentelemetry/instrumentation-pg`, a separate package from the OpenTelemetry project. It wraps
  `Client.query`, `Client.connect` and the pool's `connect`, so prepared statements, transaction commands, cursor
  reads and COPY streams show up only as whatever `client.query()` call started them. Its SQL comment is skipped for
  named statements.
- <sup>34</sup> No instrumentation package; its README shows how to build query spans from the
  `postgres:query` channel by hand.
- <sup>35</sup> Separate spans for statement preparation, prepared statement execution, transaction commands,
  pipelines, each cursor fetch (linked to the query that opened the cursor) and COPY.
- <sup>36</sup> `db.client.operation.duration` and three pool metrics: connection count, maximum and pending
  requests. PostgreJS also records returned rows, timeouts, the minimum idle setting, and the time to create,
  wait for and use a connection.

## Benchmarks

PostgreJS implements the full PostgreSQL wire protocol from scratch, with no dependency on `pg`/libpq.
[`docs/BENCHMARKS.md`](docs/BENCHMARKS.md) compares it against `pg` (node-postgres) and `postgres` (postgres.js)
across connection setup, simple/prepared queries, mixed-type decoding, bulk fetches, cursor streaming and pool
concurrency, each library run through its own idiomatic fast path. The numbers there are reproducible on your own
machine via `pnpm run bench` against the repo's own
`support/docker/docker-compose.yml` Postgres instance; see [`packages/postgrejs/benchmark/README.md`](./packages/postgrejs/benchmark/README.md) for details.

The same suite runs under Bun via `pnpm run bench:bun`, where it also measures Bun's own built-in `Bun.sql` client as
a fourth library. Those results live in [`docs/BENCHMARKS-bun.md`](docs/BENCHMARKS-bun.md) and are deliberately kept
in a separate report rather than merged into the Node one: GC instrumentation, cursor streaming and binary-format
control all differ enough between the two runtimes that a single table would conflate a library difference with a
runtime difference.

Both reports list libraries in a fixed order rather than fastest-first, and mark every result statistically tied
with the leader rather than bolding a lone winner - several scenarios separate the leading drivers by about a
percent, which is less than the run-to-run spread of the measurement itself.

## Support

You can report bugs and discuss features on the [GitHub issues](https://github.com/panates/postgrejs/issues) page When
you open an issue please provide version of NodeJS and PostgreSQL server.

## Runtime Compatibility

- Node.js >= 22.x
- Bun - the same test suite runs under Bun in CI against PostgreSQL 18 on every push, so Bun is a supported target
  rather than an untested coincidence. (Coverage is collected on the Node matrix only: `c8` instruments V8's
  coverage APIs, which JavaScriptCore doesn't have.)
- Cloudflare Workers - with `nodejs_compat`, and without TLS: the runtime has no way to trust a server
  certificate, so a database behind TLS is reached through Hyperdrive instead. See
  [docs/CLOUDFLARE-WORKERS.md](docs/CLOUDFLARE-WORKERS.md).

## License

PostgreJS is available under the [BSD 3-Clause](LICENSE) license.

[npm-image]: https://img.shields.io/npm/v/postgrejs
[npm-url]: https://npmjs.org/package/postgrejs
[downloads-image]: https://img.shields.io/npm/dm/postgrejs.svg
[downloads-url]: https://npmjs.org/package/postgrejs
[ci-test-image]: https://github.com/panates/postgrejs/actions/workflows/test.yml/badge.svg
[ci-test-url]: https://github.com/panates/postgrejs/actions/workflows/test.yml
[coveralls-image]: https://img.shields.io/coveralls/panates/postgrejs/dev.svg
[coveralls-url]: https://coveralls.io/r/panates/postgrejs

---
_Source: https://npm.io/package/postgrejs · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
