-
Notifications
You must be signed in to change notification settings - Fork 0
/
query.js
107 lines (104 loc) · 2.83 KB
/
query.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
module.exports = function (mysqlConfig) {
var mysql = require('mysql');
var pool = mysql.createPool(mysqlConfig);
var transAction = require ('./transAction')(mysqlConfig);
return function (sql, callback, isStream) {
if (typeof sql == 'object' && typeof sql.length == 'number') {
transAction(sql, callback);
} else {
pool.getConnection(function(err, connection) {
if (err) {
console.log(err);
} else {
if (sql == 'transAction') {
connection.doneCallback = function (callback) {
if (typeof callback !== 'function') {
callback = function () {};
}
if (connection.released) {
return;
}
connection.release();
connection.released = true;
callback();
};
connection.autoRollback = function (callback) {
connection.rollback(function () {
connection.doneCallback(callback);
return;
});
};
connection.autoCommit = function (callback) {
connection.commit(function () {
connection.doneCallback(callback);
return;
});
};
connection.transQuery = function (sql, callback) {
if (typeof callback != 'function') {
callback = function () {};
}
connection.query({
sql: sql,
timeout: 5000
}, function (err, results) {
if (err) {
return connection.autoRollback(function () {
console.log('MYSQL_ERROR: ' + new Date());
console.log(sql);
console.log(err);
callback(err, results);
return;
});
}
callback(err, results, sql);
});
return connection;
};
connection.beginTransaction(function(err) {
if (err) {
console.log(err);
return;
}
connection.released = false;
if (typeof callback == 'function') {
callback(connection);
}
});
return;
}
if (isStream) {
// callback(err, row, next, success);
connection.query(sql).on('error', function(err) {
console.log('MYSQL_ERROR: ' + new Date());
console.log(sql);
console.log(err);
callback(err, null, function(){}, false, sql);
}).on('fields', function(fields) {
}).on('result', function(row) {
connection.pause();
var next = function () {
connection.resume();
};
callback(null, row, next, false, sql);
}).on('end', function() {
callback(err, null, function(){}, true, sql);
});
return;
}
connection.query(sql, function(err, results) {
connection.release();
if (err) {
console.log('MYSQL_ERROR: ' + new Date());
console.log(sql);
console.log(err);
}
if (typeof callback == 'function') {
callback(err, results, sql);
}
});
}
});
}
};
};