- Notifications
You must be signed in to change notification settings - Fork 0
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.
- methods
- connect
- end
- query (simple)
- query (prepared statement)
- pauseDrain
- resumeDrain
- events
- drain
- error
- notification
- notice
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.
varclient=newClient('postgres://brian:mypassword@localhost:5432/dev');varclient=newClient('postgres://brian@localhost/dev');//will use defaultsvarclient=newClient(process.env.DATABASE_URL);//something like this should get you running with herokuvarclient=newClient('/tmp');//looks for the socket file /tmp/.s.PGSQL.5432Creates a new, unconnected instance of a Client configured via supplied configuration object.
- objectconfig: can contain any of the following optional properties
- stringuser:
- default value:
process.env.USER - PostgreSQL user
- default value:
- stringdatabase:
- default value:
process.env.USER - database to use when connecting to PostgreSQL server
- default value:
- stringpassword:
- default value:
null - user's password for PostgreSQL server
- default value:
- numberport:
- default value:
5432 - port to use when connecting to PostgreSQL server
- will support unix domain sockets in future
- used to initialize underlying net.Stream()
- default value:
- stringhost:
- default value:
null - host address of PostgreSQL server
- used to initialize underlying net.Stream()
- default value:
- stringuser:
varclient=newClient({user: 'brianc',password: 'boom!'database: 'test'host: 'example.com'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.
query(string text, optional function callback) : Query
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.
- stringtext: the query text
- optional functioncallback: optionally provided function which will be passed the error object (if the query raises an error) or the entire result set buffered into memory. note: do not provide this function for large result sets unless you're okay with loading the entire result set into memory
- function callback(object error, object result)
- Called only if provided
- buffers all rows into memory before calling
- rows only buffered if callback is provided
- can impact memory when buffering large result sets (i.e. do not provide a callback)
- used as a shortcut instead of subscribing to the
rowquery event - if passed, query will still raise the
rowandendevents but will no longer raise theerrorevent - objecterror:
nullif there was no error- if PostgreSQL encountered an error during query execution, the message will be called here
- objectresult:
- and object containing the following properties:
- arrayrows:
- an array of all rows returned from the query
- each row is equal to one object passed to the Query#row callback
- arrayrows:
- and object containing the following properties:
- objecterror:
varclient=newClient({user: 'brianc',database: 'test'});client.connect();//query is executed once connection is established and//PostgreSQL server is ready for a queryvarquery=client.query("SELECT name FROM users")query.on('row',function(row){console.log(row.name);});query.on('end',client.end.bind(client));//disconnect client manuallyvarclient=newClient({user: 'brianc',database: 'test'});client.on('drain',client.end.bind(client));//disconnect client when all queries are finishedclient.connect();//query is executed once connection is established and//PostgreSQL server is ready for a queryvarquery=client.query("SELECT name FROM users",function(err,result){console.log(result.rows[0].name);})query(object config, optional function callback) : Query
query(string queryText, array values, optional function callback): Query
Creates a (optionally named) query object, queues it for execution, and returns it.
If either name or values is provided within the config object the query will be executed as a prepared statement. Otherwise, it will behave in the same manner as a simple query.
- objectconfig: can contain any of the following optional properties
- stringtext:
- The text of the query
- example:
select name from user where email = $1
- stringname:
- The name of the prepared statement
- Can be used to reference the same statement again later and is used internally to cache and skip the preparation step
- arrayvalues:
- The values to supply as parameters
- Values may be any object type supported by the Client
- stringtext:
- optional functioncallback: callback function
- function callback(object error, object result)
- Called only if provided
- buffers all rows into memory before calling
- rows only buffered if callback is provided
- can impact memory when buffering large result sets (i.e. do not provide a callback)
- used as a shortcut instead of subscribing to the
rowquery event - if passed, query will still raise the
rowandendevents but will no longer raise theerrorevent - objecterror:
nullif there was no error- if PostgreSQL encountered an error during query execution, the message will be called here
- objectresult:
- and object containing the following properties:
- arrayrows:
- an array of all rows returned from the query
- each row is equal to one object passed to the Query#row callback
- arrayrows:
- and object containing the following properties:
- objecterror:
- function callback(object error, object result)
varclient=newClient({user: 'brianc',database: 'test'});client.on('drain',client.end.bind(client));//disconnect client when all queries are finishedclient.connect();varquery=client.query({text: 'SELECT name FROM users WHERE email = $1',values: ['brianc@example.com']});query.on('row',function(row){//do something w/ yer row dataassert.equal('brianc',row.name);});varclient=newClient({user: 'brianc',database: 'test'});client.on('drain',client.end.bind(client));//disconnect client when all queries are finishedclient.connect();varagain=client.query("SELECT name FROM users WHERE email = $1",['brianc@example.com']);again.on('row',function(row){//do something elseassert.equal('brianc',row.name);});varclient=newClient({user: 'brianc',database: 'test'});client.on('drain',client.end.bind(client));//disconnect client when all queries are finishedclient.connect();//object config methodvarqueryConfig={text: 'SELECT name FROM users WHERE email = $1',values: ['brian@example.com']};client.query(queryConfig,function(err,result){assert.equal('brianc',result.rows[0]);});//text/params methodclient.query('SELECT name FROM users WHERE email = $1',['brian@example.com'],function(err,result){assert.equal('brianc',result.rows[0].name);});The proceeding examples used an 'unamed' prepared statement. PostgreSQL server caches prepared statements by name on a per client basis. If a name is supplied for the statement all following executions of the query can refer to it by name and the PostgreSQL server instance can skip the preparation step.
varclient=newClient({user: 'brianc',database: 'test'});client.on('drain',client.end.bind(client));//disconnect client when all queries are finishedclient.connect();varfirst=client.query({text: "SELECT email FROM users WHERE name = $1",values: ['brianc'],name: 'email from name'});first.on('row',function(row){assert.equal("brian@example.com",row.email);});varsecond=client.query({name: 'email from name',values: ['brianc']});second.on('row',function(row){assert.equal("brian@example.com",row.email);});//can still supply a callback methodvarthird=client.query({name: 'email from name',values: ['brianc']},function(err,result){assert.equal('brian@example.com',result.rows[0].email);});Pair of methods used to pause and resume Client from raising it's drain event when it's query queue is emptied. The drain event signifies the Client has no more pending queries and can safely be returned back to a client pool. Normally, drain will be emitted These methods come in handy for doing async work between queries or within a transaction and disabling the Client from alerting anyone it has gone idle.
varclient=newClient(/*connection params*/);client.connect();client.on('drain',function(){console.log('client has drained');});client.pauseDrain();client.query("SELECT NOW() AS when",function(err,result){console.log("first");setTimeout(function(){client.query("SELECT NOW() AS when",function(err,result){console.log("second");client.resumeDrain();//now client will emit drain});},1000);});//output: // first// second// client has drainedRaised 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.
varclient=newClient({user: 'brianc',database: 'postgres'});client.connect();varusers=client.query("select * from user");varsuperdoods=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 returnusers.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.
varclient=newClient({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.
varclient1=newClient(...)varclient2=newClient(...)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 it's 'end' is calledsetTimeout(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.
varclient=newClient(...)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));