Your main interface point with the PostgreSQL server. Client is used to create & dispatch queries to Postgres. Client also emits events from Postgres for 'LISTEN/NOTIFY' processing and non-critical error and notice messages from the server.
note: Client instances created via the constructor do not participate in connection pooling. To take advantage of connection pooling (recommended) please use the pg object.
Creates a new, unconnected client from a url based connection string postgres://user:password@host:port/database
or from the location of a domain socket folder /tmp
or /var/run/postgres
.
Internally the connection string is parsed and a config object is created with the same defaults as outlined below. All parts of the connection string url are optional. This is handy for use in managed hosting like Heroku.
var client = new Client('postgres://brian:mypassword@localhost:5432/dev');
var client = new Client('postgres://brian@localhost/dev'); //will use defaults
var client = new Client(process.env.DATABASE_URL); //something like this should get you running with heroku
var client = new Client('/tmp'); //looks for the socket file /tmp/.s.PGSQL.5432
Creates a new, unconnected instance of a Client configured via supplied configuration object.
process.env.USER
process.env.USER
null
5432
null
false
var client = new Client({
user: 'brianc',
password: 'boom!',
database: 'test',
host: 'example.com',
port: 5313
});
Will look for the Unix Domain Socket at /tmp/.s.PGSQL.5313
and connect with the rest of the supplied credentials:
var client = new Client({
user: 'brianc',
password: 'boom!',
database: 'test',
host: '/tmp',
port: 5313
});
Initializes Client's internal Connection object & net.Stream() instance. Starts communication with PostgreSQL server including password negotiation. If a callback is supplied it will be called with an instance of Error
if an error was encountered during the connection procedure, otherwise it will be called with null
for a single parameter after a connection to PostgreSQL server is established and the client is ready to dispatch queries.
note: Clients created via the pg#connect method are already connected and should not have their #connect method called.
Immediately sends a termination message to the PostgreSQL server and closes the underlying net.Stream().
note: Clients created via the pg#connect method will be automatically disconnected or placed back into the connection pool and should not have their #end method called.
Simply: Creates a query object, queues it for execution, and returns it.
In more detail: Adds a Query to the Client's internal query queue. The query is executed as a simple query within PostgresSQL, takes no parameters, and it is parsed, bound, executed, and all rows are streamed backed to the Client in one step within the PostgreSQL server. For more detailed information you can read the PostgreSQL protocol documentation.
row
query eventrow
and end
events but will no longer raise the error
eventnull
if there was no error var client = new Client({user: 'brianc', database: 'test'});
client.connect();
//query is executed once connection is established and
//PostgreSQL server is ready for a query
var query = client.query("SELECT name FROM users");
query.on('row', function(row) {
console.log(row.name);
});
query.on('end', client.end.bind(client)); //disconnect client manually
var client = new Client({user: 'brianc', database: 'test'});
client.on('drain', client.end.bind(client)); //disconnect client when all queries are finished
client.connect();
//query is executed once connection is established and
//PostgreSQL server is ready for a query
var query = client.query("SELECT name FROM users", function(err, result) {
console.log(result.rows[0].name);
})
Creates an unnamed query object, queues it for execution, and returns it.
If name
is provided within the config
object the query will be executed as a prepared statement. Otherwise, if values
is provided within the config
object the query will be executed as a parameterized query. If Otherwise, it will behave in the same manner as a simple query.
var client = new Client({user: 'brianc', database: 'test'});
client.on('drain', client.end.bind(client)); //disconnect client when all queries are finished
client.connect();
var query = client.query({
text: 'SELECT name FROM users WHERE email = $1',
values: ['[email protected]']
});
query.on('row', function(row) {
//do something w/ yer row data
assert.equal('brianc', row.name);
});
var client = new Client({user: 'brianc', database: 'test'});
client.on('drain', client.end.bind(client)); //disconnect client when all queries are finished
client.connect();
var again = client.query("SELECT name FROM users WHERE email = $1", ['[email protected]']);
again.on('row', function(row) {
//do something else
assert.equal('brianc', row.name);
});
var client = new Client({user: 'brianc', database: 'test'});
client.on('drain', client.end.bind(client)); //disconnect client when all queries are finished
client.connect();
//object config method
var queryConfig = {
text: 'SELECT name FROM users WHERE email = $1',
values: ['[email protected]']
};
client.query(queryConfig, function(err, result) {
assert.equal('brianc', result.rows[0]);
});
//text/params method
client.query('SELECT name FROM users WHERE email = $1', ['[email protected]'], function(err, result) {
assert.equal('brianc', result.rows[0].name);
});
(See Prepared Statements for a more detailed discussion of Prepared Statements in node-postgres
.)
Creates a named query object, queues it for execution, and returns it.:
name
is provided within the config
object does query result in a prepared statement.text
and name
are provided within the config
, the query will result in the creation of a prepared statement.value
and name
provided within the config
, the prepared statement will be executed. (Note: if the prepared statement takes no parameters, use value:[]
.)PostgreSQL server caches prepared statements by name on a per (postgres) session basis. Subsequent queries may refer to the prepared statement by name, and the PostgresQL server instance can skip the preparation step.
var client = new Client({user: 'brianc', database: 'test'});
client.on('drain', client.end.bind(client)); //disconnect client when all queries are finished
client.connect();
var first = client.query({
text: "SELECT email FROM users WHERE name = $1",
values: ['brianc'],
name: 'email from name'
});
first.on('row', function(row) {
assert.equal("[email protected]", row.email);
});
var second = client.query({
name: 'email from name',
values: ['brianc']
});
second.on('row', function(row) {
assert.equal("[email protected]", row.email);
});
//can still supply a callback method
var third = client.query({name: 'email from name', values: ['brianc']}, function(err, result) {
assert.equal('[email protected]', result.rows[0].email);
});
select name from user where email = $1
row
query eventrow
and end
events but will no longer raise the error
eventnull
if there was no errorRaised when the internal query queue has been emptied and all queued queries have been executed. Useful for disconnecting the client after running an undetermined number of queries.
var client = new Client({user: 'brianc', database: 'postgres'});
client.connect();
var users = client.query("select * from user");
var superdoods = client.query("select * from superman");
client.on('drain', client.end.bind(client));
//carry on doing whatever it was you wanted with the query results once they return
users.on('row', function(row){ ...... });
Raised when the client recieves an error message from PostgreSQL or when the underlying stream raises an error. The single parameter passed to the listener will be the error message or error object.
var client = new Client({user: 'not a valid user name', database: 'postgres'});
client.connect();
client.on('error', function(error) {
console.log(error);
});
Used for "LISTEN/NOTIFY" interactions. You can do some fun pub-sub style stuff with this.
var client1 = new Client(...)
var client2 = new Client(...)
client1.connect();
client2.connect();
client1.on('notification', function(msg) {
console.log(msg.channel); //outputs 'boom'
client1.end();
});
client1.query("LISTEN boom");
//need to let the first query actually complete
//client1 will remain listening to channel 'boom' until its 'end' is called
setTimeout(function() {
client2.query("NOTIFY boom", function() {
client2.end();
});
}, 1000);
Emitted from PostgreSQL server when non-critical events happen. Libpq printf
's these out to stdout if the behavior is not overridden. Yucky. Thankfully node-postgres overrides the default behavior and emits an event (instead of printing to stdout) on the client which received the notice event.
var client = new Client(...)
client.on('notice', function(msg) {
console.log("notice: %j", msg);
});
//create a table with an id will cause a notice about creating an implicit seq or something like that...
client.query('create temp table boom(id serial, size integer)');
client.on('drain', client.end.bind(client));