-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
119 lines (108 loc) · 2.62 KB
/
index.js
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
module.exports = function(options){
options = options || {};
if(!(options.user && options.password)){
throw "database> user or password unspecified, cannot configure module";
}
var opts = {
host: "localhost"
, port: "3306"
, user: null
, log: false
, password: null
, database: null
, queries: null
, poolSize: 10
, includeFields: null
}
Object.keys(options).forEach(function(item, idx, arr){
opts[item] = options[item] || opts[item];
});
if(options.initQueries != null){
opts.initQueries = options.initQueries;
}else{
opts.initQueries = true;
}
if(options.cluster){
options.minSize = ~~options.minSize || 10;
opts.numCPUs = options.numCPUs || require("os").cpus().length;
opts.poolSize = Math.ceil(opts.poolSize / opts.numCPUs);
if(opts.poolSize < options.minSize){
opts.poolSize = options.minSize;
}
}
var mysql = require("mysql")
, poolModule = require("generic-pool")
, queriesManager = require("./lib/queriesManager")
, pool = poolModule.Pool({
max: opts.poolSize
, create: function(callback){
var client = mysql.createConnection({
host: opts.host
, port: opts.port
, user: opts.user
, password: opts.password
, database: opts.database
});
client.connect();
callback(null, client);
}
, destroy: function(client){
// console.log("FINISHED");
client.end();
}
});
if(options.queriesModule){
opts.queries = options.queriesModule(opts);
}
return function(cb){
var init
, initPool
, query;
cb = cb || function(){};
if(opts.initQueries){
query = { type: "init" };
}else{
query = "SHOW DATABASES;";
}
initPool = poolModule.Pool({
max: opts.poolSize
, create: function(callback){
var client = mysql.createConnection({
host: opts.host
, port: opts.port
, user: opts.user
, password: opts.password
});
client.connect();
callback(null, client);
}
, destroy: function(client){
client.end();
}
});
init = queriesManager(opts, initPool);
init(query, function(err, resp){
cleanUp(init, initPool);
if(opts.log){
console.log("init database>\n" + JSON.stringify(resp));
}
if(err){
if(err == "queries> Invalid query type: init"){
console.log("queries> WARNING! There are no database init queries");
}else{
return cb(err, null);
}
}
cb(null, queriesManager(opts, pool));
});
}
function cleanUp(init, initPool){
initPool.drain(function(){
initPool.destroyAllNow();
delete initPool;
initPool = undefined;
delete init;
init = undefined;
});
}
};