forked from CartoDB/node-postgres
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
96 lines (80 loc) · 2.55 KB
/
Copy pathindex.js
File metadata and controls
96 lines (80 loc) · 2.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var Client = require(__dirname+'/client');
var defaults = require(__dirname + '/defaults');
//external genericPool module
var genericPool = require('generic-pool');
//cache of existing client pools
var pools = {};
var PG = function(clientConstructor) {
EventEmitter.call(this);
this.Client = clientConstructor;
this.Connection = require(__dirname + '/connection');
this.defaults = defaults;
};
util.inherits(PG, EventEmitter);
PG.prototype.end = function() {
Object.keys(pools).forEach(function(name) {
var pool = pools[name];
pool.drain(function() {
pool.destroyAllNow();
});
})
}
PG.prototype.connect = function(config, callback) {
var self = this;
var c = config;
var cb = callback;
//allow for no config to be passed
if(typeof c === 'function') {
cb = c;
c = defaults;
}
//get unique pool name even if object was used as config
var poolName = typeof(c) === 'string' ? c : c.user+c.host+c.port+c.database;
var pool = pools[poolName];
if(pool) return pool.acquire(cb);
var pool = pools[poolName] = genericPool.Pool({
name: poolName,
create: function(callback) {
var client = new self.Client(c);
client.connect(function(err) {
if(err) return callback(err);
//handle connected client background errors by emitting event
//via the pg object and then removing errored client from the pool
client.on('error', function(e) {
self.emit('error', e, client);
pool.destroy(client);
});
callback(null, client);
});
client.on('drain', function() {
pool.release(client);
});
},
destroy: function(client) {
client.end();
},
max: defaults.poolSize,
idleTimeoutMillis: defaults.poolIdleTimeout,
reapIntervalMillis: defaults.reapIntervalMillis,
log: defaults.poolLog
});
return pool.acquire(cb);
}
// 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
if(typeof c === 'function')
c = defaults;
var cancellingClient = new this.Client(c);
cancellingClient.cancel(client, query);
}
module.exports = new PG(Client);
//lazy require native module...the native module may not have installed
module.exports.__defineGetter__("native", function() {
delete module.exports.native;
return (module.exports.native = new PG(require(__dirname + '/native')));
});
module.exports.types = require('./types');