diff --git a/lib/defaults.js b/lib/defaults.js index 9f5687b05..59214865b 100644 --- a/lib/defaults.js +++ b/lib/defaults.js @@ -39,6 +39,7 @@ var defaults = module.exports = { client_encoding: "", ssl: false, + max_connections: 10000, application_name : undefined, fallback_application_name: undefined diff --git a/lib/index.js b/lib/index.js index 02b89905a..c0267fbf6 100644 --- a/lib/index.js +++ b/lib/index.js @@ -13,6 +13,8 @@ var PG = function(clientConstructor) { this.pools = pool; this.Connection = Connection; this.types = require('pg-types'); + this.num_connections = 0; + this.max_connections = this.defaults.max_connections; }; util.inherits(PG, EventEmitter); @@ -39,18 +41,27 @@ PG.prototype.end = function() { } }; - PG.prototype.connect = function(config, callback) { if(typeof config == "function") { callback = config; config = null; } - var pool = this.pools.getOrCreate(config); - pool.connect(callback); - if(!pool.listeners('error').length) { - //propagate errors up to pg object - pool.on('error', this.emit.bind(this, 'error')); + if(this.max_connections && this.num_connections >= this.max_connections) { + return callback && callback(Error("Connection limit", this.max_connections, "reached")); } + var client = new this.Client(config); + // Max connections waiting to connect + this.num_connections++; + var _this = this; + client.connect(function(err) { + _this.num_connections--; + if(err) { + return callback && callback(err); + } + return callback && callback(null, client, function() { + client.end(); + }); + }); }; // cancel the query runned by the given client diff --git a/lib/pool.js b/lib/pool.js index b85a67383..c58ed3234 100644 --- a/lib/pool.js +++ b/lib/pool.js @@ -78,7 +78,8 @@ var pools = { if(err) { pool.destroy(client); } else { - pool.release(client); + pool.destroy(client); + // pool.release(client); } }); });