diff --git a/Readme.md b/Readme.md index abd5ef727..47951549a 100644 --- a/Readme.md +++ b/Readme.md @@ -214,6 +214,15 @@ pool.getConnection(function(err, connection) { }); ``` +If you need to set session variables on the connection before it gets used, +you can listen to the `connection` event. + +```js +pool.on('connection', function(err, connection) { + connection.query('SET SESSION auto_increment_increment=1') +}) +``` + When you are done with a connection, just call `connection.end()` and the connection will return to the pool, ready to be used again by someone else. diff --git a/lib/Pool.js b/lib/Pool.js index 9925fdf94..2ae5fe638 100644 --- a/lib/Pool.js +++ b/lib/Pool.js @@ -1,9 +1,13 @@ var mysql = require('../'); var Connection = require('./Connection'); +var EventEmitter = require('events').EventEmitter; +var Util = require('util'); module.exports = Pool; +Util.inherits(Pool, EventEmitter); function Pool(options) { + EventEmitter.call(this); this.config = options.config; this.config.connectionConfig.pool = this; @@ -39,6 +43,7 @@ Pool.prototype.getConnection = function (cb) { return cb(err); } + this.emit('connection', null, connection); return cb(null, connection); }.bind(this)); } diff --git a/test/integration/pool/test-connection-event.js b/test/integration/pool/test-connection-event.js new file mode 100644 index 000000000..e01d0757c --- /dev/null +++ b/test/integration/pool/test-connection-event.js @@ -0,0 +1,15 @@ +var common = require('../../common'); +var assert = require('assert'); +var Connection = require(common.lib + '/Connection'); +var pool = common.createPool(); + +var connectionEventHappened = false; +pool.on('connection', function(err, connection) { + connectionEventHappened = true; +}) + +pool.getConnection(function(err, connection) { + if (err) throw err; + assert.equal(connectionEventHappened, true); + pool.end(); +}); \ No newline at end of file