pg-sidekick v0.1.2
PG-SIDEKICK
pg-sidekick is a low-level wrapper around the postgres, pg-pool and pg-query-stream modules that centralises access to the most commonly-used functionalities of these modules and adds small bits of useful logic here and there.
Status
- Unstable and just released.
- Needs more in-depth tests.
- Mainly used for learning purposes on personal projects and developed accordingly, working towards a more stable release.
- Feedback and PR are always welcome.
If you're looking for a production-ready component, I suggest using the much more popular and tested pg-promise.
How to use
Sidekick()
The Sidekick class exported by pg-sidekick manages an internal pool of connections through the pg-pool module and accepts the same options in its constructor.
var Sidekick = require('pg-sidekick');
var sidekick = Sidekick(opts);sidekick.connect(cb)
This is a proxy method for pg-pool's connect() method and returns an instance of postgres's Client.
sidekick.connect(function(err, client) {});
sidekick.connect().then(function(client) {});sidekick.query(query, opts, cb)
This method wraps postgres's client.query() method, adding a bit of logic in the supported options.
sidekick.query(query, opts, function(err, results) {});
sidekick.query(query, opts).then(function(results) {});The query parameter can both be a plain SQL string or an object with the following properties:
name- the name of the statement (if using prepared statements)text- a SQL string with$<num>placeholdersvalues- an array of parameters
The options supported through the opts parameter are the following:
rows: true- if true, directly returns the array of rows rather than the parentresultobject.ensure: false- if true, the query will result in aSidekick.NoRowsErrorerror if no rows are returned.single: false- if true, the query will return only the first row.
sidekick.stream()
This method uses pg-query-stream's new QueryStream() to create a stream of rows matching the provided query.
sidekick.stream(query, opts, function(err, stream) {});
sidekick.stream(query, opts).then(function(stream) {});The query parameter can both be a plain SQL string or an object with the following properties:
name- the name of the statement (if using prepared statements)text- a SQL string with$<num>placeholdersvalues- an array of parameters
sidekick.begin()
This method returns a transaction object. Such object provides the same .query() and .stream() methods of the Sidekick instance and additional .rollback() and .commit() methods to handle transaction semantics.
sidekick.begin().then(function(transaction) {
transaction.query('INSERT ...')
.then(function() {
return transaction.commit();
});
});Tests
$ psql sidekick < test/main.sql
$ mochaLicense
MIT. See LICENSE.md.