# JavaScript PostgreSQL libraries

JavaScript PostgreSQL libraries connect Node.js and serverless code to a PostgreSQL database and run SQL queries. A client keeps a pool of open connections and sends each query's values as parameters separate from the SQL text. These libraries let apps and backend services read and write relational data without opening a new database connection for every request.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [pg](#node-postgres) | 372.0M | 13.2K | Sep 2026 | MIT |
| [postgres](#postgres-js) | 145.4M | 8.8K | Nov 2026 | Unlicense |
| [@neondatabase/serverless](#neon) | 28.6M | 557 | Nov 2026 | MIT |
| [pg-promise](#pg-promise) | 3.6M | 3.5K | Nov 2026 | MIT |
| [pg-native](#pg-native) | 1.3M | Not on GitHub | Sep 2026 | MIT |
| [slonik](#slonik) | 1.1M | Not on GitHub | Nov 2026 | BSD-3-Clause |
| [@databases/pg](#databases-pg) | 103.5K | Not on GitHub | Aug 2026 | MIT |
| [serverless-postgres](#serverless-postgres) | 80.2K | Not on GitHub | May 2025 | MIT |

Downloads: npm, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[node-postgres](#node-postgres) has the most monthly downloads in this comparison, at 372.0M.

## Capabilities

| Library | SQL template tag | Managed connection pool | Built-in HTTPS queries |
| --- | --- | --- | --- |
| [pg](#node-postgres) | No | Yes | No |
| [postgres](#postgres-js) | Yes | Yes | No |
| [@neondatabase/serverless](#neon) | Yes | Yes | Yes |
| [pg-promise](#pg-promise) | No | Yes | No |
| [pg-native](#pg-native) | No | No | No |
| [slonik](#slonik) | Yes | Yes | No |
| [@databases/pg](#databases-pg) | Yes | Yes | No |
| [serverless-postgres](#serverless-postgres) | No | No | No |

## Libraries

### pg

[GitHub](https://github.com/brianc/node-postgres) · [npm](https://www.npmjs.com/package/pg) · [Docs](https://cdn.jsdelivr.net/npm/pg@8.23.1/README.md)

Connects Node.js applications to PostgreSQL through query and connection APIs.

- Downloads / mo: 372.0M
- Stars: 13.2K
- Last release: 8.23.1
- License: MIT
- Capabilities: [From the pg docs](https://cdn.jsdelivr.net/npm/pg@8.23.1/README.md)

**Strengths**

- **Pools reusable connections.** Use Pool for a shared set of database connections.
- **Caches named prepared statements.** Name a query to reuse its plan on the same connection.

**Watch out for**

- **Transactions need one checked-out client.** Run all transaction statements on the same borrowed client.
- **Borrowed clients must be released.** Return clients to the pool even after query errors.

```sh
npm install pg@8.23.1
```

**drizzle-team/drizzle-orm** (36.3K stars)

[drizzle-team/drizzle-orm](https://github.com/drizzle-team/drizzle-orm) 

```javascript
async execute(placeholderValues: Record<string, unknown> | undefined = {}): Promise<T['execute']> {
		return tracer.startActiveSpan('drizzle.execute', async () => {
			const params = fillPlaceholders(this.params, placeholderValues);

			this.logger.logQuery(this.rawQueryConfig.text, params);

			const { fields, rawQueryConfig: rawQuery, client, queryConfig: query, joinsNotNullableMap, customResultMapper } =
				this;
			if (!fields && !customResultMapper) {
				return tracer.startActiveSpan('drizzle.driver.execute', async (span) => {
					span?.setAttributes({
						'drizzle.query.name': rawQuery.name,
						'drizzle.query.text': rawQuery.text,
						'drizzle.query.params': JSON.stringify(params),
					});
					return this.queryWithCache(rawQuery.text, params, async () => {
						return await client.query(rawQuery, params);
					});
				});
			}

			const result = await tracer.startActiveSpan('drizzle.driver.execute', (span) => {
				span?.setAttributes({
					'drizzle.query.name': query.name,
					'drizzle.query.text': query.text,
					'drizzle.query.params': JSON.stringify(params),
				});
				return this.queryWithCache(query.text, params, async () => {
					return await client.query(query, params);
				});
			});

			return tracer.startActiveSpan('drizzle.mapResponse', () => {
				return customResultMapper
					? customResultMapper(result.rows)
					: result.rows.map((row) => mapResultRow<T['execute']>(fields!, row, joinsNotNullableMap));
			});
		});
	}

```

[drizzle-orm/src/node-postgres/session.ts](https://github.com/drizzle-team/drizzle-orm/blob/3bcb6a27ec1f4f1602aeeb0af2f5aec61010d72d/drizzle-orm/src/node-postgres/session.ts#L133-L171) · [More projects using pg →](https://dashboard.exa.ai/playground/search?q=JavaScript%20applications%20using%20pg%20PostgreSQL%20clients%20with%20pooled%20queries%20prepared%20parameters%20and%20interactive%20transactions&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```javascript
import { Client } from 'pg';
const client = new Client();
await client.connect();
console.log((await client.query('SELECT 1 AS one')).rows);
await client.end();

```

From [README.md](https://cdn.jsdelivr.net/npm/pg@8.23.1/README.md)

### postgres

[GitHub](https://github.com/porsager/postgres) · [npm](https://www.npmjs.com/package/postgres) · [Docs](https://cdn.jsdelivr.net/npm/postgres@4.1.1/README.md)

Sends SQL template values separately through PostgreSQL protocol parameters.

- Downloads / mo: 145.4M
- Stars: 8.8K
- Last release: 4.1.1
- License: Unlicense
- Capabilities: [From the postgres docs](https://cdn.jsdelivr.net/npm/postgres@4.1.1/README.md)

**Strengths**

- **Binds values through tagged templates.** Interpolate values in sql templates; the driver sends them separately.
- **Reserves connections for transactions.** Use sql.begin to keep a transaction on its own connection.

**Watch out for**

- **numeric and decimal return strings.** Choose explicit parsing for numeric and decimal database values.
- **Undefined values are rejected.** Pass null explicitly for missing values.

```sh
npm install postgres@4.1.1
```

**drizzle-team/drizzle-orm** (36.3K stars)

[drizzle-team/drizzle-orm](https://github.com/drizzle-team/drizzle-orm) 

```javascript
async execute(placeholderValues: Record<string, unknown> | undefined = {}): Promise<T['execute']> {
		return tracer.startActiveSpan('drizzle.execute', async (span) => {
			const params = fillPlaceholders(this.params, placeholderValues);

			span?.setAttributes({
				'drizzle.query.text': this.queryString,
				'drizzle.query.params': JSON.stringify(params),
			});

			this.logger.logQuery(this.queryString, params);

			const { fields, queryString: query, client, joinsNotNullableMap, customResultMapper } = this;
			if (!fields && !customResultMapper) {
				return tracer.startActiveSpan('drizzle.driver.execute', () => {
					return this.queryWithCache(query, params, async () => {
						return await client.unsafe(query, params as any[], {
							prepare: this.prepare,
						});
					});
				});
			}

			const rows = await tracer.startActiveSpan('drizzle.driver.execute', () => {
				span?.setAttributes({
					'drizzle.query.text': query,
					'drizzle.query.params': JSON.stringify(params),
				});
				return this.queryWithCache(query, params, async () => {
					return await client.unsafe(query, params as any[], {
						prepare: this.prepare,
					}).values();
				});
			});

			return tracer.startActiveSpan('drizzle.mapResponse', () => {
				return customResultMapper
					? customResultMapper(rows)
					: rows.map((row) => mapResultRow<T['execute']>(fields!, row, joinsNotNullableMap));
			});
		});
	}

```

[drizzle-orm/src/postgres-js/session.ts](https://github.com/drizzle-team/drizzle-orm/blob/3bcb6a27ec1f4f1602aeeb0af2f5aec61010d72d/drizzle-orm/src/postgres-js/session.ts#L39-L79) · [More projects using postgres →](https://dashboard.exa.ai/playground/search?q=JavaScript%20applications%20using%20postgres%20PostgreSQL%20clients%20with%20pooled%20queries%20prepared%20parameters%20and%20interactive%20transactions&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```javascript
import postgres from 'postgres';
const sql = postgres();
console.log(await sql`SELECT 1 AS one`);
await sql.end();

```

From [README.md](https://cdn.jsdelivr.net/npm/postgres@4.1.1/README.md)

### @neondatabase/serverless

[GitHub](https://github.com/neondatabase/serverless) · [npm](https://www.npmjs.com/package/@neondatabase/serverless) · [Docs](https://cdn.jsdelivr.net/npm/@neondatabase/serverless@1.2.1/README.md)

Runs PostgreSQL queries over HTTP or WebSockets in JavaScript runtimes.

- Downloads / mo: 28.6M
- Stars: 557
- Last release: 1.2.1
- License: MIT
- Capabilities: [From the @neondatabase/serverless docs](https://cdn.jsdelivr.net/npm/@neondatabase/serverless@1.2.1/README.md)

**Strengths**

- **Queries over HTTP requests.** Use neon for one-shot queries through fetch.
- **Supports interactive transactions over WebSockets.** Use Pool or Client for sessions and dependent transaction queries.

**Watch out for**

- **HTTP batches are not interactive.** Use WebSocket Pool or Client for session-dependent transactions.
- **Serverless pools need request-local cleanup.** Create, use, and close WebSocket clients inside the same request handler.

```sh
npm install @neondatabase/serverless@1.2.1
```

**drizzle-team/drizzle-orm** (36.3K stars)

[drizzle-team/drizzle-orm](https://github.com/drizzle-team/drizzle-orm) 

```javascript
async execute(placeholderValues: Record<string, unknown> | undefined = {}): Promise<T['execute']> {
		const params = fillPlaceholders(this.params, placeholderValues);

		this.logger.logQuery(this.rawQueryConfig.text, params);

		const { fields, client, rawQueryConfig: rawQuery, queryConfig: query, joinsNotNullableMap, customResultMapper } =
			this;
		if (!fields && !customResultMapper) {
			return await this.queryWithCache(rawQuery.text, params, async () => {
				return await client.query(rawQuery, params);
			});
		}

		const result = await this.queryWithCache(query.text, params, async () => {
			return await client.query(query, params);
		});

		return customResultMapper
			? customResultMapper(result.rows)
			: result.rows.map((row) => mapResultRow<T['execute']>(fields!, row, joinsNotNullableMap));
	}

```

[drizzle-orm/src/neon-serverless/session.ts](https://github.com/drizzle-team/drizzle-orm/blob/3bcb6a27ec1f4f1602aeeb0af2f5aec61010d72d/drizzle-orm/src/neon-serverless/session.ts#L139-L159) · [More projects using @neondatabase/serverless →](https://dashboard.exa.ai/playground/search?q=JavaScript%20applications%20using%20%40neondatabase/serverless%20PostgreSQL%20clients%20with%20pooled%20queries%20prepared%20parameters%20and%20interactive%20transactions&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```javascript
import { neon } from '@neondatabase/serverless';
const sql = neon(process.env.DATABASE_URL);
console.log(await sql`SELECT 1 AS one`);

```

From [README.md](https://cdn.jsdelivr.net/npm/@neondatabase/serverless@1.2.1/README.md)

### pg-promise

[GitHub](https://github.com/vitaly-t/pg-promise) · [npm](https://www.npmjs.com/package/pg-promise) · [Docs](https://cdn.jsdelivr.net/npm/pg-promise@12.8.0/README.md)

Checks query results with methods named for the expected row count.

- Downloads / mo: 3.6M
- Stars: 3.5K
- Last release: 12.8.0
- License: MIT
- Capabilities: [From the pg-promise docs](https://cdn.jsdelivr.net/npm/pg-promise@12.8.0/README.md)

**Strengths**

- **Checks expected result row counts.** Use result-specific methods to reject unexpected numbers of rows.
- **Reuses connections across related queries.** Group related queries in task; use tx for automatic transactions.

**Watch out for**

- **Brace placeholders conflict with templates.** Keep those placeholders in ordinary strings instead of JavaScript template literals.

```sh
npm install pg-promise@12.8.0
```

**Quickstart**

```javascript
import pgPromise from 'pg-promise';
const pgp = pgPromise();
const db = pgp(process.env.DATABASE_URL);
console.log(await db.one('SELECT 1 AS one'));
pgp.end();

```

From [Database.html](https://cdn.jsdelivr.net/npm/pg-promise@12.8.0/README.md) · [Find projects using pg-promise →](https://dashboard.exa.ai/playground/search?q=JavaScript%20applications%20using%20pg-promise%20PostgreSQL%20clients%20with%20pooled%20queries%20prepared%20parameters%20and%20interactive%20transactions&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

### pg-native

[GitHub](https://github.com/brianc/node-postgres) · [npm](https://www.npmjs.com/package/pg-native) · [Docs](https://cdn.jsdelivr.net/npm/pg-native@3.9.1/README.md)

Connects to PostgreSQL through native libpq with synchronous and callback query interfaces.

- Downloads / mo: 1.3M
- Last release: 3.9.1
- License: MIT
- Capabilities: [From the pg-native docs](https://cdn.jsdelivr.net/npm/pg-native@3.9.1/README.md)

```sh
npm install pg-native@3.9.1
```

**Quickstart**

```javascript
const Client = require('pg-native');
const client = new Client();
client.connectSync();
console.log(client.querySync('SELECT 1 AS one'));
client.end();

```

From [README.md](https://cdn.jsdelivr.net/npm/pg-native@3.9.1/README.md) · [Find projects using pg-native →](https://dashboard.exa.ai/playground/search?q=pg-native%20GitHub%20projects)

### slonik

[GitHub](https://github.com/gajus/slonik) · [npm](https://www.npmjs.com/package/slonik) · [Docs](https://cdn.jsdelivr.net/npm/slonik@49.13.0/README.md)

Builds PostgreSQL queries from SQL tokens, with assertions and transaction scoping.

- Downloads / mo: 1.1M
- Last release: 49.13.0
- License: BSD-3-Clause
- Capabilities: [From the slonik docs](https://cdn.jsdelivr.net/npm/slonik@49.13.0/README.md)

```sh
npm install slonik@49.13.0
```

**Sairyss/domain-driven-hexagon** (15.0K stars)

[Sairyss/domain-driven-hexagon](https://github.com/Sairyss/domain-driven-hexagon) 

```javascript
public async transaction<T>(handler: () => Promise<T>): Promise<T> {
    return this.pool.transaction(async (connection) => {
      this.logger.debug(
        `[${RequestContextService.getRequestId()}] transaction started`,
      );
      if (!RequestContextService.getTransactionConnection()) {
        RequestContextService.setTransactionConnection(connection);
      }

      try {
        const result = await handler();
        this.logger.debug(
          `[${RequestContextService.getRequestId()}] transaction committed`,
        );
        return result;
      } catch (e) {
        this.logger.debug(
          `[${RequestContextService.getRequestId()}] transaction aborted`,
        );
        throw e;
      } finally {
        RequestContextService.cleanTransactionConnection();
      }
    });
  }

```

[src/libs/db/sql-repository.base.ts](https://github.com/Sairyss/domain-driven-hexagon/blob/5c2d15a7e2d69e83dfddf28468ee9f30e02c30de/src/libs/db/sql-repository.base.ts#L205-L229) · [More projects using slonik →](https://dashboard.exa.ai/playground/search?q=slonik%20GitHub%20projects)

**Quickstart**

```javascript
import { createPool, sql } from 'slonik';
const pool = await createPool(process.env.DATABASE_URL);
console.log((await pool.query(sql.unsafe`SELECT 1 AS one`)).rows);
await pool.end();

```

From [index.d.ts](https://cdn.jsdelivr.net/npm/slonik@49.13.0/dist/index.d.ts)

### @databases/pg

[GitHub](https://github.com/ForbesLindesay/atdatabases) · [npm](https://www.npmjs.com/package/@databases/pg) · [Docs](https://cdn.jsdelivr.net/npm/@databases/pg@6.1.0/README.md)

Runs SQL-tagged queries through a PostgreSQL connection pool with transaction scopes and streaming.

- Downloads / mo: 103.5K
- Last release: 6.1.0
- License: MIT
- Capabilities: [From the @databases/pg docs](https://cdn.jsdelivr.net/npm/@databases/pg@6.1.0/README.md)

```sh
npm install @databases/pg@6.1.0
```

**oskardudycz/EventSourcing.NodeJS** (508 stars)

[oskardudycz/EventSourcing.NodeJS](https://github.com/oskardudycz/EventSourcing.NodeJS) 

```javascript
export const getPostgres = (): ConnectionPool => {
  if (!db) {
    if (!config.postgres.connectionString) {
      throw new Error(
        'Postgres connection string not set. Please define "DATABASE_URL" environment variable',
      );
    }

    if (!config.postgres.schemaName) {
      throw new Error(
        'Postgres schema name string not set. Please define "DATABASE_SCHEMA" environment variable',
      );
    }

    db = createConnectionPool({
      connectionString: config.postgres.connectionString,
      schema: config.postgres.schemaName,
    });
  }

  return db;
};

```

[samples/from_crud_to_eventsourcing/src/core/postgres.ts](https://github.com/oskardudycz/EventSourcing.NodeJS/blob/0ca156437ca6fed3fa8ac23fc33a8abbfd4699b6/samples/from_crud_to_eventsourcing/src/core/postgres.ts#L14-L35) · [More projects using @databases/pg →](https://dashboard.exa.ai/playground/search?q=%40databases/pg%20GitHub%20projects)

**Quickstart**

```javascript
import createConnectionPool, { sql } from '@databases/pg';
const db = createConnectionPool({ connectionString: process.env.DATABASE_URL });
console.log(await db.query(sql`SELECT 1 AS one`));
await db.dispose();

```

From [index.d.ts](https://cdn.jsdelivr.net/npm/@databases/pg@6.1.0/lib/index.d.ts)

### serverless-postgres

[GitHub](https://github.com/MatteoGioioso/serverless-pg) · [npm](https://www.npmjs.com/package/serverless-postgres) · [Docs](https://cdn.jsdelivr.net/npm/serverless-postgres@2.1.2/README.md)

Wraps a single pg client for serverless functions with connection retry and backoff.

- Downloads / mo: 80.2K
- Last release: 2.1.2
- License: MIT
- Capabilities: [From the serverless-postgres docs](https://cdn.jsdelivr.net/npm/serverless-postgres@2.1.2/README.md)

```sh
npm install serverless-postgres@2.1.2
```

**EqualifyEverything/equalify** (146 stars)

[EqualifyEverything/equalify](https://github.com/EqualifyEverything/equalify) 

```javascript
export const migrateStaleBlockers = async () => {
    const body = (event.body as any) || {};
    const phase: string = body.phase;
    const auditId: string | undefined = body.auditId;
    const dryRun: boolean = !!body.dryRun;

    if (!phase) {
        return {
            statusCode: 400,
            body: JSON.stringify({ error: "phase is required: 'ignored_hashes' | 'scan_counts' | 'move_stale'" }),
        };
    }

    await db.connect();
    const t0 = Date.now();

    try {
        if (phase === "ignored_hashes") {
            // Backfill content_hash_id on existing ignored_blockers rows by joining
            // back to blockers. Safe to re-run (NULL-only update).
            const auditFilter = auditId ? `AND ib.audit_id = $1` : "";
            const values = auditId ? [auditId] : [];

            const result = await db.query({
                text: `
                    ${dryRun ? "SELECT COUNT(*) AS updated FROM" : "UPDATE"} ignored_blockers ib
                    ${dryRun ? "JOIN" : "SET content_hash_id = b.content_hash_id FROM"} blockers b
                    ${dryRun ? "ON" : "WHERE"} ib.blocker_id = b.id
                    AND ib.content_hash_id IS NULL
                    ${auditFilter}
                `,
                values,
            });

            const updated = dryRun ? result.rows[0]?.updated : result.rowCount;
            await db.clean();
            return {
                statusCode: 200,
                body: JSON.stringify({ phase, dryRun, updated, ms: Date.now() - t0 }),
            };
        }

        if (phase === "scan_counts") {
            // Backfill blocker_count + equalified_count on every scan row from the
            // active blockers table. MUST run BEFORE any blockers are moved to stale.
            const auditFilter = auditId ? `WHERE s.audit_id = $1` : "";
            const values = auditId ? [auditId] : [];

            if (dryRun) {
                const result = await db.query({
                    text: `SELECT COUNT(*) AS scan_count FROM scans s ${auditFilter}`,
                    values,
                });
                await db.clean();
                return {
                    statusCode: 200,
                    body: JSON.stringify({ phase, dryRun, scansToUpdate: result.rows[0]?.scan_count, ms: Date.now() - t0 }),
                };
            }

            const result = await db.query({
                text: `
                    UPDATE scans s SET
                        blocker_count = COALESCE((SELECT COUNT(*) FROM blockers WHERE scan_id = s.id), 0),
                        equalified_count = COALESCE((SELECT COUNT(*) FROM blockers WHERE scan_id = s.id AND equalified = true), 0)
                    ${auditFilter}
                `,
                values,
            });

            await db.clean();
            return {
                statusCode: 200,
                body: JSON.stringify({ phase, scansUpdated: result.rowCount, ms: Date.now() - t0 }),
            };
        }

        if (phase === "move_stale") {
            // Move blockers for non-latest scans (per audit) from blockers → stale_blockers.
            // Batched: process N stale scans per Lambda invocation. Caller re-invokes until done.
            const scansPerBatch: number = body.scansPerBatch ?? 5;
            const maxBatches: number = body.maxBatches ?? 20;
            // Stop starting new batches with this much headroom left in the Lambda budget.
            // Default 100s (fits 2-min Lambda). Bump for longer Lambdas via body.softDeadlineMs.
            const softDeadlineMs: number = body.softDeadlineMs ?? 100000;

            // Pre-check: how many stale scans remain to migrate (have blockers still in active table)
            const remainingResult = await db.query({
                text: `
                    WITH latest AS (
                        SELECT DISTINCT ON (audit_id) id
                        FROM scans
                        ${auditId ? "WHERE audit_id = $1" : ""}
                        ORDER BY audit_id, created_at DESC
                    )
                    SELECT COUNT(DISTINCT b.scan_id) AS remaining
                    FROM blockers b
                    WHERE b.scan_id IS NOT NULL
                    AND b.scan_id NOT IN (SELECT id FROM latest)
                    ${auditId ? "AND b.audit_id = $1" : ""}
                `,
                values: auditId ? [auditId] : [],
            });
            const remainingStaleScans = parseInt(remainingResult.rows[0]?.remaining ?? "0", 10);

            if (dryRun) {
                await db.clean();
                return {
                    statusCode: 200,
                    body: JSON.stringify({ phase, dryRun, remainingStaleScans, ms: Date.now() - t0 }),
                };
            }

            let batchesRun = 0;
            let totalRowsMoved = 0;
            const batchResults: any[] = [];

            while (batchesRun < maxBatches && Date.now() - t0 < softDeadlineMs) {
                const moveResult = await db.query({
                    text: `
                        WITH latest AS (
                            SELECT DISTINCT ON (audit_id) id
                            FROM scans
                            ${auditId ? "WHERE audit_id = $1" : ""}
                            ORDER BY audit_id, created_at DESC
                        ),
                        target_scans AS (
                            SELECT DISTINCT b.scan_id
                            FROM blockers b
                            WHERE b.scan_id IS NOT NULL
                            AND b.scan_id NOT IN (SELECT id FROM latest)
                            ${auditId ? "AND b.audit_id = $1" : ""}
                            LIMIT ${scansPerBatch}
                        ),
                        moved AS (
                            DELETE FROM blockers
                            WHERE scan_id IN (SELECT scan_id FROM target_scans)
                            RETURNING id, created_at, updated_at, audit_id, content, content_normalized,
                                      content_hash_id, targets, equalified, url_id, scan_id, short_id
                        )
                        INSERT INTO stale_blockers
                            (id, created_at, updated_at, audit_id, content, content_normalized,
                             content_hash_id, targets, equalified, url_id, scan_id, short_id)
                        SELECT id, created_at, updated_at, audit_id, content, content_normalized,
                               content_hash_id, targets, equalified, url_id, scan_id, short_id
                        FROM moved
                    `,
                    values: auditId ? [auditId] : [],
                });

                const rowsMoved = moveResult.rowCount ?? 0;
                batchesRun++;
                totalRowsMoved += rowsMoved;
                batchResults.push({ batch: batchesRun, rowsMoved });

                if (rowsMoved === 0) break; // nothing left
            }

            await db.clean();
            return {
                statusCode: 200,
                body: JSON.stringify({
                    phase,
                    batchesRun,
                    totalRowsMoved,
                    remainingStaleScansBefore: remainingStaleScans,
                    ms: Date.now() - t0,
                    stoppedReason: batchesRun >= maxBatches
                        ? "max_batches_reached"
                        : Date.now() - t0 >= softDeadlineMs
                            ? "soft_deadline"
                            : "no_more_work",
                    batches: batchResults,
                }),
            };
        }

        if (phase === "move_orphan_blocker_messages") {
            // After move_stale, blocker_messages rows still reference the moved blockers.
            // Move those orphans to stale_blocker_messages so the link table shrinks too.
            // Batched: process rowsPerBatch rows per round.
            const rowsPerBatch: number = body.rowsPerBatch ?? 200000;
            const maxBatches: number = body.maxBatches ?? 50;
            const softDeadlineMs: number = body.softDeadlineMs ?? 100000;

            let totalRowsMoved = 0;
            let batchesRun = 0;
            const batchResults: any[] = [];

            while (batchesRun < maxBatches && Date.now() - t0 < softDeadlineMs) {
                const moveResult = await db.query({
                    text: `
                        WITH targets AS (
                            SELECT bm.id
                            FROM blocker_messages bm
                            WHERE NOT EXISTS (
                                SELECT 1 FROM blockers b WHERE b.id = bm.blocker_id
                            )
                            LIMIT ${rowsPerBatch}
                        ),
                        moved AS (
                            DELETE FROM blocker_messages
                            WHERE id IN (SELECT id FROM targets)
                            RETURNING id, created_at, updated_at, message_id, blocker_id
                        )
                        INSERT INTO stale_blocker_messages
                            (id, created_at, updated_at, message_id, blocker_id)
                        SELECT id, created_at, updated_at, message_id, blocker_id FROM moved
                    `,
                });

                const rowsMoved = moveResult.rowCount ?? 0;
                batchesRun++;
                totalRowsMoved += rowsMoved;
                batchResults.push({ batch: batchesRun, rowsMoved });

                if (rowsMoved === 0) break;
            }

            await db.clean();
            return {
                statusCode: 200,
                body: JSON.stringify({
                    phase,
                    batchesRun,
                    totalRowsMoved,
                    ms: Date.now() - t0,
                    stoppedReason: batchesRun >= maxBatches
                        ? "max_batches_reached"
                        : Date.now() - t0 >= softDeadlineMs
                            ? "soft_deadline"
                            : "no_more_work",
                    batches: batchResults,
                }),
            };
        }

        if (phase === "vacuum_full") {
            // VACUUM FULL rewrites the heap to reclaim space from dead tuples.
            // Takes an ACCESS EXCLUSIVE lock for the duration — table is unavailable.
            // Hasura SQL console won't let you run this (TX wrapper); this route works
            // because serverless-postgres runs each query non-transactionally.
            const tableName: string = body.tableName;
            if (!tableName || !/^[a-z_]+$/.test(tableName)) {
                await db.clean();
                return { statusCode: 400, body: JSON.stringify({ error: "tableName required, lowercase letters/underscores only" }) };
            }
            await db.query({ text: `VACUUM FULL public.${tableName}` });
            await db.clean();
            return {
                statusCode: 200,
                body: JSON.stringify({ phase, tableName, ms: Date.now() - t0 }),
            };
        }

        await db.clean();
        return {
            statusCode: 400,
            body: JSON.stringify({ error: `unknown phase '${phase}'` }),
        };
    } catch (err: any) {
        try { await db.clean(); } catch {}
        console.error("migrateStaleBlockers error:", err);
        return {
            statusCode: 500,
            body: JSON.stringify({ error: err?.message || String(err), phase, ms: Date.now() - t0 }),
        };
    }
};

```

[apps/backend/routes/internal/migrateStaleBlockers.ts](https://github.com/EqualifyEverything/equalify/blob/30dd97a2e32550554d6336000d73b7506f6ae384/apps/backend/routes/internal/migrateStaleBlockers.ts#L19-L287) · [More projects using serverless-postgres →](https://dashboard.exa.ai/playground/search?q=serverless-postgres%20GitHub%20projects)

**Quickstart**

```javascript
const ServerlessClient = require('serverless-postgres');
const client = new ServerlessClient({ connectionString: process.env.DATABASE_URL });
async function handler() {
  await client.connect();
  const result = await client.query('SELECT 1 AS one');
  await client.clean();
  return result.rows;
}
module.exports.handler = handler;

```

From [README.md](https://cdn.jsdelivr.net/npm/serverless-postgres@2.1.2/README.md)

## FAQ

### Which JavaScript PostgreSQL library should I use?

[node-postgres](#node-postgres) suits general Node.js apps that want explicit pool and client control. [Postgres.js](#postgres-js) suits code that writes queries as tagged template literals. [Neon serverless driver](#neon) suits serverless and edge functions that query over HTTP or WebSockets.

### What is the Neon serverless driver?

The [Neon serverless driver](#neon) runs PostgreSQL queries over HTTPS or WebSockets from JavaScript runtimes. Its WebSocket mode offers a Pool and Client compatible with node-postgres.

### What is pg Pool?

Pool is the connection pool class in [node-postgres](#node-postgres). It keeps connections open and hands one to each query instead of connecting per request.

### What is Slonik?

[Slonik](#slonik) is a PostgreSQL client that builds queries from SQL tokens. It adds result assertions, transaction scoping, and schema validation of rows.

### node-postgres vs Postgres.js: which should I use?

[node-postgres](#node-postgres) uses parameterized query configs with an explicit pool and client lifecycle. [Postgres.js](#postgres-js) writes queries as tagged templates with an automatically managed pool.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best JavaScript PostgreSQL client libraries pg postgres pg-promise Neon code examples pooling parameters transactions",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
