Registry / database / pg-cursor

pg-cursor

JSON →
library2.19.0jsnpmunverified

pg-cursor is a specialized extension for the `node-postgres` library, enabling Node.js applications to utilize PostgreSQL result cursors. This functionality allows developers to fetch large query results incrementally in manageable chunks, effectively preventing out-of-memory issues that can arise when loading massive datasets into memory all at once. The library is currently at version 2.19.0 and is actively maintained as part of the broader `node-postgres` ecosystem, with updates typically released to ensure compatibility, address bugs, or introduce minor enhancements. Its primary differentiator lies in providing an efficient, streaming approach to data retrieval from PostgreSQL, which is crucial for high-performance applications dealing with extensive database tables. A key technical requirement is its exclusive compatibility with the pure JavaScript `pg` client, explicitly stating it does not support native PostgreSQL bindings.

npm install pg-cursor
INSTALL
IMPORT
SIG · PG-CURSOR
P
pg-cursor
databasejavascriptv2.19.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Cursor
import Cursor from 'pg-cursor';
import { Cursor } from 'pg-cursor';
The `Cursor` class is the default export of the module for ESM.
Cursor
const Cursor = require('pg-cursor');
const { Cursor } = require('pg-cursor');
The `Cursor` class is the default export of the module for CommonJS.

Demonstrates connecting to a PostgreSQL database, creating a cursor for a large query, reading rows in batches, processing them, and properly closing the cursor and client connection.

import { Client } from 'pg'; import Cursor from 'pg-cursor'; async function processLargeResult() { const client = new Client({ user: process.env.PGUSER ?? 'postgres', host: process.env.PGHOST ?? 'localhost', database: process.env.PGDATABASE ?? 'your_database', password: process.env.PGPASSWORD ?? 'password', port: parseInt(process.env.PGPORT ?? '5432', 10), }); await client.connect(); console.log('Connected to database.'); const query = 'SELECT id, data FROM large_table ORDER BY id'; // Replace large_table with your table const cursor = client.query(new Cursor(query)); const BATCH_SIZE = 100; let rowsProcessed = 0; try { while (true) { const rows = await new Promise<any[]>((resolve, reject) => { cursor.read(BATCH_SIZE, (err, batchRows) => { if (err) return reject(err); resolve(batchRows); }); }); if (rows.length === 0) { break; // No more rows to read } for (const row of rows) { // console.log(`Processing row ID: ${row.id}`); // Perform your row-specific logic here rowsProcessed++; } if (rows.length < BATCH_SIZE) { break; // Less than batch size means we've reached the end } } console.log(`Successfully processed ${rowsProcessed} rows using a cursor.`); } catch (error) { console.error('Error during cursor processing:', error); } finally { try { await cursor.close(); console.log('Cursor closed.'); } catch (closeError) { console.warn('Error closing cursor (might be already closed or connection issue):', closeError); } await client.end(); console.log('Database connection ended.'); } } processLargeResult().catch(err => console.error('Unhandled error:', err));
Debug
Known issues
gotchapg-cursor is strictly compatible only with the pure JavaScript `pg` client. It will not function correctly if your `node-postgres` setup uses native PostgreSQL bindings (e.g., via `pg-native`).
fix
Ensure you have `npm install pg` and not `npm install pg-native` or similar native binding packages. If `pg` is installed, verify that its pure JavaScript client is being utilized.
affects: >=1.0.0
gotchaForgetting to close the cursor after all rows have been processed or an error occurs can lead to resource leaks on the PostgreSQL server, holding open transaction slots and potentially locking resources.
fix
Always ensure `cursor.close()` is called in a `finally` block or after successful processing to release server resources, even if an error prevents full iteration.
affects: >=1.0.0
gotchaUsing `pg-cursor` with `pg` versions older than `^8` might lead to unexpected behavior or compatibility issues, as `pg-cursor` specifies `pg@^8` as a peer dependency.
fix
Upgrade your `pg` package to version 8 or higher to ensure full compatibility with `pg-cursor`. Run `npm install pg@latest`.
affects: <8.0.0
Errors
Common errors & fixes
TypeError: client.query is not a function
Attempting to use `pg-cursor` with a client that is not a `pg.Client` instance, or before `client.connect()` has resolved.
fix
Ensure you are passing a connected `pg.Client` instance to the cursor creation process (e.g., `client.query(new Cursor(...))`) and that the client is successfully connected to the database.
Error: portal 'C_...' does not exist
This error typically indicates that an attempt was made to operate on a PostgreSQL cursor (portal) that has already been closed or no longer exists on the server. This can happen if `cursor.close()` was called prematurely, or the client connection was lost/ended.
fix
Review your cursor lifecycle management. Ensure `cursor.read()` calls are not made after `cursor.close()` or after the client connection has been terminated. Wrap cursor operations in `try...finally` to ensure proper closing.
Error: A statement has been issued against a connection that is not a pure JS client.
This explicit error message confirms `pg-cursor` detected the use of `pg-native` or another non-pure JavaScript client implementation.
fix
Uninstall any native PostgreSQL client bindings (e.g., `pg-native`) and ensure only the pure JavaScript `pg` package is installed and used in your project.
Upgrade
Version history
2.19.0latest on npm
Audit
Dependencies
pgrequiredRequired as a peer dependency for database connectivity and query execution. Must be the pure JavaScript client, not native bindings.
Agent activity
4 hits · last 30 days
node
4
Resources
pg-cursor — npm install pg-cursor · libregistry