pg-async
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.
Example
; // using default connectionconst pgAsync = ; const userTable = 'user';const sqlUserByLogin = SQL` select id from $ID where login = `; { const userId = await pgAsyncvalue; // userId is guaranted here, // pgAsync.value requires query yielding exactly one row with one column. await pgAsync;}
Install
$ npm install --save pg-async
API
Configuring Connection Options
connectionOptions driver
- The default export of
pg-async
isPgAsync
class which let you configure connection options - Connection options defaults to
pg.defaults
- Optional
driver
let you choose underlying library - To use the native bindings you must
npm install --save pg-native
; // using default connectionconst pgAsync = ; // using connection stringconst pgAsync = 'postgres://user:secret@host:port/database'; // using connection objectconst pgAsync = user password host port database ...; // using default for current user, with native driver// install pg-native package manuallyconst pgAsync = null 'native';const pgAsync = null native;
await pgAsync.query(SQL`...`) -> pg.Result
await pgAsync.query(sql, values...) -> pg.Result
await pgAsync.queryArgs(sql, [values]) -> pg.Result
- Execute SQL and return
Result
object from underlyingpg
library - Interesting properties on
Result
object are:rowCount
Number – returned rowsoid
Number – Postgres oidrows
Array – Actual result ofpgAsync.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 length-
dataTypeModifier
Number
await pgAsync.rows(SQL`...`) -> array of objects
await pgAsync.rows(sql, values...) -> array of objects
await pgAsync.rowsArgs(sql, [values]) -> array of objects
- Execute SQL and return array of key/value objects (
result.rows
)
await pgAsync.row(SQL`...`) -> object
await pgAsync.row(sql, values...) -> object
await pgAsync.rowArgs(sql, [values]) -> object
- Execute SQL and return single key/value object. If query yields more than one or none rows, promise will be rejected.
- Rejected promise throw exception at
await
location.
await pgAsync.value(SQL`...`) -> any
await pgAsync.value(sql, values...) -> any
await pgAsync.valueArgs(sql, [values]) -> any
- Same as row, but query must yields single column in single row, otherwise throws.
await pgAsync.connect(async (client) => innerResult) -> innerResult
- Execute multiple queries in sequence on same connection. This is handy for transactions.
asyncFunc
here has signatureasync (client, pgClient) => { ... }
- provided
client
has async methods:query
,rows
,row
,value
as abovequeryArgs
,rowsArgs
,rowArgs
,valueArgs
as abovestartTransaction
,commit
,rollback
- start new transaction manually. UsepgAsync.transaction
when possible
client
itself is shorthand forquery
await pgAsync.transaction(async (client) => innerResult) -> innerResult
Transaction is similar to connect
but automatically start and commit transaction,
rollback on throwen error
Example:
const pgAsync = ; { return pgAsync;} { // ... try const result = await ; // transaction is commited catch err // transaction is rollbacked // ...}
await pgAsync.getClient([connectionOptions]) -> {client, done}
- Get unwrapped
pg.Client
callback based instance.
You should not call this method unless you know what are you doing. - Client must be returned to pool manually by calling
done()
pgAsync.closeConnections()
- Disconnects all idle clients within all active pools, and has all client pools terminate.
See
pool.end()
- This actually terminates all connections on driver used by Pg instance
Features
-
pg
driver support -
pg.native
driver support -
debug
— Enable debugging withDEBUG="pg-async"
environment variable - Transaction API wrapper - Postgres does not support nested transactions
- Template tag SQL formatting
- Transaction
SAVEPOINT
support - Cursor API wrapper
If 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.
License (MIT)
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.