UNPKG

7.03 kBMarkdownView Raw
1# pg-async
2[![Npm Version](https://badge.fury.io/js/pg-async.svg)](https://badge.fury.io/js/pg-async)
3[![Dependency Status](https://david-dm.org/langpavel/node-pg-async.svg)](https://david-dm.org/langpavel/node-pg-async)
4[![devDependency Status](https://david-dm.org/langpavel/node-pg-async/dev-status.svg)](https://david-dm.org/langpavel/node-pg-async#info=devDependencies)
5[![Build Status](https://circleci.com/gh/langpavel/node-pg-async.svg?style=shield)](https://circleci.com/gh/langpavel/node-pg-async)
6[![Coverage Status](https://coveralls.io/repos/github/langpavel/node-pg-async/badge.svg?branch=master)](https://coveralls.io/github/langpavel/node-pg-async?branch=master)
7
8Tiny but powerful Promise based PostgreSQL client for node.js
9designed for easy use with ES7 async/await.<br/>
10Based on [node-postgres](https://github.com/brianc/node-postgres) (known as `pg` in npm registry).
11Can use `pg` or native `pg-native` backend.
12
13## Install
14
15```
16$ npm install --save pg-async
17```
18
19## API
20
21#### Configuring Connection Options
22```js
23new PgAsync([connectionOptions], [driver])
24```
25
26* The only export of `pg-async` is `PgAsync` class which let you configure connection options
27* Connection options defaults to [`pg.defaults`](https://github.com/brianc/node-postgres/wiki/pg#pgdefaults)
28* Optional `driver` let you choose underlying library
29* To use the [native bindings](https://github.com/brianc/node-pg-native.git) you must `npm install --save pg-native`
30
31```js
32import PgAsync from 'pg-async';
33
34// using default connection
35const pgAsync = new PgAsync();
36
37// using connection string
38const pgAsync = new PgAsync('postgres://user:secret@host:port/database');
39
40// using connection object
41const pgAsync = new PgAsync({user, password, host, port, database, ...});
42
43// using default for current user, with native driver
44// install pg-native package manually
45const pgAsync = new PgAsync(null, 'native');
46const pgAsync = new PgAsync(null, require('pg').native);
47```
48
49---
50
51#### `await pgAsync.query(sql, values...) -> pg.Result`
52#### `await pgAsync.queryArgs(sql, [values]) -> pg.Result`
53
54* Execute SQL and return `Result` object from underlying `pg` library
55* Interesting properties on `Result` object are:
56 * `rowCount` Number ­– returned rows
57 * `oid` Number ­– Postgres oid
58 * `rows` Array ­– Actual result of `pgAsync.rows()`
59 * `rowAsArray` Boolean
60 * `fields` Array of:
61 * `name` String ­– name or alias of column
62 * `tableID` Number ­– oid of table or 0
63 * `columnID` Number ­– index of column in table or 0
64 * `dataTypeID` Number ­– oid of data type
65 * `dataTypeSize` Number ­– size in bytes od colum, -1 for variable length
66 * ­`dataTypeModifier` Number
67
68---
69
70#### `await pgAsync.rows(sql, values...) -> array of objects`
71#### `await pgAsync.rowsArgs(sql, [values]) -> array of objects`
72
73* Execute SQL and return array of key/value objects (`result.rows`)
74
75---
76
77#### `await pgAsync.row(sql, values...) -> object`
78#### `await pgAsync.rowArgs(sql, [values]) -> object`
79
80* Execute SQL and return single key/value object.
81 If query yields more than one or none rows, promise will be rejected.
82* Rejected promise throw exception at **`await`** location.
83
84---
85
86#### `await pgAsync.value(sql, values...) -> any`
87#### `await pgAsync.valueArgs(sql, [values]) -> any`
88
89* Same as row, but query must yields single column in single row, otherwise throws.
90
91---
92
93#### `await pgAsync.connect(async (client) => innerResult) -> innerResult`
94
95* Execute multiple queries in sequence on same connection. This is handy for transactions.
96* `asyncFunc` here has signature `async (client, pgClient) => { ... }`
97* provided `client` has async methods:
98 * `query`, `rows`, `row`, `value` as above
99 * `queryArgs`, `rowsArgs`, `rowArgs`, `valueArgs` as above
100 * `startTransaction`, `commit`, `rollback` - start new transaction manually. Use `pgAsync.transaction` when possible
101* `client` itself is shorthand for `query`
102
103---
104
105#### `await pgAsync.transaction(async (client) => innerResult) -> innerResult`
106
107Transaction is similar to `connect` but automatically start and commit transaction,
108rollback on throwen error
109__Example:__
110
111```js
112const pgAsync = new PgAsync();
113
114function moveMoney(fromAccount, toAccount, amount) {
115 return pgAsync.transaction(async (client) => {
116 let movementFrom, movementTo, movementId;
117 const sql = 'INSERT INTO bank_account (account, amount) VALUES ($1, $2) RETURNS id';
118 movementFrom = await client.value(sql, [fromAccount, -amount]);
119 movementTo = await client.value(sql, [toAccount, amount]);
120 return {movementFrom, movementTo}
121 });
122}
123
124async function doTheWork() {
125 ...
126 try {
127 const result = await moveMoney('alice', 'bob', 19.95);
128 // transaction is commited
129 } catch (err) {
130 // transaction is rollbacked
131 }
132 ...
133}
134```
135
136---
137
138#### `await pgAsync.getClient([connectionOptions]) -> {client, done}`
139
140* Get unwrapped `pg.Client` callback based instance.<br/>
141 You should not call this method unless you know what are you doing.
142* Client must be returned to pool manually by calling `done()`
143
144---
145
146#### `pgAsync.closeConnections()`
147
148* Disconnects all idle clients within all active pools, and has all client pools terminate.
149 See [`pg.end()`](https://github.com/brianc/node-postgres/wiki/pg#end)
150* This actually terminates all connections on driver used by Pg instance
151
152---
153
154## Features
155
156 * [x] `pg` driver support
157 * [x] `pg.native` driver support
158 * [x] [`debug`](https://github.com/visionmedia/debug#readme) — Enable debugging with `DEBUG="pg-async"` environment variable
159 * [x] Transaction API wrapper - Postgres does not support nested transactions
160 * [ ] Transaction `SAVEPOINT` support
161 * [ ] Cursor API wrapper
162
163If you miss something, don't be shy, just
164[open new issue!](https://github.com/langpavel/node-pg-async/issues)
165It will be nice if you label your issue with prefix `[bug]` `[doc]` `[question]` `[typo]`
166etc.
167
168## License (MIT)
169
170Copyright (c) 2016 Pavel Lang (langpavel@phpskelet.org)
171
172<small>
173Permission 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:
174
175The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
176
177THE 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.
178</small>