-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdb.js
More file actions
75 lines (59 loc) · 1.85 KB
/
db.js
File metadata and controls
75 lines (59 loc) · 1.85 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
var config = require('./config');
var mysql = require('mysql')
, async = require('async')
var PRODUCTION_DB = config.dbname;
exports.MODE_TEST = 'mode_test'
exports.MODE_PRODUCTION = 'mode_production'
var state = {
pool: null,
mode: null,
}
exports.connect = function(mode, done) {
state.pool = mysql.createPool({
host: config.dbhost,
user: config.dbuser ,
password: config.dbpwd,
database: mode === exports.MODE_PRODUCTION ? PRODUCTION_DB : TEST_DB
});
state.pool.getConnection(function(err,connection){
if (err) {
//connection.release();
return done({"code" : 100, "status" : "Error in connection database"});
}
console.log('connected as id ' + connection.threadId);
connection.query("show tables",function(err,rows){
if(!err) {
connection.release();
console.log(rows);
}
});
connection.on('error', function(err) {
return done({"code" : 100, "status" : "Error in connection database"});
});
});
//console.log(state.pool)
state.mode = mode
done()
}
exports.get = function() {
return state.pool
}
exports.fixtures = function(data) {
var pool = state.pool
if (!pool) return done(new Error('Missing database connection.'))
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)
}