node-postgres/lib/index.js

68 lines
1.9 KiB
JavaScript
Raw Normal View History

var EventEmitter = require('events').EventEmitter;
2011-10-11 08:40:52 +08:00
var util = require('util');
var Client = require(__dirname+'/client');
var defaults = require(__dirname + '/defaults');
var pool = require(__dirname + '/pool');
var Connection = require(__dirname + '/connection');
2011-08-30 11:48:17 +08:00
var PG = function(clientConstructor) {
EventEmitter.call(this);
this.defaults = defaults;
this.Client = pool.Client = clientConstructor;
this.Query = this.Client.Query;
this.pools = pool;
this.Connection = Connection;
2014-03-16 04:41:36 +08:00
this.types = require('pg-types');
2011-08-30 11:48:17 +08:00
};
2011-10-11 08:40:52 +08:00
util.inherits(PG, EventEmitter);
2011-08-30 11:48:17 +08:00
PG.prototype.end = function() {
var self = this;
Object.keys(self.pools.all).forEach(function(key) {
var pool = self.pools.all[key];
delete self.pools.all[key];
pool.drain(function() {
pool.destroyAllNow();
});
2013-01-21 21:52:00 +08:00
});
};
2011-08-30 11:48:17 +08:00
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'));
2011-08-30 11:48:17 +08:00
}
2013-01-21 21:52:00 +08:00
};
2011-11-02 23:07:14 +08:00
// cancel the query runned by the given client
PG.prototype.cancel = function(config, client, query) {
var c = config;
//allow for no config to be passed
2013-01-21 21:52:00 +08:00
if(typeof c === 'function') {
2011-11-02 23:07:14 +08:00
c = defaults;
2013-01-21 21:52:00 +08:00
}
2011-11-02 23:07:14 +08:00
var cancellingClient = new this.Client(c);
cancellingClient.cancel(client, query);
2013-01-21 21:52:00 +08:00
};
2011-11-02 23:07:14 +08:00
var forceNative = Object.prototype.hasOwnProperty.call(process.env, 'NODE_PG_FORCE_NATIVE');
if (forceNative) {
module.exports = new PG(require(__dirname + '/native'));
} else {
module.exports = new PG(Client);
2012-09-19 01:30:50 +08:00
//lazy require native module...the native module may not have installed
module.exports.__defineGetter__("native", function() {
delete module.exports.native;
module.exports.native = new PG(require(__dirname + '/native'));
return module.exports.native;
});
}