Skip to content

Commit 0c24ff3

Browse files
committed
Update readme
1 parent cbbd8d4 commit 0c24ff3

File tree

1 file changed

+18
-210
lines changed

1 file changed

+18
-210
lines changed

README.md

+18-210
Original file line numberDiff line numberDiff line change
@@ -13,193 +13,9 @@ Non-blocking PostgreSQL client for node.js. Pure JavaScript and optional native
1313
$ npm install pg
1414
```
1515

16-
## Intro & Examples
16+
## [Documentation](https://node-postgres.com)
1717

18-
There are 3 ways of executing queries
19-
20-
1. Passing the query to a pool
21-
2. Borrowing a client from a pool and executing the query with it
22-
3. Obtaining an exclusive client and executing the query with it
23-
24-
It is recommended to pass the query to a pool as often as possible. If that isn't possible, because of long and complex transactions for example, borrow a client from a pool. Just remember to initialize the pool only once in your code so you maximize reusability of connections.
25-
26-
### Why pooling?
27-
28-
If you're working on something like a web application which makes frequent queries you'll want to access the PostgreSQL server through a pool of clients. Why? For one thing, there is ~20-30 millisecond delay (YMMV) when connecting a new client to the PostgreSQL server because of the startup handshake. Furthermore, PostgreSQL can support only a limited number of clients...it depends on the amount of ram on your database server, but generally more than 100 clients at a time is a __very bad thing__. :tm: Additionally, PostgreSQL can only execute 1 query at a time per connected client, so pipelining all queries for all requests through a single, long-lived client will likely introduce a bottleneck into your application if you need high concurrency.
29-
30-
With that in mind we can imagine a situation where you have a web server which connects and disconnects a new client for every web request or every query (don't do this!). If you get only 1 request at a time everything will seem to work fine, though it will be a touch slower due to the connection overhead. Once you get >100 simultaneous requests your web server will attempt to open 100 connections to the PostgreSQL backend and :boom: you'll run out of memory on the PostgreSQL server, your database will become unresponsive, your app will seem to hang, and everything will break. Boooo!
31-
32-
__Good news__: node-postgres ships with built in client pooling. Client pooling allows your application to use a pool of already connected clients and reuse them for each request to your application. If your app needs to make more queries than there are available clients in the pool the queries will queue instead of overwhelming your database & causing a cascading failure. :thumbsup:
33-
34-
node-postgres uses [pg-pool](https://github.com/brianc/node-pg-pool.git) to manage pooling. It bundles it and exports it for convenience. If you want, you can `require('pg-pool')` and use it directly - it's the same as the constructor exported at `pg.Pool`.
35-
36-
It's __highly recommended__ you read the documentation for [pg-pool](https://github.com/brianc/node-pg-pool.git).
37-
38-
[Here is an up & running quickly example](https://github.com/brianc/node-postgres/wiki/Example)
39-
40-
For more information about `config.ssl` check [TLS (SSL) of nodejs](https://nodejs.org/dist/latest-v4.x/docs/api/tls.html)
41-
42-
### Pooling example
43-
44-
Let's create a pool in `./lib/db.js` which will be reused across the whole project
45-
46-
```javascript
47-
const pg = require('pg');
48-
49-
// create a config to configure both pooling behavior
50-
// and client options
51-
// note: all config is optional and the environment variables
52-
// will be read if the config is not present
53-
var config = {
54-
user: 'foo', //env var: PGUSER
55-
database: 'my_db', //env var: PGDATABASE
56-
password: 'secret', //env var: PGPASSWORD
57-
host: 'localhost', // Server hosting the postgres database
58-
port: 5432, //env var: PGPORT
59-
max: 10, // max number of clients in the pool
60-
idleTimeoutMillis: 30000, // how long a client is allowed to remain idle before being closed
61-
};
62-
63-
//this initializes a connection pool
64-
//it will keep idle connections open for 30 seconds
65-
//and set a limit of maximum 10 idle clients
66-
const pool = new pg.Pool(config);
67-
68-
pool.on('error', function (err, client) {
69-
// if an error is encountered by a client while it sits idle in the pool
70-
// the pool itself will emit an error event with both the error and
71-
// the client which emitted the original error
72-
// this is a rare occurrence but can happen if there is a network partition
73-
// between your application and the database, the database restarts, etc.
74-
// and so you might want to handle it and at least log it out
75-
console.error('idle client error', err.message, err.stack);
76-
});
77-
78-
//export the query method for passing queries to the pool
79-
module.exports.query = function (text, values, callback) {
80-
console.log('query:', text, values);
81-
return pool.query(text, values, callback);
82-
};
83-
84-
// the pool also supports checking out a client for
85-
// multiple operations, such as a transaction
86-
module.exports.connect = function (callback) {
87-
return pool.connect(callback);
88-
};
89-
```
90-
91-
Now if in `./foo.js` you want to pass a query to the pool
92-
93-
```js
94-
const pool = require('./lib/db');
95-
96-
//to run a query we just pass it to the pool
97-
//after we're done nothing has to be taken care of
98-
//we don't have to return any client to the pool or close a connection
99-
pool.query('SELECT $1::int AS number', ['2'], function(err, res) {
100-
if(err) {
101-
return console.error('error running query', err);
102-
}
103-
104-
console.log('number:', res.rows[0].number);
105-
});
106-
```
107-
108-
Or if in `./bar.js` you want borrow a client from the pool
109-
110-
```js
111-
const pool = require('./lib/db');
112-
113-
//ask for a client from the pool
114-
pool.connect(function(err, client, done) {
115-
if(err) {
116-
return console.error('error fetching client from pool', err);
117-
}
118-
119-
//use the client for executing the query
120-
client.query('SELECT $1::int AS number', ['1'], function(err, result) {
121-
//call `done(err)` to release the client back to the pool (or destroy it if there is an error)
122-
done(err);
123-
124-
if(err) {
125-
return console.error('error running query', err);
126-
}
127-
console.log(result.rows[0].number);
128-
//output: 1
129-
});
130-
});
131-
```
132-
133-
For more examples, including how to use a connection pool with promises and async/await see the [example](https://github.com/brianc/node-postgres/wiki/Example) page in the wiki.
134-
135-
### Obtaining an exclusive client, example
136-
137-
```js
138-
var pg = require('pg');
139-
140-
// instantiate a new client
141-
// the client will read connection information from
142-
// the same environment variables used by postgres cli tools
143-
var client = new pg.Client();
144-
145-
// connect to our database
146-
client.connect(function (err) {
147-
if (err) throw err;
148-
149-
// execute a query on our database
150-
client.query('SELECT $1::text as name', ['brianc'], function (err, result) {
151-
if (err) throw err;
152-
153-
// just print the result to the console
154-
console.log(result.rows[0]); // outputs: { name: 'brianc' }
155-
156-
// disconnect the client
157-
client.end(function (err) {
158-
if (err) throw err;
159-
});
160-
});
161-
});
162-
163-
```
164-
165-
## [More Documentation](https://github.com/brianc/node-postgres/wiki)
166-
167-
## Native Bindings
168-
169-
To install the [native bindings](https://github.com/brianc/node-pg-native.git):
170-
171-
```sh
172-
$ npm install pg pg-native
173-
```
174-
175-
176-
node-postgres contains a pure JavaScript protocol implementation which is quite fast, but you can optionally use [native](https://github.com/brianc/node-pg-native) [bindings](https://github.com/brianc/node-libpq) for a 20-30% increase in parsing speed (YMMV). Both versions are adequate for production workloads. I personally use the pure JavaScript implementation because I like knowing what's going on all the way down to the binary on the socket, and it allows for some fancier [use](https://github.com/brianc/node-pg-cursor) [cases](https://github.com/brianc/node-pg-query-stream) which are difficult to do with libpq. :smile:
177-
178-
To use the native bindings, first install [pg-native](https://github.com/brianc/node-pg-native.git). Once pg-native is installed, simply replace `var pg = require('pg')` with `var pg = require('pg').native`. Make sure any exported constructors from `pg` are from the native instance. Example:
179-
180-
```js
181-
var pg = require('pg').native
182-
var Pool = require('pg').Pool // bad! this is not bound to the native client
183-
var Client = require('pg').Client // bad! this is the pure JavaScript client
184-
185-
var pg = require('pg').native
186-
var Pool = pg.Pool // good! a pool bound to the native client
187-
var Client = pg.Client // good! this client uses libpq bindings
188-
```
189-
190-
#### API differences
191-
192-
node-postgres abstracts over the pg-native module to provide the same interface as the pure JavaScript version. Care has been taken to keep the number of api differences between the two modules to a minimum.
193-
However, currently some differences remain, especially :
194-
* the error object in pg-native is different : notably, the information about the postgres error code is not present in field `code` but in the field `sqlState` , and the name of a few other fields is different (see https://github.com/brianc/node-postgres/issues/938, https://github.com/brianc/node-postgres/issues/972).
195-
So for example, if you rely on error.code in your application, your will have to adapt your code to work with native bindings.
196-
* the notification object has a few less properties (see https://github.com/brianc/node-postgres/issues/1045)
197-
* column objects have less properties (see https://github.com/brianc/node-postgres/issues/988)
198-
* the modules https://github.com/brianc/node-pg-copy-streams and https://github.com/brianc/node-pg-query-stream do not work with native bindings (you will have to require 'pg' to use them).
199-
200-
Thus, it is recommended you use either the pure JavaScript or native bindings in both development and production and don't mix & match them in the same process - it can get confusing!
201-
202-
## Features
18+
### Features
20319

20420
* pure JavaScript client and native libpq bindings share _the same api_
20521
* connection pooling
@@ -210,47 +26,39 @@ Thus, it is recommended you use either the pure JavaScript or native bindings in
21026
* async notifications with `LISTEN/NOTIFY`
21127
* bulk import & export with `COPY TO/COPY FROM`
21228

213-
## Extras
29+
### Extras
21430

21531
node-postgres is by design pretty light on abstractions. These are some handy modules we've been using over the years to complete the picture.
21632
Entire list can be found on [wiki](https://github.com/brianc/node-postgres/wiki/Extras)
21733

34+
## Support
35+
36+
node-postgres is free software. If you encounter a bug with the library please open an issue on the [github repo](https://github.com/brianc/node-postgres). If you have questions unanswered by the documentation please open an issue pointing out how the documentation was unclear & I will do my best to make it better!
37+
38+
When you open an issue please provide:
39+
- version of node
40+
- version of postgres
41+
- smallest possible snippet of code to reproduce the problem
42+
43+
You can also follow me [@briancarlson](https://twitter.com/briancarlson) if that's your thing. I try to always announce noteworthy changes & developments with node-postgres on twitter.
44+
45+
### Professional Support
46+
47+
I offer professional support for node-postgres. I provide implementation, training, and many years of expertise on how to build applications with node, express, PostgreSQL, and react/redux. Please contact me at [brian.m.carlson@gmail.com](mailto:brian.m.carlson@gmail.com) to discuss how I can help your company be more successful!
48+
21849
## Contributing
21950

22051
__:heart: contributions!__
22152

222-
If you need help getting the tests running locally or have any questions about the code when working on a patch please feel free to email me or gchat me.
223-
22453
I will __happily__ accept your pull request if it:
22554
- __has tests__
22655
- looks reasonable
22756
- does not break backwards compatibility
22857

229-
Information about the testing processes is in the [wiki](https://github.com/brianc/node-postgres/wiki/Testing).
230-
231-
Open source belongs to all of us, and we're all invited to participate!
232-
23358
## Troubleshooting and FAQ
23459

23560
The causes and solutions to common errors can be found among the [Frequently Asked Questions(FAQ)](https://github.com/brianc/node-postgres/wiki/FAQ)
23661

237-
## Support
238-
239-
If at all possible when you open an issue please provide
240-
- version of node
241-
- version of postgres
242-
- smallest possible snippet of code to reproduce the problem
243-
244-
Usually I'll pop the code into the repo as a test. Hopefully the test fails. Then I make the test pass. Then everyone's happy!
245-
246-
If you need help or run into _any_ issues getting node-postgres to work on your system please report a bug or contact me directly. I am usually available via google-talk at my github account public email address. Remember this is a labor of love, and though I try to get back to everything sometimes life takes priority, and I might take a while. It helps if you use nice code formatting in your issue, search for existing answers before posting, and come back and close out the issue if you figure out a solution. The easier you can make it for me, the quicker I'll try and respond to you!
247-
248-
If you need deeper support, have application specific questions, would like to sponsor development, or want consulting around node & postgres please send me an email, I'm always happy to discuss!
249-
250-
I usually tweet about any important status updates or changes to node-postgres on twitter.
251-
Follow me [@briancarlson](https://twitter.com/briancarlson) to keep up to date.
252-
253-
25462
## License
25563

25664
Copyright (c) 2010-2017 Brian Carlson (brian.m.carlson@gmail.com)

0 commit comments

Comments
 (0)