PostgreSQL :elephant: client for node.js designed for easy use with ES7 async/await based on node-postgres
Tiny but powerful Promise based PostgreSQL client for node.js
designed for easy use with ES7 async/await.
Based on node-postgres (known as pg in npm registry).
Can use pg or native pg-native backend.
import PgAsync, {SQL} from 'pg-async';
// using default connection
const pgAsync = new PgAsync();
const userTable = 'user';
const sqlUserByLogin = (login) => SQL`
select id
from $ID${userTable}
where login = ${login}
`;
async function setPassword(login, newPwd) {
const userId = await pgAsync.value(sqlUserByLogin(login));
// userId is guaranted here,
// pgAsync.value requires query yielding exactly one row with one column.
await pgAsync.query(SQL`
update $ID${userTable} set
passwd = ${newPwd}
where userId = ${userId}
`);
}
$ npm install --save pg-async
new PgAsync([connectionOptions], [driver])
pg-async is PgAsync class which let you configure connection optionspg.defaultsdriver let you choose underlying librarynpm install --save pg-nativeimport PgAsync from 'pg-async';
// using default connection
const pgAsync = new PgAsync();
// using connection string
const pgAsync = new PgAsync({connectionString: 'postgres://user:secret@host:port/database'});
// using connection object
const pgAsync = new PgAsync({user, password, host, port, database, ...});
// using default for current user, with native driver
// install pg-native package manually
const pgAsync = new PgAsync(null, 'native');
const pgAsync = new PgAsync(null, require('pg').native);
await pgAsync.query(SQL`...`) -> pg.Resultawait pgAsync.query(sql, values...) -> pg.Resultawait pgAsync.queryArgs(sql, [values]) -> pg.ResultResult object from underlying pg libraryResult object are:
rowCount Number – returned rowsoid Number – Postgres oidrows Array – Actual result of pgAsync.rows()rowAsArray Booleanfields Array of:
name String – name or alias of columntableID Number – oid of table or 0columnID Number – index of column in table or 0dataTypeID Number – oid of data typedataTypeSize Number – size in bytes od colum, -1 for variable lengthdataTypeModifier Numberawait pgAsync.rows(SQL`...`) -> array of objectsawait pgAsync.rows(sql, values...) -> array of objectsawait pgAsync.rowsArgs(sql, [values]) -> array of objectsresult.rows)await pgAsync.row(SQL`...`) -> objectawait pgAsync.row(sql, values...) -> objectawait pgAsync.rowArgs(sql, [values]) -> objectawait location.await pgAsync.value(SQL`...`) -> anyawait pgAsync.value(sql, values...) -> anyawait pgAsync.valueArgs(sql, [values]) -> anyawait pgAsync.connect(async (client) => innerResult) -> innerResultasyncFunc here has signature async (client, pgClient) => { ... }client has async methods:
query, rows, row, value as abovequeryArgs, rowsArgs, rowArgs, valueArgs as abovestartTransaction, commit, rollback - start new transaction manually. Use pgAsync.transaction when possibleclient itself is shorthand for queryawait pgAsync.transaction(async (client) => innerResult) -> innerResultTransaction is similar to connect but automatically start and commit transaction,
rollback on throwen error
Example:
const pgAsync = new PgAsync();
function moveMoney(fromAccount, toAccount, amount) {
return pgAsync.transaction(async (client) => {
let movementFrom, movementTo, movementId;
const sql = `
INSERT INTO bank_account (account, amount)
VALUES ($1, $2)
RETURNING id
`;
movementFrom = await client.value(sql, [fromAccount, -amount]);
movementTo = await client.value(sql, [toAccount, amount]);
return {movementFrom, movementTo}
});
}
async function doTheWork() {
// ...
try {
const result = await moveMoney('alice', 'bob', 19.95);
// transaction is commited
} catch (err) {
// transaction is rollbacked
}
// ...
}
await pgAsync.getClient([connectionOptions]) -> {client, done}pg.Client callback based instance.done()pgAsync.closeConnections()pool.end()pg driver supportpg.native driver supportdebug — Enable debugging with DEBUG="pg-async" environment variableSAVEPOINT supportIf you miss something, don’t be shy, just
open new issue!
It will be nice if you label your issue with prefix [bug] [doc] [question] [typo]
etc.
Copyright (c) 2016 Pavel Lang (langpavel@phpskelet.org)
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. </small>