Skip to content

Commit

Permalink
Add a top level query() shorthand and fix some related docs
Browse files Browse the repository at this point in the history
  • Loading branch information
vampirical committed Mar 7, 2024
1 parent 8189a1a commit 73129c9
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 6 deletions.
33 changes: 27 additions & 6 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,8 +127,9 @@ const SQL = {
* Creates and manages a connection around a callback.
*
* @param {function} callback
* @param {pg.Pool} [pool]
* @param {boolean} [autoDestroyConn=false]
* @param {Object} [options]
* @param {pg.Pool} [options.pool]
* @param {boolean} [options.autoDestroyConn=false]
* @returns {Promise<*>}
*/
async connected(callback, {pool = null, autoDestroyConn = false} = {}) {
Expand Down Expand Up @@ -159,10 +160,11 @@ const SQL = {
* Creates and manages a transaction around a callback.
*
* @param {function} callback
* @param {pg.Client} [conn]
* @param {pg.Pool} [pool]
* @param {boolean} [allowNested=false]
* @param {boolean} [autoDestroyConn=false]
* @param {Object} [options]
* @param {pg.Client} [options.conn]
* @param {pg.Pool} [options.pool]
* @param {boolean} [options.allowNested=false]
* @param {boolean} [options.autoDestroyConn=false]
* @returns {Promise<*>}
*/
async transaction(callback, {conn = null, pool = null, allowNested = false, autoDestroyConn = false} = {}) {
Expand Down Expand Up @@ -226,6 +228,25 @@ const SQL = {
}
},

/**
* Shorthand for one-off query.
*
* @param {string} test - SQL query.
* @param {Array} [values]
* @param {Object} [options]
* @param {pg.Pool} [options.pool]
* @param {boolean} [options.autoDestroyConn=false]
* @param {string} [options.name] - node-pg passthrough
* @param {string} [options.rowMode] - node-pg passthrough
* @param {*} [options.types] - node-pg passthrough
* @returns {Promise<pg.Result>}
*/
async query(text, values = null, {pool = null, autoDestroyConn = false, name = undefined, rowMode = undefined, types = undefined} = {}) {
return this.connected(async function(conn) {
return conn.query({text, values, name, rowMode, types});
}, {pool, autoDestroyConn});
},

/**
* Where AND.
*
Expand Down
8 changes: 8 additions & 0 deletions tests/poolsAndConns.js
Original file line number Diff line number Diff line change
Expand Up @@ -271,3 +271,11 @@ test('transaction autoDestroyConn', async (t) => {
t.true(conn._the_one === undefined);
}, {pool});
});

test('query one-off', async (t) => {
const pool = createTestPool(1);

const result = await SQL.query('SELECT 5 foo', null, {pool});
t.is(result.rows.length, 1);
t.is(result.rows[0].foo, 5);
});

0 comments on commit 73129c9

Please sign in to comment.