What is pg-cursor?
The pg-cursor npm package provides a way to handle large result sets in PostgreSQL by using server-side cursors. This allows you to fetch rows in smaller chunks, which can be more efficient and less memory-intensive than fetching all rows at once.
What are pg-cursor's main functionalities?
Creating a Cursor
This feature allows you to create a cursor for a given SQL query. The cursor can then be used to fetch rows in smaller chunks.
const { Client } = require('pg');
const Cursor = require('pg-cursor');
const client = new Client();
await client.connect();
const cursor = client.query(new Cursor('SELECT * FROM large_table'));
Fetching Rows
This feature allows you to fetch a specified number of rows from the cursor. This can be done repeatedly to fetch all rows in manageable chunks.
cursor.read(100, (err, rows) => {
if (err) throw err;
console.log(rows);
});
Closing the Cursor
This feature allows you to close the cursor when you are done fetching rows. This is important for freeing up resources on the server.
cursor.close((err) => {
if (err) throw err;
client.end();
});
Other packages similar to pg-cursor
pg-query-stream
The pg-query-stream package provides a way to stream rows from a PostgreSQL query. It is similar to pg-cursor in that it allows you to handle large result sets efficiently. However, pg-query-stream uses a readable stream interface, which can be more convenient for some use cases.
pg-promise
The pg-promise package is a PostgreSQL interface for Node.js that supports promises. It includes a feature for streaming rows from a query, similar to pg-cursor. However, pg-promise offers a broader range of features for working with PostgreSQL, including transaction management and query formatting.
node-pg-cursor
Use a PostgreSQL result cursor from node with an easy to use API.
why?
Sometimes you need to iterate through a table in chunks. It's extremely inefficient to use hand-crafted LIMIT
and OFFSET
queries to do this.
PostgreSQL provides built-in functionality to fetch a "cursor" to your results and page through the cursor efficiently fetching chunks of the results with full MVCC compliance.
This actually ends up pairing very nicely with node's asyncness and handling a lot of data. PostgreSQL is rad.
example
var Cursor = require('pg-cursor')
var pg = require('pg')
pg.connect(function(err, client, done) {
var cursor = client.query(new Cursor('SELECT * FROM some_table WHERE prop > $1', [100]))
cursor.read(100, function(err, rows) {
if(err) {
return done(err)
}
if(!rows.length) return done()
cursor.read(2000, function(err, rows) {
})
})
});
api
var Cursor = require('pg-cursor')
constructor Cursor(string queryText, array queryParameters)
Creates an instance of a query cursor. Pass this instance to node-postgres client#query
cursor#read(int rowCount, function callback(Error err, Array rows, Result result)
Read rowCount
rows from the cursor instance. The callback
will be called when the rows are available, loaded into memory, parsed, and converted to JavaScript types.
If the cursor has read to the end of the result sets all subsequent calls to cursor#read
will return a 0 length array of rows. I'm open to other ways to signal the end of a cursor, but this has worked out well for me so far.
result
is a special https://github.com/brianc/node-postgres/wiki/Query#result-object object that can be used to accumulate rows.
cursor#close(function callback(Error err))
Closes the backend portal before itterating through the entire result set. Useful when you want to 'abort' out of a read early but continue to use the same client for other queries after the cursor is finished.
install
$ npm install pg-cursor
note: this depends on either npm install pg
or npm install pg.js
, but you must be using the pure JavaScript client. This will not work with the native bindings.
license
The MIT License (MIT)
Copyright (c) 2013 Brian M. Carlson
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.