-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.js
101 lines (86 loc) · 2.62 KB
/
db.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
var mysql = require('mysql'),
async = require('async')
var PRODUCTION_DB = 'finalAppProd',
TEST_DB = 'finalAppTest'
exports.MODE_TEST = 'mode_test'
exports.MODE_PRODUCTION = 'mode_production'
var state = {
pool: null,
mode: null,
}
exports.connect = function(mode, done) {
if (mode === exports.MODE_PRODUCTION) {
state.pool = mysql.createPoolCluster()
state.pool.add('WRITE', {
connectionLimit: 100,
host: 'localhost',
user: 'root',
password: 'pass',
database: PRODUCTION_DB
})
state.pool.add('READ1', {
connectionLimit: 100,
host: 'localhost',
user: 'root',
password: 'pass',
database: PRODUCTION_DB
})
state.pool.add('READ2', {
connectionLimit: 100,
host: 'localhost',
user: 'root',
password: 'pass',
database: PRODUCTION_DB
})
} else {
state.pool = mysql.createPool({
connectionLimit: 100,
host: 'localhost',
user: 'root',
password: 'pass',
database: TEST_DB
})
}
state.mode = mode
done()
}
exports.READ = 'read'
exports.WRITE = 'write'
exports.get = function(type, done) {
var pool = state.pool
if (!pool) return done(new Error('Missing database connection.'))
if (type === exports.WRITE) {
state.pool.getConnection('WRITE', function(err, connection) {
if (err) return done(err)
done(null, connection)
})
} else {
state.pool.getConnection('READ*', function(err, connection) {
if (err) return done(err)
done(null, connection)
})
}
}
//TODO:needs debugging
exports.fixtures = function(data, done) {
var connection = state.pool
if (!pool) return done(new Error('Missing database connection.'))
console.log("storing data");
var names = Object.keys(data.tables)
async.each(names, function(name, cb) {
async.each(data.tables[name], function(row, cb) {
var keys = Object.keys(row),
values = keys.map(function(key) {
return "'" + row[key] + "'"
})
pool.query('INSERT INTO ' + name + ' (' + keys.join(',') + ') VALUES (' + values.join(',') + ')', cb)
}, cb)
}, done)
}
exports.drop = function(tables, done) {
var pool = state.pool
if (!pool) return done(new Error('Missing database connection.'))
async.each(tables, function(name, cb) {
pool.query('DELETE * FROM ' + name, cb)
}, done)
}